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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
559d5010ff14e31dd532b5a40561f3a050ed3dbb | 7,514 | cpp | C++ | src/modules/bluetooth_controller/bluetooth_controller.cpp | hidder11/controller-receiver | 3a2795f8baf0abf6043a17e0879972fc433dbdbc | [
"MIT"
] | 1 | 2018-06-15T05:58:57.000Z | 2018-06-15T05:58:57.000Z | src/modules/bluetooth_controller/bluetooth_controller.cpp | hidder11/controller-receiver | 3a2795f8baf0abf6043a17e0879972fc433dbdbc | [
"MIT"
] | null | null | null | src/modules/bluetooth_controller/bluetooth_controller.cpp | hidder11/controller-receiver | 3a2795f8baf0abf6043a17e0879972fc433dbdbc | [
"MIT"
] | null | null | null | #include <goliath/bluetooth_controller.h>
using namespace goliath::btc;
BluetoothController::BluetoothController(const std::string &newDevicePath, std::string &newDeviceAddress) {
devicePath = newDevicePath.c_str();
deviceAddress = newDeviceAddress;
}
bool BluetoothController::connect() {
int nTries = 5;
std::ostringstream oss;
oss << "rfcomm connect hci0 " << deviceAddress << " > /dev/null 2>&1 &";
std::string cmd = oss.str();
BOOST_LOG_TRIVIAL(debug) << "\"" << cmd.c_str() << "\" executed";
system("pkill rfcomm");
system(cmd.c_str());
for (int i = 0; i < nTries; i++) {
if (connected()) {
if (!serialPort.is_open()) {
serialPort.open(devicePath);
}
return true;
}
sleep(2);
}
return false;
}
void BluetoothController::start(const std::string &newDevicePath, std::string &newDeviceAddress) {
devicePath = newDevicePath.c_str();
deviceAddress = newDeviceAddress;
BOOST_LOG_TRIVIAL(info) << "Connecting to " << deviceAddress.c_str() << " on " << devicePath;
while (!connect()) {
BOOST_LOG_TRIVIAL(error) << "Could not connect to controller, retrying...";
};
BOOST_LOG_TRIVIAL(info) << "Connected to controller.";
serialPort.set_option(boost::asio::serial_port_base::baud_rate(38400));
serialPort.set_option(boost::asio::serial_port_base::character_size(8));
}
void BluetoothController::start() {
BOOST_LOG_TRIVIAL(info) << "Connecting to " << deviceAddress.c_str() << " on " << devicePath;
while (!connect()) {
BOOST_LOG_TRIVIAL(error) << "Could not connect to controller, retrying...";
};
BOOST_LOG_TRIVIAL(info) << "Connected to controller.";
serialPort.set_option(boost::asio::serial_port_base::baud_rate(38400));
serialPort.set_option(boost::asio::serial_port_base::character_size(8));
}
void BluetoothController::reconnect() {
if (serialPort.is_open()) {
serialPort.close();
}
BOOST_LOG_TRIVIAL(info) << "Reconnecting to " << deviceAddress.c_str() << " on " << devicePath;
while (!connect()) {
BOOST_LOG_TRIVIAL(error) << "Could not reconnect to controller, retrying...";
};
clear();
BOOST_LOG_TRIVIAL(info) << "Reconnected to controller.";
}
bool BluetoothController::connected() {
if (access(devicePath, W_OK) == -1) {
return false;
};
if (!serialPort.is_open()) {
serialPort.open(devicePath);
serialPort.set_option(boost::asio::serial_port_base::baud_rate(38400)); // Default for bluetooth
serialPort.set_option(boost::asio::serial_port_base::character_size(8));
}
const boost::system::error_code ec;
boost::asio::write(serialPort, boost::asio::buffer("write_test"));
serialPort.close();
if(ec){
return false;
}
return true;
}
Input BluetoothController::receive() {
char c;
auto *buffer = new char[BUFFER_SIZE];
int i = 0;
try {
// Read commands from serial
while (boost::asio::read(serialPort, boost::asio::buffer(&c, 1)) == 1) {
buffer[i++] = c;
if (c == '}') {
break; // End of command
}
}
} catch (const boost::system::system_error &ex) {
BOOST_LOG_TRIVIAL(error) << "Boost error: " << ex.code() << ", " << ex.what();
return Input(InputError::IE_CONNECTION_LOST);
}
return convertInput(buffer);
}
void BluetoothController::send(Status status, int value) {
boost::system::error_code error;
try {
lastMessage.set(status, value);
std::ostringstream oss;
oss << "{" << static_cast<int>(status) << ":" << value << "}";
std::string message = oss.str();
boost::asio::write(serialPort, boost::asio::buffer(message), error);
if (error) {
BOOST_LOG_TRIVIAL(error) << error.message().c_str();
return;
}
BOOST_LOG_TRIVIAL(debug) << "Sent status message \"" << message.c_str() << "\" to controller.";
} catch (const boost::system::system_error &ex) {
BOOST_LOG_TRIVIAL(error) << "Could not send status message to controller.";
}
}
void BluetoothController::send(int severity, std::string message) {
boost::system::error_code error;
try {
std::ostringstream oss;
oss << "{" << severity << ":" << message << "}";
std::string message = oss.str();
boost::asio::write(serialPort, boost::asio::buffer(message), error);
if (error) {
BOOST_LOG_TRIVIAL(error) << error.message().c_str();
return;
}
BOOST_LOG_TRIVIAL(debug) << "Sent log message \"" << message.c_str() << "\" to controller.";
} catch (const boost::system::system_error &ex) {
BOOST_LOG_TRIVIAL(error) << "Could not send log message to controller.";
}
}
void BluetoothController::sendLast() {
if (lastMessage.isSet) {
boost::system::error_code error;
try {
std::ostringstream oss;
oss << "{" << static_cast<int>(lastMessage.status) << ":" << lastMessage.value << "}";
std::string message = oss.str();
boost::asio::write(serialPort, boost::asio::buffer(message), error);
if (error) {
BOOST_LOG_TRIVIAL(error) << error.message().c_str();
return;
}
} catch (const boost::system::system_error &ex) {
BOOST_LOG_TRIVIAL(error) << "Could not send message to controller.";
}
}
}
Input BluetoothController::convertInput(char *buffer) {
if (buffer != 0) {
std::string command(buffer);
std::vector<std::size_t> pos;
pos.emplace_back(command.find('{'));
pos.emplace_back(command.find(';'));
pos.emplace_back(command.find(':'));
pos.emplace_back(command.find('}'));
if (pos[0] != std::string::npos && pos[1] != std::string::npos && pos[2] != std::string::npos &&
pos[3] != std::string::npos && std::is_sorted(begin(pos), end(pos))) {
std::string type = command.substr(pos[0] + 1, pos[1] - pos[0] - 1);
std::string key = command.substr(pos[1] + 1, pos[2] - pos[1] - 1);
std::string value = command.substr(pos[2] + 1, pos[3]);
return Input(type, key, value);
}
BOOST_LOG_TRIVIAL(warning) << "Invalid message \"" << command.c_str() << "\" received.";
return Input(InputError::IE_WRONG_FORMAT);
}
BOOST_LOG_TRIVIAL(warning) << "Empty message received.";
return Input(InputError::IE_EMPTY);
}
void BluetoothController::clear() {
if (0 == ::tcflush(serialPort.lowest_layer().native_handle(), TCIOFLUSH)) {
boost::system::error_code();
} else {
boost::system::error_code(errno, boost::asio::error::get_system_category());
}
BOOST_LOG_TRIVIAL(info) << "Serial buffer flushed.";
}
BluetoothController::BluetoothController() {
}
StatusMessage::StatusMessage(Status stat, short val) {
status = stat;
value = val;
}
void StatusMessage::set(Status stat, short val) {
status = stat;
value = val;
isSet = true;
}
StatusMessage::StatusMessage() {
status = Status::BT_CONNECTED;
value = 0;
}
Input::Input(std::string type, std::string control, std::string value) : type(type), control(control), value(value) {
error = InputError ::IE_SUCCES;
}
Input::Input(InputError error) : error(error) {}
| 30.056 | 117 | 0.602475 | [
"vector"
] |
559f00a0b2633ade0170757fda56d59010827c93 | 8,779 | cpp | C++ | common/exportFiles.cpp | cordafab/SuperCages-project | 797d28bab18c9c44027af8c9d94d9e5efe4ceade | [
"MIT"
] | 16 | 2020-04-26T16:41:38.000Z | 2022-03-27T00:13:27.000Z | common/exportFiles.cpp | cordafab/SuperCages-project | 797d28bab18c9c44027af8c9d94d9e5efe4ceade | [
"MIT"
] | null | null | null | common/exportFiles.cpp | cordafab/SuperCages-project | 797d28bab18c9c44027af8c9d94d9e5efe4ceade | [
"MIT"
] | 7 | 2020-04-27T13:04:43.000Z | 2022-03-09T08:22:41.000Z | #include "exportFiles.h"
using namespace std;
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include "geom/transform.h"
void saveMesh(const char * filename,
const std::vector<double> & vertices,
const std::vector<int> & faces)
{
string str(filename);
string filetype = str.substr(str.size()-3,3);
if ( filetype.compare("obj") == 0 ||
filetype.compare("OBJ") == 0 )
{
saveOBJ(filename, vertices, faces);
}
else
if ( filetype.compare("ply") == 0 ||
filetype.compare("PLY") == 0 )
{
savePLY(filename, vertices, faces);
}
else
if ( filetype.compare("off") == 0 ||
filetype.compare("OFF") == 0 )
{
//loadOFF(filename, vertices, faces);
}
else
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveMesh() : file format not supported yet " << endl;
exit(-1);
}
}
void saveOBJ ( const char * filename ,
const std::vector<double> & vertices ,
const std::vector<int> & faces )
{
ofstream fp;
fp.open (filename);
fp.precision(6);
fp.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
if(!fp)
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveOBJ() : couldn't open output file " << filename << endl;
exit(-1);
}
for(int i=0; i<(int)vertices.size(); i+=3)
{
fp << "v " << vertices[i] << " " << vertices[i+1] << " " << vertices[i+2] << endl;
}
for(int i=0; i<(int)faces.size(); i+=3)
{
fp << "f " << faces[i]+1 << " " << faces[i+1]+1 << " " << faces[i+2]+1 << endl;
}
fp.close();
}
void savePLY(const char *filename,
const std::vector<double> & vertices,
const std::vector<int> & faces)
{
}
void saveWeights(const char * filename,
const Weights * weights)
{
ofstream fp;
fp.open (filename);
fp.precision(6);
fp.setf( std::ios::fixed, std::ios::floatfield ); // floatfield set to fixed
if(!fp)
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveWeights() : couldn't open output file " << filename << endl;
exit(-1);
}
for(ulong i = 0; i < weights->getNumberOfVertices(); i++)
{
for(ulong j = 0; j < weights->getNumberOfHandles(); j++)
{
double w = weights->getWeight(j,i);
if(w != 0.0)
{
fp << j << " " << i << " " << w << std::endl;
}
}
}
fp.close();
}
void saveAnimation(const char * filename,
const std::vector<double> & t,
const std::vector<std::vector<double>> & cageKeyframes,
const std::vector<std::vector<cg3::Transform>> & restSkelKeyframes,
const std::vector<std::vector<cg3::Transform>> & deformedSkelKeyframes)
{
ofstream fp;
fp.open (filename);
fp.precision(6);
fp.setf( std::ios::fixed, std::ios::floatfield ); // floatfield set to fixed
if(!fp)
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveWeights() : couldn't open output file " << filename << endl;
exit(-1);
}
for( unsigned long i = 0; i < t.size(); ++i )
{
fp << "k " << t[i] << endl; //keyframe
}
for( unsigned long i = 0; i < t.size(); ++i )
{
for( unsigned long j = 0; j < cageKeyframes[i].size(); j+=3 )
{
fp << "c " //cage
<< i << " "
<< cageKeyframes[i][j+0] << " "
<< cageKeyframes[i][j+1] << " "
<< cageKeyframes[i][j+2] << endl;
}
for( unsigned long j = 0; j < restSkelKeyframes[i].size(); ++j )
{
std::vector<double> kf(16);
restSkelKeyframes[i][j].data(kf);
fp << "r " //skel
<< i << " "
<< kf[0] << " " << kf[1] << " " << kf[2] << " " << kf[3] << " "
<< kf[4] << " " << kf[5] << " " << kf[6] << " " << kf[7] << " "
<< kf[8] << " " << kf[9] << " " << kf[10] << " " << kf[11] << " "
<< kf[12] << " " << kf[13] << " " << kf[14] << " " << kf[15] <<
std::endl;
//std::cout << kfT.getEigenTransformation() << std::endl;
}
for( unsigned long j = 0; j < deformedSkelKeyframes[i].size(); ++j )
{
std::vector<double> kf(16);
deformedSkelKeyframes[i][j].data(kf);
fp << "d " //skel
<< i << " "
<< kf[0] << " " << kf[1] << " " << kf[2] << " " << kf[3] << " "
<< kf[4] << " " << kf[5] << " " << kf[6] << " " << kf[7] << " "
<< kf[8] << " " << kf[9] << " " << kf[10] << " " << kf[11] << " "
<< kf[12] << " " << kf[13] << " " << kf[14] << " " << kf[15] <<
std::endl;
//std::cout << kfT.getEigenTransformation() << std::endl;
}
}
fp.close();
}
void saveSkeleton (const char * filename,
const std::vector<cg3::Vec3d> & joints,
const std::vector<int> & fathers,
const std::vector<std::string> & names)
{
ofstream fp;
fp.open (filename);
fp.precision(6);
fp.setf( std::ios::fixed, std::ios::floatfield ); // floatfield set to fixed
if(!fp)
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveSkeleton() : couldn't open output file " << filename << endl;
exit(-1);
}
for( unsigned long i = 0; i < joints.size(); ++i )
{
fp << "j "
<< i << " "
<< names[i] << " "
<< fathers[i] << " "
<< joints[i].x() << " "
<< joints[i].y() << " "
<< joints[i].z()
<< std::endl;
}
fp.close();
}
void saveSkelAnimation (
const char * filename,
const std::vector<double> & t,
const std::vector<std::vector<cg3::Transform>> & skelKeyframes)
{
ofstream fp;
fp.open (filename);
fp.precision(6);
fp.setf( std::ios::fixed, std::ios::floatfield ); // floatfield set to fixed
if(!fp)
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveWeights() : couldn't open output file " << filename << endl;
exit(-1);
}
fp << "# V3" << std::endl;
fp << "# Composition of the .ska file:" << std::endl;
fp << "# s <keyframeIndex> <(globalCurrentPoseRotation) x y z> <(globalCurrentPoseTranslation) x y z>" << std::endl << std::endl;
for( unsigned long i = 0; i < t.size(); ++i )
{
fp << "k " << t[i] << std::endl; //keyframe
}
for( unsigned long i = 0; i < t.size(); ++i )
{
for( unsigned long j = 0; j < skelKeyframes[i].size(); ++j )
{
cg3::Vec3d r = skelKeyframes[i][j].getRotation().toEuler();
cg3::Vec3d t = skelKeyframes[i][j].getTranslation();
fp << "s " //skel
<< i << " "
<< r[0] << " " << r[1] << " " << r[2] << " "
<< t[0] << " " << t[1] << " " << t[2] << " " <<
std::endl;
}
}
fp.close();
}
void saveCageAnimation (
const char * filename,
const std::vector<double> & t,
const std::vector<std::vector<double> > & cageKeyframes)
{
ofstream fp;
fp.open (filename);
fp.precision(6);
fp.setf( std::ios::fixed, std::ios::floatfield ); // floatfield set to fixed
if(!fp)
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveWeights() : couldn't open output file " << filename << endl;
exit(-1);
}
for( unsigned long i = 0; i < t.size(); ++i )
{
fp << "k " << t[i] << endl; //keyframe
}
for( unsigned long i = 0; i < t.size(); ++i )
{
for( unsigned long j = 0; j < cageKeyframes[i].size(); j+=3 )
{
fp << "c " //cage
<< i << " "
<< cageKeyframes[i][j+0] << " "
<< cageKeyframes[i][j+1] << " "
<< cageKeyframes[i][j+2] << endl;
}
}
fp.close();
}
void saveDoubleVec(const char * filename, const std::vector<double> & params)
{
ofstream fp;
fp.open (filename);
fp.precision(6);
fp.setf( std::ios::fixed, std::ios::floatfield ); // floatfield set to fixed
if(!fp)
{
cerr << "ERROR : " << __FILE__ << ", line " << __LINE__ << " : saveDoubleVec() : couldn't open output file " << filename << endl;
exit(-1);
}
for( unsigned long i = 0; i < params.size(); ++i )
{
fp << params[i] << endl; //keyframe
}
fp.close();
}
| 28.047923 | 135 | 0.454608 | [
"vector",
"transform"
] |
55a06ff2b4fead30510e18217eb8a7cafbcaa264 | 5,401 | cxx | C++ | plugins/examples/gpu_test.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 1 | 2020-07-26T10:54:41.000Z | 2020-07-26T10:54:41.000Z | plugins/examples/gpu_test.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | null | null | null | plugins/examples/gpu_test.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | null | null | null | #include <cgv/signal/rebind.h>
#include <cgv/base/register.h>
#include <cgv/gui/provider.h>
#include <cgv/gui/trigger.h>
#include <cgv/render/drawable.h>
#include <cgv/render/texture.h>
#include <cgv/render/frame_buffer.h>
#include <cgv/render/shader_program.h>
#include <cgv_gl/gl/gl.h>
#include <cgv/media/font/font.h>
#include <cgv/math/ftransform.h>
using namespace cgv::base;
using namespace cgv::data;
using namespace cgv::media::font;
using namespace cgv::signal;
using namespace cgv::render;
using namespace cgv::gui;
class gpu_test :
public base,
public drawable,
public provider
{
protected:
font_face_ptr font_face;
texture tex;
texture img_tex;
texture depth_tex;
render_buffer db;
shader_program prog;
shader_code vs, fs, v_lib, f_lib;
frame_buffer fb;
double angle;
bool show_tex, show_img_tex;
bool do_shader_setup_by_hand;
bool use_depth_texture;
public:
/// define format and texture filters in constructor
gpu_test() :
tex("uint8[R,G,B,A]", TF_NEAREST, TF_NEAREST),
img_tex("uint8[R,G,B]", TF_NEAREST, TF_NEAREST),
depth_tex("[D]", TF_NEAREST, TF_NEAREST),
db("[D]")
{
font_face = find_font("Arial")->get_font_face(FFA_ITALIC);
angle = 0;
show_tex = show_img_tex = true;
use_depth_texture = true;
do_shader_setup_by_hand = false;
connect(get_animation_trigger().shoot, this, &gpu_test::timer_event);
}
/// timer increments angle, updates gui and posts a redraw
void timer_event(double t, double dt)
{
angle += 100*dt;
update_member(&angle);
post_redraw();
}
std::string get_type_name() const
{
return "gpu_test";
}
bool init(context& ctx)
{
bool success = true;
// create textures
success = img_tex.create_from_image(ctx, "res://cgv_logo.png");
// create in the size of the 3D view
int w = ctx.get_width();
int h = ctx.get_height();
tex.set_width(w);
tex.set_height(h);
success = tex.create(ctx) && success;
depth_tex.set_width(w);
depth_tex.set_height(h);
success = depth_tex.create(ctx) && success;
// set up frame buffer object
db.create(ctx,w,h);
success = fb.create(ctx,w,h) && success;
if (use_depth_texture)
fb.attach(ctx,depth_tex);
else
fb.attach(ctx,db);
fb.attach(ctx,tex);
// and check whether it is complete now
success = fb.is_complete(ctx) && success;
if (do_shader_setup_by_hand) {
// set up shader program by reading and compiling each code
success = vs.read_and_compile(ctx, "gpu_test.glvs") && success;
success = fs.read_and_compile(ctx, "gpu_test.glfs") && success;
success = v_lib.read_and_compile(ctx, "my_support_functions.glsl", ST_VERTEX) && success;
success = f_lib.read_and_compile(ctx, "my_support_functions.glsl", ST_FRAGMENT) && success;
success = prog.create(ctx) && success;
success = prog.attach_code(ctx, vs) && success;
success = prog.attach_code(ctx, fs) && success;
success = prog.attach_code(ctx, v_lib) && success;
success = prog.attach_code(ctx, f_lib) && success;
success = prog.link(ctx, true) && success;
}
else
// set up shader program through shader program file
success = prog.build_program(ctx, "gpu_test.glpr") && success;
if (!success)
std::cout << "init failed" << std::endl;
return success;
}
void init_frame(context& ctx)
{
// activate frame buffer object rendering to texture tex
fb.enable(ctx);
glPushAttrib(GL_COLOR_BUFFER_BIT);
// clear screen
glClearColor(0,1,1,1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// draw text
//ctx.ref_default_shader_program().enable(ctx);
ctx.set_color(rgb(0.0f));
ctx.push_pixel_coords();
ctx.set_cursor(200,400);
ctx.enable_font_face(font_face, 40);
ctx.output_stream() << "test\ntext" << std::endl;
ctx.pop_pixel_coords();
//ctx.ref_default_shader_program().disable(ctx);
// draw rotating cube
ctx.ref_surface_shader_program().enable(ctx);
ctx.set_color(rgb(1.0f,0.0f,0.0f));
ctx.push_modelview_matrix();
ctx.mul_modelview_matrix(cgv::math::rotate4<double>(angle, 1, 0, 0));
ctx.tesselate_unit_cube();
ctx.pop_modelview_matrix();
ctx.ref_surface_shader_program().disable(ctx);
glPopAttrib();
fb.disable(ctx);
}
void draw(context& ctx)
{
// enable textures in different texture units
tex.enable(ctx, 0);
img_tex.enable(ctx, 1);
// enable shader program
prog.enable(ctx);
ctx.set_color(rgb(1.0f));
// set uniform variables including texture units
prog.set_uniform(ctx,"show_tex", show_tex);
prog.set_uniform(ctx,"show_img_tex", show_img_tex);
prog.set_uniform(ctx,"tex", 0);
prog.set_uniform(ctx,"img_tex", 1);
prog.set_uniform(ctx, "map_color_to_material", 3);
// draw scene
ctx.tesselate_unit_cube();
// disable shader program
prog.disable(ctx);
// and textures
img_tex.disable(ctx);
tex.disable(ctx);
}
void clear(context& ctx)
{
// destruct all allocated objects
tex.destruct(ctx);
img_tex.destruct(ctx);
depth_tex.destruct(ctx);
db.destruct(ctx);
fb.destruct(ctx);
prog.destruct(ctx);
vs.destruct(ctx);
fs.destruct(ctx);
v_lib.destruct(ctx);
f_lib.destruct(ctx);
}
void create_gui()
{
add_view("angle", angle);
add_member_control(this, "show_tex", show_tex, "check");
add_member_control(this, "show_img_tex", show_img_tex, "check");
}
};
factory_registration<gpu_test> fr_gpu_test("new/render/gpu_test", 'U', true); | 27.697436 | 94 | 0.69987 | [
"render",
"object",
"3d"
] |
55a175f8a3bd2f7c45b248d7277201b1537b97bb | 10,672 | cpp | C++ | deps/common/time/datetime.cpp | penggan666/miniob | 23a3c30e06b06958f70aa9dc2c31e70354e2b708 | [
"Apache-2.0"
] | 1 | 2022-03-02T03:41:13.000Z | 2022-03-02T03:41:13.000Z | deps/common/time/datetime.cpp | Wind-Gone/OceanBase-Contest-Miniob | b16d6b2c6785abf99eb816ff8c7417bafd1ddf96 | [
"MIT"
] | null | null | null | deps/common/time/datetime.cpp | Wind-Gone/OceanBase-Contest-Miniob | b16d6b2c6785abf99eb816ff8c7417bafd1ddf96 | [
"MIT"
] | null | null | null | /* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */
//
// Created by Longda on 2010
//
#include "common/time/datetime.h"
#include "pthread.h"
#include "stdio.h"
#include "string.h"
#include <iomanip>
#include <sstream>
#include <string>
namespace common {
DateTime::DateTime(std::string &xml_str) {
tm tmp;
sscanf(xml_str.c_str(), "%04d-%02d-%02dT%02d:%02d:%02dZ", &tmp.tm_year,
&tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour, &tmp.tm_min, &tmp.tm_sec);
m_date = julian_date(tmp.tm_year, tmp.tm_mon, tmp.tm_mday);
m_time = make_hms(tmp.tm_hour, tmp.tm_min, tmp.tm_sec, 0);
}
time_t DateTime::str_to_time_t(std::string &xml_str) {
tm tmp;
sscanf(xml_str.c_str(), "%04d-%02d-%02dT%02d:%02d:%02dZ", &tmp.tm_year,
&tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour, &tmp.tm_min, &tmp.tm_sec);
m_date = julian_date(tmp.tm_year, tmp.tm_mon, tmp.tm_mday);
m_time = make_hms(tmp.tm_hour, tmp.tm_min, tmp.tm_sec, 0);
return to_time_t();
}
std::string DateTime::time_t_to_str(int timet) {
std::ostringstream oss;
oss << std::dec << std::setw(10) << timet;
return oss.str();
}
std::string DateTime::time_t_to_xml_str(time_t timet) {
std::string ret_val;
std::ostringstream oss;
struct tm tmbuf;
tm *tm_info = gmtime_r(&timet, &tmbuf);
oss << tm_info->tm_year + 1900 << "-";
if ((tm_info->tm_mon + 1) <= 9)
oss << "0";
oss << tm_info->tm_mon + 1 << "-";
if (tm_info->tm_mday <= 9)
oss << "0";
oss << tm_info->tm_mday << "T";
if (tm_info->tm_hour <= 9)
oss << "0";
oss << tm_info->tm_hour << ":";
if (tm_info->tm_min <= 9)
oss << "0";
oss << tm_info->tm_min << ":";
if (tm_info->tm_sec <= 9)
oss << "0";
oss << tm_info->tm_sec << "Z";
ret_val = oss.str();
return ret_val;
}
std::string DateTime::str_to_time_t_str(std::string &xml_str) {
tm tmp;
std::ostringstream oss;
sscanf(xml_str.c_str(), "%04d-%02d-%02dT%02d:%02d:%02dZ", &tmp.tm_year,
&tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour, &tmp.tm_min, &tmp.tm_sec);
m_date = julian_date(tmp.tm_year, tmp.tm_mon, tmp.tm_mday);
m_time = make_hms(tmp.tm_hour, tmp.tm_min, tmp.tm_sec, 0);
time_t timestamp = to_time_t();
oss << std::dec << std::setw(10) << timestamp;
return oss.str();
}
time_t DateTime::nowtimet() {
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec;;
}
DateTime DateTime::now() {
struct timeval tv;
gettimeofday(&tv, 0);
return from_time_t(tv.tv_sec, tv.tv_usec / 1000);
}
//! Return date and time as a string in Xml Schema date-time format
std::string DateTime::to_xml_date_time() {
std::string ret_val;
tm tm_info;
std::ostringstream oss;
tm_info = to_tm();
oss << tm_info.tm_year + 1900 << "-";
if ((tm_info.tm_mon + 1) <= 9)
oss << "0";
oss << tm_info.tm_mon + 1 << "-";
if (tm_info.tm_mday <= 9)
oss << "0";
oss << tm_info.tm_mday << "T";
if (tm_info.tm_hour <= 9)
oss << "0";
oss << tm_info.tm_hour << ":";
if (tm_info.tm_min <= 9)
oss << "0";
oss << tm_info.tm_min << ":";
if (tm_info.tm_sec <= 9)
oss << "0";
oss << tm_info.tm_sec << "Z";
ret_val = oss.str();
return ret_val;
}
time_t DateTime::add_duration(std::string xml_duration) {
add_duration_date_time(xml_duration);
return to_time_t();
}
void DateTime::add_duration_date_time(std::string xml_duration) {
// start datetime values
int s_year, s_month, s_day;
int s_hour, s_min, s_sec, s_millis = 0;
get_ymd(s_year, s_month, s_day);
get_hms(s_hour, s_min, s_sec, s_millis);
// temp values
int tmp_month, tmp_sec, tmp_min, tmp_hour, tmp_day;
// duration values
struct tm dur_t;
parse_duration(xml_duration, dur_t);
// end values
int e_year, e_month, e_day, e_hour, e_min, e_sec, e_millis = 0;
// months
tmp_month = s_month + dur_t.tm_mon;
e_month = ((tmp_month - 1) % 12) + 1;
int carry_month = ((tmp_month - 1) / 12);
// years
e_year = s_year + dur_t.tm_year + carry_month;
// seconds
tmp_sec = s_sec + dur_t.tm_sec;
e_sec = tmp_sec % 60;
int carry_sec = tmp_sec / 60;
// minutes
tmp_min = s_min + dur_t.tm_min + carry_sec;
e_min = tmp_min % 60;
int carry_min = tmp_min / 60;
// hours
tmp_hour = s_hour + dur_t.tm_hour + carry_min;
e_hour = tmp_hour % 24;
int carry_hr = tmp_hour / 24;
// days
if (s_day > max_day_in_month_for(e_year, e_month)) {
tmp_day = max_day_in_month_for(e_year, e_month);
} else {
if (s_day < 1) {
tmp_day = 1;
} else {
tmp_day = s_day;
}
}
e_day = tmp_day + dur_t.tm_mday + carry_hr;
int carry_day = 0;
while (true) {
if (e_day < 1) {
e_day = e_day + max_day_in_month_for(e_year, e_month - 1);
carry_day = -1;
} else {
if (e_day > max_day_in_month_for(e_year, e_month)) {
e_day -= max_day_in_month_for(e_year, e_month);
carry_day = 1;
} else {
break;
}
}
tmp_month = e_month + carry_day;
e_month = ((tmp_month - 1) % 12) + 1;
e_year = e_year + (tmp_month - 1) / 12;
}
m_date = julian_date(e_year, e_month, e_day);
m_time = make_hms(e_hour, e_min, e_sec, e_millis);
return;
}
int DateTime::max_day_in_month_for(int yr, int month) {
int tmp_month = ((month - 1) % 12) + 1;
int tmp_year = yr + ((tmp_month - 1) / 12);
if (tmp_month == MON_JAN || tmp_month == MON_MAR || tmp_month == MON_MAY ||
tmp_month == MON_JUL || tmp_month == MON_AUG || tmp_month == MON_OCT ||
tmp_month == MON_DEC) {
return 31;
} else {
if (tmp_month == MON_APR || tmp_month == MON_JUN || tmp_month == MON_SEP ||
tmp_month == MON_NOV)
return 30;
else {
if (tmp_month == MON_FEB && ((0 == tmp_year % 400) ||
((0 != tmp_year % 100) && 0 == tmp_year % 4))) {
return 29;
} else
return 28;
}
}
}
void DateTime::parse_duration(std::string dur_str, struct tm &tm_t) {
std::string::size_type index = 0;
bzero(&tm_t, sizeof(tm_t));
if (dur_str[index] != 'P') {
return;
}
int ind_t = dur_str.find('T', 0);
index++;
int ind_y = dur_str.find('Y', index);
if (ind_y != -1) {
int sign = 1;
if (dur_str[index] == '-') {
sign = -1;
index++;
}
std::string sY = dur_str.substr(index, ind_y);
sscanf(sY.c_str(), "%d", &tm_t.tm_year);
tm_t.tm_year *= sign;
index = ind_y + 1;
}
int ind_m = dur_str.find('M', index);
if ((ind_m != -1) && (((ind_t > -1) && (ind_m < ind_t)) || ind_t == -1)) {
int sign = 1;
if (dur_str[index] == '-') {
sign = -1;
index++;
}
sscanf(dur_str.substr(index, ind_m).c_str(), "%d", &tm_t.tm_mon);
tm_t.tm_mon *= sign;
index = ind_m + 1;
}
int ind_d = dur_str.find('D', index);
int sign = 1;
if (ind_d != -1) {
if (dur_str[index] == '-') {
sign = -1;
index++;
}
sscanf(dur_str.substr(index, ind_d).c_str(), "%d", &tm_t.tm_mday);
tm_t.tm_mday *= sign;
// index = ind_d + 1; // not used
}
if (ind_t == -1) {
tm_t.tm_hour = tm_t.tm_min = tm_t.tm_sec = 0;
return;
}
index = ind_t + 1;
int ind_h = dur_str.find('H', index);
if (ind_h != -1) {
int sign = 1;
if (dur_str[index] == '-') {
sign = -1;
index++;
}
sscanf(dur_str.substr(index, ind_h).c_str(), "%d", &tm_t.tm_hour);
tm_t.tm_hour *= sign;
index = ind_h + 1;
}
int ind_min = dur_str.find('M', index);
if (ind_min != -1) {
int sign = 1;
if (dur_str[index] == '-') {
sign = -1;
index++;
}
sscanf(dur_str.substr(index, ind_min).c_str(), "%d", &tm_t.tm_min);
tm_t.tm_min *= sign;
index = ind_min + 1;
}
int ind_s = dur_str.find('S', index);
if (ind_s != -1) {
int sign = 1;
if (dur_str[index] == '-') {
sign = -1;
index++;
}
sscanf(dur_str.substr(index, ind_s).c_str(), "%d", &tm_t.tm_sec);
tm_t.tm_sec *= sign;
}
return;
}
// generate OBJ_ID_TIMESTMP_DIGITS types unique timestamp string
// caller doesn't need get any lock
#define OBJ_ID_TIMESTMP_DIGITS 14
std::string Now::unique() {
struct timeval tv;
u64_t temp;
static u64_t last_unique = 0;
#if defined(LINUX)
static pthread_mutex_t mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
#elif defined(__MACH__)
static pthread_mutex_t mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER;
#endif
gettimeofday(&tv, NULL);
temp = (((u64_t) tv.tv_sec) << 20) + tv.tv_usec;
pthread_mutex_lock(&mutex);
if (temp > last_unique) {
// record last timeStamp
last_unique = temp;
} else {
// increase the last timeStamp and use it as unique timestamp
// as NTP may sync local time clock backward.
// after time catch up, will change back to use time again.
last_unique++;
// set the new last_unique as unique timestamp
temp = last_unique;
}
pthread_mutex_unlock(&mutex);
// further refine below code, the common time unique function
// should not cover OBJ_ID_TIMESTMP_DIGITS, which is only
// related with the object id.
std::ostringstream oss;
oss << std::hex << std::setw(OBJ_ID_TIMESTMP_DIGITS) << std::setfill('0')
<< temp;
return oss.str();
}
bool DateTime::is_valid_xml_datetime(const std::string &str) {
// check length. 20 is the length of a xml date
if (str.length() != 20)
return false;
// check each character is correct
const char *const flag = "0000-00-00T00:00:00Z";
for (unsigned int i = 0; i < str.length(); ++i) {
if (flag[i] == '0') {
if (!isdigit(str[i]))
return false;
} else if (flag[i] != str[i]) {
return false;
}
}
// check month, date, hour, min, second is valid
tm tmp;
int ret =
sscanf(str.c_str(), "%04d-%02d-%02dT%02d:%02d:%02dZ", &tmp.tm_year,
&tmp.tm_mon, &tmp.tm_mday, &tmp.tm_hour, &tmp.tm_min, &tmp.tm_sec);
if (ret != 6)
return false; // should have 6 match
if (tmp.tm_mon > 12 || tmp.tm_mon <= 0)
return false;
if (tmp.tm_mday > 31 || tmp.tm_mday <= 0)
return false;
if (tmp.tm_hour > 24 || tmp.tm_hour < 0)
return false;
if (tmp.tm_min > 60 || tmp.tm_min < 0)
return false;
if (tmp.tm_sec > 60 || tmp.tm_sec < 0)
return false;
return true;
}
} //namespace common | 27.364103 | 111 | 0.612819 | [
"object"
] |
55a59b422e69d02cf13c70179d7a9018364bf0d0 | 2,837 | cpp | C++ | copasi/UI/CQMathMatrixWidget.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | copasi/UI/CQMathMatrixWidget.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | copasi/UI/CQMathMatrixWidget.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | // Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include "CQMathMatrixWidget.h"
#include "copasi.h"
#include "qtUtilities.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"
#include "model/CModel.h"
/**
* Constructs a CQMathMatrixWidget which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
CQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent)
: CopasiWidget(parent)
{
setupUi(this);
CColorScaleSimple * tcs = new CColorScaleSimple();
mpArrayWidget1->setColorCoding(tcs);
tcs->setMinMax(-1.5, 1.5);
mpArrayWidget1->setColorScalingAutomatic(false);
tcs = new CColorScaleSimple();
mpArrayWidget2->setColorCoding(tcs);
tcs->setMinMax(-1.5, 1.5);
mpArrayWidget2->setColorScalingAutomatic(false);
tcs = new CColorScaleSimple();
mpArrayWidget3->setColorCoding(tcs);
tcs->setMinMax(-1.5, 1.5);
mpArrayWidget3->setColorScalingAutomatic(false);
}
/*
* Destroys the object and frees any allocated resources
*/
CQMathMatrixWidget::~CQMathMatrixWidget()
{}
void CQMathMatrixWidget::loadMatrices()
{
assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
const CModel* pModel = (*CCopasiRootContainer::getDatamodelList())[0]->getModel();
const CArrayAnnotation * tmp;
tmp = dynamic_cast<const CArrayAnnotation *>
(pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)")));
mpArrayWidget1->setArrayAnnotation(tmp);
tmp = dynamic_cast<const CArrayAnnotation *>
(pModel->getObject(CCopasiObjectName("Array=Reduced stoichiometry(ann)")));
mpArrayWidget2->setArrayAnnotation(tmp);
tmp = dynamic_cast<const CArrayAnnotation *>
(pModel->getObject(CCopasiObjectName("Array=Link matrix(ann)")));
mpArrayWidget3->setArrayAnnotation(tmp);
}
void CQMathMatrixWidget::clearArrays()
{
mpArrayWidget1->setArrayAnnotation(NULL);
mpArrayWidget2->setArrayAnnotation(NULL);
mpArrayWidget3->setArrayAnnotation(NULL);
}
//*************************************
bool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action
C_UNUSED(action), const std::string & C_UNUSED(key))
{
clearArrays();
return true;
}
bool CQMathMatrixWidget::leave()
{
return true;
}
bool CQMathMatrixWidget::enterProtected()
{
loadMatrices();
return true;
}
| 27.278846 | 93 | 0.725062 | [
"object",
"model"
] |
55ac241cc164a5d73481954a5ae8a7b88d0d855b | 65,956 | cpp | C++ | CloakEngine/DX12Manager.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakEngine/DX12Manager.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | CloakEngine/DX12Manager.cpp | Bizzarrus/CloakEngine | 0890eaada76b91be89702d2a6ec2dcf9b2901fb9 | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#if CHECK_OS(WINDOWS,10)
#include "Implementation/Rendering/DX12/Manager.h"
#include "Implementation/Rendering/DX12/Allocator.h"
#include "Implementation/Rendering/DX12/ColorBuffer.h"
#include "Implementation/Rendering/DX12/DepthBuffer.h"
#include "Implementation/Rendering/DX12/PipelineState.h"
#include "Implementation/Rendering/DX12/RootSignature.h"
#include "Implementation/Rendering/DX12/StructuredBuffer.h"
#include "Implementation/Rendering/DX12/SwapChain.h"
#include "Implementation/Rendering/DX12/Defines.h"
#include "Implementation/Rendering/DX12/Lib.h"
#include "Implementation/Rendering/DX12/Casting.h"
#include "Implementation/Rendering/DX12/VideoEncoder.h"
#include "Implementation/Rendering/DX12/Query.h"
#include "Implementation/Global/Game.h"
#include "Implementation/Rendering/Context.h"
#include "Implementation/Global/Video.h"
#include "CloakEngine/Global/Game.h"
#include "CloakEngine/Helper/StringConvert.h"
#include <limits>
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
//#define USE_DX_DEBUG
#if (defined(_DEBUG) && defined(USE_DX_DEBUG))
#include <dxgidebug.h>
#pragma comment(lib,"dxguid.lib")
typedef HRESULT(__stdcall *PFN_DXGI_GET_DEBUG_INTERFACE)(const IID&, void**);
#endif
#define CE_MAX(a,b) (((a) > (b)) ? (a) : (b))
#define CE_MIN(a,b) (((a) < (b)) ? (a) : (b))
#define COLOR_ORDER_SET(p,color,L,type) if constexpr(p>0){t[p-1]=ToType<type, expLen, std::is_signed_v<type>>::Call(color.L);}
#define COLOR_ORDER_GET(p,color,L,type) if constexpr(p>0){color->L=FromType<type, expLen, std::is_signed_v<type>>::Call(t[p-1]);} else {color->L=0;}
namespace CloakEngine {
namespace Impl {
namespace Rendering {
namespace DX12 {
namespace Manager_v1 {
constexpr DWORD g_ThreadSyncWait = 125;
constexpr DWORD g_ThreadSyncMaxWait = 500;
constexpr uint32_t CONTEXT_TYPE_COUNT = 2;
constexpr D3D_SHADER_MODEL SUPPORTED_SHADER_MODELS[] = {
D3D_SHADER_MODEL_6_5,
D3D_SHADER_MODEL_6_4,
D3D_SHADER_MODEL_6_3,
D3D_SHADER_MODEL_6_2,
D3D_SHADER_MODEL_6_1,
D3D_SHADER_MODEL_6_0,
D3D_SHADER_MODEL_5_1,
};
constexpr D3D_FEATURE_LEVEL SUPPORTED_FEATURE_LEVELS[] = {
D3D_FEATURE_LEVEL_12_1,
D3D_FEATURE_LEVEL_12_0,
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
};
constexpr D3D_FEATURE_LEVEL MINIMAL_FEATURE_LEVEL = SUPPORTED_FEATURE_LEVELS[ARRAYSIZE(SUPPORTED_FEATURE_LEVELS) - 1];
#if (defined(_DEBUG) && defined(USE_DX_DEBUG))
constexpr UINT FACTORY_FLAGS = DXGI_CREATE_FACTORY_DEBUG;
#else
constexpr UINT FACTORY_FLAGS = 0;
#endif
CLOAK_FORCEINLINE std::string CLOAK_CALL FEATURE_LEVEL_NAME(In D3D_FEATURE_LEVEL lvl)
{
switch (lvl)
{
case D3D_FEATURE_LEVEL_9_1: return "DX 9.1";
case D3D_FEATURE_LEVEL_9_2: return "DX 9.2";
case D3D_FEATURE_LEVEL_9_3: return "DX 9.3";
case D3D_FEATURE_LEVEL_10_0: return "DX 10.0";
case D3D_FEATURE_LEVEL_10_1: return "DX 10.1";
case D3D_FEATURE_LEVEL_11_0: return "DX 11.0";
case D3D_FEATURE_LEVEL_11_1: return "DX 11.1";
case D3D_FEATURE_LEVEL_12_0: return "DX 12.0";
case D3D_FEATURE_LEVEL_12_1: return "DX 12.1";
default: return std::to_string(lvl);
}
}
CLOAK_FORCEINLINE constexpr bool CLOAK_CALL __CheckFeatureLevelArray()
{
for (size_t a = 1; a < ARRAYSIZE(SUPPORTED_FEATURE_LEVELS); a++)
{
if (SUPPORTED_FEATURE_LEVELS[a] >= SUPPORTED_FEATURE_LEVELS[a - 1]) { return false; }
}
return true;
}
static_assert(__CheckFeatureLevelArray(), "List of supported feature levels must be sorted from highest to lowest!");
struct AdapterInfo {
IDXGIAdapter1* Adapter;
IDXGIOutput* Output;
HMONITOR Monitor;
};
#define CREATE_AND_POPULATE(Name, Prev) if(SUCCEEDED(hRet) && device->Prev != nullptr) { device->Name = device->Prev; } else { device->Prev = nullptr; hRet = Lib::D3D12CreateDevice(adapter, MINIMAL_FEATURE_LEVEL, CE_QUERY_ARGS(&device->Name)); if(SUCCEEDED(hRet)){ API::Global::Log::WriteToLog("DirectX 12 API Version: " #Name); }}
inline HRESULT CreateDevice(In IDXGIAdapter* adapter, Out GraphicDevice* device)
{
HRESULT hRet = E_NOINTERFACE;
CREATE_AND_POPULATE(V6, V6); //Highest supported version, so Prev == Name
CREATE_AND_POPULATE(V5, V6);
CREATE_AND_POPULATE(V4, V5);
CREATE_AND_POPULATE(V3, V4);
CREATE_AND_POPULATE(V2, V3);
CREATE_AND_POPULATE(V1, V2);
CREATE_AND_POPULATE(V0, V1);
return hRet;
}
#undef CREATE_AND_POPULATE
CLOAK_CALL Manager::Manager()
{
m_factory = nullptr;
m_device = nullptr;
m_isReady = false;
m_init = false;
m_isReady = false;
m_queues = nullptr;
m_adapterCount = 0;
DEBUG_NAME(Manager);
}
CLOAK_CALL Manager::~Manager()
{
}
HRESULT CLOAK_CALL_THIS Manager::Create(In UINT adapterID)
{
VideoEncoder* ve = new VideoEncoder();
Impl::Global::Video::Initialize(ve);
SAVE_RELEASE(ve);
HRESULT hRet = E_FAIL;
#if (defined(_DEBUG) && defined(USE_DX_DEBUG))
ID3D12Debug* debug = nullptr;
hRet = Lib::D3D12GetDebugInterface(CE_QUERY_ARGS(&debug));
if (CloakDebugCheckOK(hRet, API::Global::Debug::Error::GRAPHIC_ENABLE_DEBUG, false, "Could not load debug layer"))
{
debug->EnableDebugLayer();
}
SAVE_RELEASE(debug);
#endif
if (!IsReady() && m_init.exchange(true) == false)
{
IDXGIFactory5* factory;
hRet = Lib::CreateDXGIFactory2(FACTORY_FLAGS, CE_QUERY_ARGS(&factory));
if (CloakCheckError(hRet, API::Global::Debug::Error::GRAPHIC_INIT_FACTORY, true)) { return hRet; }
m_factory = factory;
API::List<AdapterInfo> adapters;
GraphicDevice device;
AdapterInfo adi;
for (UINT b = 0; factory->EnumAdapters1(b, &adi.Adapter) == S_OK; b++)
{
DXGI_ADAPTER_DESC1 desc;
hRet = adi.Adapter->GetDesc1(&desc);
if (SUCCEEDED(hRet) && (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0)
{
//Check for DX12 support:
hRet = Lib::D3D12CreateDevice(adi.Adapter, MINIMAL_FEATURE_LEVEL, __uuidof(ID3D12Device), nullptr);
if (SUCCEEDED(hRet))
{
std::string adn = std::to_string(b + 1) + ": " + API::Helper::StringConvert::ConvertToU8(desc.Description);
for (UINT c = 0; adi.Adapter->EnumOutputs(c, &adi.Output) == S_OK; c++)
{
DXGI_OUTPUT_DESC od;
adi.Output->GetDesc(&od);
adi.Monitor = od.Monitor;
adapters.push_back(adi);
adi.Adapter->AddRef();
m_adapterNames.push_back(adn + " (Display " + std::to_string(c + 1) + ")");
}
}
}
adi.Adapter->Release();
}
hRet = E_FAIL;
m_monitor = static_cast<HMONITOR>(INVALID_HANDLE_VALUE);
size_t adapID = adapters.size();
if (adapterID < adapters.size())
{
adapID = adapterID;
hRet = CreateDevice(adapters[adapterID].Adapter, &device);
if (SUCCEEDED(hRet)) { goto created_device; }
}
for (size_t b = 0; b < adapters.size(); b++)
{
adapID = b;
if (b != adapterID)
{
hRet = CreateDevice(adapters[b].Adapter, &device);
if (SUCCEEDED(hRet)) { goto created_device; }
}
}
//WARP (sorftware) device:
IDXGIAdapter* warp = nullptr;
hRet = m_factory.load()->EnumWarpAdapter(CE_QUERY_ARGS(&warp));
if (CloakCheckOK(hRet, API::Global::Debug::Error::GRAPHIC_NO_ADAPTER, true))
{
adapID = adapters.size();
hRet = CreateDevice(warp, &device);
if (SUCCEEDED(hRet))
{
warp->Release();
goto created_device;
}
}
warp->Release();
created_device:
if (SUCCEEDED(hRet))
{
if (adapID < adapters.size())
{
API::Global::Log::WriteToLog("GPU: " + m_adapterNames[adapID]);
#ifdef _DEBUG
CloakDebugLog("All aviable gpus:");
for (size_t a = 0; a < m_adapterNames.size(); a++)
{
CloakDebugLog("\t" + std::to_string(a) + ": " + m_adapterNames[a]);
}
#endif
m_monitor = adapters[adapID].Monitor;
IDXGIAdapter3* ad = nullptr;
if (SUCCEEDED(adapters[adapID].Adapter->QueryInterface(CE_QUERY_ARGS(&ad))))
{
//TODO: Query for memory budget and register memory budget change event
//See https://docs.microsoft.com/en-us/windows/desktop/direct3d12/residency
ad->Release();
}
//TODO: Query aviable display modes of adapter adapID
}
else
{
API::Global::Log::WriteToLog("GPU: Windows Advanced Rasterization Platform");
m_monitor = static_cast<HMONITOR>(INVALID_HANDLE_VALUE);
}
}
for (size_t b = 0; b < adapters.size(); b++)
{
adapters[b].Adapter->Release();
adapters[b].Output->Release();
}
if (CloakCheckError(hRet, API::Global::Debug::Error::GRAPHIC_NO_DEVICE, true)) { return hRet; }
m_device = new Device(device);
//Feature Level:
{
D3D12_FEATURE_DATA_FEATURE_LEVELS options;
options.MaxSupportedFeatureLevel = MINIMAL_FEATURE_LEVEL;
options.NumFeatureLevels = ARRAYSIZE(SUPPORTED_FEATURE_LEVELS);
options.pFeatureLevelsRequested = SUPPORTED_FEATURE_LEVELS;
hRet = device.V0->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &options, sizeof(options));
if (CloakCheckError(hRet, API::Global::Debug::Error::GRAPHIC_FEATURE_CHECK, true)) { return hRet; }
m_featureLevel = options.MaxSupportedFeatureLevel;
API::Global::Log::WriteToLog("Feature Level: " + FEATURE_LEVEL_NAME(m_featureLevel));
}
//Hardware Options
{
D3D12_FEATURE_DATA_D3D12_OPTIONS options;
hRet = device.V0->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options));
if (CloakCheckError(hRet, API::Global::Debug::Error::GRAPHIC_FEATURE_CHECK, true)) { return hRet; }
m_hardwareSettings.ResourceBindingTier = Casting::CastBackward(options.ResourceBindingTier);
m_hardwareSettings.TypedUAV = options.TypedUAVLoadAdditionalFormats;
m_hardwareSettings.TiledResourcesSupport = Casting::CastBackward(options.TiledResourcesTier);
m_hardwareSettings.CrossAdapterSupport = Casting::CastBackward(options.CrossNodeSharingTier);
m_hardwareSettings.ConservativeRasterizationSupport = Casting::CastBackward(options.ConservativeRasterizationTier);
m_hardwareSettings.StandardSwizzle64KBSupported = options.StandardSwizzle64KBSupported == TRUE;
m_hardwareSettings.ResourceHeapTier = Casting::CastBackward(options.ResourceHeapTier);
if (m_adapterCount == 1) { m_hardwareSettings.CrossAdapterSupport = API::Rendering::CROSS_ADAPTER_NOT_SUPPORTED; }
API::Global::Log::WriteToLog("Resource Binding Tier: " + std::to_string(m_hardwareSettings.ResourceBindingTier));
API::Global::Log::WriteToLog("Tiled Resources Tier: " + std::to_string(m_hardwareSettings.TiledResourcesSupport));
API::Global::Log::WriteToLog("Typed UAV Formats support: " + std::to_string(m_hardwareSettings.TypedUAV));
API::Global::Log::WriteToLog("Cross Adapter support: " + std::to_string(m_hardwareSettings.CrossAdapterSupport));
API::Global::Log::WriteToLog("Conservative Rasterization support: " + std::to_string(m_hardwareSettings.ConservativeRasterizationSupport));
API::Global::Log::WriteToLog("Standard swizzle 64 kb supported: " + std::to_string(m_hardwareSettings.StandardSwizzle64KBSupported));
API::Global::Log::WriteToLog("Resource Heap Tier: " + std::to_string(m_hardwareSettings.ResourceHeapTier));
}
//Hardware Options 1
{
D3D12_FEATURE_DATA_D3D12_OPTIONS1 options;
HRESULT h = device.V0->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS1, &options, sizeof(options));
m_hardwareSettings.LaneCount = SUCCEEDED(h) ? options.WaveLaneCountMin : 4;
API::Global::Log::WriteToLog("Wave size: " + std::to_string(m_hardwareSettings.LaneCount));
if (m_hardwareSettings.LaneCount < 4) { hRet = E_FAIL; }
}
//Hardware Options 2
{
D3D12_FEATURE_DATA_D3D12_OPTIONS2 options;
HRESULT h = device.V0->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS2, &options, sizeof(options));
if (SUCCEEDED(h))
{
m_hardwareSettings.AllowDepthBoundsTests = options.DepthBoundsTestSupported == TRUE;
}
else
{
m_hardwareSettings.AllowDepthBoundsTests = false;
}
API::Global::Log::WriteToLog("Depth Bounds Tests: " + std::to_string(m_hardwareSettings.AllowDepthBoundsTests));
}
//Hardware Options 3
{
D3D12_FEATURE_DATA_D3D12_OPTIONS3 options;
HRESULT h = device.V0->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &options, sizeof(options));
if (SUCCEEDED(h))
{
m_hardwareSettings.ViewInstanceSupport = Casting::CastBackward(options.ViewInstancingTier);
m_hardwareSettings.CopyContextAllowTimestampQueries = options.CopyQueueTimestampQueriesSupported == TRUE;
}
else
{
m_hardwareSettings.ViewInstanceSupport = API::Rendering::VIEW_INSTANCE_NOT_SUPPORTED;
m_hardwareSettings.CopyContextAllowTimestampQueries = false;
}
API::Global::Log::WriteToLog("View Instancing Tier: " + std::to_string(m_hardwareSettings.ViewInstanceSupport));
API::Global::Log::WriteToLog("Copy Context allow timestamp queries: " + std::to_string(m_hardwareSettings.CopyContextAllowTimestampQueries));
}
//Hardware Options 5
{
D3D12_FEATURE_DATA_D3D12_OPTIONS5 options;
HRESULT h = device.V0->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS5, &options, sizeof(options));
if (SUCCEEDED(h))
{
m_hardwareSettings.Raytracing.Supported = Casting::CastBackward(options.RaytracingTier);
m_hardwareSettings.Raytracing.TiledSRVTier3 = options.SRVOnlyTiledResourceTier3 == TRUE;
}
else
{
m_hardwareSettings.Raytracing.Supported = API::Rendering::RAYTRACING_NOT_SUPPORTED;
m_hardwareSettings.Raytracing.TiledSRVTier3 = false;
}
API::Global::Log::WriteToLog("Raytracing Tier: " + std::to_string(m_hardwareSettings.Raytracing.Supported));
API::Global::Log::WriteToLog("Raytracing Support Tier 3 Tiled SRV: " + std::to_string(m_hardwareSettings.Raytracing.TiledSRVTier3));
}
//Hardware Options 6
{
D3D12_FEATURE_DATA_D3D12_OPTIONS6 options;
HRESULT h = device.V0->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS6, &options, sizeof(options));
if (SUCCEEDED(h))
{
m_hardwareSettings.VariableShadingRate.Supported = Casting::CastBackward(options.VariableShadingRateTier);
m_hardwareSettings.VariableShadingRate.ImageTileSize = options.ShadingRateImageTileSize;
if (options.VariableShadingRateTier != D3D12_VARIABLE_SHADING_RATE_TIER_NOT_SUPPORTED) { m_hardwareSettings.VariableShadingRate.MaxShadingRate = options.AdditionalShadingRatesSupported ? API::Rendering::SHADING_RATE_X4 : API::Rendering::SHADING_RATE_X2; }
else { m_hardwareSettings.VariableShadingRate.MaxShadingRate = API::Rendering::SHADING_RATE_X1; }
}
else
{
m_hardwareSettings.VariableShadingRate.Supported = API::Rendering::VARIABLE_SHADING_RATE_NOT_SUPPORTED;
m_hardwareSettings.VariableShadingRate.MaxShadingRate = API::Rendering::SHADING_RATE_X1;
m_hardwareSettings.VariableShadingRate.ImageTileSize = 0;
}
API::Global::Log::WriteToLog("VSR Tier: " + std::to_string(m_hardwareSettings.VariableShadingRate.Supported));
API::Global::Log::WriteToLog("VSR Image Tile Size: " + std::to_string(m_hardwareSettings.VariableShadingRate.ImageTileSize));
API::Global::Log::WriteToLog("VSR Max Shading Rate: " + std::to_string(m_hardwareSettings.VariableShadingRate.MaxShadingRate));
}
//Shader Model
{
D3D12_FEATURE_DATA_SHADER_MODEL options;
HRESULT h = E_FAIL;
for (size_t a = 0; a < ARRAYSIZE(SUPPORTED_SHADER_MODELS); a++)
{
options.HighestShaderModel = SUPPORTED_SHADER_MODELS[a];
h = device.V0->CheckFeatureSupport(D3D12_FEATURE_SHADER_MODEL, &options, sizeof(options));
if (SUCCEEDED(h)) { break; }
}
if (SUCCEEDED(h))
{
switch (options.HighestShaderModel)
{
case D3D_SHADER_MODEL_6_5: m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_6_5; API::Global::Log::WriteToLog("Shader Model: DX 6.5"); break;
case D3D_SHADER_MODEL_6_4: m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_6_4; API::Global::Log::WriteToLog("Shader Model: DX 6.4"); break;
case D3D_SHADER_MODEL_6_3: m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_6_3; API::Global::Log::WriteToLog("Shader Model: DX 6.3"); break;
case D3D_SHADER_MODEL_6_2: m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_6_2; API::Global::Log::WriteToLog("Shader Model: DX 6.2"); break;
case D3D_SHADER_MODEL_6_1: m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_6_1; API::Global::Log::WriteToLog("Shader Model: DX 6.1"); break;
case D3D_SHADER_MODEL_6_0: m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_6_0; API::Global::Log::WriteToLog("Shader Model: DX 6.0"); break;
case D3D_SHADER_MODEL_5_1:
default: m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_5_1; API::Global::Log::WriteToLog("Shader Model: DX 5.1"); break;
}
}
else
{
m_hardwareSettings.ShaderModel = API::Rendering::MODEL_HLSL_5_1;
API::Global::Log::WriteToLog("Shader Model: DX 5.1");
}
}
//Root Signature Version
{
D3D12_FEATURE_DATA_ROOT_SIGNATURE options;
options.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_1;
HRESULT h = device.V0->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &options, sizeof(options));
if (SUCCEEDED(h) && Lib::D3D12SerializeVersionedRootSignature != nullptr) { m_hardwareSettings.RootVersion = Casting::CastBackward(options.HighestVersion); }
else { m_hardwareSettings.RootVersion = API::Rendering::ROOT_SIGNATURE_VERSION_1_0; }
API::Global::Log::WriteToLog("Root Signature Version: " + std::to_string(m_hardwareSettings.RootVersion));
}
//Allow Tearing
{
BOOL tearing = FALSE;
HRESULT h = factory->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &tearing, sizeof(tearing));
m_hardwareSettings.AllowTearing = SUCCEEDED(h) && tearing == TRUE;
API::Global::Log::WriteToLog("Allow Tearing: " + std::to_string(m_hardwareSettings.AllowTearing));
}
//Prepare multi adapter system:
m_adapterCount = device.V0->GetNodeCount();
API::Global::Log::WriteToLog("Adapter Count: " + std::to_string(m_adapterCount));
if (m_hardwareSettings.CrossAdapterSupport == API::Rendering::CROSS_ADAPTER_NOT_SUPPORTED) { m_adapterCount = 1; }
m_queues = reinterpret_cast<Queue*>(API::Global::Memory::MemoryHeap::Allocate(sizeof(Queue)*m_adapterCount));
for (size_t a = 0; a < m_adapterCount; a++)
{
::new(&m_queues[a])Queue(m_device, m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << a), a + 1, this, m_hardwareSettings.CrossAdapterSupport);
}
m_isReady = true;
}
return hRet;
}
void CLOAK_CALL_THIS Manager::Update()
{
for (size_t a = 0; a < m_adapterCount; a++) { m_queues[a].Update(); }
}
HMONITOR CLOAK_CALL_THIS Manager::GetMonitor() const { return m_monitor; }
void CLOAK_CALL_THIS Manager::ShutdownAdapters()
{
if (m_init.exchange(false) == true)
{
m_isReady = false;
for (size_t a = 0; a < m_adapterCount; a++)
{
m_queues[a].Shutdown();
}
}
}
void CLOAK_CALL_THIS Manager::ShutdownMemory()
{
for (size_t a = 0; a < m_adapterCount; a++) { m_queues[a].~Queue(); }
API::Global::Memory::MemoryHeap::Free(m_queues);
}
void CLOAK_CALL_THIS Manager::ShutdownDevice()
{
SAVE_RELEASE(m_device);
IDXGIFactory3* factory = m_factory.exchange(nullptr);
RELEASE(factory);
#if (defined(_DEBUG) && defined(USE_DX_DEBUG))
HMODULE hMod = GetModuleHandle(L"Dxgidebug.dll");
if (hMod == NULL) { CloakDebugLog("No DXGIDebug.dll aviable!"); }
else
{
PFN_DXGI_GET_DEBUG_INTERFACE DXGIGetDebugInterface = (PFN_DXGI_GET_DEBUG_INTERFACE)GetProcAddress(hMod, "DXGIGetDebugInterface");
IDXGIDebug* debug = nullptr;
HRESULT hRet = DXGIGetDebugInterface(CE_QUERY_ARGS(&debug));
if (FAILED(hRet)) { CloakDebugLog("Could not create dxgi debug interface!"); }
else
{
debug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL);
}
SAVE_RELEASE(debug);
}
#endif
}
void CLOAK_CALL_THIS Manager::InitializeBuffer(In API::Rendering::IResource* dst, In size_t size, In_reads_bytes(size) const void* data, In_opt bool wait)
{
ICopyContext* graphic = nullptr;
IResource* rsc = nullptr;
if (SUCCEEDED(dst->QueryInterface(CE_QUERY_ARGS(&rsc))))
{
m_queues[rsc->GetNodeID() - 1].CreateContext(CE_QUERY_ARGS(&graphic), QUEUE_TYPE_COPY);
#ifdef _DEBUG
graphic->SetSourceFile(std::string(__FILE__) + " @ " + std::to_string(__LINE__));
#endif
graphic->WriteBuffer(dst, 0, data, size);
graphic->CloseAndExecute(wait);
SAVE_RELEASE(graphic);
}
SAVE_RELEASE(rsc);
}
void CLOAK_CALL_THIS Manager::InitializeTexture(In API::Rendering::IResource* dst, In UINT numSubresources, In_reads(numSubresources) API::Rendering::SUBRESOURCE_DATA data[], In_opt bool wait) const
{
UpdateTextureSubresource(dst, 0, numSubresources, data, wait);
}
void CLOAK_CALL_THIS Manager::UpdateTextureSubresource(In API::Rendering::IResource* dst, In UINT firstSubresource, In UINT numSubresources, In_reads(numSubresources) API::Rendering::SUBRESOURCE_DATA data[], In_opt bool wait) const
{
ICopyContext* graphic = nullptr;
IResource* rsc = nullptr;
if (SUCCEEDED(dst->QueryInterface(CE_QUERY_ARGS(&rsc))))
{
m_queues[rsc->GetNodeID() - 1].CreateContext(CE_QUERY_ARGS(&graphic), QUEUE_TYPE_COPY);
#ifdef _DEBUG
graphic->SetSourceFile(std::string(__FILE__) + " @ " + std::to_string(__LINE__));
#endif
graphic->WriteBuffer(dst, firstSubresource, numSubresources, data);
graphic->CloseAndExecute(wait);
SAVE_RELEASE(graphic);
}
SAVE_RELEASE(rsc);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) API::Rendering::IResource* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::VIEW_TYPE Type, In_opt API::Rendering::DescriptorPageType page)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, Type, page);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) API::Rendering::IPixelBuffer* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::VIEW_TYPE Type, In_opt API::Rendering::DescriptorPageType page)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, Type, page);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) API::Rendering::IColorBuffer* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::VIEW_TYPE Type, In_opt API::Rendering::DescriptorPageType page)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, Type, page);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) API::Rendering::IDepthBuffer* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::VIEW_TYPE Type)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, Type);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) API::Rendering::IGraphicBuffer* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::DescriptorPageType page)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, API::Rendering::VIEW_TYPE::CBV, page);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) API::Rendering::IStructuredBuffer* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::DescriptorPageType page)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, API::Rendering::VIEW_TYPE::CBV, page);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) API::Rendering::IConstantBuffer* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::DescriptorPageType page)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, API::Rendering::VIEW_TYPE::CBV, page);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
void CLOAK_CALL_THIS Manager::GenerateViews(In_reads(bufferSize) IColorBuffer* buffer[], In_opt size_t bufferSize, In_opt API::Rendering::VIEW_TYPE Type, In_opt API::Rendering::DescriptorPageType page)
{
Resource** buf = NewArray(Resource*, bufferSize);
size_t ns = 0;
for (size_t a = 0; a < bufferSize; a++)
{
buf[a] = nullptr;
if (SUCCEEDED(buffer[a]->QueryInterface(CE_QUERY_ARGS(&buf[ns])))) { ns++; }
}
Resource::GenerateViews(buf, ns, Type, page);
for (size_t a = 0; a < ns; a++) { buf[a]->Release(); }
DeleteArray(buf);
}
#ifdef _DEBUG
void CLOAK_CALL_THIS Manager::BeginContextFile(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID, In REFIID riid, Outptr void** ptr, In const std::string& file) const
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(type, nodeID, &qtype, &node);
IContext* c = nullptr;
m_queues[node].CreateContext(CE_QUERY_ARGS(&c), qtype);
c->SetSourceFile(file);
c->QueryInterface(riid, ptr);
c->Release();
}
#else
void CLOAK_CALL_THIS Manager::BeginContext(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID, In REFIID riid, Outptr void** ptr) const
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(type, nodeID, &qtype, &node);
m_queues[node].CreateContext(riid, ptr, qtype);
}
#endif
uint64_t CLOAK_CALL_THIS Manager::FlushExecutions(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID, In_opt bool wait)
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(type, nodeID, &qtype, &node);
return m_queues[node].FlushExecutions(nullptr, wait, qtype);
}
API::Rendering::SHADER_MODEL CLOAK_CALL_THIS Manager::GetShaderModel() const { return m_hardwareSettings.ShaderModel; }
bool CLOAK_CALL_THIS Manager::IsReady() const { return m_isReady; }
uint64_t CLOAK_CALL_THIS Manager::IncrementFence(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID)
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(type, nodeID, &qtype, &node);
return m_queues[node].IncrementFence(qtype);
}
bool CLOAK_CALL_THIS Manager::IsFenceComplete(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID, In uint64_t val)
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(type, nodeID, &qtype, &node);
return m_queues[node].IsFenceComplete(qtype, val);
}
bool CLOAK_CALL_THIS Manager::WaitForFence(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID, In uint64_t val)
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(type, nodeID, &qtype, &node);
return m_queues[node].WaitForFence(qtype, val);
}
void CLOAK_CALL_THIS Manager::WaitForGPU()
{
uint64_t* vals = reinterpret_cast<uint64_t*>(alloca(sizeof(uint64_t) * m_adapterCount * 2));
for (size_t a = 0; a < m_adapterCount; a++)
{
vals[(a << 1) + 0] = m_queues[a].IncrementFence(Impl::Rendering::QUEUE_TYPE_COPY);
vals[(a << 1) + 1] = m_queues[a].IncrementFence(Impl::Rendering::QUEUE_TYPE_DIRECT);
}
for (size_t a = 0; a < m_adapterCount; a++)
{
m_queues[a].WaitForFence(Impl::Rendering::QUEUE_TYPE_COPY, vals[(a << 1) + 0]);
m_queues[a].WaitForFence(Impl::Rendering::QUEUE_TYPE_DIRECT, vals[(a << 1) + 1]);
}
}
bool CLOAK_CALL_THIS Manager::SupportMultiThreadedRendering() const { return true; }
bool CLOAK_CALL_THIS Manager::GetFactory(In REFIID riid, Outptr void** ptr) const
{
if (IsReady())
{
return SUCCEEDED(m_factory.load()->QueryInterface(riid, ptr));
}
return false;
}
bool CLOAK_CALL_THIS Manager::UpdateFactory()
{
if (IsReady())
{
IDXGIFactory5* factory = m_factory.load();
if (factory->IsCurrent() == FALSE)
{
IDXGIFactory5* nf = nullptr;
HRESULT hRet = Lib::CreateDXGIFactory2(FACTORY_FLAGS, CE_QUERY_ARGS(&nf));
if (SUCCEEDED(hRet))
{
m_factory = nf;
SAVE_RELEASE(factory);
return true;
}
}
}
return false;
}
Ret_maybenull IDevice* CLOAK_CALL_THIS Manager::GetDevice() const
{
if (m_device != nullptr && IsReady())
{
m_device->AddRef();
return m_device;
}
return nullptr;
}
API::Rendering::IPipelineState* CLOAK_CALL_THIS Manager::CreatePipelineState() const
{
return PipelineState::Create(this);
}
API::Rendering::IQuery* CLOAK_CALL_THIS Manager::CreateQuery(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In API::Rendering::QUERY_TYPE type) const
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(contextType, nodeID, &qtype, &node);
return new Query(m_queues[node].GetQueryPool(), qtype, type);
}
IRootSignature* CLOAK_CALL_THIS Manager::CreateRootSignature() const
{
return new RootSignature();
}
IColorBuffer* CLOAK_CALL_THIS Manager::CreateColorBuffer(In ISwapChain* base, In uint32_t textureNum) const
{
return ColorBuffer::CreateFromSwapChain(base, textureNum);
}
IColorBuffer* CLOAK_CALL_THIS Manager::CreateColorBuffer(In const API::Rendering::TEXTURE_DESC& desc, In size_t nodeID, In UINT nodeMask) const
{
return ColorBuffer::Create(desc, nodeID, nodeMask);
}
IDepthBuffer* CLOAK_CALL_THIS Manager::CreateDepthBuffer(In const API::Rendering::DEPTH_DESC& desc, In size_t nodeID, In UINT nodeMask) const
{
return DepthBuffer::Create(desc, nodeID, nodeMask);
}
CE::RefPointer<ISwapChain> CLOAK_CALL_THIS Manager::CreateSwapChain(In const API::Global::Graphic::Settings& gset, Out_opt HRESULT* hRet)
{
CE::RefPointer<ISwapChain> sc = CE::RefPointer<ISwapChain>::Construct<SwapChain>(this, m_hardwareSettings);
HRESULT hr = sc->Recreate(gset);
if (hRet != nullptr) { *hRet = hr; }
return sc;
}
bool CLOAK_CALL_THIS Manager::EnumerateAdapter(In size_t id, Out std::string* name) const
{
if (name != nullptr && id < m_adapterNames.size())
{
*name = m_adapterNames[id];
return true;
}
return false;
}
size_t CLOAK_CALL_THIS Manager::GetNodeCount() const { return m_adapterCount; }
const API::Rendering::Hardware& CLOAK_CALL_THIS Manager::GetHardwareSetting() const { return m_hardwareSettings; }
namespace APIManager {
CLOAK_INTERFACE_BASIC IColorOrder{
public:
virtual size_t CLOAK_CALL_THIS GetByteSize() const = 0;
virtual void CLOAK_CALL_THIS CopyColor(In const API::Helper::Color::RGBA& color, Out uint8_t* bytes) = 0;
virtual void CLOAK_CALL_THIS CopyBytes(In const uint8_t* bytes, Out API::Helper::Color::RGBA* color) = 0;
virtual void CLOAK_CALL_THIS Delete() = 0;
};
template<typename type, size_t expLen, bool sign> struct ToType {
static type CLOAK_CALL Call(In float f)
{
int64_t e;
int64_t s;
const int64_t maxEXP = (1ULL << expLen) - 1;
if (f == 0)
{
e = 0;
s = 0;
}
else if (f != f)//NaN
{
e = maxEXP;
s = (1 << ((sizeof(type) << 3) - (expLen + 1))) - 1;
}
else if (std::abs(f) == std::numeric_limits<float>::infinity())//Infinity
{
e = maxEXP;
s = 0;
}
else
{
int ex;
float m = std::frexp(std::abs(f), &ex) * 2;
e = (static_cast<int64_t>(ex) - 1) + ((1i64 << (expLen - 1)) - 1);
if (e <= 0)//Denormalized
{
m /= (1ULL << (-e));
e = 0;
s = static_cast<int64_t>((1i64 << ((sizeof(type) << 3) - (expLen + 1))) * static_cast<double>(m));
}
else if (e >= maxEXP)//Overflow
{
e = maxEXP;
s = 0;
}
else
{
s = static_cast<int64_t>((1i64 << ((sizeof(type) << 3) - (expLen + 1))) * static_cast<double>(m - 1));
}
}
const type sr = static_cast<type>((std::copysign(1.0f, f) < 0) ? (1ULL << ((sizeof(type) << 3) - 1)) : 0);
const type er = static_cast<type>(e << ((sizeof(type) << 3) - (expLen + 1)));
return static_cast<type>(sr | er | s);
}
};
template<typename type, bool sign> struct ToType<type, 0, sign> {
static type CLOAK_CALL Call(In float col)
{
if (col != col) { return 0; }
else if (col == std::numeric_limits<float>::infinity()) { return std::numeric_limits<type>::max(); }
return static_cast<type>(CE_MIN(1, CE_MAX(0, col))*std::numeric_limits<type>::max());
}
};
template<typename type> struct ToType<type, 0, true> {
static type CLOAK_CALL Call(In float col)
{
if (col != col) { return 0; }
else if (col == std::numeric_limits<float>::infinity()) { return std::numeric_limits<type>::max(); }
return static_cast<type>(CE_MIN(1, CE_MAX(-1, col))*std::numeric_limits<type>::max());
}
};
template<> struct ToType<float, 8, true> {
static float CLOAK_CALL Call(In float col) { return col; }
};
template<typename type, size_t expLen, bool sign> struct FromType {
static float CLOAK_CALL Call(In type h)
{
const bool s = (h & (1ULL << ((sizeof(type) << 3) - 1))) != 0;
const uint64_t e = (h >> ((sizeof(type) << 3) - (expLen + 1))) & ((1ULL << expLen) - 1);
const uint64_t m = h & ((1ULL << ((sizeof(type) << 3) - (expLen + 1))) - 1);
if (e == 0 && m == 0) { return 0; }
if (e == (1ULL << expLen) - 1)
{
if (m == 0) { return std::numeric_limits<float>::infinity(); }
return std::numeric_limits<float>::quiet_NaN();
}
const float x = (static_cast<float>(m) / (1ULL << ((sizeof(type) << 3) - (expLen + 1)))) + (e == 0 ? 0 : 1);
const int shift = static_cast<int>(e - ((1ULL << (expLen - 1)) - 1));
return std::copysign(std::ldexpf(x, shift), s ? -1.0f : 1.0f);
}
};
template<typename type, bool sign> struct FromType<type, 0, sign> {
static float CLOAK_CALL Call(In type col)
{
const float t = static_cast<float>(static_cast<long double>(col) / std::numeric_limits<type>::max());
return CE_MIN(1, CE_MAX(0, t));
}
};
template<typename type> struct FromType<type, 0, true> {
static float CLOAK_CALL Call(In type col)
{
const float t = static_cast<float>(static_cast<long double>(col) / std::numeric_limits<type>::max());
return CE_MIN(1, CE_MAX(-1, t));
}
};
template<> struct FromType<float, 8, true> {
static float CLOAK_CALL Call(In float col) { return col; }
};
template<typename type, size_t inR, size_t inG, size_t inB, size_t inA, size_t expLen> class ColorOrder : public IColorOrder {
public:
static constexpr size_t ByteSize = (inR > 0 ? sizeof(type) : 0) + (inG > 0 ? sizeof(type) : 0) + (inB > 0 ? sizeof(type) : 0) + (inA > 0 ? sizeof(type) : 0);
size_t CLOAK_CALL_THIS GetByteSize() const override { return ByteSize; }
void CLOAK_CALL_THIS CopyColor(In const API::Helper::Color::RGBA& color, Out uint8_t* bytes) override
{
type* t = reinterpret_cast<type*>(bytes);
COLOR_ORDER_SET(inR, color, R, type);
COLOR_ORDER_SET(inG, color, G, type);
COLOR_ORDER_SET(inB, color, B, type);
COLOR_ORDER_SET(inA, color, A, type);
}
void CLOAK_CALL_THIS CopyBytes(In const uint8_t* bytes, Out API::Helper::Color::RGBA* color) override
{
const type* t = reinterpret_cast<const type*>(bytes);
COLOR_ORDER_GET(inR, color, R, type);
COLOR_ORDER_GET(inG, color, G, type);
COLOR_ORDER_GET(inB, color, B, type);
COLOR_ORDER_GET(inA, color, A, type);
}
void* CLOAK_CALL operator new(In size_t s) { return API::Global::Memory::MemoryPool::Allocate(s); }
void CLOAK_CALL operator delete(In void* ptr) { return API::Global::Memory::MemoryPool::Free(ptr); }
void CLOAK_CALL_THIS Delete() { delete this; }
};
inline IColorOrder* GetColorOrderByFormat(In API::Rendering::Format format)
{
switch (format)
{
case CloakEngine::API::Rendering::Format::R32G32B32A32_FLOAT:
return new ColorOrder<float, 1, 2, 3, 4, 8>();
case CloakEngine::API::Rendering::Format::R32G32B32A32_UINT:
return new ColorOrder<uint32_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R32G32B32A32_SINT:
return new ColorOrder<int32_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R32G32B32_FLOAT:
return new ColorOrder<float, 1, 2, 3, 0, 8>();
case CloakEngine::API::Rendering::Format::R32G32B32_UINT:
return new ColorOrder<uint32_t, 1, 2, 3, 0, 0>();
case CloakEngine::API::Rendering::Format::R32G32B32_SINT:
return new ColorOrder<int32_t, 1, 2, 3, 0, 0>();
case CloakEngine::API::Rendering::Format::R16G16B16A16_UNORM:
return new ColorOrder<uint16_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R16G16B16A16_UINT:
return new ColorOrder<uint16_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R16G16B16A16_SNORM:
return new ColorOrder<int16_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R16G16B16A16_SINT:
return new ColorOrder<int16_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R16G16B16A16_FLOAT:
return new ColorOrder<uint16_t, 1, 2, 3, 4, 5>();
case CloakEngine::API::Rendering::Format::R32G32_FLOAT:
return new ColorOrder<float, 1, 2, 0, 0, 8>();
case CloakEngine::API::Rendering::Format::R32G32_UINT:
return new ColorOrder<uint32_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R32G32_SINT:
return new ColorOrder<int32_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8G8B8A8_UNORM:
return new ColorOrder<uint8_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R8G8B8A8_UNORM_SRGB:
return new ColorOrder<uint8_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R8G8B8A8_UINT:
return new ColorOrder<uint8_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R8G8B8A8_SNORM:
return new ColorOrder<int8_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R8G8B8A8_SINT:
return new ColorOrder<int8_t, 1, 2, 3, 4, 0>();
case CloakEngine::API::Rendering::Format::R16G16_UNORM:
return new ColorOrder<uint16_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16G16_UINT:
return new ColorOrder<uint16_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16G16_SNORM:
return new ColorOrder<int16_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16G16_SINT:
return new ColorOrder<int16_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16G16_FLOAT:
return new ColorOrder<uint16_t, 1, 2, 0, 0, 5>();
case CloakEngine::API::Rendering::Format::R32_FLOAT:
return new ColorOrder<float, 1, 0, 0, 0, 8>();
case CloakEngine::API::Rendering::Format::R32_UINT:
return new ColorOrder<uint32_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R32_SINT:
return new ColorOrder<int32_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8G8_UNORM:
return new ColorOrder<uint8_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8G8_UINT:
return new ColorOrder<uint8_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8G8_SNORM:
return new ColorOrder<int8_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8G8_SINT:
return new ColorOrder<int8_t, 1, 2, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16_UNORM:
return new ColorOrder<uint16_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16_UINT:
return new ColorOrder<uint16_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16_SNORM:
return new ColorOrder<int16_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16_SINT:
return new ColorOrder<int16_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R16_FLOAT:
return new ColorOrder<uint16_t, 1, 0, 0, 0, 5>();
case CloakEngine::API::Rendering::Format::R8_UNORM:
return new ColorOrder<uint8_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8_UINT:
return new ColorOrder<uint8_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8_SNORM:
return new ColorOrder<int8_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::R8_SINT:
return new ColorOrder<int8_t, 1, 0, 0, 0, 0>();
case CloakEngine::API::Rendering::Format::A8_UNORM:
return new ColorOrder<uint8_t, 0, 0, 0, 1, 0>();
case CloakEngine::API::Rendering::Format::B8G8R8A8_UNORM:
return new ColorOrder<uint8_t, 3, 2, 1, 4, 0>();
case CloakEngine::API::Rendering::Format::B8G8R8X8_UNORM:
return new ColorOrder<uint8_t, 3, 2, 1, 4, 0>();
case CloakEngine::API::Rendering::Format::B8G8R8A8_UNORM_SRGB:
return new ColorOrder<uint8_t, 3, 2, 1, 4, 0>();
case CloakEngine::API::Rendering::Format::B8G8R8X8_UNORM_SRGB:
return new ColorOrder<uint8_t, 3, 2, 1, 4, 0>();
default:
break;
}
return nullptr;
}
inline bool CLOAK_CALL NextMipMap(Inout uint32_t* W, Inout uint32_t* H)
{
if (*W == 1 && *H == 1) { return false; }
if (*W > 1) { *W >>= 1; }
if (*H > 1) { *H >>= 1; }
return true;
}
inline void CLOAK_CALL CopyDataToSRD(Inout API::Rendering::SUBRESOURCE_DATA* srd, In uint32_t W, In uint32_t H, In API::Rendering::Format format, In const API::Helper::Color::RGBA* data)
{
IColorOrder* ord = GetColorOrderByFormat(format);
if (CloakCheckOK(ord != nullptr, API::Global::Debug::Error::GRAPHIC_FORMAT_UNSUPPORTED, true))
{
const size_t bys = ord->GetByteSize();
srd->RowPitch = W*bys;
srd->SlicePitch = H*srd->RowPitch;
uint8_t* bytes = NewArray(uint8_t, srd->SlicePitch);
srd->pData = bytes;
size_t byp = 0;
for (uint32_t y = 0; y < H; y++)
{
for (uint32_t x = 0; x < W; x++, byp += bys)
{
const size_t p = (static_cast<size_t>(y)*W) + x;
ord->CopyColor(data[p], &bytes[byp]);
}
}
}
ord->Delete();
}
}
API::Rendering::IColorBuffer* CLOAK_CALL_THIS Manager::CreateColorBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In const API::Rendering::TEXTURE_DESC& desc, In const API::Helper::Color::RGBA* const* colorData) const
{
IColorBuffer* res = nullptr;
API::Rendering::SUBRESOURCE_DATA* srd = nullptr;
size_t srdSize = 0;
uint32_t usedSrdSize = 0;
uint32_t W = desc.Width;
uint32_t H = desc.Height;
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
switch (desc.Type)
{
case API::Rendering::TEXTURE_TYPE::TEXTURE:
{
srdSize = desc.Texture.MipMaps;
srd = NewArray(API::Rendering::SUBRESOURCE_DATA, srdSize);
uint32_t lastMipMap = 0;
for (size_t a = 0; a < desc.Texture.MipMaps; a++)
{
APIManager::CopyDataToSRD(&(srd[a]), W, H, desc.Format, colorData[a]);
lastMipMap = static_cast<uint32_t>(a);
if (APIManager::NextMipMap(&W, &H) == false) { break; }
}
usedSrdSize = lastMipMap + 1;
res = CreateColorBuffer(desc, nid, nodeMask);
break;
}
case API::Rendering::TEXTURE_TYPE::TEXTURE_ARRAY:
{
srdSize = desc.TextureArray.Images*desc.TextureArray.MipMaps;
srd = NewArray(API::Rendering::SUBRESOURCE_DATA, srdSize);
uint32_t lastMip = desc.TextureArray.MipMaps - 1;
for (size_t a = 0; a < desc.TextureArray.Images; a++)
{
uint32_t iW = W;
uint32_t iH = H;
uint32_t lmip = 0;
for (uint32_t b = 0; b < lastMip + 1; b++)
{
lmip = b;
if (APIManager::NextMipMap(&iW, &iH) == false) { break; }
}
lastMip = CE_MIN(lastMip, lmip);
}
usedSrdSize = desc.TextureArray.Images*(lastMip + 1);
for (size_t a = 0; a < desc.TextureArray.Images; a++)
{
uint32_t iW = W;
uint32_t iH = H;
for (size_t b = 0; b < lastMip + 1; b++)
{
size_t pd = b + (a*desc.TextureArray.MipMaps);
size_t pi = b + (a*(lastMip + 1));
APIManager::CopyDataToSRD(&srd[pi], iW, iH, desc.Format, colorData[pd]);
APIManager::NextMipMap(&iW, &iH);
}
}
res = CreateColorBuffer(desc, nid, nodeMask);
break;
}
case API::Rendering::TEXTURE_TYPE::TEXTURE_CUBE:
{
srdSize = 6 * desc.TextureCube.MipMaps;
uint32_t lastMip = desc.TextureCube.MipMaps - 1;
for (size_t a = 0; a < 6; a++)
{
uint32_t iW = W;
uint32_t iH = H;
uint32_t lmip = 0;
for (uint32_t b = 0; b < lastMip + 1; b++)
{
lmip = b;
if (APIManager::NextMipMap(&iW, &iH) == false) { break; }
}
lastMip = CE_MIN(lastMip, lmip);
}
usedSrdSize = 6 * (lastMip + 1);
srd = NewArray(API::Rendering::SUBRESOURCE_DATA, srdSize);
for (size_t a = 0; a < srdSize; a++)
{
APIManager::CopyDataToSRD(&srd[a], W, H, desc.Format, colorData[a]);
}
res = CreateColorBuffer(desc, nid, nodeMask);
break;
}
default:
break;
}
InitializeTexture(res, static_cast<UINT>(usedSrdSize), srd, true);
for (size_t a = 0; a < srdSize; a++) { DeleteArray(reinterpret_cast<const uint8_t*>(srd[a].pData)); }
DeleteArray(srd);
return res;
}
API::Rendering::IColorBuffer* CLOAK_CALL_THIS Manager::CreateColorBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In const API::Rendering::TEXTURE_DESC& desc, In API::Helper::Color::RGBA** colorData) const
{
IColorBuffer* res = nullptr;
API::Rendering::SUBRESOURCE_DATA* srd = nullptr;
size_t srdSize = 0;
uint32_t usedSrdSize = 0;
uint32_t W = desc.Width;
uint32_t H = desc.Height;
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
switch (desc.Type)
{
case API::Rendering::TEXTURE_TYPE::TEXTURE:
{
srdSize = desc.Texture.MipMaps;
srd = NewArray(API::Rendering::SUBRESOURCE_DATA, srdSize);
uint32_t lastMipMap = 0;
for (size_t a = 0; a < desc.Texture.MipMaps; a++)
{
APIManager::CopyDataToSRD(&(srd[a]), W, H, desc.Format, colorData[a]);
lastMipMap = static_cast<uint32_t>(a);
if (APIManager::NextMipMap(&W, &H) == false) { break; }
}
usedSrdSize = lastMipMap + 1;
res = CreateColorBuffer(desc, nid, nodeMask);
break;
}
case API::Rendering::TEXTURE_TYPE::TEXTURE_ARRAY:
{
srdSize = desc.TextureArray.Images*desc.TextureArray.MipMaps;
srd = NewArray(API::Rendering::SUBRESOURCE_DATA, srdSize);
uint32_t lastMip = desc.TextureArray.MipMaps - 1;
for (size_t a = 0; a < desc.TextureArray.Images; a++)
{
uint32_t iW = W;
uint32_t iH = H;
uint32_t lmip = 0;
for (uint32_t b = 0; b < lastMip + 1; b++)
{
lmip = b;
if (APIManager::NextMipMap(&iW, &iH) == false) { break; }
}
lastMip = CE_MIN(lastMip, lmip);
}
usedSrdSize = desc.TextureArray.Images*(lastMip + 1);
for (size_t a = 0; a < desc.TextureArray.Images; a++)
{
uint32_t iW = W;
uint32_t iH = H;
for (size_t b = 0; b < lastMip + 1; b++)
{
size_t pd = b + (a*desc.TextureArray.MipMaps);
size_t pi = b + (a*(lastMip + 1));
APIManager::CopyDataToSRD(&srd[pi], iW, iH, desc.Format, colorData[pd]);
APIManager::NextMipMap(&iW, &iH);
}
}
res = CreateColorBuffer(desc, nid, nodeMask);
break;
}
case API::Rendering::TEXTURE_TYPE::TEXTURE_CUBE:
{
srdSize = 6 * desc.TextureCube.MipMaps;
uint32_t lastMip = desc.TextureCube.MipMaps - 1;
for (size_t a = 0; a < 6; a++)
{
uint32_t iW = W;
uint32_t iH = H;
uint32_t lmip = 0;
for (uint32_t b = 0; b < lastMip + 1; b++)
{
lmip = b;
if (APIManager::NextMipMap(&iW, &iH) == false) { break; }
}
lastMip = CE_MIN(lastMip, lmip);
}
usedSrdSize = 6 * (lastMip + 1);
srd = NewArray(API::Rendering::SUBRESOURCE_DATA, usedSrdSize);
for (size_t a = 0; a < 6; a++)
{
uint32_t iW = W;
uint32_t iH = H;
for (uint32_t b = 0; b <= lastMip; b++)
{
const size_t p = (a*(lastMip + 1)) + b;
CLOAK_ASSUME(p < usedSrdSize);
APIManager::CopyDataToSRD(&srd[p], iW, iH, desc.Format, colorData[p]);
const bool r = APIManager::NextMipMap(&iW, &iH);
CLOAK_ASSUME(r == true || b == lastMip);
}
}
res = CreateColorBuffer(desc, nid, nodeMask);
break;
}
default:
break;
}
InitializeTexture(res, static_cast<UINT>(usedSrdSize), srd, true);
for (size_t a = 0; a < srdSize; a++) { DeleteArray(reinterpret_cast<const uint8_t*>(srd[a].pData)); }
DeleteArray(srd);
return res;
}
API::Rendering::IColorBuffer* CLOAK_CALL_THIS Manager::CreateColorBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In const API::Rendering::TEXTURE_DESC& desc) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return CreateColorBuffer(desc, nid, nodeMask);
}
API::Rendering::IDepthBuffer* CLOAK_CALL_THIS Manager::CreateDepthBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In const API::Rendering::DEPTH_DESC& desc) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return CreateDepthBuffer(desc, nid, nodeMask);
}
API::Rendering::IVertexBuffer* CLOAK_CALL_THIS Manager::CreateVertexBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In UINT vertexCount, In UINT vertexSize, In_reads(vertexCount*vertexSize) const void* data) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return VertexBuffer::Create(nodeMask, nid, vertexCount, vertexSize, data);
}
API::Rendering::IIndexBuffer* CLOAK_CALL_THIS Manager::CreateIndexBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In UINT size, In_reads(size) const uint16_t* data) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return IndexBuffer::Create(nodeMask, nid, size, false, data);
}
API::Rendering::IIndexBuffer* CLOAK_CALL_THIS Manager::CreateIndexBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In UINT size, In_reads(size) const uint32_t* data) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return IndexBuffer::Create(nodeMask, nid, size, true, data);
}
API::Rendering::IConstantBuffer* CLOAK_CALL_THIS Manager::CreateConstantBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In UINT elementSize, In_reads_opt(elementSize) const void* data) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return ConstantBuffer::Create(nodeMask, nid, elementSize, data);
}
API::Rendering::IStructuredBuffer* CLOAK_CALL_THIS Manager::CreateStructuredBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In UINT elementCount, In UINT elementSize, In_reads(elementSize) const void* data, In_opt bool counterBuffer) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return StructuredBuffer::Create(nodeMask, nid, counterBuffer, elementCount, elementSize, data);
}
API::Rendering::IStructuredBuffer* CLOAK_CALL_THIS Manager::CreateStructuredBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In UINT elementCount, In UINT elementSize, In_opt bool counterBuffer, In_reads_opt(elementSize) const void* data) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return StructuredBuffer::Create(nodeMask, nid, counterBuffer, elementCount, elementSize, data);
}
API::Rendering::IByteAddressBuffer* CLOAK_CALL_THIS Manager::CreateByteAddressBuffer(In API::Rendering::CONTEXT_TYPE contextType, In uint32_t nodeID, In_opt UINT count) const
{
const size_t nid = GetNodeID(contextType, nodeID);
const UINT nodeMask = m_adapterCount == 1 ? 0 : static_cast<UINT>(1 << nid);
return ByteAddressBuffer::Create(nodeMask, nid, count);
}
size_t CLOAK_CALL_THIS Manager::GetDataPos(In const API::Rendering::TEXTURE_DESC& desc, In uint32_t MipMap, In_opt uint32_t Image) const
{
uint32_t mipMaps = 0;
uint32_t images = 0;
switch (desc.Type)
{
case API::Rendering::TEXTURE_TYPE::TEXTURE:
mipMaps = desc.Texture.MipMaps;
images = 0;
break;
case API::Rendering::TEXTURE_TYPE::TEXTURE_ARRAY:
mipMaps = desc.TextureArray.MipMaps;
images = desc.TextureArray.Images;
break;
case API::Rendering::TEXTURE_TYPE::TEXTURE_CUBE:
mipMaps = desc.TextureCube.MipMaps;
images = 6;
break;
default:
break;
}
return CE_MIN(mipMaps, MipMap) + (CE_MIN(Image, images)*mipMaps);
}
size_t CLOAK_CALL_THIS Manager::GetNodeID(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID) const
{
UINT r = 0;
GetNodeInfo(type, nodeID, nullptr, &r);
return r;
}
IQueue* CLOAK_CALL_THIS Manager::GetQueueByNodeID(In size_t nodeID) const
{
assert(nodeID < m_adapterCount);
return &m_queues[nodeID];
}
ISingleQueue* CLOAK_CALL_THIS Manager::GetQueue(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID) const
{
UINT node;
QUEUE_TYPE qtype;
GetNodeInfo(type, nodeID, &qtype, &node);
return m_queues[node].GetSingleQueue(qtype);
}
void CLOAK_CALL_THIS Manager::ReadBuffer(In size_t dstByteSize, Out_writes(dstByteSize) void* dst, In API::Rendering::IPixelBuffer* src, In_opt UINT subresource) const
{
if (dstByteSize > 0 && dst != nullptr)
{
CopyContext* graphic = nullptr;
Resource* srcRc = nullptr;
if (SUCCEEDED(src->QueryInterface(CE_QUERY_ARGS(&srcRc))))
{
m_queues[srcRc->GetNodeID() - 1].CreateContext(CE_QUERY_ARGS(&graphic), QUEUE_TYPE_COPY);
#ifdef _DEBUG
graphic->SetSourceFile(std::string(__FILE__) + " @ " + std::to_string(__LINE__));
#endif
API::Rendering::ReadBack temp = graphic->ReadBack(src, subresource);
graphic->CloseAndExecute(true);
graphic->Release();
const size_t rs = temp.GetSize();
memcpy(dst, temp.GetData(), std::min(rs, dstByteSize));
if (rs < dstByteSize) { memset(dst, 0, dstByteSize - rs); }
srcRc->Release();
}
}
}
void CLOAK_CALL_THIS Manager::ReadBuffer(In size_t dstByteSize, Out_writes(dstByteSize) void* dst, In API::Rendering::IGraphicBuffer* src) const
{
if (dstByteSize > 0 && dst != nullptr)
{
CopyContext* graphic = nullptr;
Resource* srcRc = nullptr;
if (SUCCEEDED(src->QueryInterface(CE_QUERY_ARGS(&srcRc))))
{
m_queues[srcRc->GetNodeID() - 1].CreateContext(CE_QUERY_ARGS(&graphic), QUEUE_TYPE_COPY);
#ifdef _DEBUG
graphic->SetSourceFile(std::string(__FILE__) + " @ " + std::to_string(__LINE__));
#endif
API::Rendering::ReadBack temp = graphic->ReadBack(src);
graphic->CloseAndExecute(true);
graphic->Release();
const size_t rs = temp.GetSize();
memcpy(dst, temp.GetData(), std::min(rs, dstByteSize));
if (rs < dstByteSize) { memset(dst, 0, dstByteSize - rs); }
srcRc->Release();
}
}
}
void CLOAK_CALL_THIS Manager::ReadBuffer(In size_t dstSize, Out_writes(dstSize) API::Helper::Color::RGBA* color, In API::Rendering::IColorBuffer* src, In_opt UINT subresource) const
{
if (dstSize > 0 && color != nullptr)
{
CopyContext* graphic = nullptr;
Resource* srcRc = nullptr;
if (SUCCEEDED(src->QueryInterface(CE_QUERY_ARGS(&srcRc))))
{
APIManager::IColorOrder* ord = APIManager::GetColorOrderByFormat(src->GetFormat());
if (CloakCheckOK(ord != nullptr, API::Global::Debug::Error::GRAPHIC_FORMAT_UNSUPPORTED, true))
{
m_queues[srcRc->GetNodeID() - 1].CreateContext(CE_QUERY_ARGS(&graphic), QUEUE_TYPE_COPY);
#ifdef _DEBUG
graphic->SetSourceFile(std::string(__FILE__) + " @ " + std::to_string(__LINE__));
#endif
API::Rendering::ReadBack temp = graphic->ReadBack(src, subresource);
graphic->CloseAndExecute(true);
graphic->Release();
uint8_t* data = reinterpret_cast<uint8_t*>(temp.GetData());
const size_t bs = static_cast<size_t>(temp.GetSize() / ord->GetByteSize());
const size_t ds = bs < dstSize ? bs : dstSize;
for (size_t a = 0; a < ds; a++) { ord->CopyBytes(&data[a*ord->GetByteSize()], &color[a]); }
for (size_t a = bs; a < dstSize; a++) { color[a] = API::Helper::Color::RGBA(0, 0, 0, 0); }
}
ord->Delete();
}
srcRc->Release();
}
}
ID3D12CommandQueue* CLOAK_CALL_THIS Manager::GetCommandQueue() const
{
return m_queues[0].GetCommandQueue(QUEUE_TYPE_DIRECT);
}
Success(return == true) bool CLOAK_CALL_THIS Manager::iQueryInterface(In REFIID riid, Outptr void** ptr)
{
if (riid == __uuidof(API::Rendering::Manager_v1::IManager)) { *ptr = (API::Rendering::Manager_v1::IManager*)this; return true; }
else RENDERING_QUERY_IMPL(ptr, riid, Manager, Manager_v1, SavePtr);
}
void CLOAK_CALL_THIS Manager::GetNodeInfo(In API::Rendering::CONTEXT_TYPE type, In uint32_t nodeID, Out QUEUE_TYPE* qtype, Out UINT* node) const
{
UINT b = 0;
switch (type)
{
case CloakEngine::API::Rendering::CONTEXT_TYPE_GRAPHIC:
if (qtype != nullptr) { *qtype = QUEUE_TYPE_DIRECT; }
b = 0;
break;
case CloakEngine::API::Rendering::CONTEXT_TYPE_GRAPHIC_COPY:
if (qtype != nullptr) { *qtype = QUEUE_TYPE_COPY; }
b = 0;
break;
case CloakEngine::API::Rendering::CONTEXT_TYPE_PHYSICS:
if (qtype != nullptr) { *qtype = QUEUE_TYPE_DIRECT; }
b = 1;
break;
case CloakEngine::API::Rendering::CONTEXT_TYPE_PHYSICS_COPY:
if (qtype != nullptr) { *qtype = QUEUE_TYPE_COPY; }
b = 1;
break;
default:
break;
}
if (node != nullptr)
{
if (m_adapterCount <= 1) { *node = 0; }
else
{
UINT c = b + static_cast<UINT>(nodeID * CONTEXT_TYPE_COUNT);
if (m_adapterCount % CONTEXT_TYPE_COUNT == 0) { c += c / m_adapterCount; }
*node = c % m_adapterCount;
}
}
}
}
}
}
}
}
#endif | 45.206306 | 332 | 0.618306 | [
"model"
] |
55b3e17e578ca1ef857fb14e8232fa808f53444c | 2,068 | cpp | C++ | platforms/leetcode/0072_stone-game-viii.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | 2 | 2020-09-17T09:04:00.000Z | 2020-11-20T19:43:18.000Z | platforms/leetcode/0072_stone-game-viii.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | platforms/leetcode/0072_stone-game-viii.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | #include "../../template.hpp"
using i32 = std::int32_t;
using i64 = std::int64_t;
//const i32 INF = 1000000000 + 7;
const i32 fastio_ = ([](){std::ios_base::sync_with_stdio(0); std::cin.tie(0);return 0;})();
i32 prefix[100002];
i32 dp[100002];
i32 rec(vector<i32>& arr, i32 n) {
if (n == arr.size()) return prefix[n];
if (dp[n] != -1) return dp[n];
return dp[n] = max(
prefix[n] - rec(arr, n + 1),
rec(arr, n + 1));
}
i32 rec(vector<i32> arr) {
memset(prefix, 0, sizeof(prefix));
memset(dp, -1, sizeof(dp));
i32 n = arr.size();
for (i32 i = 1; i <= n; ++i) {
prefix[i] = prefix[i - 1] + arr[i - 1];
}
return rec(arr, 2);
}
i32 tab(vector<i32> arr) {
memset(prefix, 0, sizeof(prefix));
memset(dp, 0, sizeof(dp));
i32 n = arr.size();
for (i32 i = 1; i <= n; ++i) {
prefix[i] = prefix[i - 1] + arr[i - 1];
}
dp[n] = prefix[n];
for (i32 i = n - 1; i >= 2; --i) {
dp[i] = max(dp[i + 1], prefix[i] - dp[i + 1]);
}
return dp[2];
}
int main() { TimeMeasure _;
cout << rec({-1,2,-3,4,-5}) << endl; // 5
cout << rec({7,-6,5,10,5,-2,-6}) << endl; // 13
cout << rec({-10,-12}) << endl; // -22
cout << rec({-39,-23,-43,-7,25,-36,-32,17,-42,-5,-11}) << endl; // 11
cout << rec({25,-35,-37,4,34,43,16,-33,0,-17,-31,-42,-42,38,12,-5,-43,-10,-37,12}) << endl; // 38
cout << rec({-53,-56,90,-74,-50,29,37,64,-31,-54,74,-80,-18,-69,-44,73,99,-47,-35,71,-55,-27,34,1,-66,-63,3,-34,33,91,-25,-40,-33,68,-34,-32,69,44,-54}) << endl; // 54
cout << endl;
cout << tab({-1,2,-3,4,-5}) << endl; // 5
cout << tab({7,-6,5,10,5,-2,-6}) << endl; // 13
cout << tab({-10,-12}) << endl; // -22
cout << tab({-39,-23,-43,-7,25,-36,-32,17,-42,-5,-11}) << endl; // 11
cout << tab({25,-35,-37,4,34,43,16,-33,0,-17,-31,-42,-42,38,12,-5,-43,-10,-37,12}) << endl; // 38
cout << tab({-53,-56,90,-74,-50,29,37,64,-31,-54,74,-80,-18,-69,-44,73,99,-47,-35,71,-55,-27,34,1,-66,-63,3,-34,33,91,-25,-40,-33,68,-34,-32,69,44,-54}) << endl; // 54
}
| 35.655172 | 171 | 0.48646 | [
"vector"
] |
55b40ddbbb8f901d640493f6fceb3e92311c24e7 | 6,302 | cc | C++ | frc971/control_loops/drivetrain/distance_spline_test.cc | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | frc971/control_loops/drivetrain/distance_spline_test.cc | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | frc971/control_loops/drivetrain/distance_spline_test.cc | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | #include "frc971/control_loops/drivetrain/distance_spline.h"
#include <vector>
#include "aos/testing/test_shm.h"
#include "gflags/gflags.h"
#include "gtest/gtest.h"
#if defined(SUPPORT_PLOT)
#include "third_party/matplotlib-cpp/matplotlibcpp.h"
#endif
DEFINE_bool(plot, false, "If true, plot");
namespace frc971 {
namespace control_loops {
namespace drivetrain {
namespace testing {
// Test fixture with a spline from 0, 0 to 1, 1
class ParameterizedDistanceSplineTest
: public ::testing::TestWithParam<::std::vector<Spline>> {
protected:
ParameterizedDistanceSplineTest()
: distance_spline_(::std::vector<Spline>(GetParam())) {}
::aos::testing::TestSharedMemory shm_;
DistanceSpline distance_spline_;
};
// Tests that the derivitives of xy integrate back up to the position.
TEST_P(ParameterizedDistanceSplineTest, XYIntegral) {
::std::vector<double> distances_plot;
::std::vector<double> x_plot;
::std::vector<double> y_plot;
::std::vector<double> ix_plot;
::std::vector<double> iy_plot;
::std::vector<double> dx_plot;
::std::vector<double> dy_plot;
::std::vector<double> idx_plot;
::std::vector<double> idy_plot;
const int num_points = 10000;
::Eigen::Matrix<double, 2, 1> point = distance_spline_.XY(0.0);
::Eigen::Matrix<double, 2, 1> dpoint = distance_spline_.DXY(0.0);
const double ddistance =
distance_spline_.length() / static_cast<double>(num_points - 1);
for (int i = 0; i < num_points; ++i) {
const double distance = ddistance * static_cast<double>(i);
const ::Eigen::Matrix<double, 2, 1> expected_point =
distance_spline_.XY(distance);
const ::Eigen::Matrix<double, 2, 1> expected_dpoint =
distance_spline_.DXY(distance);
distances_plot.push_back(distance);
x_plot.push_back(expected_point(0));
y_plot.push_back(expected_point(1));
ix_plot.push_back(point(0));
iy_plot.push_back(point(1));
dx_plot.push_back(expected_dpoint(0));
dy_plot.push_back(expected_dpoint(1));
idx_plot.push_back(dpoint(0));
idy_plot.push_back(dpoint(1));
EXPECT_LT((point - expected_point).norm(), 1e-2) << ": At distance "
<< distance;
EXPECT_LT((dpoint - expected_dpoint).norm(), 1e-2) << ": At distance "
<< distance;
// We need to record the starting state without integrating.
if (i == 0) {
continue;
}
point += dpoint * ddistance;
dpoint += distance_spline_.DDXY(distance) * ddistance;
EXPECT_FLOAT_EQ(distance_spline_.DDXY(distance).norm(),
::std::abs(distance_spline_.DTheta(distance)));
}
#if defined(SUPPORT_PLOT)
// Conditionally plot the functions and their integrals to aid debugging.
if (FLAGS_plot) {
matplotlibcpp::figure();
matplotlibcpp::plot(distances_plot, x_plot, {{"label", "x"}});
matplotlibcpp::plot(distances_plot, ix_plot, {{"label", "ix"}});
matplotlibcpp::plot(distances_plot, y_plot, {{"label", "y"}});
matplotlibcpp::plot(distances_plot, iy_plot, {{"label", "iy"}});
matplotlibcpp::plot(distances_plot, dx_plot, {{"label", "dx"}});
matplotlibcpp::plot(distances_plot, idx_plot, {{"label", "idx"}});
matplotlibcpp::plot(distances_plot, dy_plot, {{"label", "dy"}});
matplotlibcpp::plot(distances_plot, idy_plot, {{"label", "idy"}});
matplotlibcpp::legend();
matplotlibcpp::figure();
matplotlibcpp::plot(x_plot, y_plot, {{"label", "spline"}});
matplotlibcpp::legend();
matplotlibcpp::show();
}
#endif
}
// Tests that the derivitives of xy integrate back up to the position.
TEST_P(ParameterizedDistanceSplineTest, ThetaIntegral) {
::std::vector<double> distances_plot;
::std::vector<double> theta_plot;
::std::vector<double> itheta_plot;
::std::vector<double> dtheta_plot;
::std::vector<double> idtheta_plot;
const int num_points = 10000;
double theta = distance_spline_.Theta(0.0);
double dtheta = distance_spline_.DTheta(0.0);
const double ddistance =
distance_spline_.length() / static_cast<double>(num_points - 1);
for (int i = 0; i < num_points; ++i) {
const double distance = ddistance * static_cast<double>(i);
const double expected_theta = distance_spline_.Theta(distance);
const double expected_dtheta = distance_spline_.DTheta(distance);
distances_plot.push_back(distance);
theta_plot.push_back(expected_theta);
itheta_plot.push_back(theta);
dtheta_plot.push_back(expected_dtheta);
idtheta_plot.push_back(dtheta);
EXPECT_NEAR(expected_theta, theta, 1e-2) << ": At distance " << distance;
EXPECT_NEAR(expected_dtheta, dtheta, 1e-2) << ": At distance " << distance;
// We need to record the starting state without integrating.
if (i == 0) {
continue;
}
theta += dtheta * ddistance;
dtheta += distance_spline_.DDTheta(distance) * ddistance;
}
#if defined(SUPPORT_PLOT)
// Conditionally plot the functions and their integrals to aid debugging.
if (FLAGS_plot) {
matplotlibcpp::figure();
matplotlibcpp::plot(distances_plot, theta_plot, {{"label", "theta"}});
matplotlibcpp::plot(distances_plot, itheta_plot, {{"label", "itheta"}});
matplotlibcpp::plot(distances_plot, dtheta_plot, {{"label", "dtheta"}});
matplotlibcpp::plot(distances_plot, idtheta_plot, {{"label", "idtheta"}});
matplotlibcpp::legend();
matplotlibcpp::show();
}
#endif
}
INSTANTIATE_TEST_CASE_P(
DistanceSplineTest, ParameterizedDistanceSplineTest,
::testing::Values(
::std::vector<Spline>(
{Spline(Spline4To6((::Eigen::Matrix<double, 2, 4>() << 0.0, 0.5,
0.5, 1.0, 0.0, 0.0, 1.0, 1.0)
.finished()))}),
::std::vector<Spline>(
{Spline(Spline4To6((::Eigen::Matrix<double, 2, 4>() << 0.0, 0.5,
0.5, 1.0, 0.0, 0.0, 1.0, 1.0)
.finished())),
Spline(Spline4To6((::Eigen::Matrix<double, 2, 4>() << 1.0, 1.5,
1.5, 2.0, 1.0, 1.0, 0.0, 0.0)
.finished()))})));
} // namespace testing
} // namespace drivetrain
} // namespace control_loops
} // namespace frc971
| 36.218391 | 79 | 0.64662 | [
"vector"
] |
55b8083e63766fe81e954183af4228fb101da506 | 6,779 | cc | C++ | src/log_writer.cc | aexoden/chatstats | 07b7321cb6eed4d667ba1de9abbd29249286154f | [
"MIT"
] | null | null | null | src/log_writer.cc | aexoden/chatstats | 07b7321cb6eed4d667ba1de9abbd29249286154f | [
"MIT"
] | null | null | null | src/log_writer.cc | aexoden/chatstats | 07b7321cb6eed4d667ba1de9abbd29249286154f | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2012 Jason Lynch <jason@calindora.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <iostream>
#include <giomm/dataoutputstream.h>
#include "log_writer.hh"
const Glib::ustring LogWriter::TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S+0000";
void LogWriter::write(Glib::RefPtr<Gio::File> file, std::vector<std::shared_ptr<Session>> sessions)
{
Glib::RefPtr<Gio::DataOutputStream> file_stream = Gio::DataOutputStream::create(file->create_file());
bool first_session = true;
for (auto session : sessions)
{
if (!first_session)
file_stream->put_string("\n");
file_stream->put_string(Glib::ustring::compose("%1\n", this->_format_session_start(session->start)).raw());
if (!session->target.empty())
file_stream->put_string(Glib::ustring::compose("%1\n", this->_format_session_target(session->target)).raw());
for (auto event : session->events)
{
Glib::ustring message;
switch (event->type)
{
case EventType::ACTION:
message = this->_format_action(event);
break;
case EventType::CTCP:
message = this->_format_ctcp(event);
break;
case EventType::JOIN:
message = this->_format_join(event);
break;
case EventType::KICK:
message = this->_format_kick(event);
break;
case EventType::MESSAGE:
message = this->_format_message(event);
break;
case EventType::MODE_CHANGE:
message = this->_format_mode_change(event);
break;
case EventType::NICK_CHANGE:
message = this->_format_nick_change(event);
break;
case EventType::NOTICE:
message = this->_format_notice(event);
break;
case EventType::PART:
message = this->_format_part(event);
break;
case EventType::QUIT:
message = this->_format_quit(event);
break;
case EventType::TOPIC_CHANGE:
message = this->_format_topic_change(event);
break;
default:
continue;
}
file_stream->put_string(Glib::ustring::compose("%1\n", message).raw());
}
file_stream->put_string(Glib::ustring::compose("%1\n", this->_format_session_stop(session->stop)).raw());
first_session = false;
}
}
Glib::ustring LogWriter::_format_session_start(std::shared_ptr<const Glib::DateTime> timestamp)
{
return Glib::ustring::compose("Session Start: %1", timestamp->format(LogWriter::TIMESTAMP_FORMAT));
}
Glib::ustring LogWriter::_format_session_stop(std::shared_ptr<const Glib::DateTime> timestamp)
{
return Glib::ustring::compose("Session Stop: %1", timestamp->format(LogWriter::TIMESTAMP_FORMAT));
}
Glib::ustring LogWriter::_format_session_target(const Glib::ustring & target)
{
return Glib::ustring::compose("Session Target: %1", target);
}
Glib::ustring LogWriter::_format_action(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] * %2 %3", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
Glib::ustring LogWriter::_format_ctcp(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] [%2] %3", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
Glib::ustring LogWriter::_format_join(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] *** %2 joins", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string());
}
Glib::ustring LogWriter::_format_kick(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] *** %2 kicks %3 (%4)", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->object.to_string(), event->message);
}
Glib::ustring LogWriter::_format_message(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] <%2> %3", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
Glib::ustring LogWriter::_format_mode_change(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] *** %2 sets mode: %3", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
Glib::ustring LogWriter::_format_nick_change(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] *** %2 is now known as %3", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->object.to_string());
}
Glib::ustring LogWriter::_format_notice(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] -%2- %3", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
Glib::ustring LogWriter::_format_part(const std::shared_ptr<const Event> & event)
{
if (event->message.empty())
return Glib::ustring::compose("[%1] *** %2 parts", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string());
else
return Glib::ustring::compose("[%1] *** %2 parts (%3)", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
Glib::ustring LogWriter::_format_quit(const std::shared_ptr<const Event> & event)
{
if (event->message.empty())
return Glib::ustring::compose("[%1] *** %2 quits", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string());
else
return Glib::ustring::compose("[%1] *** %2 quits (%3)", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
Glib::ustring LogWriter::_format_topic_change(const std::shared_ptr<const Event> & event)
{
return Glib::ustring::compose("[%1] *** %2 changes topic to '%3'", event->timestamp->format(LogWriter::TIMESTAMP_FORMAT), event->subject.to_string(), event->message);
}
| 38.95977 | 186 | 0.716772 | [
"object",
"vector"
] |
55c9889ecd9fb79aadaacc8b6a51d12609726266 | 1,429 | hpp | C++ | ajg/synth/engines/tmpl/options.hpp | legutierr/synth | 7540072bde2ea9c8258c2dca69d2ed3bd62fb991 | [
"BSL-1.0"
] | 1 | 2016-04-10T14:13:34.000Z | 2016-04-10T14:13:34.000Z | ajg/synth/engines/tmpl/options.hpp | legutierr/synth | 7540072bde2ea9c8258c2dca69d2ed3bd62fb991 | [
"BSL-1.0"
] | null | null | null | ajg/synth/engines/tmpl/options.hpp | legutierr/synth | 7540072bde2ea9c8258c2dca69d2ed3bd62fb991 | [
"BSL-1.0"
] | null | null | null | // (C) Copyright 2014 Alvaro J. Genial (http://alva.ro)
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).
#ifndef AJG_SYNTH_ENGINES_TMPL_OPTIONS_HPP_INCLUDED
#define AJG_SYNTH_ENGINES_TMPL_OPTIONS_HPP_INCLUDED
#include <vector>
namespace ajg {
namespace synth {
namespace engines {
namespace tmpl {
enum tag_mode
{ xml
, html
, loose
};
template <class Value>
struct options {
public:
typedef options options_type;
typedef Value value_type;
typedef typename value_type::traits_type traits_type;
typedef typename traits_type::boolean_type boolean_type;
public:
BOOST_STATIC_CONSTANT(boolean_type, case_sensitive = false);
BOOST_STATIC_CONSTANT(boolean_type, shortcut_syntax = true);
BOOST_STATIC_CONSTANT(boolean_type, loop_variables = true);
BOOST_STATIC_CONSTANT(boolean_type, global_variables = false);
BOOST_STATIC_CONSTANT(tmpl::tag_mode, tag_mode = loose); // TODO: Implement.
public:
options() {}
};
}}}} // namespace ajg::synth::engines::tmpl
#endif // AJG_SYNTH_ENGINES_TMPL_OPTIONS_HPP_INCLUDED
| 30.404255 | 94 | 0.641008 | [
"vector"
] |
55ca197b90c3ff0187f01afeaaf713a3fb1ab415 | 1,277 | cpp | C++ | src/tdme/tools/shared/views/EntityDisplayView.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/tools/shared/views/EntityDisplayView.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/tools/shared/views/EntityDisplayView.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | #include <tdme/tools/shared/views/EntityDisplayView.h>
#include <string>
#include <vector>
#include <tdme/engine/Engine.h>
#include <tdme/engine/Entity.h>
#include <tdme/tools/shared/controller/EntityDisplaySubScreenController.h>
#include <tdme/tools/shared/model/LevelEditorEntity.h>
using tdme::tools::shared::views::EntityDisplayView;
using std::vector;
using std::string;
using tdme::engine::Engine;
using tdme::engine::Entity;
using tdme::tools::shared::controller::EntityDisplaySubScreenController;
using tdme::tools::shared::model::LevelEditorEntity;
EntityDisplayView::EntityDisplayView(EntityDisplaySubScreenController* entityDisplaySubScreenController)
{
this->engine = Engine::getInstance();
this->entityDisplaySubScreenController = entityDisplaySubScreenController;
displayGroundPlate = false;
displayShadowing = false;
}
EntityDisplayView::~EntityDisplayView() {
}
void EntityDisplayView::display(LevelEditorEntity* entity)
{
if (entity != nullptr) {
auto model = engine->getEntity("model");
if (model != nullptr) model->setContributesShadows(displayShadowing);
if (model != nullptr) model->setReceivesShadows(displayShadowing);
auto ground = engine->getEntity("ground");
if (ground != nullptr) ground->setEnabled(displayGroundPlate);
}
}
| 30.404762 | 105 | 0.783085 | [
"vector",
"model"
] |
55da7a63bfea48068d4a78796677dd1d6c33420d | 11,619 | hpp | C++ | src/tests/count.hpp | vreverdy/bit-algorithms | bc12928d46846eb32b3d9e0a006549a947c4803f | [
"BSD-3-Clause"
] | 16 | 2019-06-17T23:56:15.000Z | 2021-07-04T23:35:31.000Z | src/tests/count.hpp | bkille/bit-algorithms | bc12928d46846eb32b3d9e0a006549a947c4803f | [
"BSD-3-Clause"
] | 3 | 2019-04-28T04:53:31.000Z | 2019-06-01T15:15:11.000Z | src/tests/count.hpp | bkille/bit-algorithms | bc12928d46846eb32b3d9e0a006549a947c4803f | [
"BSD-3-Clause"
] | 6 | 2019-03-13T19:21:36.000Z | 2020-01-01T12:31:34.000Z | // ============================== COUNT TESTS =============================== //
// Project: The Experimental Bit Algorithms Library
// Name: count.hpp
// Description: Tests for std::count bit iterator overloads
// Creator: Vincent Reverdy
// Contributor(s): Vincent Reverdy [2019]
// Collin Gress [2019]
// License: BSD 3-Clause License
// ========================================================================== //
#ifndef _COUNT_TESTS_HPP_INCLUDED
#define _COUNT_TESTS_HPP_INCLUDED
// ========================================================================== //
// ============================== PREAMBLE ================================== //
// C++ standard library
// Project sources
// Third party libraries
#include "catch2.hpp"
TEMPLATE_TEST_CASE("Single number: correctly counts number of set bits in random number",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
std::string bit_str = all_zero_str(num_binary_digits);
std::size_t num_bits_to_set = random_number<std::size_t>(0, num_binary_digits);
bit_str = set_n_random_bits(bit_str, num_bits_to_set);
std::size_t expected_bits_set = num_bits_to_set;
num_type num = string_as_bits<num_type>(bit_str);
std::size_t num_bits_set = count(bit::bit_iterator<num_type*>(&num, 0),
bit::bit_iterator<num_type*>(&num + 1, 0), bit::bit1);
REQUIRE(num_bits_set == expected_bits_set);
}
TEMPLATE_TEST_CASE("Single number: correctly counts number of unset bits in random number",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
std::string bit_str = all_one_str(num_binary_digits);
std::size_t num_bits_to_unset = random_number<std::size_t>(0, num_binary_digits);
bit_str = unset_n_random_bits(bit_str, num_bits_to_unset);
std::size_t expected_bits_unset = num_bits_to_unset;
num_type num = string_as_bits<num_type>(bit_str);
std::size_t num_bits_unset = count(bit::bit_iterator<num_type*>(&num, 0),
bit::bit_iterator<num_type*>(&num + 1, 0), bit::bit0);
REQUIRE(num_bits_unset == expected_bits_unset);
}
TEMPLATE_TEST_CASE("Single number: correctly counts number of unset bits where bits all zero",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
num_type num = 0;
std::size_t num_bits_unset = count(bit::bit_iterator<num_type*>(&num, 0),
bit::bit_iterator<num_type*>(&num + 1, 0), bit::bit0);
REQUIRE(num_bits_unset == num_binary_digits);
}
TEMPLATE_TEST_CASE("Single number: correctly counts number of unset bits where bits all one",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
num_type num = -1;
std::size_t num_bits_unset = count(bit::bit_iterator<num_type*>(&num, 0),
bit::bit_iterator<num_type*>(&num + 1, 0), bit::bit0);
REQUIRE(num_bits_unset == 0);
}
TEMPLATE_TEST_CASE("Single number: correctly counts number of set bits where bits all zero",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
num_type num = 0;
std::size_t num_bits_set = count(bit::bit_iterator<num_type*>(&num, 0),
bit::bit_iterator<num_type*>(&num + 1, 0), bit::bit1);
REQUIRE(num_bits_set == 0);
}
TEMPLATE_TEST_CASE("Single number: correctly counts number of set bits where bits all one",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
num_type num = -1;
std::size_t num_bits_set = count(bit::bit_iterator<num_type*>(&num, 0),
bit::bit_iterator<num_type*>(&num + 1, 0), bit::bit1);
REQUIRE(num_bits_set == num_binary_digits);
}
TEMPLATE_TEST_CASE("Vector: correctly counts number of set bits in vector of random numbers",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
std::size_t vec_len = random_number<std::size_t>(2, 100);
std::size_t expected_bits_set = 0;
std::vector<num_type> nums;
for (std::size_t i = 0; i < vec_len; i++) {
std::size_t num_bits_to_set = random_number<num_type>(0, num_binary_digits);
std::string str = all_zero_str(num_binary_digits);
str = set_n_random_bits(str, num_bits_to_set);
num_type num = string_as_bits<num_type>(str);
nums.push_back(num);
expected_bits_set += num_bits_to_set;
}
auto nums_begin = nums.begin();
auto nums_end = nums.end();
std::size_t num_bits_set = count(
bit::bit_iterator<decltype(nums_begin)>(nums_begin),
bit::bit_iterator<decltype(nums_end)>(nums_end),
bit::bit1
);
REQUIRE(num_bits_set == expected_bits_set);
}
TEMPLATE_TEST_CASE("Vector: correctly counts number of unset bits in vector of random numbers",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
std::size_t vec_len = random_number<std::size_t>(2, 100);
std::size_t expected_bits_unset = 0;
std::vector<num_type> nums;
for (std::size_t i = 0; i < vec_len; i++) {
std::size_t num_bits_to_unset = random_number<num_type>(0, num_binary_digits);
std::string str = all_one_str(num_binary_digits);
str = unset_n_random_bits(str, num_bits_to_unset);
num_type num = string_as_bits<num_type>(str);
nums.push_back(num);
expected_bits_unset += num_bits_to_unset;
}
auto nums_begin = nums.begin();
auto nums_end = nums.end();
std::size_t num_bits_unset = count(
bit::bit_iterator<decltype(nums_begin)>(nums_begin),
bit::bit_iterator<decltype(nums_end)>(nums_end),
bit::bit0
);
REQUIRE(num_bits_unset == expected_bits_unset);
}
TEMPLATE_TEST_CASE("Vector: correctly counts number of set bits where bits all one",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
std::size_t vec_len = random_number<std::size_t>(2, 100);
std::size_t expected_bits_set = num_binary_digits * vec_len;
std::vector<num_type> nums(vec_len, -1);
auto nums_begin = nums.begin();
auto nums_end = nums.end();
std::size_t num_bits_set = count(
bit::bit_iterator<decltype(nums_begin)>(nums_begin),
bit::bit_iterator<decltype(nums_end)>(nums_end),
bit::bit1
);
REQUIRE(num_bits_set == expected_bits_set);
}
TEMPLATE_TEST_CASE("Vector: correctly counts number of unset bits where bits all one",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
std::size_t vec_len = random_number<std::size_t>(2, 100);
std::size_t expected_bits_unset = 0;
std::vector<num_type> nums(vec_len, -1);
auto nums_begin = nums.begin();
auto nums_end = nums.end();
std::size_t num_bits_unset = count(
bit::bit_iterator<decltype(nums_begin)>(nums_begin),
bit::bit_iterator<decltype(nums_end)>(nums_end),
bit::bit0
);
REQUIRE(num_bits_unset == expected_bits_unset);
}
TEMPLATE_TEST_CASE("Vector: correclty counts number of set bits where bits all zero",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
std::size_t vec_len = random_number<std::size_t>(2, 100);
std::size_t expected_bits_set = 0;
std::vector<num_type> nums(vec_len, 0);
auto nums_begin = nums.begin();
auto nums_end = nums.end();
std::size_t num_bits_set = count(
bit::bit_iterator<decltype(nums_begin)>(nums_begin),
bit::bit_iterator<decltype(nums_end)>(nums_end),
bit::bit1
);
REQUIRE(num_bits_set == expected_bits_set);
}
TEMPLATE_TEST_CASE("Vector: correctly counts number of unset bits where bits all zero",
"[count]", unsigned short, unsigned int, unsigned long, unsigned long long) {
using num_type = TestType;
constexpr auto num_binary_digits = bit::binary_digits<num_type>::value;
std::size_t vec_len = random_number<std::size_t>(2, 100);
std::size_t expected_bits_unset = num_binary_digits * vec_len;
std::vector<num_type> nums(vec_len, 0);
auto nums_begin = nums.begin();
auto nums_end = nums.end();
std::size_t num_bits_unset = count(
bit::bit_iterator<decltype(nums_begin)>(nums_begin),
bit::bit_iterator<decltype(nums_end)>(nums_end),
bit::bit0
);
REQUIRE(num_bits_unset == expected_bits_unset);
}
TEMPLATE_PRODUCT_TEST_CASE("Count: multi-word",
"[template][product]",
(std::vector, std::list, std::forward_list),
(unsigned char, unsigned short,
unsigned int, unsigned long)) {
using container_type = TestType;
using num_type = typename container_type::value_type;
auto container_size = 1 << 5;
auto digits = bit::binary_digits<num_type>::value;
container_type bitcont1 = make_random_container<container_type>
(container_size);
auto boolcont1 = bitcont_to_boolcont(bitcont1);
auto bfirst1 = bit::bit_iterator<decltype(std::begin(bitcont1))>(std::begin(bitcont1));
auto blast1 = bit::bit_iterator<decltype(std::end(bitcont1))>(std::end(bitcont1));
auto bool_first1 = std::begin(boolcont1);
auto bool_last1 = std::end(boolcont1);
auto bool_first1_t = bool_first1;
auto bfirst1_t = bfirst1;
auto bool_last1_t = bool_last1;
auto blast1_t = blast1;
auto bret = bit::count(bfirst1_t, blast1_t, bit::bit1);
auto bool_ret = std::count(bool_first1_t, bool_last1_t, true);
REQUIRE(bret == bool_ret);
std::advance(bfirst1_t, 3);
std::advance(bool_first1_t, 3);
bret = bit::count(bfirst1_t, blast1_t, bit::bit1);
bool_ret = std::count(bool_first1_t, bool_last1_t, true);
REQUIRE(bret == bool_ret);
bool_last1_t = bool_first1;
std::advance(bool_last1_t, (container_size-1)*digits-digits/2);
blast1_t = bfirst1;
std::advance(blast1_t, (container_size-1)*digits-digits/2);
bret = bit::count(bfirst1_t, blast1_t, bit::bit1);
bool_ret = std::count(bool_first1_t, bool_last1_t, true);
REQUIRE(bret == bool_ret);
bool_first1_t = bool_first1;
bool_last1_t = bool_first1;
std::advance(bool_first1_t, 2);
std::advance(bool_last1_t, digits-2);
bfirst1_t = bfirst1;
blast1_t = bfirst1;
std::advance(bfirst1_t, 2);
std::advance(blast1_t, digits-2);
bret = bit::count(bfirst1_t, blast1_t, bit::bit1);
bool_ret = std::count(bool_first1_t, bool_last1_t, true);
REQUIRE(bret == bool_ret);
}
// ========================================================================== //
#endif // _COUNT_TESTS_HPP_INCLUDED
// ========================================================================== //
| 35.641104 | 96 | 0.658232 | [
"vector"
] |
55e1a404f46c971bc87036e74d78530920fe8138 | 29,178 | cpp | C++ | external_software/relion/src/ctffind_runner.cpp | leschzinerlab/cryoem-cloud-tools | d2d310423f406535a4b5f5ea78deaf2767e93348 | [
"MIT"
] | 7 | 2017-12-04T13:41:32.000Z | 2021-07-12T02:33:20.000Z | external_software/relion/src/ctffind_runner.cpp | cianfrocco-lab/cryoem-cloud-tools | d2d310423f406535a4b5f5ea78deaf2767e93348 | [
"MIT"
] | 61 | 2017-04-02T05:50:44.000Z | 2017-11-22T02:32:43.000Z | external_software/relion/src/ctffind_runner.cpp | leschzinerlab/AWS | d2d310423f406535a4b5f5ea78deaf2767e93348 | [
"MIT"
] | 9 | 2017-08-20T00:06:46.000Z | 2021-09-23T06:50:15.000Z | /***************************************************************************
*
* Author: "Sjors H.W. Scheres"
* MRC Laboratory of Molecular Biology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This complete copyright notice must be included in any revised version of the
* source code. Additional authorship citations may be added, but existing
* author citations must be preserved.
***************************************************************************/
#include "src/ctffind_runner.h"
#ifdef CUDA
#include "src/gpu_utils/cuda_mem_utils.h"
#endif
void CtffindRunner::read(int argc, char **argv, int rank)
{
parser.setCommandLine(argc, argv);
int gen_section = parser.addSection("General options");
int ctf_section = parser.addSection("CTF estimation");
fn_in = parser.getOption("--i", "STAR file with all input micrographs, or a unix wildcard to all micrograph files, e.g. \"mics/*.mrc\"");
do_use_without_doseweighting = parser.checkOption("--use_noDW", "Estimate CTFs from rlnMicrographNameNoDW instead of rlnMicrographName (only after MotionCor2)");
fn_out = parser.getOption("--o", "Directory, where all output files will be stored", "CtfEstimate/");
do_only_join_results = parser.checkOption("--only_make_star", "Don't estimate any CTFs, only join all logfile results in a STAR file");
continue_old = parser.checkOption("--only_do_unfinished", "Only estimate CTFs for those micrographs for which there is not yet a logfile with Final values.");
// Use a smaller squared part of the micrograph to estimate CTF (e.g. to avoid film labels...)
ctf_win = textToInteger(parser.getOption("--ctfWin", "Size (in pixels) of a centered, squared window to use for CTF-estimation", "-1"));
int mic_section = parser.addSection("Microscopy parameters");
// First parameter line in CTFFIND
Cs = textToFloat(parser.getOption("--CS", "Spherical Aberration (mm) ","2.0"));
Voltage = textToFloat(parser.getOption("--HT", "Voltage (kV)","300"));
AmplitudeConstrast = textToFloat(parser.getOption("--AmpCnst", "Amplitude constrast", "0.1"));
Magnification = textToFloat(parser.getOption("--XMAG", "Magnification", "60000"));
PixelSize = textToFloat(parser.getOption("--DStep", "Detector pixel size (um)", "14"));
int ctffind_section = parser.addSection("CTFFIND parameters");
// Second parameter line in CTFFIND
fn_ctffind_exe = parser.getOption("--ctffind_exe","Location of ctffind executable (or through RELION_CTFFIND_EXECUTABLE environment variable)","");
box_size = textToFloat(parser.getOption("--Box", "Size of the boxes to calculate FFTs", "512"));
resol_min = textToFloat(parser.getOption("--ResMin", "Minimum resolution (in A) to include in calculations", "100"));
resol_max = textToFloat(parser.getOption("--ResMax", "Maximum resolution (in A) to include in calculations", "7"));
min_defocus = textToFloat(parser.getOption("--dFMin", "Minimum defocus value (in A) to search", "10000"));
max_defocus = textToFloat(parser.getOption("--dFMax", "Maximum defocus value (in A) to search", "50000"));
step_defocus = textToFloat(parser.getOption("--FStep", "defocus step size (in A) for search", "250"));
amount_astigmatism = textToFloat(parser.getOption("--dAst", "amount of astigmatism (in A)", "0"));
int ctffind4_section = parser.addSection("CTFFIND4 parameters");
is_ctffind4 = parser.checkOption("--is_ctffind4", "The provided CTFFIND executable is CTFFIND4 (version 4.1+)");
do_movie_thon_rings = parser.checkOption("--do_movie_thon_rings", "Calculate Thon rings from movie frames?");
avg_movie_frames = textToInteger(parser.getOption("--avg_movie_frames", "Average over how many movie frames (try to get 4 e-/A2)", "1"));
movie_rootname = parser.getOption("--movie_rootname", "Rootname plus extension for movies", "_movie.mrcs");
do_phaseshift = parser.checkOption("--do_phaseshift", "Estimate the phase shift in the images (e.g. from a phase-plate)");
phase_min = textToFloat(parser.getOption("--phase_min", "Minimum phase shift (in degrees)", "0."));
phase_max = textToFloat(parser.getOption("--phase_max", "Maximum phase shift (in degrees)", "180."));
phase_step = textToFloat(parser.getOption("--phase_step", "Step in phase shift (in degrees)", "10."));
nr_threads = textToInteger(parser.getOption("--j", "Number of threads (for CTFIND4 only)", "1"));
do_large_astigmatism = parser.checkOption("--large_astigmatism", "Do you expect large astigmatism?");
int gctf_section = parser.addSection("Gctf parameters");
do_use_gctf = parser.checkOption("--use_gctf", "Use Gctf instead of CTFFIND to estimate the CTF parameters");
fn_gctf_exe = parser.getOption("--gctf_exe","Location of Gctf executable (or through RELION_GCTF_EXECUTABLE environment variable)","");
angpix = textToFloat(parser.getOption("--angpix", "Magnified pixel size in Angstroms", "1."));
do_ignore_ctffind_params = parser.checkOption("--ignore_ctffind_params", "Use Gctf default parameters instead of CTFFIND parameters");
do_EPA = parser.checkOption("--EPA", "Use equi-phase averaging to calculate Thon rinds in Gctf");
do_validation = parser.checkOption("--do_validation", "Use validation inside Gctf to analyse quality of the fit?");
additional_gctf_options = parser.getOption("--extra_gctf_options", "Additional options for Gctf", "");
gpu_ids = parser.getOption("--gpu", "Device ids for each MPI-thread, e.g 0:1:2:3","");
// Initialise verb for non-parallel execution
verb = 1;
// Check for errors in the command-line option
if (parser.checkForErrors())
REPORT_ERROR("Errors encountered on the command line (see above), exiting...");
}
void CtffindRunner::usage()
{
parser.writeUsage(std::cout);
}
void CtffindRunner::initialise()
{
// Get the CTFFIND executable
if (fn_ctffind_exe == "")
{
char * penv;
penv = getenv ("RELION_CTFFIND_EXECUTABLE");
if (penv!=NULL)
fn_ctffind_exe = (std::string)penv;
}
// Get the GCTF executable
if (do_use_gctf && fn_gctf_exe == "")
{
char * penv;
penv = getenv ("RELION_GCTF_EXECUTABLE");
if (penv!=NULL)
fn_gctf_exe = (std::string)penv;
}
if (do_use_gctf && ctf_win>0)
REPORT_ERROR("CtffindRunner::initialise ERROR: Running Gctf together with --ctfWin is not implemented, please use CTFFIND instead.");
// Make sure fn_out ends with a slash
if (fn_out[fn_out.length()-1] != '/')
fn_out += "/";
// Set up which micrographs to estimate CTFs from
if (fn_in.isStarFile())
{
MetaDataTable MDin;
MDin.read(fn_in);
fn_micrographs_all.clear();
fn_micrographs_widose_all.clear();
FOR_ALL_OBJECTS_IN_METADATA_TABLE(MDin)
{
FileName fn_mic, fn_mic2;
if (do_use_without_doseweighting)
{
MDin.getValue(EMDL_MICROGRAPH_NAME_WODOSE, fn_mic);
MDin.getValue(EMDL_MICROGRAPH_NAME, fn_mic2);
fn_micrographs_all.push_back(fn_mic);
fn_micrographs_widose_all.push_back(fn_mic2);
}
else
{
MDin.getValue(EMDL_MICROGRAPH_NAME, fn_mic);
fn_micrographs_all.push_back(fn_mic);
}
}
}
else
{
fn_in.globFiles(fn_micrographs_all);
}
// If we're continuing an old run, see which micrographs have not been finished yet...
if (continue_old)
{
fn_micrographs.clear();
fn_micrographs_widose.clear();
for (long int imic = 0; imic < fn_micrographs_all.size(); imic++)
{
FileName fn_microot = fn_micrographs_all[imic].without(".mrc");
RFLOAT defU, defV, defAng, CC, HT, CS, AmpCnst, XMAG, DStep, maxres=-1., valscore = -1., phaseshift = 0.;
if (!getCtffindResults(fn_microot, defU, defV, defAng, CC,
HT, CS, AmpCnst, XMAG, DStep, maxres, valscore, phaseshift, false)) // false: dont warn if not found Final values
{
fn_micrographs.push_back(fn_micrographs_all[imic]);
if (do_use_without_doseweighting)
fn_micrographs_widose.push_back(fn_micrographs_widose_all[imic]);
}
}
}
else
{
fn_micrographs = fn_micrographs_all;
fn_micrographs_widose = fn_micrographs_widose_all;
}
// Make symbolic links of the input micrographs in the output directory because ctffind and gctf write output files alongside the input micropgraph
char temp [180];
char *cwd = getcwd(temp, 180);
currdir = std::string(temp);
// Make sure fn_out ends with a slash
if (currdir[currdir.length()-1] != '/')
currdir += "/";
FileName prevdir="";
for (size_t i = 0; i < fn_micrographs.size(); i++)
{
FileName myname = fn_micrographs[i];
if (do_movie_thon_rings)
myname = myname.withoutExtension() + movie_rootname;
// Remove the UNIQDATE part of the filename if present
FileName output = getOutputFileWithNewUniqueDate(myname, fn_out);
// Create output directory if neccesary
FileName newdir = output.beforeLastOf("/");
if (newdir != prevdir)
{
std::string command = " mkdir -p " + newdir;
int res = system(command.c_str());
}
int slk = symlink((currdir+myname).c_str(), output.c_str());
}
if (do_use_gctf && fn_micrographs.size()>0)
{
#ifdef CUDA
untangleDeviceIDs(gpu_ids, allThreadIDs);
if (allThreadIDs[0].size()==0 || (!std::isdigit(*gpu_ids.begin())) )
{
if (verb>0)
std::cout << "gpu-ids not specified, threads will automatically be mapped to devices (incrementally)."<< std::endl;
HANDLE_ERROR(cudaGetDeviceCount(&devCount));
}
#endif
// Find the dimensions of the first micrograph, to later on ensure all micrographs are the same size
Image<double> Itmp;
Itmp.read(fn_micrographs[0], false); // false means only read header!
xdim = XSIZE(Itmp());
ydim = YSIZE(Itmp());
}
if (is_ctffind4 && ctf_win > 0 && do_movie_thon_rings)
REPORT_ERROR("CtffindRunner::initialise ERROR: You cannot use a --ctfWin operation on movies.");
if (verb > 0)
{
if (do_use_gctf)
std::cout << " Using Gctf executable in: " << fn_gctf_exe << std::endl;
else
std::cout << " Using CTFFIND executable in: " << fn_ctffind_exe << std::endl;
std::cout << " to estimate CTF parameters for the following micrographs: " << std::endl;
if (continue_old)
std::cout << " (skipping all micrographs for which a logfile with Final values already exists " << std::endl;
for(unsigned int i = 0; i < fn_micrographs.size(); ++i)
std::cout << " * " << fn_micrographs[i] << std::endl;
}
}
void CtffindRunner::run()
{
if (!do_only_join_results)
{
int barstep;
if (verb > 0)
{
if (do_use_gctf)
std::cout << " Estimating CTF parameters using Kai Zhang's Gctf ..." << std::endl;
else
{
if (is_ctffind4)
std::cout << " Estimating CTF parameters using Alexis Rohou's and Niko Grigorieff's CTFFIND4.1 ..." << std::endl;
else
std::cout << " Estimating CTF parameters using Niko Grigorieff's CTFFIND ..." << std::endl;
}
init_progress_bar(fn_micrographs.size());
barstep = XMIPP_MAX(1, fn_micrographs.size() / 60);
}
std::vector<std::string> allmicnames;
for (long int imic = 0; imic < fn_micrographs.size(); imic++)
{
if (do_use_gctf)
{
//addToGctfJobList(imic, allmicnames);
executeGctf(imic, allmicnames, imic+1==fn_micrographs.size());
}
else if (is_ctffind4)
{
executeCtffind4(imic);
}
else
{
executeCtffind3(imic);
}
if (verb > 0 && imic % barstep == 0)
progress_bar(imic);
}
if (verb > 0)
progress_bar(fn_micrographs.size());
}
joinCtffindResults();
}
void CtffindRunner::joinCtffindResults()
{
MetaDataTable MDctf;
for (long int imic = 0; imic < fn_micrographs_all.size(); imic++)
{
FileName fn_microot = fn_micrographs_all[imic].without(".mrc");
RFLOAT defU, defV, defAng, CC, HT, CS, AmpCnst, XMAG, DStep;
RFLOAT maxres = -999., valscore = -999., phaseshift = -999.;
bool has_this_ctf = getCtffindResults(fn_microot, defU, defV, defAng, CC,
HT, CS, AmpCnst, XMAG, DStep, maxres, valscore, phaseshift);
if (!has_this_ctf)
{
std::cerr << " WARNING: skipping, since cannot get CTF values for " << fn_micrographs_all[imic] <<std::endl;
}
else
{
FileName fn_root = getOutputFileWithNewUniqueDate(fn_microot, fn_out);
FileName fn_ctf = fn_root + ".ctf:mrc";
MDctf.addObject();
if (do_use_without_doseweighting)
{
MDctf.setValue(EMDL_MICROGRAPH_NAME_WODOSE, fn_micrographs_all[imic]);
MDctf.setValue(EMDL_MICROGRAPH_NAME, fn_micrographs_widose_all[imic]);
}
else
MDctf.setValue(EMDL_MICROGRAPH_NAME, fn_micrographs_all[imic]);
MDctf.setValue(EMDL_CTF_IMAGE, fn_ctf);
MDctf.setValue(EMDL_CTF_DEFOCUSU, defU);
MDctf.setValue(EMDL_CTF_DEFOCUSV, defV);
MDctf.setValue(EMDL_CTF_DEFOCUS_ANGLE, defAng);
MDctf.setValue(EMDL_CTF_VOLTAGE, HT);
MDctf.setValue(EMDL_CTF_CS, CS);
MDctf.setValue(EMDL_CTF_Q0, AmpCnst);
MDctf.setValue(EMDL_CTF_MAGNIFICATION, XMAG);
MDctf.setValue(EMDL_CTF_DETECTOR_PIXEL_SIZE, DStep);
MDctf.setValue(EMDL_CTF_FOM, CC);
if (fabs(maxres + 999.) > 0.)
MDctf.setValue(EMDL_CTF_MAXRES, maxres);
if (fabs(phaseshift + 999.) > 0.)
MDctf.setValue(EMDL_CTF_PHASESHIFT, phaseshift);
if (fabs(valscore + 999.) > 0.)
MDctf.setValue(EMDL_CTF_VALIDATIONSCORE, valscore);
}
}
MDctf.write(fn_out+"micrographs_ctf.star");
std::cout << " Done! Written out: " << fn_out << "micrographs_ctf.star" << std::endl;
if (do_use_gctf)
{
FileName fn_gctf_junk = "micrographs_all_gctf";
if (exists(fn_gctf_junk))
remove(fn_gctf_junk.c_str());
fn_gctf_junk = "extra_micrographs_all_gctf";
if (exists(fn_gctf_junk))
remove(fn_gctf_junk.c_str());
}
}
void CtffindRunner::executeGctf(long int imic, std::vector<std::string> &allmicnames, bool is_last, int rank)
{
// Always add the new micrograph to the TODO list
Image<double> Itmp;
FileName outputfile = getOutputFileWithNewUniqueDate(fn_micrographs[imic], fn_out);
Itmp.read(outputfile, false); // false means only read header!
if (XSIZE(Itmp()) != xdim || YSIZE(Itmp()) != ydim)
REPORT_ERROR("CtffindRunner::executeGctf ERROR: Micrographs do not all have the same size! " + fn_micrographs[imic] + " is different from the first micrograph!");
if (ZSIZE(Itmp()) > 1 || NSIZE(Itmp()) > 1)
REPORT_ERROR("CtffindRunner::executeGctf ERROR: No movies or volumes allowed for " + fn_micrographs[imic]);
allmicnames.push_back(outputfile);
// Execute Gctf every 20 images, and always for the last one
if ( ((imic+1)%20) == 0 || is_last)
{
std::string command = fn_gctf_exe;
//command += " --ctfstar " + fn_out + "tt_micrographs_ctf.star";
command += " --apix " + floatToString(angpix);
command += " --cs " + floatToString(Cs);
command += " --kV " + floatToString(Voltage);
command += " --ac " + floatToString(AmplitudeConstrast);
command += " --astm " + floatToString(amount_astigmatism);
command += " --logsuffix _gctf.log";
if (!do_ignore_ctffind_params)
{
command += " --boxsize " + floatToString(box_size);
command += " --resL " + floatToString(resol_min);
command += " --resH " + floatToString(resol_max);
command += " --defL " + floatToString(min_defocus);
command += " --defH " + floatToString(max_defocus);
command += " --defS " + floatToString(step_defocus);
}
if (do_phaseshift)
{
command += " --phase_shift_L " + floatToString(phase_min);
command += " --phase_shift_H " + floatToString(phase_max);
command += " --phase_shift_S " + floatToString(phase_step);
}
if (do_EPA)
command += " --do_EPA ";
if (do_validation)
command += " --do_validation ";
for (size_t i = 0; i<allmicnames.size(); i++)
command += " " + allmicnames[i];
if (allThreadIDs[0].size()==0 || (!std::isdigit(*gpu_ids.begin())) )
{
// Automated mapping
command += " -gid " + integerToString(rank % devCount);
}
else
{
// User-specified mapping
command += " -gid " + allThreadIDs[rank][0];
}
// extra Gctf options
command += " " + additional_gctf_options;
// Redirect all gctf output
command += " >> " + fn_out + "gctf" + integerToString(rank)+".out 2>> " + fn_out + "gctf" + integerToString(rank)+".err";
//std::cerr << " command= " << command << std::endl;
int res = system(command.c_str());
// Cleanup all the symbolic links again
//for (size_t i = 0; i < allmicnames.size(); i++)
// remove(allmicnames[i].c_str());
// Re-set the allmicnames vector
allmicnames.clear();
}
}
void CtffindRunner::executeCtffind3(long int imic)
{
FileName fn_mic = getOutputFileWithNewUniqueDate(fn_micrographs[imic], fn_out);
FileName fn_root = fn_mic.withoutExtension();
FileName fn_script = fn_root + "_ctffind3.com";
FileName fn_log = fn_root + "_ctffind3.log";
FileName fn_ctf = fn_root + ".ctf";
FileName fn_mic_win;
std::ofstream fh;
fh.open((fn_script).c_str(), std::ios::out);
if (!fh)
REPORT_ERROR( (std::string)"CtffindRunner::execute_ctffind cannot create file: " + fn_script);
// If given, then put a square window of ctf_win on the micrograph for CTF estimation
if (ctf_win > 0)
{
// Window micrograph to a smaller, squared sub-micrograph to estimate CTF on
fn_mic_win = fn_root + "_win.mrc";
// Read in micrograph, window and write out again
Image<RFLOAT> I;
I.read(fn_mic);
I().setXmippOrigin();
I().window(FIRST_XMIPP_INDEX(ctf_win), FIRST_XMIPP_INDEX(ctf_win), LAST_XMIPP_INDEX(ctf_win), LAST_XMIPP_INDEX(ctf_win));
// Calculate mean, stddev, min and max
RFLOAT avg, stddev, minval, maxval;
I().computeStats(avg, stddev, minval, maxval);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_MIN, minval);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_MAX, maxval);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_AVG, avg);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_STDDEV, stddev);
I.write(fn_mic_win);
}
else
fn_mic_win = fn_mic;
std::string ctffind4_options = (is_ctffind4) ? " --omp-num-threads " + integerToString(nr_threads) + " --old-school-input-ctffind4 " : "";
// Write script to run ctffind
fh << "#!/usr/bin/env csh"<<std::endl;
fh << fn_ctffind_exe << ctffind4_options << " > " << fn_log << " << EOF"<<std::endl;
// line 1: input image
if (do_movie_thon_rings)
fh << fn_mic_win.withoutExtension() + movie_rootname << std::endl;
else
fh << fn_mic_win << std::endl;
// line 2: diagnostic .ctf image
fh << fn_ctf << std::endl;
// line 3: CS[mm], HT[kV], AmpCnst, XMAG, DStep[um]
fh << Cs << ", " << Voltage << ", " << AmplitudeConstrast << ", " << Magnification << ", " << PixelSize<< std::endl;
// line 4: Box, ResMin[A], ResMax[A], dFMin[A], dFMax[A], FStep[A], dAst[A]
fh << box_size << ", " << resol_min << ", " << resol_max << ", " << min_defocus << ", " << max_defocus << ", " << step_defocus << ", " << amount_astigmatism << std::endl;
if (is_ctffind4)
{
// line 4: Movie Thon rings: $input_is_stack_of_frames,$number_of_frames_to_average
if (do_movie_thon_rings)
fh << " 1 " << integerToString(avg_movie_frames) << std::endl;
else
fh << " 0 1" << std::endl;
// line 5: Phase-shifts: $find_phase_shift,$min_ps,$max_ps,$step_ps (in rads)
if (do_phaseshift)
fh << " 1, " << DEG2RAD(phase_min) << ", " << DEG2RAD(phase_max) << ", " << DEG2RAD(phase_step) << std::endl;
else
fh << " 0, 0, 3.15, 0.2" << std::endl;
}
fh <<"EOF"<<std::endl;
fh.close();
// Execute ctffind
std::string command = "csh "+ fn_script;
if (system(command.c_str()))
std::cerr << "WARNING: there was an error in executing: " << command << std::endl;
// Remove windowed file again
if (ctf_win > 0)
{
if( remove( fn_mic_win.c_str() ) != 0 )
std::cerr << "WARNING: there was an error deleting windowed micrograph file " << fn_mic_win << std::endl;
}
}
void CtffindRunner::executeCtffind4(long int imic)
{
FileName fn_mic = getOutputFileWithNewUniqueDate(fn_micrographs[imic], fn_out);
FileName fn_root = fn_mic.withoutExtension();
FileName fn_script = fn_root + "_ctffind4.com";
FileName fn_log = fn_root + "_ctffind4.log";
FileName fn_ctf = fn_root + ".ctf";
FileName fn_mic_win;
std::ofstream fh;
fh.open((fn_script).c_str(), std::ios::out);
if (!fh)
REPORT_ERROR( (std::string)"CtffindRunner::execute_ctffind cannot create file: " + fn_script);
// If given, then put a square window of ctf_win on the micrograph for CTF estimation
if (ctf_win > 0)
{
if (do_movie_thon_rings)
REPORT_ERROR("CtffindRunner::ERROR: cannot use window-operation on movies..");
// Window micrograph to a smaller, squared sub-micrograph to estimate CTF on
fn_mic_win = fn_root + "_win.mrc";
// Read in micrograph, window and write out again
Image<RFLOAT> I;
I.read(fn_mic);
I().setXmippOrigin();
I().window(FIRST_XMIPP_INDEX(ctf_win), FIRST_XMIPP_INDEX(ctf_win), LAST_XMIPP_INDEX(ctf_win), LAST_XMIPP_INDEX(ctf_win));
// Calculate mean, stddev, min and max
RFLOAT avg, stddev, minval, maxval;
I().computeStats(avg, stddev, minval, maxval);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_MIN, minval);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_MAX, maxval);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_AVG, avg);
I.MDMainHeader.setValue(EMDL_IMAGE_STATS_STDDEV, stddev);
I.write(fn_mic_win);
}
else
fn_mic_win = fn_mic;
//std::string ctffind4_options = " --omp-num-threads " + integerToString(nr_threads);
std::string ctffind4_options = "";
// Write script to run ctffind
fh << "#!/usr/bin/env csh"<<std::endl;
fh << fn_ctffind_exe << ctffind4_options << " > " << fn_log << " << EOF"<<std::endl;
// line 1: input image
if (do_movie_thon_rings)
{
fh << fn_mic_win.withoutExtension() + movie_rootname << std::endl;
fh << "yes" << std::endl;
fh << avg_movie_frames << std::endl;
}
else
fh << fn_mic_win << std::endl;
// line 2: diagnostic .ctf image
fh << fn_ctf << std::endl;
fh << PixelSize << std::endl;
fh << Voltage << std::endl;
fh << Cs << std::endl;
fh << AmplitudeConstrast << std::endl;
fh << box_size << std::endl;
fh << resol_min << std::endl;
fh << resol_max << std::endl;
fh << min_defocus << std::endl;
fh << max_defocus << std::endl;
fh << step_defocus << std::endl;
// Do you know what astigmatism is present?
fh << "no" << std::endl;
// Do you expect very large astigmatism?
if (do_large_astigmatism)
fh << "yes" << std::endl;
else
fh << "no" << std::endl;
// Use a restraint on astigmatism?
fh << "yes" << std::endl;
// Expected (tolerated) astigmatism
fh << amount_astigmatism << std::endl;
if (do_phaseshift)
{
fh << "yes" << std::endl;
fh << DEG2RAD(phase_min) << std::endl;
fh << DEG2RAD(phase_max) << std::endl;
fh << DEG2RAD(phase_step) << std::endl;
}
else
fh << "no" << std::endl;
// Set expert options?
fh << "no" << std::endl;
fh <<"EOF"<<std::endl;
fh << "exit 0" << std::endl;
fh.close();
// Execute ctffind
FileName command = "csh "+ fn_script;
if (system(command.c_str()))
std::cerr << "WARNING: there was an error in executing: " << command << std::endl;
// Remove windowed file again
if (ctf_win > 0)
{
if( remove( fn_mic_win.c_str() ) != 0 )
std::cerr << "WARNING: there was an error deleting windowed micrograph file " << fn_mic_win << std::endl;
}
}
bool CtffindRunner::getCtffindResults(FileName fn_microot, RFLOAT &defU, RFLOAT &defV, RFLOAT &defAng, RFLOAT &CC,
RFLOAT &HT, RFLOAT &CS, RFLOAT &AmpCnst, RFLOAT &XMAG, RFLOAT &DStep,
RFLOAT &maxres, RFLOAT &valscore, RFLOAT &phaseshift, bool do_warn)
{
if (is_ctffind4)
{
return getCtffind4Results(fn_microot, defU, defV, defAng, CC, HT, CS, AmpCnst, XMAG, DStep,
maxres, phaseshift, do_warn);
}
else
{
return getCtffind3Results(fn_microot, defU, defV, defAng, CC, HT, CS, AmpCnst, XMAG, DStep,
maxres, phaseshift, valscore, do_warn);
}
}
bool CtffindRunner::getCtffind3Results(FileName fn_microot, RFLOAT &defU, RFLOAT &defV, RFLOAT &defAng, RFLOAT &CC,
RFLOAT &HT, RFLOAT &CS, RFLOAT &AmpCnst, RFLOAT &XMAG, RFLOAT &DStep,
RFLOAT &maxres, RFLOAT &phaseshift, RFLOAT &valscore, bool do_warn)
{
FileName fn_root = getOutputFileWithNewUniqueDate(fn_microot, fn_out);
FileName fn_log = fn_root + "_ctffind3.log";
if (do_use_gctf)
fn_log = fn_root + "_gctf.log";
std::ifstream in(fn_log.data(), std::ios_base::in);
if (in.fail())
return false;
// Start reading the ifstream at the top
in.seekg(0);
// Proceed until the next "Final values" statement
// The loop statement may be necessary for data blocks that have a list AND a table inside them
bool Final_is_found = false;
bool Cs_is_found = false;
std::string line;
std::vector<std::string> words;
while (getline(in, line, '\n'))
{
// Find data_ lines
if (line.find("CS[mm], HT[kV], AmpCnst, XMAG, DStep[um]") != std::string::npos)
{
getline(in, line, '\n');
tokenize(line, words);
if (words.size() == 5)
{
Cs_is_found = true;
CS = textToFloat(words[0]);
HT = textToFloat(words[1]);
AmpCnst = textToFloat(words[2]);
XMAG = textToFloat(words[3]);
DStep = textToFloat(words[4]);
}
}
int nr_exp_cols = (do_phaseshift) ? 7 : 6;
if (line.find("Final Values") != std::string::npos)
{
tokenize(line, words);
if (words.size() == nr_exp_cols)
{
Final_is_found = true;
defU = textToFloat(words[0]);
defV = textToFloat(words[1]);
defAng = textToFloat(words[2]);
if (do_use_gctf && do_phaseshift)
{
phaseshift = textToFloat(words[3]);
CC = textToFloat(words[4]);
}
else
CC = textToFloat(words[3]);
}
}
if (do_use_gctf)
{
if (line.find("Resolution limit estimated by EPA:") != std::string::npos)
{
tokenize(line, words);
maxres = textToFloat(words[words.size()-1]);
}
if (line.find("OVERALL_VALIDATION_SCORE:") != std::string::npos)
{
tokenize(line, words);
valscore = textToFloat(words[words.size()-1]);
}
}
}
if (!Cs_is_found)
{
if (do_warn)
std::cerr << "WARNING: cannot find line with Cs[mm], HT[kV], etc values in " << fn_log << std::endl;
return false;
}
if (!Final_is_found)
{
if (do_warn)
std::cerr << "WARNING: cannot find line with Final values in " << fn_log << std::endl;
return false;
}
in.close();
return Final_is_found;
}
bool CtffindRunner::getCtffind4Results(FileName fn_microot, RFLOAT &defU, RFLOAT &defV, RFLOAT &defAng, RFLOAT &CC,
RFLOAT &HT, RFLOAT &CS, RFLOAT &AmpCnst, RFLOAT &XMAG, RFLOAT &DStep,
RFLOAT &maxres, RFLOAT &phaseshift, bool do_warn)
{
FileName fn_root = getOutputFileWithNewUniqueDate(fn_microot, fn_out);
FileName fn_log = fn_root + "_ctffind4.log";
std::ifstream in(fn_log.data(), std::ios_base::in);
if (in.fail())
return false;
// Start reading the ifstream at the top
in.seekg(0);
std::string line;
std::vector<std::string> words;
bool found_log = false;
while (getline(in, line, '\n'))
{
// Find the file with the summary of the results
if (line.find("Summary of results") != std::string::npos)
{
tokenize(line, words);
fn_log = words[words.size() - 1];
found_log = true;
break;
}
}
in.close();
if (!found_log)
return false;
// Now open the file with the summry of the results
std::ifstream in2(fn_log.data(), std::ios_base::in);
if (in2.fail())
return false;
bool Final_is_found = false;
bool Cs_is_found = false;
while (getline(in2, line, '\n'))
{
// Find data_ lines
if (line.find("acceleration voltage:") != std::string::npos)
{
Cs_is_found = true;
tokenize(line, words);
if (words.size() < 19)
REPORT_ERROR("ERROR: Unexpected number of words on data line with acceleration voltage in " + fn_log);
CS = textToFloat(words[13]);
HT = textToFloat(words[8]);
AmpCnst = textToFloat(words[18]);
DStep = textToFloat(words[3]);
XMAG = 10000.;
}
else if (line.find("Columns: ") != std::string::npos)
{
getline(in2, line, '\n');
tokenize(line, words);
if (words.size() < 7)
REPORT_ERROR("ERROR: Unexpected number of words on data line below Columns line in " + fn_log);
Final_is_found = true;
defU = textToFloat(words[1]);
defV = textToFloat(words[2]);
defAng = textToFloat(words[3]);
if (do_phaseshift)
phaseshift = RAD2DEG(textToFloat(words[4]));
CC = textToFloat(words[5]);
if (words[6] == "inf")
maxres= 999.;
else
maxres = textToFloat(words[6]);
}
}
if (!Cs_is_found)
{
if (do_warn)
std::cerr << " WARNING: cannot find line with acceleration voltage etc in " << fn_log << std::endl;
return false;
}
if (!Final_is_found)
{
if (do_warn)
std::cerr << "WARNING: cannot find line with Final values in " << fn_log << std::endl;
return false;
}
in2.close();
return Final_is_found;
}
| 34.818616 | 171 | 0.67167 | [
"vector"
] |
55f113ccc65177f509d87ff7626ea167d6828c0e | 957 | cpp | C++ | Visual Studio 2010/Projects/bjarneStroustrupC++PartII/bjarneStroustrupCFLTK/Chapter19Exercise14.cpp | Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 9 | 2018-10-24T15:16:47.000Z | 2021-12-14T13:53:50.000Z | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter19Exercise14.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | null | null | null | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter19Exercise14.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 7 | 2018-10-29T15:30:37.000Z | 2021-01-18T15:15:09.000Z | /*
TITLE GUI to "Hunt the wumpus" Chapter19Exercise14.cpp
"Bjarne Stroustrup "C++ Programming: Principles and Practice.""
COMMENT
Objective: Provide a simple GUI interface output to the
"Hunt the Wumpus" from Chapter 18.
Take the input from an input box and display a
map of of the part of the cave currently known
to the player in a window.
Input: -
Output: -
Author: Chris B. Kirov
Date: 06. 2. 2016
*/
#include <iostream>
#include <time.h>
#include <string>
#include <set>
#include <vector>
#include <sstream>
#include "GUI.h"
#include "Window.h"
#include "Graph.h"
#include "Simple_window.h"
#include "D:\C++ Projects\Visual Studio 2010\Projects\bjarneStroustrupC++PartIII\bjarneStroustrupC++PartIII\Chapter18Exercise12.h"
#include "Chapter19Exercise14.h"
int main()
{
try
{
Hunt_the_Wumpus hw;
return gui_main();
}
catch (std::exception& e)
{
std::cerr << e.what();
}
getchar ();
} | 22.255814 | 130 | 0.685475 | [
"vector"
] |
55f1efbc448e17bb9a77bc64982a30a7fe47eef3 | 6,681 | cpp | C++ | DemoFramework/FslSimpleUI/Base/source/FslSimpleUI/Base/Control/CheckBox.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 3 | 2019-01-19T20:21:24.000Z | 2021-08-10T02:11:32.000Z | DemoFramework/FslSimpleUI/Base/source/FslSimpleUI/Base/Control/CheckBox.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoFramework/FslSimpleUI/Base/source/FslSimpleUI/Base/Control/CheckBox.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-08-10T02:11:33.000Z | 2021-08-10T02:11:33.000Z | /****************************************************************************************************************************************************
* Copyright (c) 2015 Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the Freescale Semiconductor, Inc. nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************************************************************************************/
#include <FslSimpleUI/Base/Control/CheckBox.hpp>
#include <FslBase/Exceptions.hpp>
#include <FslBase/Log/Log.hpp>
#include <FslBase/Math/EqualHelper.hpp>
#include <FslGraphics/Color.hpp>
#include <FslGraphics/Font/TextureAtlasBitmapFont.hpp>
#include <FslGraphics/Render/Adapter/INativeBatch2D.hpp>
#include <FslGraphics/Render/AtlasFont.hpp>
#include <FslSimpleUI/Base/Event/WindowEventPool.hpp>
#include <FslSimpleUI/Base/Event/WindowContentChangedEvent.hpp>
#include <FslSimpleUI/Base/Event/WindowInputClickEvent.hpp>
#include <FslSimpleUI/Base/PropertyTypeFlags.hpp>
#include <FslSimpleUI/Base/UIDrawContext.hpp>
#include <FslSimpleUI/Base/WindowContext.hpp>
#include <algorithm>
#include <cassert>
#include <cmath>
namespace Fsl
{
namespace UI
{
CheckBox::CheckBox(const std::shared_ptr<WindowContext>& context)
: BaseWindow(context)
, m_text()
, m_font(context->DefaultFont)
, m_texChecked()
, m_texUnchecked()
, m_isChecked(false)
{
Enable(WindowFlags(WindowFlags::DrawEnabled | WindowFlags::ClickInput));
}
void CheckBox::SetFont(const std::shared_ptr<AtlasFont>& value)
{
if (!value)
throw std::invalid_argument("font can not be null");
if (value != m_font)
{
m_font = value;
PropertyUpdated(PropertyType::Content);
}
}
void CheckBox::SetText(const std::string& value)
{
if (value != m_text)
{
m_text = value;
PropertyUpdated(PropertyType::Content);
}
}
void CheckBox::SetCheckedTexture(const AtlasTexture2D& value)
{
if (value != m_texChecked)
{
m_texChecked = value;
PropertyUpdated(PropertyType::Content);
}
}
void CheckBox::SetUncheckedTexture(const AtlasTexture2D& value)
{
if (value != m_texUnchecked)
{
m_texUnchecked = value;
PropertyUpdated(PropertyType::Content);
}
}
void CheckBox::SetIsChecked(const bool value)
{
if (value != m_isChecked)
{
m_isChecked = value;
PropertyUpdated(PropertyType::Content);
SendEvent(GetEventPool()->AcquireWindowContentChangedEvent(0));
}
}
void CheckBox::Toggle()
{
SetIsChecked(!m_isChecked);
}
void CheckBox::WinDraw(const UIDrawContext& context)
{
BaseWindow::WinDraw(context);
if (m_text.size() == 0)
return;
const auto batch = GetContext()->Batch2D;
batch->ChangeTo(BlendState::AlphaBlend);
Vector2 position = context.TargetRect.TopLeft();
if (m_text.size() > 0)
{
auto fontInfo = m_font->GetAtlasBitmapFont();
auto measured = fontInfo.MeasureString(m_text.c_str(), 0, m_text.size());
measured.Y = fontInfo.LineSpacing();
float centeredY = 0.0f;
if (measured.Y < context.TargetRect.Height())
centeredY = std::floor((context.TargetRect.Height() - measured.Y) * 0.5f);
const auto pFont = m_font.get();
assert(pFont != nullptr);
batch->DrawString(pFont->GetAtlasTexture(), pFont->GetAtlasBitmapFont(), m_text, Vector2(position.X, position.Y + centeredY), Color::White());
position.X += measured.X;
}
const AtlasTexture2D& rTex = m_isChecked ? m_texChecked : m_texUnchecked;
if (rTex.IsValid())
{
float centeredY = 0.0f;
if (rTex.GetSize().Y < context.TargetRect.Height())
centeredY = std::floor((context.TargetRect.Height() - rTex.GetSize().Y) * 0.5f);
batch->Draw(rTex, Vector2(position.X, position.Y + centeredY), Color::White());
}
}
void CheckBox::OnClickInput(const RoutedEventArgs& args, const std::shared_ptr<WindowInputClickEvent>& theEvent)
{
if (!theEvent->IsHandled() && theEvent->IsBegin() && !theEvent->IsRepeat())
{
theEvent->Handled();
SetIsChecked(!m_isChecked);
}
}
Vector2 CheckBox::ArrangeOverride(const Vector2& finalSize)
{
return finalSize;
}
Vector2 CheckBox::MeasureOverride(const Vector2& availableSize)
{
Vector2 size;
if (m_text.size() > 0)
{
auto fontInfo = m_font->GetAtlasBitmapFont();
auto measured = fontInfo.MeasureString(m_text.c_str(), 0, m_text.size());
size = Vector2(measured.X, fontInfo.LineSpacing());
}
const Point2 sizeTex1 = m_texChecked.IsValid() ? m_texChecked.GetSize() : Point2();
const Point2 sizeTex2 = m_texUnchecked.IsValid() ? m_texChecked.GetSize() : Point2();
const Point2 sizeTex(std::max(sizeTex1.X, sizeTex2.X), std::max(sizeTex1.Y, sizeTex2.Y));
size.X += sizeTex.X;
size.Y = std::max(size.Y, static_cast<float>(sizeTex.Y));
return size;
}
}
}
| 33.074257 | 150 | 0.643616 | [
"render"
] |
55f26ff65d77e4c02cf4da1497f7d6b81cc7f7b9 | 1,156 | hpp | C++ | libiop/bcs/common_bcs_parameters.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/bcs/common_bcs_parameters.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/bcs/common_bcs_parameters.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | /**@file
*****************************************************************************
Specialized IOP that implements the BCS16 transformation.
*****************************************************************************
* @author This file is part of libiop (see AUTHORS)
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LIBIOP_SNARK_COMMON_COMMON_BCS_PARARMETERS_HPP_
#define LIBIOP_SNARK_COMMON_COMMON_BCS_PARARMETERS_HPP_
#include <algorithm>
#include <cstddef>
#include <type_traits>
#include <map>
#include <vector>
#include "libiop/bcs/bcs_common.hpp"
#include "libiop/bcs/hashing/hash_enum.hpp"
#include "libiop/bcs/hashing/hashing.hpp"
#include "libiop/bcs/hashing/blake2b.hpp"
#include "libiop/bcs/pow.hpp"
namespace libiop {
template<typename FieldT, typename MT_root_hash>
bcs_transformation_parameters<FieldT, MT_root_hash> default_bcs_params(
const bcs_hash_type hash_type, const size_t security_parameter);
} // namespace libiop
#include "libiop/bcs/common_bcs_parameters.tcc"
#endif // LIBIOP_SNARK_COMMON_COMMON_BCS_PARARMETERS_HPP_
| 34 | 79 | 0.639273 | [
"vector"
] |
55fe75e787b99ca1dc6bc579e6d33a6370ea929f | 1,279 | cpp | C++ | Hackerrank/Organizing_Container.cpp | parth1614/DSA_Questions | 7083952eb310a21f7e30267efa437dfbb8c0f88f | [
"MIT"
] | null | null | null | Hackerrank/Organizing_Container.cpp | parth1614/DSA_Questions | 7083952eb310a21f7e30267efa437dfbb8c0f88f | [
"MIT"
] | null | null | null | Hackerrank/Organizing_Container.cpp | parth1614/DSA_Questions | 7083952eb310a21f7e30267efa437dfbb8c0f88f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void swap(vector<vector<int>>& container){
vector<int> sum(container.size(),0);
vector<int> type(container.size(),0);
int flag;
//long sum = 0;
for(int i=0;i<container.size();++i){
for(int j=0;j<container.size();++j){
sum[i] = sum[i] + container[i][j]; //Adding rows in single cell
type[j] = type[j] + container[i][j]; //adding columns in single cell
}
}
sort(sum.begin(),sum.end());
sort(type.begin(),type.end());
for(int i=0;i<container.size();++i){
if(sum[i]!=type[i]){
flag = 0;
}
else {
flag = 1;
}
}
if(flag==0){
cout<<"Impossible"<<endl;
}
else if(flag==1){
cout<<"Possible"<<endl;
}
}
int main(){
int q;
cin>>q;
while(q--){
vector<vector<int>> container;
int n;
cin>>n;
for(int i=0;i<n;++i){
vector<int> temp;
for(int j=0;j<n;++j){
int val;
cin>>val;
temp.push_back(val);
}
container.push_back(temp);
temp.clear();
}
swap(container);
}
}
| 22.051724 | 81 | 0.44097 | [
"vector"
] |
55ff9e28c65a47ee775fa4957d7915c16f420887 | 21,572 | cc | C++ | gazebo/gui/model/JointCreationDialog_TEST.cc | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-07-14T19:36:51.000Z | 2020-04-01T06:47:59.000Z | gazebo/gui/model/JointCreationDialog_TEST.cc | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-20T21:04:49.000Z | 2017-10-19T19:32:38.000Z | gazebo/gui/model/JointCreationDialog_TEST.cc | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015-2016 Open Source Robotics Foundation
*
* 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 "gazebo/gui/ConfigWidget.hh"
#include "gazebo/gui/model/ModelEditorEvents.hh"
#include "gazebo/gui/model/JointCreationDialog.hh"
#include "gazebo/gui/model/JointCreationDialog_TEST.hh"
#include "test_config.h"
/////////////////////////////////////////////////
void JointCreationDialog_TEST::Type()
{
// Create a joint maker
auto jointMaker = new gazebo::gui::JointMaker();
QVERIFY(jointMaker != NULL);
// Create a dialog
auto jointCreationDialog = new gazebo::gui::JointCreationDialog(jointMaker);
QVERIFY(jointCreationDialog != NULL);
// Open it
jointCreationDialog->Open(gazebo::gui::JointMaker::JOINT_HINGE);
QVERIFY(jointCreationDialog->isVisible());
// Check there are 8 radio buttons for joint types
auto radioButtons = jointCreationDialog->findChildren<QRadioButton *>();
QCOMPARE(radioButtons.size(), 8);
// Get the config widget
auto configWidget =
jointCreationDialog->findChild<gazebo::gui::ConfigWidget *>();
QVERIFY(configWidget != NULL);
// Check that only the correct button is checked (Revolute - 1)
for (int i = 0; i < radioButtons.size(); ++i)
{
if (i == 1)
QVERIFY(radioButtons[i]->isChecked());
else
QVERIFY(!radioButtons[i]->isChecked());
}
// Check there's one joint axis widget
QVERIFY(configWidget->WidgetVisible("axis1"));
QVERIFY(!configWidget->WidgetVisible("axis2"));
// Set type to ball joint
radioButtons[6]->click();
// Check that only the correct button is checked (Ball - 6)
for (int i = 0; i < radioButtons.size(); ++i)
{
if (i == 6)
QVERIFY(radioButtons[i]->isChecked());
else
QVERIFY(!radioButtons[i]->isChecked());
}
// Check there's no joint axis widget
QVERIFY(!configWidget->WidgetVisible("axis1"));
QVERIFY(!configWidget->WidgetVisible("axis2"));
// Set type to Revolute 2 joint
radioButtons[2]->click();
// Check that only the correct button is checked (Revolute 2 - 2)
for (int i = 0; i < radioButtons.size(); ++i)
{
if (i == 2)
QVERIFY(radioButtons[i]->isChecked());
else
QVERIFY(!radioButtons[i]->isChecked());
}
// Check there are both joint axis widgets
QVERIFY(configWidget->WidgetVisible("axis1"));
QVERIFY(configWidget->WidgetVisible("axis2"));
delete jointCreationDialog;
delete jointMaker;
}
/////////////////////////////////////////////////
void JointCreationDialog_TEST::Links()
{
// Create a joint maker
auto jointMaker = new gazebo::gui::JointMaker();
QVERIFY(jointMaker != NULL);
// Add links to list
std::vector<std::string> scopedLinkNames =
{"model::link1", "model::link2", "model::link3",
"model::nested_model::link4"};
std::vector<std::string> linkNames;
for (auto scopedName : scopedLinkNames)
{
gazebo::gui::model::Events::linkInserted(scopedName);
linkNames.push_back(scopedName.substr(scopedName.find("::")+2));
}
// Create a dialog
auto jointCreationDialog = new gazebo::gui::JointCreationDialog(jointMaker);
QVERIFY(jointCreationDialog != NULL);
// Open it
jointCreationDialog->Open(gazebo::gui::JointMaker::JOINT_HINGE);
QVERIFY(jointCreationDialog->isVisible());
// Get the config widget
auto configWidget =
jointCreationDialog->findChild<gazebo::gui::ConfigWidget *>();
QVERIFY(configWidget != NULL);
// Get the parent and child widgets
auto parentWidget = configWidget->ConfigChildWidgetByName("parentCombo");
QVERIFY(parentWidget != NULL);
auto childWidget = configWidget->ConfigChildWidgetByName("childCombo");
QVERIFY(childWidget != NULL);
// Get parent and child combo boxes
auto parentCombo = parentWidget->findChild<QComboBox *>();
QVERIFY(parentCombo != NULL);
auto childCombo = childWidget->findChild<QComboBox *>();
QVERIFY(childCombo != NULL);
// Check that each combo box has an empty option plus all link options
int linkSize = static_cast<int>(linkNames.size());
QVERIFY(parentCombo->count() == 1 + linkSize);
QVERIFY(childCombo->count() == 1 + linkSize);
for (int i = 1; i < parentCombo->count(); ++i)
{
QVERIFY(parentCombo->itemText(i).toStdString() == linkNames[i-1]);
QVERIFY(childCombo->itemText(i).toStdString() == linkNames[i-1]);
}
// Check there are no links selected yet
QVERIFY(configWidget->EnumWidgetValue("parentCombo") == "");
QVERIFY(configWidget->EnumWidgetValue("childCombo") == "");
// Check only parent is enabled
QVERIFY(!configWidget->WidgetReadOnly("parentCombo"));
QVERIFY(configWidget->WidgetReadOnly("childCombo"));
QVERIFY(configWidget->WidgetReadOnly("axis1"));
QVERIFY(configWidget->WidgetReadOnly("axis2"));
QVERIFY(configWidget->WidgetReadOnly("align"));
QVERIFY(configWidget->WidgetReadOnly("joint_pose"));
QVERIFY(configWidget->WidgetReadOnly("relative_pose"));
// Get push buttons (reset, cancel, create)
auto pushButtons = jointCreationDialog->findChildren<QPushButton *>();
QCOMPARE(pushButtons.size(), 3);
// Check that create button is disabled
for (auto button : pushButtons)
QCOMPARE(button->isEnabled(), button->text() != "Create");
// Set parent from 3D scene
jointCreationDialog->SetParent(scopedLinkNames[0]);
// Check that the parent link was selected
QVERIFY(configWidget->EnumWidgetValue("parentCombo") == linkNames[0]);
QVERIFY(configWidget->EnumWidgetValue("childCombo") == "");
// Check that now child is also enabled
QVERIFY(!configWidget->WidgetReadOnly("parentCombo"));
QVERIFY(!configWidget->WidgetReadOnly("childCombo"));
QVERIFY(configWidget->WidgetReadOnly("axis1"));
QVERIFY(configWidget->WidgetReadOnly("axis2"));
QVERIFY(configWidget->WidgetReadOnly("align"));
QVERIFY(configWidget->WidgetReadOnly("joint_pose"));
QVERIFY(configWidget->WidgetReadOnly("relative_pose"));
// Check that create button is disabled
for (auto button : pushButtons)
QCOMPARE(button->isEnabled(), button->text() != "Create");
// Set child from 3D scene
jointCreationDialog->SetChild(scopedLinkNames[1]);
// Check that the child link was selected
QVERIFY(configWidget->EnumWidgetValue("parentCombo") == linkNames[0]);
QVERIFY(configWidget->EnumWidgetValue("childCombo") == linkNames[1]);
// Check that now all widgets are enabled
QVERIFY(!configWidget->WidgetReadOnly("parentCombo"));
QVERIFY(!configWidget->WidgetReadOnly("childCombo"));
QVERIFY(!configWidget->WidgetReadOnly("axis1"));
QVERIFY(!configWidget->WidgetReadOnly("axis2"));
QVERIFY(!configWidget->WidgetReadOnly("align"));
QVERIFY(!configWidget->WidgetReadOnly("joint_pose"));
QVERIFY(!configWidget->WidgetReadOnly("relative_pose"));
for (auto button : pushButtons)
QVERIFY(button->isEnabled());
// Get swap button
auto swapButton =
jointCreationDialog->findChild<QToolButton *>("JointCreationSwapButton");
QVERIFY(swapButton != NULL);
// Trigger swap
swapButton->click();
// Check that the parent link was selected
QVERIFY(configWidget->EnumWidgetValue("parentCombo") == linkNames[1]);
QVERIFY(configWidget->EnumWidgetValue("childCombo") == linkNames[0]);
// Set child from dialog, same as parent
childCombo->setCurrentIndex(1);
// Check that the child link was selected
QVERIFY(configWidget->EnumWidgetValue("parentCombo") == linkNames[1]);
QVERIFY(configWidget->EnumWidgetValue("childCombo") == linkNames[1]);
// Check that create button is disabled
for (auto button : pushButtons)
QCOMPARE(button->isEnabled(), button->text() != "Create");
// Set parent from dialog, valid value
parentCombo->setCurrentIndex(2);
// Check that the child link was selected
QVERIFY(configWidget->EnumWidgetValue("parentCombo") == linkNames[2]);
QVERIFY(configWidget->EnumWidgetValue("childCombo") == linkNames[1]);
// Set parent from dialog, valid value
childCombo->setCurrentIndex(3);
// Check that the child link was selected
QVERIFY(configWidget->EnumWidgetValue("parentCombo") == linkNames[2]);
QVERIFY(configWidget->EnumWidgetValue("childCombo") == linkNames[3]);
// Check that all buttons are enabled
for (auto button : pushButtons)
QVERIFY(button->isEnabled());
// Trigger create
auto createButton = jointCreationDialog->findChild<QPushButton *>(
"JointCreationCreateButton");
QVERIFY(createButton != NULL);
createButton->click();
// Check dialog was closed
QVERIFY(!jointCreationDialog->isVisible());
delete jointCreationDialog;
delete jointMaker;
}
/////////////////////////////////////////////////
void JointCreationDialog_TEST::Axis()
{
// Create a joint maker
auto jointMaker = new gazebo::gui::JointMaker();
QVERIFY(jointMaker != NULL);
// Add links to list
std::vector<std::string> scopedLinkNames =
{"model::link1", "model::link2", "model::link3"};
std::vector<std::string> linkNames;
for (auto scopedName : scopedLinkNames)
{
gazebo::gui::model::Events::linkInserted(scopedName);
linkNames.push_back(scopedName.substr(scopedName.find("::")+2));
}
// Create a dialog
auto jointCreationDialog = new gazebo::gui::JointCreationDialog(jointMaker);
QVERIFY(jointCreationDialog != NULL);
// Open it
jointCreationDialog->Open(gazebo::gui::JointMaker::JOINT_HINGE2);
QVERIFY(jointCreationDialog->isVisible());
// Get push buttons (reset, cancel, create)
auto pushButtons = jointCreationDialog->findChildren<QPushButton *>();
QCOMPARE(pushButtons.size(), 3);
// Get the config widget
auto configWidget =
jointCreationDialog->findChild<gazebo::gui::ConfigWidget *>();
QVERIFY(configWidget != NULL);
// Set child and parent from 3D scene
jointCreationDialog->SetParent(scopedLinkNames[0]);
jointCreationDialog->SetChild(scopedLinkNames[1]);
// Check that all widgets are enabled
QVERIFY(!configWidget->WidgetReadOnly("parentCombo"));
QVERIFY(!configWidget->WidgetReadOnly("childCombo"));
QVERIFY(!configWidget->WidgetReadOnly("axis1"));
QVERIFY(!configWidget->WidgetReadOnly("axis2"));
QVERIFY(!configWidget->WidgetReadOnly("align"));
QVERIFY(!configWidget->WidgetReadOnly("joint_pose"));
QVERIFY(!configWidget->WidgetReadOnly("relative_pose"));
for (auto button : pushButtons)
QVERIFY(button->isEnabled());
// Check that both joint axis widgets are visible
QVERIFY(configWidget->WidgetVisible("axis1"));
QVERIFY(configWidget->WidgetVisible("axis2"));
// Check default values
QVERIFY(configWidget->Vector3dWidgetValue("axis1") ==
ignition::math::Vector3d::UnitX);
QVERIFY(configWidget->Vector3dWidgetValue("axis2") ==
ignition::math::Vector3d::UnitY);
// Set an axis to be zero
auto axis1Widget = configWidget->ConfigChildWidgetByName("axis1");
QVERIFY(axis1Widget != NULL);
auto axis1Spins = axis1Widget->findChildren<QDoubleSpinBox *>();
QVERIFY(axis1Spins.size() == 3u);
axis1Spins[0]->setValue(0.0);
QTest::keyClick(axis1Spins[1], Qt::Key_Enter);
// Check that create button is disabled
for (auto button : pushButtons)
QCOMPARE(button->isEnabled(), button->text() != "Create");
// Set it back to a valid value
axis1Spins[2]->setValue(1.0);
QTest::keyClick(axis1Spins[1], Qt::Key_Enter);
// Check that all buttons are enabled again
for (auto button : pushButtons)
QVERIFY(button->isEnabled());
// Check new value
QVERIFY(configWidget->Vector3dWidgetValue("axis1") ==
ignition::math::Vector3d::UnitZ);
QVERIFY(configWidget->Vector3dWidgetValue("axis2") ==
ignition::math::Vector3d::UnitY);
// Get reset button
auto resetButton =
jointCreationDialog->findChild<QPushButton *>("JointCreationResetButton");
QVERIFY(resetButton != NULL);
// Trigger reset
resetButton->click();
// Check widgets were reset
QVERIFY(configWidget->Vector3dWidgetValue("axis1") ==
ignition::math::Vector3d::UnitX);
QVERIFY(configWidget->Vector3dWidgetValue("axis2") ==
ignition::math::Vector3d::UnitY);
delete jointCreationDialog;
delete jointMaker;
}
/////////////////////////////////////////////////
void JointCreationDialog_TEST::Align()
{
// Create a joint maker
auto jointMaker = new gazebo::gui::JointMaker();
QVERIFY(jointMaker != NULL);
// Add links to list
std::vector<std::string> scopedLinkNames =
{"model::link1", "model::link2", "model::link3"};
std::vector<std::string> linkNames;
for (auto scopedName : scopedLinkNames)
{
gazebo::gui::model::Events::linkInserted(scopedName);
linkNames.push_back(scopedName.substr(scopedName.find("::")+2));
}
// Create a dialog
auto jointCreationDialog = new gazebo::gui::JointCreationDialog(jointMaker);
QVERIFY(jointCreationDialog != NULL);
// Open it
jointCreationDialog->Open(gazebo::gui::JointMaker::JOINT_HINGE2);
QVERIFY(jointCreationDialog->isVisible());
// Get push buttons (reset, cancel, create)
auto pushButtons = jointCreationDialog->findChildren<QPushButton *>();
QCOMPARE(pushButtons.size(), 3);
// Get the config widget
auto configWidget =
jointCreationDialog->findChild<gazebo::gui::ConfigWidget *>();
QVERIFY(configWidget != NULL);
// Set child and parent from 3D scene
jointCreationDialog->SetParent(scopedLinkNames[0]);
jointCreationDialog->SetChild(scopedLinkNames[1]);
// Check that all widgets are enabled
QVERIFY(!configWidget->WidgetReadOnly("parentCombo"));
QVERIFY(!configWidget->WidgetReadOnly("childCombo"));
QVERIFY(!configWidget->WidgetReadOnly("axis1"));
QVERIFY(!configWidget->WidgetReadOnly("axis2"));
QVERIFY(!configWidget->WidgetReadOnly("align"));
QVERIFY(!configWidget->WidgetReadOnly("joint_pose"));
QVERIFY(!configWidget->WidgetReadOnly("relative_pose"));
for (auto button : pushButtons)
QVERIFY(button->isEnabled());
// Get align widget and check it has all the buttons
auto alignWidget = configWidget->ConfigChildWidgetByName("align");
QVERIFY(alignWidget != NULL);
auto alignButtons = alignWidget->findChildren<QToolButton *>();
QVERIFY(alignButtons.size() == 9u);
auto alignReverseCheckboxes = alignWidget->findChildren<QCheckBox *>();
QVERIFY(alignReverseCheckboxes.size() == 3u);
// Check that only one button per axis can be checked at a time
alignButtons[0]->click();
QVERIFY(alignButtons[0]->isChecked());
QVERIFY(!alignButtons[1]->isChecked());
QVERIFY(!alignButtons[2]->isChecked());
alignButtons[1]->click();
QVERIFY(!alignButtons[0]->isChecked());
QVERIFY(alignButtons[1]->isChecked());
QVERIFY(!alignButtons[2]->isChecked());
// Check that checked button is toggled on click
alignButtons[1]->click();
QVERIFY(!alignButtons[0]->isChecked());
QVERIFY(!alignButtons[1]->isChecked());
QVERIFY(!alignButtons[2]->isChecked());
// Check a button per axis and check they are checked at the same time
alignButtons[0]->click();
alignButtons[3]->click();
alignButtons[6]->click();
QVERIFY(alignButtons[0]->isChecked());
QVERIFY(alignButtons[3]->isChecked());
QVERIFY(alignButtons[6]->isChecked());
// Check that any number of Reverse checkboxes can be active at the same time.
alignReverseCheckboxes[0]->click();
QVERIFY(alignReverseCheckboxes[0]->isChecked());
QVERIFY(!alignReverseCheckboxes[1]->isChecked());
QVERIFY(!alignReverseCheckboxes[2]->isChecked());
alignReverseCheckboxes[1]->click();
QVERIFY(alignReverseCheckboxes[0]->isChecked());
QVERIFY(alignReverseCheckboxes[1]->isChecked());
QVERIFY(!alignReverseCheckboxes[2]->isChecked());
alignReverseCheckboxes[2]->click();
QVERIFY(alignReverseCheckboxes[0]->isChecked());
QVERIFY(alignReverseCheckboxes[1]->isChecked());
QVERIFY(alignReverseCheckboxes[2]->isChecked());
// Check that all buttons are disabled when the link is changed
auto parentWidget = configWidget->ConfigChildWidgetByName("parentCombo");
QVERIFY(parentWidget != NULL);
auto parentCombo = parentWidget->findChild<QComboBox *>();
QVERIFY(parentCombo != NULL);
parentCombo->setCurrentIndex(2);
for (auto button : alignButtons)
QVERIFY(!button->isChecked());
for (auto checkbox : alignReverseCheckboxes)
QVERIFY(!checkbox->isChecked());
// Try aligning links then updating relative pose and see if
// the align widgets are unchecked.
alignButtons[0]->click();
QVERIFY(alignButtons[0]->isChecked());
alignReverseCheckboxes[0]->click();
QVERIFY(alignReverseCheckboxes[0]->isChecked());
// simulate an align pose update callback
jointCreationDialog->UpdateRelativePose(ignition::math::Pose3d());
// Set relative pose and verify
ignition::math::Pose3d pose(1, -0.2, 3.3, 0.1, -0.2, 0);
jointCreationDialog->UpdateRelativePose(pose);
QVERIFY(configWidget->PoseWidgetValue("relative_pose") == pose);
// Check that all buttons are disabled when the pose has changed
for (auto button : alignButtons)
QVERIFY(!button->isChecked());
for (auto checkbox : alignReverseCheckboxes)
QVERIFY(!checkbox->isChecked());
delete jointCreationDialog;
delete jointMaker;
}
/////////////////////////////////////////////////
void JointCreationDialog_TEST::RelativePose()
{
// Create a joint maker
auto jointMaker = new gazebo::gui::JointMaker();
QVERIFY(jointMaker != NULL);
// Add links to list
std::vector<std::string> scopedLinkNames =
{"model::link1", "model::link2", "model::link3"};
std::vector<std::string> linkNames;
for (auto scopedName : scopedLinkNames)
{
gazebo::gui::model::Events::linkInserted(scopedName);
linkNames.push_back(scopedName.substr(scopedName.find("::")+2));
}
// Create a dialog
auto jointCreationDialog = new gazebo::gui::JointCreationDialog(jointMaker);
QVERIFY(jointCreationDialog != NULL);
// Open it
jointCreationDialog->Open(gazebo::gui::JointMaker::JOINT_HINGE2);
QVERIFY(jointCreationDialog->isVisible());
// Get push buttons (reset, cancel, create)
auto pushButtons = jointCreationDialog->findChildren<QPushButton *>();
QCOMPARE(pushButtons.size(), 3);
// Get the config widget
auto configWidget =
jointCreationDialog->findChild<gazebo::gui::ConfigWidget *>();
QVERIFY(configWidget != NULL);
// Check the default value
QVERIFY(configWidget->PoseWidgetValue("relative_pose") ==
ignition::math::Pose3d::Zero);
// Set child and parent from 3D scene
jointCreationDialog->SetParent(scopedLinkNames[0]);
jointCreationDialog->SetChild(scopedLinkNames[1]);
// Check that all widgets are enabled
QVERIFY(!configWidget->WidgetReadOnly("parentCombo"));
QVERIFY(!configWidget->WidgetReadOnly("childCombo"));
QVERIFY(!configWidget->WidgetReadOnly("axis1"));
QVERIFY(!configWidget->WidgetReadOnly("axis2"));
QVERIFY(!configWidget->WidgetReadOnly("align"));
QVERIFY(!configWidget->WidgetReadOnly("joint_pose"));
QVERIFY(!configWidget->WidgetReadOnly("relative_pose"));
for (auto button : pushButtons)
QVERIFY(button->isEnabled());
// Update the relative pose from 3D
ignition::math::Pose3d pose(1, -0.2, 3.3, 0.1, -0.2, 0);
jointCreationDialog->UpdateRelativePose(pose);
// Check the widget was updated
QVERIFY(configWidget->PoseWidgetValue("relative_pose") == pose);
// Get relative pose widget and check it has all the spins
auto relPosWidget = configWidget->ConfigChildWidgetByName("relative_pose");
QVERIFY(relPosWidget != NULL);
auto spins = relPosWidget->findChildren<QDoubleSpinBox *>();
QVERIFY(spins.size() == 6u);
// Change spin value and check it reflects on the widget
spins[0]->setValue(100.0);
QTest::keyClick(spins[1], Qt::Key_Enter);
// Check the relative pose was reset
QVERIFY(configWidget->PoseWidgetValue("relative_pose") ==
ignition::math::Pose3d(100.0, pose.Pos().Y(), pose.Pos().Z(),
pose.Rot().Roll(), pose.Rot().Pitch(), pose.Rot().Yaw()));
delete jointCreationDialog;
delete jointMaker;
}
/////////////////////////////////////////////////
void JointCreationDialog_TEST::Cancel()
{
// Create a joint maker
auto jointMaker = new gazebo::gui::JointMaker();
QVERIFY(jointMaker != NULL);
// Add links to list
std::vector<std::string> scopedLinkNames =
{"model::link1", "model::link2", "model::link3"};
std::vector<std::string> linkNames;
for (auto scopedName : scopedLinkNames)
{
gazebo::gui::model::Events::linkInserted(scopedName);
linkNames.push_back(scopedName.substr(scopedName.find("::")+2));
}
// Create a dialog
auto jointCreationDialog = new gazebo::gui::JointCreationDialog(jointMaker);
QVERIFY(jointCreationDialog != NULL);
// Open it
jointCreationDialog->Open(gazebo::gui::JointMaker::JOINT_HINGE2);
QVERIFY(jointCreationDialog->isVisible());
// Trigger cancel
auto cancelButton = jointCreationDialog->findChild<QPushButton *>(
"JointCreationCancelButton");
QVERIFY(cancelButton != NULL);
cancelButton->click();
// Check dialog was closed
QVERIFY(!jointCreationDialog->isVisible());
delete jointCreationDialog;
delete jointMaker;
}
// Generate a main function for the test
QTEST_MAIN(JointCreationDialog_TEST)
| 33.758998 | 80 | 0.706981 | [
"vector",
"model",
"3d"
] |
55ffcc6a36cabe1c5998d3d5485c04369716edf7 | 135,733 | cpp | C++ | src/clistats.cpp | rjp/clistats | 8055d15a7cbab4de848659ee8bf9cbfeceb155b3 | [
"MIT"
] | null | null | null | src/clistats.cpp | rjp/clistats | 8055d15a7cbab4de848659ee8bf9cbfeceb155b3 | [
"MIT"
] | null | null | null | src/clistats.cpp | rjp/clistats | 8055d15a7cbab4de848659ee8bf9cbfeceb155b3 | [
"MIT"
] | null | null | null |
/**
* Computes command line interface statistics for a stream of delimited input numbers.
* @author Daniel Pulido <dpmcmlxxvi@gmail.com>
* @copyright Copyright (c) 2014 Daniel Pulido <dpmcmlxxvi@gmail.com>
* @file clistats.cpp
* @license MIT License (http://opensource.org/licenses/MIT)
*/
/* Standard headers */
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <cstdlib>
#include <string>
#include <utility>
#include <vector>
// macros for logging message
#define LOG_MESSAGE(level, message) \
{ \
if (level <= Logger::logLevel) \
{ \
std::stringstream msg; \
msg << message << std::endl; \
Logger::log(level) << msg.str(); \
} \
}
/**
* @struct ApplicationProperties
* @brief Application wide properties
*/
struct ApplicationProperties
{
/**
* Application version
* @returns Version string
*/
static
std::string
version()
{
return ApplicationProperties::VERSION_MAJOR + "." +
ApplicationProperties::VERSION_MINOR + "." +
ApplicationProperties::VERSION_PATCH;
}
static std::string NAME;
static std::string AUTHOR;
static std::string VERSION_MAJOR;
static std::string VERSION_MINOR;
static std::string VERSION_PATCH;
};
std::string ApplicationProperties::NAME = "clistats";
std::string ApplicationProperties::AUTHOR = "dpmcmlxxvi@gmail.com";
std::string ApplicationProperties::VERSION_MAJOR = "1";
std::string ApplicationProperties::VERSION_MINOR = "0";
std::string ApplicationProperties::VERSION_PATCH = "0";
/**
* @struct Logger
* @brief Simple logger
* @details Should be invoked via macro "LOG_MESSAGE(Logger::Level, "message");"
*/
struct Logger
{
/**
* @enum Logger level
*/
struct Level
{
/**
* Level type
*/
enum Type
{
FATAL = 0,
ERROR,
WARNING,
INFO,
DEBUG,
DETAIL
};
};
/**
* Log message. Logger level is written to current stream line then returns stream. User is expected to add EOL.
* @return Logging stream corresponding to log level
*/
static std::ostream & log(Logger::Level::Type level)
{
std::string label = (level==Logger::Level::FATAL ? "FATAL":
(level==Logger::Level::ERROR ? "ERROR":
(level==Logger::Level::WARNING? "WARNING":
(level==Logger::Level::INFO ? "INFO":
(level==Logger::Level::DEBUG ? "DEBUG":"DETAIL")))));
std::ostream * os = (level <= Logger::Level::WARNING ? &std::cerr : &std::cout);
*os << std::left << std::setw(7) << label << ": ";
return *os;
}
/**
* Global application log level
*/
static Level::Type logLevel;
};
// Initialize static variable
Logger::Level::Type Logger::logLevel = Logger::Level::FATAL;
/**
* @class StringParser
* @brief String parsing methods
*/
class StringParser
{
public:
/**
* Parse number to string
* @param[in] value Value to parse
* @param[in] isScientific True of string format should be scientific otherwise format is fixed
* @return String representation of input value
*/
template <class T>
static
std::string
parseNumber(T value,
bool isScientific = false)
{
// Check for NaN to consistently return "nan"
volatile double d = (double)value;
if (d != d) return "nan";
std::string entry;
std::stringstream parser;
parser << (isScientific ? std::scientific : std::fixed) << value;
parser >> entry;
return entry;
}
/**
* Parse statistic to string. If statistic was based on a count of zero then returns nan string.
* @param[in] count Number of data points on which statistic was based on.
* @param[in] value Value to parse
* @param[in] nan String to return is statistic was not based on non-zero counts
* @param[in] isScientific True of string format should be scientific otherwise format is fixed
* @return String representation of input statistic
*/
template <class T>
static
std::string
parseStatistic(int count,
T value,
std::string nan = "nan",
bool isScientific = false)
{
if (count <= 0) return nan;
return StringParser::parseNumber<T>(value, isScientific);
}
/**
* Replace first n occurences of src with dst in content
* @param[out] content String to replace content of
* @param[in] src Source string to search for and replace with dst
* @param[in] dst Destination string to replace src with
* @param[in] n Number of times with which to replace src
*/
static
void
replacen(std::string & content,
std::string const & src,
std::string const & dst,
unsigned int const n = 1)
{
if(src.empty()) return;
unsigned int count = 0;
unsigned int pos = 0;
while((pos = content.find(src, pos)) != std::string::npos)
{
content.replace(pos, src.length(), dst);
pos += dst.length();
if (++count == n) return;
}
}
/**
* Convert string to template type value
* @param[in] src Source string
* @param[out] dst Destination value
* @return True if parsing successful otherwise false
*/
template <class T>
static
bool
toValue(std::string const & src,
T & dst)
{
std::istringstream parser(src.c_str());
parser >> dst;
if (!parser) return false;
return (parser.rdbuf()->in_avail() == 0);
}
/**
* Trim leading and trailing white spaces
* @param[in] src Source string
* @return Trimmed string
*/
static
const std::string
trim(const std::string & src)
{
std::string::size_type startpos = src.find_first_not_of(" \t");
std::string::size_type endpos = src.find_last_not_of(" \t");
return (std::string::npos==startpos ? "" : src.substr(startpos,endpos-startpos+1));
}
/**
* Update width with current value's string size
* @param[in] value Value to parse
* @param[inout] width Width to update
*/
template <class T>
static
void
updateWidthNumber(T value,
long & width)
{
std::string entry = StringParser::parseNumber<T>(value);
width = (width < (long) entry.size() ? entry.size() : width);
}
/**
* Update width with current value's string size
* @param[in] value Value to parse
* @param[inout] width Width to update
*/
static
void
updateWidthString(std::string value,
long & width)
{
std::string entry = value;
width = (width < (long) entry.size() ? entry.size() : width);
}
};
/**
* @class StringSplitter
* @brief Splits a source string into tokens given a delimiter character
*/
class StringSplitter
{
public:
/**
* Subscript type for use with operator[]
*/
typedef std::vector<std::string>::size_type size_type;
public:
/**
* Create StringSplitter
*/
StringSplitter()
{
}
/**
* Create and initialize a new StringSplitter
* @param[in] src Source string to split
* @param[in] delim The delimiter to split the string around
* @param[in] duplicate If true then duplicate sequential delimiters are treated as one delimiter
* @param[in] mask Boolean mask of tokens to keep. If token index is false in mask or is out of range then that token not discarded.
*/
StringSplitter(std::string const & src,
std::string const & delim,
bool duplicate = false,
std::vector<bool> const & mask = std::vector<bool>())
{
this->initialize(src, delim, duplicate, mask);
}
/**
* Retrieve the token at the specified index
* @param[in] index Token index
* @return The token at the specified index
*/
std::string const &
at(size_type index) const
{
return this->_tokens.at(index);
}
/**
* Get reference to underlying split string vector
* @return Vector of split string
*/
const std::vector<std::string> &
get() const
{
return this->_tokens;
}
/**
* Initialize splitter with a new source and delimiter
* @param[in] src The string to split
* @param[in] delim The delimiter to split the string around
* @param[in] duplicate If true then duplicate sequential delimiters are treated as one delimiter
* @param[in] mask Boolean mask of tokens to keep. If token index is false in mask or is out of range then that token not discarded.
*/
void
initialize(std::string const & src,
std::string const & delim,
bool duplicate = false,
std::vector<bool> const & mask = std::vector<bool>())
{
std::vector<std::string> tokens;
std::string::size_type startpos = 0;
std::string::size_type endpos = 0;
unsigned int index = 0;
bool doParse = true;
while (doParse)
{
endpos = src.find(delim, startpos);
// Check delimiter is not duplicate
bool isDuplicate = (duplicate && (endpos == startpos));
if (!isDuplicate)
{
// Check entry is not masked out
bool isMasked = (mask.size()!=0) && (( (index >= mask.size()) || (!mask.at(index)) ));
if (!isMasked)
{
tokens.push_back(src.substr(startpos, endpos - startpos));
}
index++;
}
// We just copied the last token
if (endpos == std::string::npos) break;
// Exclude the delimiter in the next search
startpos = endpos + delim.size();
}
this->_tokens.swap(tokens);
}
/**
* Retrieve the number of split tokens
* @return The number of split tokens
*/
size_type
size() const
{
return this->_tokens.size();
}
/**
* Retrieve all the tokens
* @return Vector of split tokens
*/
std::vector<std::string>
tokens() const
{
return this->_tokens;
}
/**
* Convert string to template type value
* @param[in] index Token index
* @param[out] dst Destination value
* @return True if parsing successful otherwise false
*/
template <class T>
bool
toValue(size_type index,
T & dst) const
{
return StringParser::toValue<T>(this->at(index), dst);
}
/**
* Convert string to template type value
* @param[in] index Token index
* @param[out] dst Destination value
* @return True if parsing successful otherwise false
* @throws std::runtime_error if unable to parse string
*/
template <class T>
T
toValue(size_type index) const
{
T & dst;
bool isGood = this->toValue<T>(this->at(index), dst);
if (!isGood) throw std::runtime_error("Unable to parse string = " + this->at(index));
}
/**
* Convert string to range of integers. Expected format is
* "A:B". If a range is found (e.g., 3:5) then the array
* of numbers from the first to the second are returned
* (e.g., [3,4,5]). If no range delimiter is found then the string
* is assumed to be a single integer and parsing is attempted.
* @param[in] src Source string
* @param[out] dst Destination vector to which integers are appended
* @param[in] delim Optional range delimiter string. Default = ":"
* @return True if parsing succeeded otherwise false
*/
static
bool
toIntegers(std::string const & src,
std::vector<int> & dst,
std::string delim = ":")
{
int start = 0;
int stop = 0;
StringSplitter splitter(src, delim);
if (splitter.size() == 1)
{
// If one token then try to parse and set start = stop
bool good = StringParser::toValue<int>(splitter.at(0), start);
if (!good) return false;
stop = start;
}
else if (splitter.size() == 2)
{
// If two tokens then try to parse start and stop
bool goodStart = StringParser::toValue<int>(splitter.at(0), start);
if (!goodStart) return false;
bool goodStop = StringParser::toValue<int>(splitter.at(1), stop);
if (!goodStop) return false;
// Swap so start is before stop
if (stop < start)
{
std::swap(start, stop);
}
}
else
{
// If not 1 or 2 tokens then fail
return false;
}
// Create array of integers
for (int i = start; i < stop+1; i++)
{
dst.push_back(i);
}
return true;
}
private:
/**
* Contains the split tokens
*/
std::vector<std::string> _tokens;
};
/**
* @class FixedSizeCache
* @brief Implements a fixed size cache of sortable items. Once full it is up to the user
* to empty the cache with #reset before adding more items.
* @details As items are added the cache count increases. However, the cache count
* is different from its size. The size is fixed while the count will satisfy
* 0 <= count <= size. In addition, the smallest and largest items are computed.
* Therefore, the comparison operator "<" must be defined for the item type stored.
*/
template <class T>
class FixedSizeCache
{
public:
/**
* @param[in] size Number of cache entries to store before merging with histogram. Must be larger than 0.
*/
FixedSizeCache(int const size = 1000) :
_count(0)
{
this->initialize(size);
}
/**
* Add value to cache
* @throws std::exception if cache is already full
*/
void
add(T value)
{
if (this->full()) throw std::runtime_error("FixedSizeCache::add() called on full cache");
this->_data.at(this->_count) = value;
this->_count++;
}
/**
* Get cache entry
* @throws std::exception if index if out-of-range of cache count
* @return Cache entry at index
*/
T
at(int const index) const
{
if (index >= this->_count) throw std::runtime_error("FixedSizeCache index out-of-range");
return this->_data.at(index);
}
/**
* Get the cache count
* @return Cache count
*/
int
count() const
{
return this->_count;
}
/**
* Test if cache is empty
* @return True of cache is empty otherwise false
*/
bool
empty() const
{
return (this->_count == 0);
}
/**
* Test if cache is full
* @return True if cache is full otherwise false
*/
bool
full() const
{
return (this->_count >= (int)this->_data.size());
}
/**
* Reinitializes the cache sizes and clears the cache count
*/
void
initialize(int const size)
{
this->_data.resize(size, 0);
this->reset();
}
/**
* Largest cache value
* @return Maximum value in cache
* @throws std::exception if cache is empty
*/
T
max() const
{
if (this->empty()) throw std::runtime_error("FixedSizeCache::max() called on empty cache");
return *std::max_element(this->_data.begin(), this->_data.begin() + this->_count);
}
/**
* Smallest cache value
* @return Minimum value in cache
* @throws std::exception if cache is empty
*/
T
min() const
{
if (this->empty()) throw std::runtime_error("FixedSizeCache::min() called on empty cache");
return *std::min_element(this->_data.begin(), this->_data.begin() + this->_count);
}
/**
* Clears the cache but leaves the size the same
*/
void
reset()
{
this->_data.assign(this->_data.size(), 0);
this->_count = 0;
}
private:
/**
* Number of stored values in cache
*/
int _count;
/**
* Cache data
*/
std::vector<T> _data;
};
/**
* @struct DynamicHistogramOptions
*/
struct DynamicHistogramOptions
{
/**
* @param[in] enabled True if histogram is enabled otherwise new data is not added histogram
* @param[in] binCount Number of bins in histogram
* @param[in] cacheSize Size of cache to store points not within histogram bounds
*/
DynamicHistogramOptions(bool enabled = true, int binCount = 100, int cacheSize = 1000) :
binCount(binCount),
cacheSize(cacheSize),
enabled(enabled)
{
}
int binCount;
int cacheSize;
bool enabled;
};
/**
* @class DynamicHistogram
* @brief A 1D frequency histogram with uniform bins that dynamically grows as needed.
* @details A uniform bin histogram and a cache are maintained. Any value added that is not
* contained within the histogram bounds is added to the cache. The histogram and
* cache are merged when the cache is full or when the user invokes any method that
* accesses the histogram. The template parameter should only be a basic numeric data
* type (char, short, int, float, double). The histogram is 0-indexed.
* Can be used as a base class where the #merge method is overridden to implement
* different rules for merging the histogram with the cache.
* @warning
* - The histogram access methods should generally not be called before enough points
* have been added to the histogram. The minimum number of points before calling them
* is dependent on the data's statistics but should be on the order of the cache size
* or there is no more data to be added. If called too soon the histogram #merge function
* is called and may cause a poor initial estimate of the optimal bin width.
* - Internally all calculations are double precision, so setting the template parameter
* to a 64-bit integer will cast all values to a double causing rounding errors.
*/
template <class T>
class DynamicHistogram
{
public:
/**
* @param[in] binCount Number of bins in histogram. Must be larger than 0.
* @param[in] cacheSize Number of cache entries to store before merging with histogram. Must be larger than 0.
*/
DynamicHistogram(DynamicHistogramOptions const & options = DynamicHistogramOptions()) :
_binCount(options.binCount),
_binMax(-std::numeric_limits<double>::max()),
_binMin(std::numeric_limits<double>::max()),
_binWidth(0),
_enabled(options.enabled),
_initialized(false),
_numMerges(0)
{
this->_cache.initialize(options.cacheSize);
this->_frequencies.resize(options.binCount, 0);
this->_temp.resize(options.binCount, 0);
}
/**
*/
virtual
~DynamicHistogram()
{
}
/**
* Add new value to histogram.
* @param[in] value New value to add to histogram.
* @return True if value was added to current histogram. False if the value was added to the cache or the histogram is disabled.
*/
bool
add(T const value)
{
if (!this->_enabled) return false;
double dValue = (double) value;
/* Add new data to cache if histogram is uninitialized or not within its bounds */
if (!(this->_initialized & this->contains_(dValue)))
{
/* If cache is full then merge the cache and the histogram first */
if (this->_cache.full())
{
this->merge();
}
/* Update cache if new value is not in merged histogram */
if (!this->contains_(dValue))
{
this->_cache.add(dValue);
return false;
}
}
/* Add new data to existing histogram */
this->add_(dValue);
return true;
}
/**
* Bin center value for the bin located at given index.
* @param[in] index Bin index
* @return Bin start value.
* @throws std::runtime_exception If histogram could not be initialized.
*/
double
bin(int const index)
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::bin - Histogram could not be initialized.");
return this->bin_(index);
}
/**
* Copy of normalized cumulative distribution function.
* @return Vector of distribution values.
* @throws std::runtime_exception If histogram could not be initialized.
*/
std::vector<double>
cdf()
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::cdf - Histogram could not be initialized.");
std::vector<double> prob = this->pdf();
double sum = 0;
for (std::vector<double>::iterator it = prob.begin(); it != prob.end(); ++it)
{
*it += sum;
sum = *it;
}
return prob;
}
/**
* Test if value is contained with histogram bin bounds
* @param[in] value Test value
* @return True if value contained within one of its bins
* @throws std::runtime_exception If histogram could not be initialized.
*/
bool
contains(double const value)
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::contains - Histogram could not be initialized.");
return this->contains_(value);
}
/**
* Access the number of bins in the current histogram.
* @return Number of histogram bins.
* @throws std::runtime_exception If histogram could not be initialized.
*/
int
count()
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::count - Histogram could not be initialized.");
return this->count_();
}
/**
* Histogram enabled state
* @return True if histogram is enabled otherwise false.
*/
bool
enabled() const
{
return this->_enabled;
}
/**
* The frequency value for the bin located at index.
* @param[in] index Bin index
* @return Frequency value.
* @throws std::runtime_exception If histogram could not be initialized.
*/
double
frequency(int const index)
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::frequency - Histogram could not be initialized.");
return this->frequency_(index);
}
/**
* Copy of frequencies.
* @return Vector of frequency values.
* @throws std::runtime_exception If histogram could not be initialized.
*/
std::vector<double>
frequencies()
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::frequencies - Histogram could not be initialized.");
return this->_frequencies;
}
/**
* The index of the bin that contains the given value.
* @param[in] value Source value to locate in a bin
* @return Bin index for given value.
* @warning If the value is out-of-range then the index is extrapolated in units of the bin width.
* Use #contains to ensure the value is within the histogram bin range.
* @throws std::runtime_exception If histogram could not be initialized.
*/
int
index(T const value)
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::index - Histogram could not be initialized.");
return this->index_(value);
}
/**
* Initialization state of histogram. Histogram gets initializes when cache gets full or the user invokes a getter.
* @return True if histogram has been initialized otherwise false.
*/
bool
initialized() const
{
return this->_initialized;
}
/**
* Return the maximum bin value
* @return Maximum bin value
* @throws std::runtime_exception If histogram could not be initialized.
*/
double
max()
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::max - Histogram could not be initialized.");
return this->_binMax;
}
/**
* Return the number of histogram merges that have been performed
* @return Number of cache merges
*/
int
merges()
{
return this->_numMerges;
}
/**
* Return the minimum bin value
* @return Minimum bin value
* @throws std::runtime_exception If histogram could not be initialized.
*/
double
min()
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::min - Histogram could not be initialized.");
return this->_binMin;
}
/**
* Estimate the k'th order statistic.
* @details The cumulative probability of the k'th order statistic is computed as #kth/#total
* then the cumulative density function is inverted and linearly interpolated to
* estimate the k'th order statistic.
* @return Value of k'th order statistic
* @throws std::runtime_exception If histogram could not be initialized.
*/
double
order(int kth)
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::order - Histogram could not be initialized.");
// Estimate of the k'th order statistic
double estimate = this->bin(0);
// Compute order's probability and clip at [0,1]
double numItems = this->total();
double probability = (double) (kth) / numItems;
probability = std::max<double>(0, probability);
probability = std::min<double>(1, probability);
// Look up probability in cdf
std::vector<double> dist = this->cdf();
int numBins = dist.size();
for (int i = 0; i < numBins-1; i++)
{
if (dist.at(i+1) == 0) continue;
if ((dist.at(i) <= probability) && (probability <= dist.at(i+1)))
{
if (dist.at(i+1) == dist.at(i))
{
// If flat cdf avoid divide-by-zero
estimate = this->bin(i) + 0.5 * (this->bin(i+1) - this->bin(i));
}
else
{
// Linearly interpolate between enclosing bins
double slope = (this->bin(i+1) - this->bin(i)) / (dist.at(i+1) - dist.at(i));
estimate = this->bin(i) + slope * (probability - dist.at(i));
}
return estimate;
}
}
return estimate;
}
/**
* Copy of normalized probability distribution function.
* @return Vector of distribution values.
* @throws std::runtime_exception If histogram could not be initialized.
*/
std::vector<double>
pdf()
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::pdf - Histogram could not be initialized.");
std::vector<double> prob(this->count_(),0);
double sum = this->total();
std::vector<double>::iterator dist = prob.begin();
for (std::vector<double>::const_iterator freq = this->_frequencies.begin(); freq != this->_frequencies.end(); ++freq)
{
*dist = (*freq) / sum;
dist++;
}
return prob;
}
/**
* Compute the total frequency sum of the histogram.
* @return Frequency sum.
* @throws std::runtime_exception If histogram could not be initialized.
*/
double
total()
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::total - Histogram could not be initialized.");
double sum = std::accumulate(this->_frequencies.begin(), this->_frequencies.end(), 0.0);
return sum;
}
/**
* Bin width for the bin located at given index.
* @param[in] index Bin index
* @return Bin center value.
* @throws std::runtime_exception If histogram could not be initialized.
*/
double
width(int const index)
{
if (!this->merge()) throw std::runtime_error("DynamicHistogram::width - Histogram could not be initialized.");
return this->width_(index);
}
/**
* Build a histogram of data statically. Dynamic growing is not used. However,
* once the histogram is built it can then continue to be used dynamically.
* @param[in] data Vector input data points to be binned.
* @param[in] binCount Number of bins in histogram. Must be larger than 0.
* @param[in] minValue Histogram left most minimum bin value. If null then data is pre-scanned to compute.
* @param[in] maxValue Histogram right most maximum bin value. If null then data is pre-scanned to compute.
* @return Output histogram with its new size equal to binCount.
* @warning If minValue and maxValue are given, any value outside the histograms bounds will be discarded.
*/
static
DynamicHistogram<T>
buildStatic(std::vector<T> & data,
DynamicHistogramOptions const & options = DynamicHistogramOptions(),
double * minValue = 0,
double * maxValue = 0)
{
DynamicHistogram<T> histogram(options);
// ======================================================================
// Check if any data
// ----------------------------------------------------------------------
if (data.empty()) return histogram;
// ======================================================================
// Check if data should be scanned for min/max
// ----------------------------------------------------------------------
double minData = (minValue == 0 ? *std::min_element(data.begin(), data.end()) : *minValue);
double maxData = (maxValue == 0 ? *std::max_element(data.begin(), data.end()) : *maxValue);
// ======================================================================
// Build exact histogram
// ----------------------------------------------------------------------
histogram._binMax = maxData;
histogram._binMin = minData;
histogram._binWidth = (histogram._binMax - histogram._binMin) / histogram._binCount;
histogram._initialized = true;
for (typename std::vector<T>::iterator it = data.begin(); it != data.end(); ++it)
{
double dValue = (double) *it;
if (histogram.contains_(dValue)) histogram.add_(dValue);
}
return histogram;
}
protected:
/**
* Merge the cache entries with the current histogram.
* @return True if merge performed otherwise false
*/
virtual
bool
merge()
{
// ======================================================================
// Don't bother merging if no data in the cache
// ----------------------------------------------------------------------
if (this->_cache.empty()) return (this->_initialized ? true : false);
// ======================================================================
// If histogram has not been initialized then build it
// ----------------------------------------------------------------------
if (!this->_initialized)
{
// Compute new bounds
this->_binMax = this->_cache.max();
this->_binMin = this->_cache.min();
this->_binWidth = (this->_binMax - this->_binMin) / (double) (this->_binCount);
// Update with cache data
for (int i = 0; i < this->_cache.count(); i++)
{
this->add_(this->_cache.at(i));
}
// Reset cache parameters
this->_cache.reset();
this->_initialized = true;
return true;
}
this->_numMerges++;
// ======================================================================
// Determine how much to expand histogram
// ----------------------------------------------------------------------
// Compute dynamic range of histogram + cache data
double cacheLeft = this->bin_(this->index_(this->_cache.min())) - 0.5 * this->width_(this->index_(this->_cache.min()));
double cacheRight = this->bin_(this->index_(this->_cache.max())) + 0.5* this->width_(this->index_(this->_cache.max()));
double newMin = std::min<double>(cacheLeft, this->_binMin);
double newMax = std::max<double>(cacheRight, this->_binMax);
// Compute how much to scale the old histogram to get the new histogram
double oldHistogramWidth = this->_binMax - this->_binMin;
double newHistogramWidth = newMax - newMin;
int histogramScale = (int) ceil((newHistogramWidth / oldHistogramWidth));
// Compute dynamic range in units of histogram scale
int newBinCountAfterScale = (int) (histogramScale * this->_binCount);
// Compute number of empty bins
double newMaxAfterScale = newMin + newBinCountAfterScale * this->_binWidth;
double emptySpace = newMaxAfterScale - newMax;
int numEmptyBins = (int) (emptySpace / this->_binWidth);
int numEmptyBinsToShift = (int) (numEmptyBins/2);
// Compute final dynamic range
double newMinFinal = newMin - numEmptyBinsToShift * this->_binWidth;
double newMaxFinal = newMinFinal + newBinCountAfterScale * this->_binWidth;
double newBinWidthFinal = (newMaxFinal-newMinFinal) / this->_binCount;
// ======================================================================
// Merge old histogram into new empty histogram
// ----------------------------------------------------------------------
for (int i = 0; i < this->_binCount; i++)
{
double oldBinCenterInNewBins = this->bin_(i);
int newBinIndex = (int)((oldBinCenterInNewBins - newMinFinal) / newBinWidthFinal);
this->_temp.at(newBinIndex) += this->frequency_(i);
}
// ======================================================================
// Swap new histogram with old histogram
// ----------------------------------------------------------------------
this->_temp.swap(this->_frequencies);
this->_temp.assign(this->_temp.size(),0);
this->_binMax = newMaxFinal;
this->_binMin = newMinFinal;
this->_binWidth = newBinWidthFinal;
// ======================================================================
// Add cache data to new histogram
// ----------------------------------------------------------------------
for (int i = 0; i < this->_cache.count(); i++)
{
this->add_(this->_cache.at(i));
}
this->_cache.reset();
return true;
}
private:
/*
* Private version of public methods that do not attempt to merge
*/
void
add_(double const value)
{
this->_frequencies.at(this->index_(value))++;
}
double
bin_(int const index)
{
return this->_binMin + this->_binWidth * (index + 0.5);
}
bool
contains_(double const value)
{
int idx = this->index_(value);
bool isContained = (idx >= 0) && (idx < (int) this->_binCount);
return isContained;
}
int
count_()
{
return this->_binCount;
}
double
frequency_(int const index)
{
return this->_frequencies.at(index);
}
int
index_(double const value)
{
if (value == this->_binMax) return (this->_binCount - 1);
int idx = (int) floor((value - this->_binMin) / this->_binWidth);
return idx;
}
double
width_(int const index)
{
return this->_binWidth;
}
protected:
/**
* Number of histogram bins
*/
int _binCount;
/**
* Histogram maximum value
*/
double _binMax;
/**
* Histogram minimum value
*/
double _binMin;
/**
* Histogram bin width
*/
double _binWidth;
/**
* Cache where values are stored until merged into the histogram
*/
FixedSizeCache<double> _cache;
/**
* Histogram initialization state
*/
bool _enabled;
/**
* Histogram frequencies
*/
std::vector<double> _frequencies;
/**
* Histogram initialization state
*/
bool _initialized;
/**
* Number of merges performs
*/
int _numMerges;
private:
/**
* Temporary container to hold new histogram frequencies during merging
*/
std::vector<double> _temp;
};
/**
* @struct DataPoint
* @brief Data container structure
*/
struct DataPoint
{
/**
* Create default DataPoint
*/
DataPoint() :
active(false),
value(0)
{
}
/**
* Create custom DataPoint
* @param[in] value DataPoint value
* @param[in] activate Active state of data point
*/
DataPoint(double value,
bool activate) :
active(activate),
value(value)
{
}
/**
* Active state of data point
*/
bool active;
/**
* DataPoint value
*/
double value;
};
/**
* @class DataVector
* @brief STL vector of #DataPoint
*/
class DataVector : public std::vector<DataPoint>
{
public:
/**
* @brief Set the active state of all entries to false
*/
void
deactivate()
{
for (DataVector::iterator it = this->begin(); it != this->end(); ++it)
{
it->active = false;
}
}
/**
* Copy subvector using mask
*/
void
copy(DataVector const & src, std::vector<bool> const & mask)
{
DataVector::copy(src, src.size(), *this, this->size(), mask, mask.size());
}
/**
* Copy subvector using mask
*/
static
void copy(DataVector const & src,
DataVector::size_type const & numSrc,
DataVector & dst,
DataVector::size_type const & numDst,
std::vector<bool> const & mask,
DataVector::size_type const & numMask)
{
// Deactivate all destination value by default
dst.deactivate();
// Copy elements
DataVector::size_type j = 0;
for (DataVector::size_type i = 0; i < numSrc; i++)
{
// Check if current value is masked out
if (i < numMask)
{
if (!mask.at(i)) continue;
}
// Add or set next value
if (j >= numDst)
{
dst.push_back(src.at(i));
}
else
{
dst.at(j) = src.at(i);
}
j++;
}
}
};
/**
* @class DataFilters
* @brief Class that tests if a data source satisfies filter requirements
*/
class DataFilters
{
private:
class NumericFilter
{
public:
NumericFilter(double const & minValue,
double const & maxValue,
bool const & isAccept = true) :
_maxValue(maxValue),
_minValue(minValue),
_isAccept(isAccept)
{
}
/**
* Check if token should be filtered
*/
bool isFiltered(double const & value) const
{
bool isInInterval = (this->_minValue <= value) && (value <= this->_maxValue);
return (this->_isAccept ? isInInterval : !isInInterval);
}
private:
double _maxValue;
double _minValue;
bool _isAccept;
};
class StringFilter
{
public:
StringFilter(std::string const & pattern,
bool const & isExact = true,
bool const & isSensitive = true,
bool const & isAccept = true) :
_pattern(pattern),
_isExact(isExact),
_isSensitive(isSensitive),
_isAccept(isAccept)
{
if (!isSensitive)
{
std::transform(this->_pattern.begin(), this->_pattern.end(), this->_pattern.begin(), ::toupper);
}
}
/**
* Check if token should be filtered
*/
bool
isFiltered(std::string const & token) const
{
std::string input;
// Check if filtering is case sensitive
input = token;
if (!this->_isSensitive)
{
std::transform(token.begin(), token.end(), input.begin(), ::toupper);
}
// Check if filtering is exact or not
bool isMatch = false;
if (this->_isExact)
{
isMatch = input.compare(this->_pattern) == 0;
}
else
{
isMatch = input.find(this->_pattern) != std::string::npos;
}
return (this->_isAccept ? isMatch : !isMatch);
}
private:
std::string _pattern;
bool _isExact;
bool _isSensitive;
bool _isAccept;
};
struct NumericFilterCase
{
NumericFilterCase(unsigned int index, NumericFilter filter) : index(index), filter(filter)
{
}
unsigned int index;
NumericFilter filter;
};
struct StringFilterCase
{
StringFilterCase(unsigned int index, StringFilter filter) : index(index), filter(filter)
{
}
unsigned int index;
StringFilter filter;
};
public:
/*
* Adds a numeric filter
* @param[in] index Column index to apply filter
* @param[in] minValue Minimum value allowed
* @param[in] maxValue Maximum value allowed
* @param[in] isAccept True if a match accepts value
* False if a match rejects value
*/
void
addNumericFilter(unsigned int const & index,
double const & minValue,
double const & maxValue,
bool const & isAccept)
{
this->_numericFilters.push_back(NumericFilterCase(index, NumericFilter(minValue, maxValue, isAccept)));
}
/*
* Adds a string filter
* @param[in] index Column index to apply filter
* @param[in] pattern Pattern to match string
* @param[in] isExact True if string match is exact
* False if string match is partial
* @param[in] isExact True if string match is case sensitive
* False if string match is case insensitive
* @param[in] isAccept True if a match accepts value
* False if a match rejects value
*/
void
addStringFilter(unsigned int const & index,
std::string const & pattern,
bool const & isExact,
bool const & isSensitive,
bool const & isAccept)
{
this->_stringFilters.push_back(StringFilterCase(index, StringFilter(pattern, isExact, isSensitive, isAccept)));
}
/*
* Tests if data points passes numeric filtering
* @param[in] data Vector of data points to test
* @return True if a data passes filter otherwise false
*/
bool
isFiltered(DataVector const & data) const
{
unsigned int size = data.size();
// Iterate through and check if any filter applies to this data point
if (this->_numericFilters.size() == 0) return true;
for (std::vector<NumericFilterCase>::const_iterator it = this->_numericFilters.begin(); it != this->_numericFilters.end(); ++it)
{
if (it->index >= size || !data.at(it->index).active) continue; // don't check if out-of-range or data is not active
if (it->filter.isFiltered(data.at(it->index).value)) return true;
}
return false;
}
/*
* Tests if strings pass string filtering
* @param[in] data Vector of strings to test
* @return True if a data passes filter otherwise false
*/
bool
isFiltered(std::vector<std::string> const & data) const
{
unsigned int size = data.size();
// Iterate through and check if any filter applies to this data point
if (this->_stringFilters.size() == 0) return true;
for (std::vector<StringFilterCase>::const_iterator it = this->_stringFilters.begin(); it != this->_stringFilters.end(); ++it)
{
if (it->index >= size) continue; // don't check if out-of-range
if (it->filter.isFiltered(data.at(it->index))) return true;
}
return false;
}
private:
std::vector<StringFilterCase> _stringFilters;
std::vector<NumericFilterCase> _numericFilters;
};
/**
* @struct StatisticsTrackerOptions
*/
struct StatisticsTrackerOptions
{
StatisticsTrackerOptions()
{
this->doCov = false;
this->doMax = false;
this->doMean = false;
this->doMin = false;
this->doVar = false;
this->histogramOptions.enabled = false;
}
bool doCov;
bool doMax;
bool doMean;
bool doMin;
bool doVar;
DynamicHistogramOptions histogramOptions;
};
/**
* @struct SamplerOptions
*/
struct SamplerOptions
{
enum SampleMode
{
DEFAULT = 0,
UNIFORM,
RANDOM
};
SamplerOptions()
{
this->mode = SamplerOptions::DEFAULT;
this->step = 1;
}
SampleMode mode;
unsigned int step;
};
/**
* @struct CommandLineOptions
*/
struct CommandLineOptions
{
CommandLineOptions()
{
this->blankEOF = false;
this->comment = "";
this->delimiter = "";
this->fileInput = "";
this->fileOutput = "";
this->filterColumns = std::vector<bool>();
this->headerRow = 0;
this->numLinesToKeep = std::numeric_limits<int>::max();
this->numLinesToReshape = 1;
this->numLinesToSkip = 0;
this->removeDuplicates = false;
this->seed = 1;
this->showCorrelation = false;
this->showCovariance = false;
this->showFilteredData = false;
this->showHistogram = false;
this->showLeastSquaresOffset = false;
this->showLeastSquaresSlope = false;
this->showStatistics = false;
this->strictParsing = false;
this->verboseLevel = 0;
}
bool blankEOF;
std::string comment;
std::string delimiter;
std::string fileInput;
std::string fileOutput;
std::vector<bool> filterColumns;
DataFilters filterRows;
unsigned int headerRow;
unsigned int numLinesToKeep;
unsigned int numLinesToReshape;
unsigned int numLinesToSkip;
bool removeDuplicates;
SamplerOptions sampling;
unsigned int seed;
bool showCorrelation;
bool showCovariance;
bool showHistogram;
bool showFilteredData;
bool showLeastSquaresOffset;
bool showLeastSquaresSlope;
bool showStatistics;
StatisticsTrackerOptions statisticsOptions;
bool strictParsing;
unsigned char verboseLevel;
};
/**
* @class CommandLineParser
*/
class CommandLineParser
{
public:
/**
* Create command line parser
* @param[in] argc Argument count
* @param[in] argv Argument array
* @throws std:runtime_error if parsing is invalid
*/
CommandLineParser(int argc,
char * argv[]) :
_showUsage(false),
_showVersion(false)
{
this->parse(argc, argv);
}
/**
* Print software usage
*/
static
void
printUsage()
{
std::cout << std::endl;
std::cout << "NAME" << std::endl;
std::cout << std::endl;
std::cout << " clistats - Command line statistics tool" << std::endl;
std::cout << std::endl;
std::cout << "SYNOPSIS" << std::endl;
std::cout << std::endl;
std::cout << " clistats [-h] [-v <level>] [-V] [-i <file>] [-o <file>] [-a <code>] [-b]" << std::endl;
std::cout << " [-c <character>] [-d <character>] [-fc <filter>] [-fn <filter>]" << std::endl;
std::cout << " [-fs <filter>] [-k <rows>] [-r] [-rs <rows>] [-s <rows>]" << std::endl;
std::cout << " [-se <seed>] [-sr <step>] [-st] [-su <step>] [-t <row>] [-cr]" << std::endl;
std::cout << " [-cv] [-fd] [-hg <bins>,[cache]] [-lo] [-ls] [-ss] < [file]" << std::endl;
std::cout << std::endl;
std::cout << "DESCRIPTION" << std::endl;
std::cout << std::endl;
std::cout << " A command line tool to compute statistics for a stream of delimited input" << std::endl;
std::cout << " numbers. It takes a stream of numbers from standard input or a redirected" << std::endl;
std::cout << " file. To stop processing and display the statistics enter the EOF signal" << std::endl;
std::cout << " (CTRL-D on POSIX systems like Linux or Cygwin or CTRL-Z on Windows)." << std::endl;
std::cout << " Alternatively, see the --blank option to use a blank row. The default" << std::endl;
std::cout << " delimiter is a comma." << std::endl;
std::cout << std::endl;
std::cout << " Delimited tokens that are not valid numeric values are skipped." << std::endl;
std::cout << " If any tokens are skipped then the resulting covariance and correlation" << std::endl;
std::cout << " are not exact and only a conservative overestimation." << std::endl;
std::cout << std::endl;
std::cout << " Note, all statistics are computed on a rolling basis and not by using the" << std::endl;
std::cout << " entire dataset, so all non-order statistics are approximations." << std::endl;
std::cout << std::endl;
std::cout << " Displayed statistics use headers that start with # to enable piping" << std::endl;
std::cout << " results to gnuplot." << std::endl;
std::cout << std::endl;
std::cout << " Available statistics to display are:" << std::endl;
std::cout << std::endl;
std::cout << " - Count" << std::endl;
std::cout << " - Minimum" << std::endl;
std::cout << " - Mean" << std::endl;
std::cout << " - Maximum" << std::endl;
std::cout << " - Standard deviation" << std::endl;
std::cout << " - Covariance" << std::endl;
std::cout << " - Correlation" << std::endl;
std::cout << " - Least Squares Slope" << std::endl;
std::cout << " - Least Squares Offset" << std::endl;
std::cout << " - Histogram" << std::endl;
std::cout << std::endl;
std::cout << "OPTIONS" << std::endl;
std::cout << std::endl;
std::cout << " General options:" << std::endl;
std::cout << std::endl;
std::cout << " -h" << std::endl;
std::cout << " --help" << std::endl;
std::cout << " Print this help message" << std::endl;
std::cout << std::endl;
std::cout << " -v <level>" << std::endl;
std::cout << " --verbose <level>" << std::endl;
std::cout << " Verbose level (0 to 5). Default = 0." << std::endl;
std::cout << std::endl;
std::cout << " -V" << std::endl;
std::cout << " --version" << std::endl;
std::cout << " Software version is displayed." << std::endl;
std::cout << std::endl;
std::cout << " I/O options:" << std::endl;
std::cout << std::endl;
std::cout << " -i <file>" << std::endl;
std::cout << " --input <file>" << std::endl;
std::cout << " Input file. Default is stdin." << std::endl;
std::cout << std::endl;
std::cout << " -o <file>" << std::endl;
std::cout << " --output <file>" << std::endl;
std::cout << " Output file. Default is stdout." << std::endl;
std::cout << std::endl;
std::cout << " file" << std::endl;
std::cout << " Input file can be redirected as standard input" << std::endl;
std::cout << std::endl;
std::cout << " Parsing options:" << std::endl;
std::cout << std::endl;
std::cout << " -a <code>" << std::endl;
std::cout << " --ascii <code>" << std::endl;
std::cout << " Use delimiter character based on it\'s ASCII code (e.g., 9 = tab)." << std::endl;
std::cout << " Can be combined with \"-d\". Multiple delimiters will be" << std::endl;
std::cout << " concatenated." << std::endl;
std::cout << std::endl;
std::cout << " -b" << std::endl;
std::cout << " --blank" << std::endl;
std::cout << " Use blank row as the EOF signal to stop processing and display" << std::endl;
std::cout << " results. Default is CTRL-D for POSIX and CTRL-Z Windows." << std::endl;
std::cout << std::endl;
std::cout << " -c <character>" << std::endl;
std::cout << " --comment <character>" << std::endl;
std::cout << " Input comment character. Rows starting with this character will" << std::endl;
std::cout << " be skipped Default is no comments are recognized." << std::endl;
std::cout << std::endl;
std::cout << " -d <character>" << std::endl;
std::cout << " --delimiter <character>" << std::endl;
std::cout << " Input delimiter character. Cannot be the same as the comment" << std::endl;
std::cout << " character. Default = \",\". Multiple delimiters will be" << std::endl;
std::cout << " concatenated." << std::endl;
std::cout << std::endl;
std::cout << " -fc <filter>" << std::endl;
std::cout << " --filterColumn" << std::endl;
std::cout << " Filter columns to process using comma delimited array of column" << std::endl;
std::cout << " indices to keep." << std::endl;
std::cout << " Format: \"<c1>,<c2>,...,<c3:c4>,...\"" << std::endl;
std::cout << " (e.g., \"1,2,3,5\" will discard column 4). Range of" << std::endl;
std::cout << " columns can be indicated using \":\" (e.g., 1:3,5)." << std::endl;
std::cout << std::endl;
std::cout << " -fn <filter>" << std::endl;
std::cout << " --filterNumeric <filter>" << std::endl;
std::cout << " Filter rows to process only those with a column matching a numeric" << std::endl;
std::cout << " criteria. Multiple filters can be used and will be processed in the" << std::endl;
std::cout << " order the -fn flags are provided." << std::endl;
std::cout << " Format: \"#,min,max,[a|r]\"" << std::endl;
std::cout << " # = Number corresponding to column index to filter" << std::endl;
std::cout << " min = Minimum numeric value (-inf for no minimum)" << std::endl;
std::cout << " max = Maximum numeric value (inf for no maximum)" << std::endl;
std::cout << " a|r = Optional letter to denote accept/reject filtering" << std::endl;
std::cout << " \"a\" denotes row is accepted if criteria is met" << std::endl;
std::cout << " \"r\" denotes row is rejected if criteria is met" << std::endl;
std::cout << std::endl;
std::cout << " -fs <filter>" << std::endl;
std::cout << " --filterString <filter>" << std::endl;
std::cout << " Filter rows to process only those with a column matching a string" << std::endl;
std::cout << " match. Multiple filters can be used and will be processed in the" << std::endl;
std::cout << " order the -fs flags are provided." << std::endl;
std::cout << " Format: \"#,p,[e|p],[s|i],[a|r]\"" << std::endl;
std::cout << " # = Number corresponding to column index to filter" << std::endl;
std::cout << " p = String of pattern to match" << std::endl;
std::cout << " e|p = Optional letter to denote exact or partial match" << std::endl;
std::cout << " s|i = Optional letter to denote case sensitive/insensitive" << std::endl;
std::cout << " a|r = Optional letter to denote accept/reject filtering" << std::endl;
std::cout << " \"a\" denotes row is accepted if criteria is met" << std::endl;
std::cout << " \"r\" denotes row is rejected if criteria is met" << std::endl;
std::cout << std::endl;
std::cout << " -k <rows>" << std::endl;
std::cout << " --keep <rows>" << std::endl;
std::cout << " Number of rows to keep after processing begins." << std::endl;
std::cout << " Default is to keep all." << std::endl;
std::cout << std::endl;
std::cout << " -r" << std::endl;
std::cout << " --remove" << std::endl;
std::cout << " Remove duplicate sequential delimiters and treat them as one" << std::endl;
std::cout << " delimiter. Default is to treat them separately." << std::endl;
std::cout << std::endl;
std::cout << " -rs <rows>" << std::endl;
std::cout << " --reshape <rows>" << std::endl;
std::cout << " Reshape every N rows in a single column. Default = 1." << std::endl;
std::cout << std::endl;
std::cout << " -s <rows>" << std::endl;
std::cout << " --skip <rows>" << std::endl;
std::cout << " Number of rows to skip before processing begins (e.g., header row)" << std::endl;
std::cout << " Default = 0 (process all rows)." << std::endl;
std::cout << std::endl;
std::cout << " -se <seed>" << std::endl;
std::cout << " --seed <seed>" << std::endl;
std::cout << " Seed for random number generator when using \"-sr\" option." << std::endl;
std::cout << " <seed> can take values in the range [1," << RAND_MAX << "]." << std::endl;
std::cout << " If set to 0 then the current time is used as the seed." << std::endl;
std::cout << " Default = 1." << std::endl;
std::cout << std::endl;
std::cout << " -sr <step>" << std::endl;
std::cout << " --samplerandom <step>" << std::endl;
std::cout << " Sample the rows to be processed randomly in intervals of given" << std::endl;
std::cout << " step size. One row is randomly chosen every \"step\" rows." << std::endl;
std::cout << " Use \"-se\" to change the random number generator seed." << std::endl;
std::cout << " Mutually exclusive with option \"-su\"." << std::endl;
std::cout << std::endl;
std::cout << " -st" << std::endl;
std::cout << " --strict" << std::endl;
std::cout << " Strictly enforce parsing to only accept rows with the same number" << std::endl;
std::cout << " of tokens as the first successfully parsed row. Default is to" << std::endl;
std::cout << " allow missing tokens." << std::endl;
std::cout << std::endl;
std::cout << " -su <step>" << std::endl;
std::cout << " --sampleuniform <step>" << std::endl;
std::cout << " Sample the rows to be processed uniformly in intervals of given" << std::endl;
std::cout << " step size. Mutually exclusive with option \"-sr\"." << std::endl;
std::cout << std::endl;
std::cout << " -t <row>" << std::endl;
std::cout << " --titles <row>" << std::endl;
std::cout << " Row containing column header titles. If absent then index is used" << std::endl;
std::cout << " for each column title." << std::endl;
std::cout << std::endl;
std::cout << " Display options:" << std::endl;
std::cout << std::endl;
std::cout << " -cr" << std::endl;
std::cout << " --correlation" << std::endl;
std::cout << " Show correlation of data." << std::endl;
std::cout << std::endl;
std::cout << " -cv" << std::endl;
std::cout << " --covariance" << std::endl;
std::cout << " Show covariance of data." << std::endl;
std::cout << std::endl;
std::cout << " -fd" << std::endl;
std::cout << " --filtered" << std::endl;
std::cout << " Show filtered data to be processed." << std::endl;
std::cout << std::endl;
std::cout << " -hg <bins>,[cache]" << std::endl;
std::cout << " --histogram <bins>,[cache]" << std::endl;
std::cout << " Compute the histogram. Number of bins is required (Default = 100)." << std::endl;
std::cout << " Cache size is optional and must be greater than 100" << std::endl;
std::cout << " (Default = 1000)." << std::endl;
std::cout << std::endl;
std::cout << " -lo" << std::endl;
std::cout << " --lsqoffset" << std::endl;
std::cout << " Show least squares linear offset." << std::endl;
std::cout << std::endl;
std::cout << " -ls" << std::endl;
std::cout << " --lsqslope" << std::endl;
std::cout << " Show least squares linear slope." << std::endl;
std::cout << std::endl;
std::cout << " -ss" << std::endl;
std::cout << " --statistics" << std::endl;
std::cout << " Show summary statistics. Enabled by default unless another display" << std::endl;
std::cout << " option is enabled." << std::endl;
std::cout << std::endl;
std::cout << "EXIT STATUS" << std::endl;
std::cout << std::endl;
std::cout << " 0 = Success" << std::endl;
std::cout << " 1 = Argument parsing failed" << std::endl;
std::cout << " 2 = Computing statistics failed" << std::endl;
std::cout << " 3 = Displaying statistics failed" << std::endl;
std::cout << std::endl;
std::cout << "BUGS" << std::endl;
std::cout << std::endl;
std::cout << " Report bugs to " << ApplicationProperties::AUTHOR << std::endl;
}
/**
* Print software version
*/
static
void
printVersion()
{
std::cout << ApplicationProperties::version() << std::endl;
}
/**
* Application usage flag
* @return True if usage was requested otherwise false
*/
bool
showUsage() const
{
return this->_showUsage;
}
/**
* Application version flag
* @return True if version was requested otherwise false
*/
bool
showVersion() const
{
return this->_showVersion;
}
private:
/**
* Parse command line arguments
* @param[in] argc Argument count
* @param[in] argv Argument array
* @throws std::runtime_error if flag argument is unrecognized or parsing its value failed
*/
void
parse(int argc,
char * argv[])
{
// Iterate through each argument until all are parsed
// If argument is recognized as a valid flag then it is parsed
// If parsing fails on flag value an exception is thrown
// If argument is not recognized as a valid flag an exception is thrown
std::list<std::string> arguments(argv, argv + argc);
arguments.pop_front(); // Remove executable name
while (!arguments.empty())
{
std::list<std::string>::iterator argument = arguments.begin();
std::string flag(*argument);
if (flag == "-h" || flag == "--help")
{
this->_showUsage = true;
return;
}
else if (flag == "-V" || flag == "--version")
{
this->_showVersion = true;
return;
}
else if (flag == "-v" || flag == "--verbose")
{
// Parse verbosity flag value for a single integer within the range of log levels
unsigned int verbose = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<unsigned int>(value, verbose);
if (!(isInt && verbose >= Logger::Level::FATAL && verbose <= Logger::Level::DETAIL))
{
throw std::runtime_error("Invalid verbose level");
}
this->options.verboseLevel = (unsigned char)verbose;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-i" || flag == "--input")
{
// Parse input file flag value for a single string
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
std::ifstream f(value.c_str());
if (!f.good())
{
throw std::runtime_error("Invalid input file");
}
this->options.fileInput = value;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-o" || flag == "--output")
{
// Parse output file flag value for a single string
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
std::ofstream f(value.c_str());
if (!f.good())
{
throw std::runtime_error("Invalid output file");
}
this->options.fileOutput = value;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-a" || flag == "--ascii")
{
// Parse delimiter flag value for a ASCII code character
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
// Covert code to character
int code = 0;
if (!(StringParser::toValue<int>(value,code) && (code >= 0) && (code <= 127)))
{
throw std::runtime_error("Invalid delimiter ASCII code");
}
char character = (char) code;
this->options.delimiter += character;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-b" || flag == "--blank")
{
this->options.blankEOF = true;
arguments.pop_front();
}
else if (flag == "-c" || flag == "--comment")
{
// Parse comment flag value for a single character
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
if (value.size() != 1)
{
throw std::runtime_error("Invalid comment character = " + value);
}
this->options.comment = value;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-d" || flag == "--delimiter")
{
// Parse delimiter flag value for a single character
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
this->options.delimiter += value;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-s" || flag == "--skip")
{
// Parse skip flag value for a single non-negative integer
int skip = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<int>(value, skip);
if (!(isInt && skip >= 0))
{
throw std::runtime_error("Invalid number of lines to skip");
}
this->options.numLinesToSkip = skip;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-k" || flag == "--keep")
{
// Parse keep flag value for a single non-negative integer
int keep = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<int>(value, keep);
if (!(isInt && keep >= 0))
{
throw std::runtime_error("Invalid number of lines to keep");
}
this->options.numLinesToKeep = keep;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-r" || flag == "--remove")
{
this->options.removeDuplicates = true;
arguments.pop_front();
}
else if (flag == "-t" || flag == "--titles")
{
// Parse titles flag value for a single positive integer
unsigned int row = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<unsigned int>(value, row);
if (!(isInt && row > 0))
{
throw std::runtime_error("Invalid header title row");
}
this->options.headerRow = row;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-fc" || flag == "--filterColumn")
{
// Parse filter flag value for a comma delimited vector of positive integers
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
// Parse filters into delimited tokens
StringSplitter parser(value, ",");
std::vector<std::string> values = parser.tokens();
std::vector<int> filters;
for (unsigned int j = 0; j < values.size(); j++)
{
// Parse string to integers and check for ranges (e.g., 3:5)
std::vector<int> range;
bool isRangeValid = StringSplitter::toIntegers(values.at(j), range);
if (!isRangeValid)
{
throw std::runtime_error("Invalid filter column value = " + values.at(j));
}
// Check each range entry is positive
for (std::vector<int>::iterator it = range.begin(); it != range.end(); ++it)
{
if (*it <= 0)
{
throw std::runtime_error("Invalid filter column value = " + values.at(j));
}
filters.push_back(*it-1);
}
}
// Populate filter mask
int maxFilter = *std::max_element(filters.begin(), filters.end());
this->options.filterColumns.resize(maxFilter+1, false);
for (unsigned int j = 0; j < filters.size(); j++)
{
this->options.filterColumns.at(filters.at(j)) = true;
}
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-fn" || flag == "--filterNumeric")
{
// Parse filter flag value for a comma delimited vector of strings
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
// Parse filters into delimited tokens
StringSplitter parser(value, ",");
std::vector<std::string> values = parser.tokens();
if (values.size() == 0)
{
throw std::runtime_error("Invalid numeric filter value = " + value);
}
// Numeric filter
if (values.size() < 3 || values.size() > 4)
{
throw std::runtime_error("Invalid numeric filter format = " + value);
}
// Check filter index is a positive integer
int column = 0;
bool isInt = StringParser::toValue<int>(values.at(0), column);
if (!(isInt && column > 0))
{
throw std::runtime_error("Invalid numeric filter column value = " + values.at(0));
}
// Check minimum value is a positive integer
double minValue = 0;
if (values.at(1).compare("-inf")==0)
{
minValue = -std::numeric_limits<double>::max();
}
else if (values.at(1).compare("inf")==0)
{
minValue = std::numeric_limits<double>::max();
}
else
{
bool isDouble = StringParser::toValue<double>(values.at(1), minValue);
if (!isDouble)
{
throw std::runtime_error("Invalid numeric filter minimum value = " + values.at(1));
}
}
// Check maximum value is a positive integer
double maxValue = 0;
if (values.at(2).compare("-inf")==0)
{
maxValue = -std::numeric_limits<double>::max();
}
else if (values.at(2).compare("inf")==0)
{
maxValue = std::numeric_limits<double>::max();
}
else
{
bool isDouble = StringParser::toValue<double>(values.at(2), maxValue);
if (!isDouble)
{
throw std::runtime_error("Invalid numeric filter maximum value = " + values.at(2));
}
}
// Check for optional filter matching
bool isAccept = true;
if (values.size() >= 4)
{
std::string accept = values.at(3);
if ((accept.compare("a") != 0) && (accept.compare("r") != 0))
{
throw std::runtime_error("Invalid string filter accept option = " + values.at(3));
}
isAccept = (accept.compare("a") == 0);
}
// Build filter
this->options.filterRows.addNumericFilter(column-1, minValue, maxValue, isAccept);
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-fs" || flag == "--filterString")
{
// Parse filter flag value for a comma delimited vector of strings
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
// Parse filters into delimited tokens
StringSplitter parser(value, ",");
std::vector<std::string> values = parser.tokens();
// Check string filter
if (values.size() < 2 || values.size() > 5)
{
throw std::runtime_error("Invalid string filter format = " + value);
}
// Check filter index is a positive integer
int column = 0;
bool isInt = StringParser::toValue<int>(values.at(0), column);
if (!(isInt && column > 0))
{
throw std::runtime_error("Invalid string filter column value = " + values.at(0));
}
// Get filter pattern
std::string pattern = values.at(1);
// Check filter matching option
bool isExact = true;
if (values.size() >= 3)
{
std::string match = values.at(2);
if ((match.compare("e") != 0) && (match.compare("p") != 0))
{
throw std::runtime_error("Invalid string filter matching option = " + values.at(2));
}
isExact = (match.compare("e") == 0);
}
// Check filter case sensitivity option
bool isSensitive = true;
if (values.size() >= 4)
{
std::string sensitivity = values.at(3);
if ((sensitivity.compare("s") != 0) && (sensitivity.compare("i") != 0))
{
throw std::runtime_error("Invalid string filter case sensitivity option = " + values.at(3));
}
isSensitive = (sensitivity.compare("s") == 0);
}
// Check filter matching option
bool isAccept = true;
if (values.size() >= 5)
{
std::string accept = values.at(4);
if ((accept.compare("a") != 0) && (accept.compare("r") != 0))
{
throw std::runtime_error("Invalid string filter accept option = " + values.at(4));
}
isAccept = (accept.compare("a") == 0);
}
// Build filter
this->options.filterRows.addStringFilter(column-1, pattern, isExact, isSensitive, isAccept);
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-rs" || flag == "--reshape")
{
// Parse skip flag value for a single positive integer
int reshape = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<int>(value, reshape);
if (!(isInt && reshape > 0))
{
throw std::runtime_error("Invalid number of lines to reshape");
}
this->options.numLinesToReshape = reshape;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-se" || flag == "--seed")
{
// Parse skip flag value for a single positive integer
int seed = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<int>(value, seed);
if (!(isInt && seed >= 0))
{
throw std::runtime_error("Invalid seed value");
}
this->options.seed = seed;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-sr" || flag == "--samplerandom")
{
// Parse step flag value for a single non-negative integer
int step = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<int>(value, step);
if (!(isInt && step >= 1))
{
throw std::runtime_error("Invalid random sampling step size. Must be >= 1.");
}
if (this->options.sampling.mode != SamplerOptions::DEFAULT)
{
throw std::runtime_error("Cannot use multiple sampling options.");
}
this->options.sampling.mode = SamplerOptions::RANDOM;
this->options.sampling.step = step;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-st" || flag == "--strict")
{
this->options.strictParsing = true;
arguments.pop_front();
}
else if (flag == "-su" || flag == "--sampleuniform")
{
// Parse step flag value for a single non-negative integer
int step = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
bool isInt = StringParser::toValue<int>(value, step);
if (!(isInt && step >= 1))
{
throw std::runtime_error("Invalid uniform sampling step size. Must be >= 1.");
}
if (this->options.sampling.mode != SamplerOptions::DEFAULT)
{
throw std::runtime_error("Cannot use multiple sampling options.");
}
this->options.sampling.mode = SamplerOptions::UNIFORM;
this->options.sampling.step = step;
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-cv" || flag == "--covariance")
{
this->options.showCovariance = true;
arguments.pop_front();
}
else if (flag == "-cr" || flag == "--correlation")
{
this->options.showCorrelation = true;
arguments.pop_front();
}
else if (flag == "-fd" || flag == "--filtered")
{
this->options.showFilteredData = true;
arguments.pop_front();
}
else if (flag == "-hg" || flag == "--histogram")
{
// Parse histogram flag value for a single positive integer
this->options.showHistogram = true;
int binCount = 0;
std::string value = "";
if ((++argument) != arguments.end())
{
value = *argument;
}
// Parse filters into delimited tokens
StringSplitter parser(value, ",");
std::vector<std::string> values = parser.tokens();
if (values.size() == 0 || (values.size() == 1 && values.at(0).empty()))
{
throw std::runtime_error("Missing histogram options");
}
if (values.size() > 2)
{
throw std::runtime_error("Invalid histogram options = " + value);
}
// Parse bin count
bool isInt = StringParser::toValue<int>(values.at(0), binCount);
if (!(isInt && binCount > 0))
{
throw std::runtime_error("Invalid number of bins = " + values.at(0));
}
this->options.statisticsOptions.histogramOptions.binCount = binCount;
// Parse cache size
if (values.size() == 2)
{
int cacheSize = 0;
bool isInt = StringParser::toValue<int>(values.at(1), cacheSize);
if (!(isInt && cacheSize >= 100))
{
throw std::runtime_error("Invalid histogram cache size = " + values.at(1));
}
this->options.statisticsOptions.histogramOptions.cacheSize = cacheSize;
}
arguments.pop_front();
arguments.pop_front();
}
else if (flag == "-lo" || flag == "--lsqoffset")
{
this->options.showLeastSquaresOffset = true;
arguments.pop_front();
}
else if (flag == "-ls" || flag == "--lsqslope")
{
this->options.showLeastSquaresSlope = true;
arguments.pop_front();
}
else if (flag == "-ss" || flag == "--statistics")
{
this->options.showStatistics = true;
arguments.pop_front();
}
else
{
throw std::runtime_error("Unrecognized flag (" + flag + "). Run \"clistats --help\" for usage.");
}
}
// Check if delimiter has been provided
if (this->options.delimiter.empty())
{
this->options.delimiter = ",";
}
// Check for conflicting options
if (this->options.delimiter == this->options.comment)
{
throw std::runtime_error("Delimiter and comment characters cannot be the same.");
}
// Check if default basic statistics should be shown
if (!this->options.showStatistics)
{
this->options.showStatistics = !(this->options.showCovariance ||
this->options.showCorrelation ||
this->options.showFilteredData ||
this->options.showHistogram ||
this->options.showLeastSquaresOffset ||
this->options.showLeastSquaresSlope);
}
// Determine what statistics should be computed
this->options.statisticsOptions.doCov = (this->options.showCovariance ||
this->options.showCorrelation ||
this->options.showLeastSquaresOffset ||
this->options.showLeastSquaresSlope);
this->options.statisticsOptions.doMax = this->options.showStatistics;
this->options.statisticsOptions.doMean = this->options.showStatistics || this->options.statisticsOptions.doCov;
this->options.statisticsOptions.doMin = this->options.showStatistics;
this->options.statisticsOptions.doVar = this->options.showStatistics;
this->options.statisticsOptions.histogramOptions.enabled = this->options.showHistogram;
}
public:
/**
* Options
*/
CommandLineOptions options;
private:
/**
* Show application usage flag
*/
bool _showUsage;
/**
* Show application version flag
*/
bool _showVersion;
};
/**
* @class StatisticsTracker
* @brief Tracks the statistics of a scalar variable.
* @details The order determines which statistics will be tracked.
* - 0 = 0th order statistic: minimum, maximum
* - 1 = 1st order statistic: mean
* - 2 = 2nd order statistic: variance
* - >3 = Not supported.
*/
class StatisticsTracker
{
public:
/**
* Custom constructor
* @param[in] name Statistic name
* @param[in] count Initial number of data points
* @param[in] minimum Initial data minimum
* @param[in] mean Initial data mean
* @param[in] maximum Initial data maximum
* @param[in] variance Initial data variance
* @param[in] options Statistics options
*/
StatisticsTracker(std::string name = "",
long count = 0,
double minimum = 0,
double mean = 0,
double maximum = 0,
double variance = 0,
StatisticsTrackerOptions const & options = StatisticsTrackerOptions()) :
_count(count),
_histogram(DynamicHistogram<double>(options.histogramOptions)),
_maximum(maximum),
_mean(mean),
_minimum(minimum),
_name(name),
_options(options),
_variance(variance)
{
}
/**
* Get data count
* @return Number of data points
*/
long
getCount(void) const
{
return this->_count;
}
/**
* Get data histogram
* @return Histogram
*/
DynamicHistogram<double>
getHistogram(void) const
{
return this->_histogram;
}
/**
* Get data minimum
* @return Data minimum
*/
double
getMinimum(void) const
{
return this->_minimum;
}
/**
* Get data mean
* @return Data mean
*/
double
getMean(void) const
{
return this->_mean;
}
/**
* Get data maximum
* @return Data maximum
*/
double
getMaximum(void) const
{
return this->_maximum;
}
/**
* Get data name
* @return Data name
*/
std::string
getName(void) const
{
return this->_name;
}
/**
* Get data variance
* @return Data variance
*/
double
getVariance(void) const
{
return this->_variance;
}
/**
* Set data name
* @param[in] name Data name
*/
void
setName(std::string const & name)
{
this->_name = name;
}
/**
* Update statistics with new data value
* @param[in] value Data value
*/
void
update(double const value)
{
// update counter
this->_count++;
// initialize if first value
if (this->_count == 1)
{
if (this->_options.doMin)
{
this->_minimum = value;
}
if (this->_options.doMax)
{
this->_maximum = value;
}
if (this->_options.doMean)
{
this->_mean = value;
}
if (this->_options.doVar)
{
this->_variance = 0;
}
if (this->_options.histogramOptions.enabled)
{
this->_histogram.add(value);
}
return;
}
// update min
if (this->_options.doMin)
{
if (value < this->_minimum)
{
this->_minimum = value;
}
}
// update max
if (this->_options.doMax)
{
if (value > this->_maximum)
{
this->_maximum = value;
}
}
if (this->_options.doMean || this->_options.doVar)
{
double delta = value - this->_mean;
if (this->_options.doMean)
{
// update mean
this->_mean += delta / (double) this->_count;
}
if (this->_options.doVar)
{
// update variance
double scale = (this->_count - 1.0) / (double) this->_count;
this->_variance *= scale;
this->_variance += delta * delta * scale / (double) this->_count;
}
}
if (this->_options.histogramOptions.enabled)
{
this->_histogram.add(value);
}
}
protected:
/**
* Statistic count
*/
long _count;
/**
* Statistic histogram
*/
DynamicHistogram<double> _histogram;
/**
* Statistic maximum
*/
double _maximum;
/**
* Statistic mean
*/
double _mean;
/**
* Statistic minimum
*/
double _minimum;
/**
* Statistic name
*/
std::string _name;
/**
* Statistics options
*/
StatisticsTrackerOptions _options;
/**
* Statistic variance
*/
double _variance;
};
/**
* @class MultivariateTracker
* @brief Tracks the statistics of a multivariate variable.
* @details The order determines which statistics will be tracked.
* - 0 = 0th order statistic: minimum, maximum
* - 1 = 1st order statistic: mean
* - 2 = 2nd order statistic: variance
* - >3 = Not supported.
*/
class MultivariateTracker
{
public:
/**
* Custom constructor
* @param[in] size Dimensional size of statistics to track
* @param[in] options Statistics options
*/
MultivariateTracker(long size = 0,
StatisticsTrackerOptions const & options = StatisticsTrackerOptions()) :
_covariance(std::vector<double>(size*size,0)),
_options(options)
{
this->initialize(size, options);
}
/**
* Get data count
* @param[in] index Index of multi-variable
* @return Number of data points
*/
long
getCount(long const index) const
{
return this->_statistics[index].getCount();
}
/**
* Get data covariance
* @param[in] i Index of i'th variable
* @param[in] j Index of j'th variable
* @return Data covariance
* @throws std::runtime_error if invalid indices
*/
double
getCovariance(long const i,
long const j) const
{
const int numPoints = this->_statistics.size();
if ((i < 0) || (i >= numPoints) || (j < 0) || (j >= numPoints)) throw std::runtime_error("Invalid covariance indices");
int k = i * numPoints + j;
return this->_covariance.at(k);
}
/**
* Get data correlation
* @param[in] i Index of i'th variable
* @param[in] j Index of j'th variable
* @return Data correlation
* @throws std::runtime_error if invalid indices
*/
double
getCorrelation(long const i,
long const j) const
{
double varI = this->getCovariance(i,i);
double varJ = this->getCovariance(j,j);
return this->getCovariance(i,j) / (sqrt(varI) * sqrt(varJ));
}
/**
* Get tracker dimension
* @return Tracker dimension
*/
long
getDimension() const
{
return (long) this->_statistics.size();
}
/**
* Get data histogram
* @param[in] index Index of multi-variable
* @return Data histogram
*/
DynamicHistogram<double>
getHistogram(long const index) const
{
return this->_statistics[index].getHistogram();
}
/**
* Get data minimum
* @param[in] index Index of multi-variable
* @return Data minimum
*/
double
getMinimum(long const index) const
{
return this->_statistics[index].getMinimum();
}
/**
* Get data mean
* @param[in] index Index of multi-variable
* @return Data mean
*/
double
getMean(long const index) const
{
return this->_statistics[index].getMean();
}
/**
* Get data maximum
* @param[in] index Index of multi-variable
* @return Data maximum
*/
double
getMaximum(long const index) const
{
return this->_statistics[index].getMaximum();
}
/**
* Get data name
* @param[in] index Index of multi-variable
* @return Data name
*/
std::string
getName(long const index) const
{
return this->_statistics[index].getName();
}
/**
* Get least squares offset between i'th (independent) and j'th (independent) variables
* @param[in] i Index of i'th variable
* @param[in] j Index of j'th variable
* @return Least squares offset
* @throws std::runtime_error if invalid indices
*/
double
getLeastSquaresOffset(long const i,
long const j) const
{
return this->getMean(j) - this->getLeastSquaresSlope(i,j) * this->getMean(i);
}
/**
* Get least squares slope between i'th (independent) and j'th (independent) variables
* @param[in] i Index of i'th variable
* @param[in] j Index of j'th variable
* @return Least squares slope
* @throws std::runtime_error if invalid indices
*/
double
getLeastSquaresSlope(long const i,
long const j) const
{
return this->getCovariance(i,j) / this->getCovariance(i,i);
}
/**
* Get data variance
* @param[in] index Index of multi-variable
* @return Data variation
*/
double
getVariance(long const index) const
{
return this->_statistics[index].getVariance();
}
/**
* Set data name
* @param[in] index Index of multi-variable
* @param[in] name Data name
*/
void
setName(long const index,
std::string name)
{
this->_statistics[index].setName(name);
}
/**
* Update statistics with new data points
* @param[in] data New data point
* @return True if statisticc updated otherwise false
*/
bool
update(DataVector const & data)
{
// Check data dimensions matches tracker dimensions
if (this->_statistics.size() != 0 && data.size() != this->_statistics.size())
{
return false;
}
// Try to initialize the tracker
if (this->_statistics.size() == 0)
{
if (data.size() == 0) return false;
this->initialize(data.size(), this->_options);
}
if (this->_options.doCov)
{
// Update covariance
const int numPoints = data.size();
for (int i = 0; i < numPoints; i++)
{
if (!data[i].active) continue;
int countI = this->_statistics[i].getCount();
double meanI = this->_statistics[i].getMean();
double deltaI = (data[i].value - meanI);
for (int j = 0; j < numPoints; j++)
{
if (!data[j].active) continue;
int countJ = this->_statistics[j].getCount();
double meanJ = this->_statistics[j].getMean();
double deltaJ = (data[j].value - meanJ);
// Conservative estimate the number of data points
double N = std::max<double>(countI+1, countJ+1);
int k = i * numPoints + j;
this->_covariance[k] *= (N-1);
this->_covariance[k] += ((N-1)/N) * (deltaI) * (deltaJ);
this->_covariance[k] /= N;
}
}
}
// Update statistics with each data point
DataVector::const_iterator datum = data.begin();
std::vector<StatisticsTracker>::iterator tracker = this->_statistics.begin();
for ( ; tracker != this->_statistics.end(); ++tracker, ++datum)
{
if (datum->active) tracker->update(datum->value);
}
return true;
}
private:
/**
* Initialize the statistics array
* @param[in] size Size of statistics array
* @param[in] options Statistics options
*/
void
initialize(long size,
StatisticsTrackerOptions const & options)
{
// Initialize scalar statistics trackers
for (long i = 0 ; i < size; ++i)
{
this->_statistics.push_back(StatisticsTracker("", 0, 0, 0, 0, 0, options));
}
// Initialize multivariate statistics
this->_covariance.resize(size*size,0);
}
protected:
/**
* Multivariate statistics
*/
std::vector<double> _covariance;
/**
* Statistics options
*/
StatisticsTrackerOptions _options;
/**
* Statistic trackers
*/
std::vector<StatisticsTracker> _statistics;
};
/**
* @class StatisticsWriter
* @brief Static class to write various statistics to a stream.
*/
class StatisticsWriter
{
public:
/**
* @class StatisticsWriter
* @brief Static class to write various statistics to a stream.
* @param[in] comment Character used to comment header rows. Default "#".
*/
StatisticsWriter(std::string comment = "#") :
_comment(comment)
{
}
/**
* Write data vector to stream
* @param[out] stream Destination stream
* @param[in] data Source data vector to write out
* @param[in] delimiter Data output delimiter
*/
void
writeData(std::ostream & stream,
DataVector const & data,
std::string const delimiter = " ")
{
for (DataVector::const_iterator it = data.begin(); it != data.end();)
{
// Skip inactive data
if (!it->active)
{
++it;
continue;
}
// Write out data
stream << it->value;
++it;
// Write out delimiter if not last entry
if (it != data.end())
{
stream << delimiter;
}
}
stream << std::endl;
}
/**
* Write tracker histograms to a stream
* @param[out] stream Destination stream
* @param[in] tracker Source tracker
*/
void
writeHistograms(std::ostream & stream,
MultivariateTracker & tracker)
{
int numDim = tracker.getDimension();
// Print no data header
if (numDim == 0)
{
int totalWidth = 20;
std::string header(totalWidth,'=');
stream << this->_comment << header << std::endl;
stream << this->_comment << std::setfill (' ') << std::setw (totalWidth/2) << "Histograms" << std::endl;
stream << this->_comment << header << std::endl;
stream << this->_comment << "No valid data" << std::endl;
return;
}
for (long i = 0; i < numDim; i++)
{
const std::string name = tracker.getName(i);
DynamicHistogram<double> histogram = tracker.getHistogram(i);
this->writeHistogram<double>(stream, name, histogram);
}
return;
}
/**
* Print MultivariateTracker matrix values and their dimension titles
* @param[out] stream Destination stream
* @param[in] tracker Source tracker
* @param[in] title Matrix title
* @param[in] matrix Pointer to matrix function
*/
template<class T>
void
writeMatrix(std::ostream & stream,
MultivariateTracker & tracker,
std::string const & title,
T (MultivariateTracker::*matrix)(long const i, long const j) const)
{
int numDim = tracker.getDimension();
// Compute column widths
std::vector<long> width(numDim,0);
for (long i = 0; i < numDim; i++)
{
StringParser::updateWidthString(tracker.getName(i), width[i]);
}
for (long i = 0; i < numDim; i++)
{
for (long j = 0; j < numDim; j++)
{
StringParser::updateWidthNumber<T>((tracker.*matrix)(i,j), width[j]);
}
}
long totalWidth = 0;
for (std::vector<long>::iterator it = width.begin(); it != width.end(); ++it)
{
(*it) += 3;
totalWidth += *it;
}
totalWidth = std::max<long>(totalWidth, 20);
// Print data headers
std::string header(totalWidth,'=');
std::string footer(totalWidth,'-');
stream << this->_comment << header << std::endl;
stream << this->_comment << std::setfill (' ') << std::setw (totalWidth/2) << title << std::endl;
stream << this->_comment << header << std::endl;
stream << this->_comment;
if (numDim == 0)
{
stream << "No Data" << std::endl;
return;
}
for (long i = 0; i < numDim; i++)
{
stream << std::right << std::setw(width[i]) << tracker.getName(i);
}
stream << std::endl;
stream << this->_comment << footer << std::endl;
// Print data
std::string indent(this->_comment.size(),' ');
for (long i = 0; i < numDim; i++)
{
stream << indent;
for (long j = 0; j < numDim; j++)
{
stream << std::right << std::setw(width[j]) << StringParser::parseNumber<T>((tracker.*matrix)(i,j));
}
stream << std::endl;
}
stream << std::endl;
return;
}
/**
* Print summary statistics
* @param[out] stream Destination stream
* @param[in] tracker Source tracker
*/
void
writeStatistics(std::ostream & stream,
MultivariateTracker & tracker)
{
int numDim = tracker.getDimension();
// Compute column widths
std::vector<long> width(6,0);
StringParser::updateWidthString("Dimension", width[0]);
StringParser::updateWidthString("Count", width[1]);
StringParser::updateWidthString("Minimum", width[2]);
StringParser::updateWidthString("Mean", width[3]);
StringParser::updateWidthString("Maximum", width[4]);
StringParser::updateWidthString("Stdev", width[5]);
for (long i = 0; i < numDim; i++)
{
StringParser::updateWidthString(tracker.getName(i), width[0]);
StringParser::updateWidthNumber<long>(tracker.getCount(i), width[1]);
StringParser::updateWidthString(StringParser::parseStatistic<double>(tracker.getCount(i), tracker.getMinimum(i)), width[2]);
StringParser::updateWidthString(StringParser::parseStatistic<double>(tracker.getCount(i), tracker.getMean(i)), width[3]);
StringParser::updateWidthString(StringParser::parseStatistic<double>(tracker.getCount(i), tracker.getMaximum(i)), width[4]);
StringParser::updateWidthString(StringParser::parseStatistic<double>(tracker.getCount(i), sqrt(tracker.getVariance(i))), width[5]);
}
long totalWidth = 0;
for (std::vector<long>::iterator it = width.begin(); it != width.end(); ++it)
{
(*it) += 3;
totalWidth += *it;
}
// Print data headers
std::string header(totalWidth,'=');
std::string footer(totalWidth,'-');
stream << this->_comment << header << std::endl;
stream << this->_comment << std::setfill (' ') << std::setw (totalWidth/2) << "Statistics" << std::endl;
stream << this->_comment << header << std::endl;
stream << this->_comment;
stream << std::right << std::setw(width[0]) << "Dimension";
stream << std::right << std::setw(width[1]) << "Count";
stream << std::right << std::setw(width[2]) << "Minimum";
stream << std::right << std::setw(width[3]) << "Mean";
stream << std::right << std::setw(width[4]) << "Maximum";
stream << std::right << std::setw(width[5]) << "Stdev";
stream << std::endl;
stream << this->_comment << footer << std::endl;
// Print data
std::string indent(this->_comment.size(),' ');
for (long i = 0; i < numDim; i++)
{
stream << indent;
stream << std::right << std::setw(width[0]) << tracker.getName(i);
stream << std::right << std::setw(width[1]) << StringParser::parseNumber<long>(tracker.getCount(i));
stream << std::right << std::setw(width[2]) << StringParser::parseStatistic<double>(tracker.getCount(i), tracker.getMinimum(i));
stream << std::right << std::setw(width[3]) << StringParser::parseStatistic<double>(tracker.getCount(i), tracker.getMean(i));
stream << std::right << std::setw(width[4]) << StringParser::parseStatistic<double>(tracker.getCount(i), tracker.getMaximum(i));
stream << std::right << std::setw(width[5]) << StringParser::parseStatistic<double>(tracker.getCount(i), sqrt(tracker.getVariance(i)));
stream << std::endl;
}
stream << std::endl;
return;
}
/**
* Write histogram to a stream
* @param[out] stream Destination stream
* @param[in] tracker Source tracker
* @param[in] histogram Histogram to write
*/
template <class T>
void
writeHistogram(std::ostream & stream,
std::string const & title,
DynamicHistogram<T> & histogram)
{
try
{
unsigned int nBins = 0;
std::vector<double> freq;
std::vector<double> pdf;
std::vector<double> cdf;
// Compute column widths
std::vector<long> width(6,0);
StringParser::updateWidthString("Bin Min", width[0]);
StringParser::updateWidthString("Bin Max", width[1]);
StringParser::updateWidthString("Center", width[2]);
StringParser::updateWidthString("Frequency", width[3]);
StringParser::updateWidthString("PDF", width[4]);
StringParser::updateWidthString("CDF", width[5]);
nBins = histogram.count();
freq = histogram.frequencies();
pdf = histogram.pdf();
cdf = histogram.cdf();
for (unsigned int i = 0; i < nBins; i++)
{
StringParser::updateWidthNumber<long>(i, width[0]);
StringParser::updateWidthNumber<double>(histogram.bin(i)-histogram.width(i)/2, width[1]);
StringParser::updateWidthNumber<double>(histogram.bin(i)+histogram.width(i)/2, width[2]);
StringParser::updateWidthNumber<long long>((long long)freq.at(i), width[3]);
StringParser::updateWidthNumber<double>(pdf.at(i), width[4]);
StringParser::updateWidthNumber<double>(cdf.at(i), width[5]);
}
long totalWidth = 0;
for (std::vector<long>::iterator it = width.begin(); it != width.end(); ++it)
{
(*it) += 3;
totalWidth += *it;
}
// Print data headers
std::string header(totalWidth,'=');
std::string footer(totalWidth,'-');
stream << this->_comment << header << std::endl;
stream << this->_comment << std::setfill (' ') << std::setw (totalWidth/2) << "Histogram of " << title << std::endl;
stream << this->_comment << header << std::endl;
stream << this->_comment;
stream << std::right << std::setw(width[0]) << "Bin"
<< std::right << std::setw(width[1]) << "Min"
<< std::right << std::setw(width[2]) << "Max"
<< std::right << std::setw(width[3]) << "Frequency"
<< std::right << std::setw(width[4]) << "PDF"
<< std::right << std::setw(width[5]) << "CDF"
<< std::endl;
// Print data
std::string indent(this->_comment.size(), ' ');
for (unsigned int i = 0; i < nBins; i++)
{
stream << indent;
stream << std::right << std::setw(width[0]) << StringParser::parseNumber<long>(i);
stream << std::right << std::setw(width[1]) << StringParser::parseNumber<double>(histogram.bin(i)-histogram.width(i)/2);
stream << std::right << std::setw(width[2]) << StringParser::parseNumber<double>(histogram.bin(i)+histogram.width(i)/2);
stream << std::right << std::setw(width[3]) << StringParser::parseNumber<long long>((long long)freq.at(i));
stream << std::right << std::setw(width[4]) << StringParser::parseNumber<double>(pdf.at(i));
stream << std::right << std::setw(width[5]) << StringParser::parseNumber<double>(cdf.at(i));
stream << std::endl;
}
}
catch (...)
{
stream << "No valid data" << std::endl;
}
stream << std::endl;
return;
}
private:
std::string _comment;
};
/**
* @class RowSampler
* @brief Class to decide if current entry should be sampled
*/
class RowSampler
{
public:
/**
* @param[in] options Sampler Options
*/
RowSampler(SamplerOptions const & options) :
_count(0),
_next(1),
_sampled(0),
_mode(options.mode),
_step(options.step)
{
}
/**
* Determine if current sample should be used
* @return True if sample should be used otherwise false
*/
bool
sample()
{
// Don't bother if samling every row
if (this->_step == 1) return true;
// Bump row counter
this->_count++;
// Check if this row is sampled
if (this->_count == this->_next)
{
// Bump sampled counter
this->_sampled++;
// If yes, determine next row in this sampling bin to sample
unsigned int row = 1;
if (this->_mode == SamplerOptions::RANDOM)
{
row = 1 + (unsigned int)(rand() % this->_step);
}
this->_next = this->_sampled * this->_step + row;
return true;
}
return false;
}
private:
/**
* Number of rows tested for sampling
*/
unsigned int _count;
/**
* Next row to sample
*/
unsigned int _next;
/**
* Sampling mode
*/
SamplerOptions::SampleMode _mode;
/**
* Number of sampled rows
*/
unsigned int _sampled;
/**
* Sampling step size
*/
unsigned int _step;
};
/**
* @class StatisticsApp
* @brief statistics application
*/
class StatisticsApp
{
public:
/**
* Create application
*/
StatisticsApp(CommandLineOptions const & options) :
_options(options),
_outputStream(0),
_tracker(MultivariateTracker(0, options.statisticsOptions))
{
Logger::logLevel = (Logger::Level::Type)this->_options.verboseLevel;
// ==================================================
// Seed random number generator
// --------------------------------------------------
srand((options.seed == 0 ? (unsigned int)time(0) : options.seed));
// ==================================================
// Define output stream
// --------------------------------------------------
this->_outputFile.open(this->_options.fileOutput.c_str(), std::ios::out);
if (!this->_outputFile.good() && !this->_options.fileOutput.empty())
{
LOG_MESSAGE(Logger::Level::ERROR, "Output file failed to open. Writting to standard output.");
}
this->_outputStream = (this->_outputFile.good() ? &this->_outputFile : &std::cout);
}
/**
* Run application
* @return Status code
*/
int
run(void)
{
// ==================================================
// Application parameters
// --------------------------------------------------
int numDim = 0;
int numDimMask = 0;
// ==================================================
// Define input stream
// --------------------------------------------------
std::ifstream fileInput(this->_options.fileInput.c_str(), std::ios::in);
std::istream * source = (fileInput.good() ? &fileInput : &std::cin);
LOG_MESSAGE(Logger::Level::INFO, ApplicationProperties::NAME << " is starting");
// ==================================================
// Define output writer
// --------------------------------------------------
StatisticsWriter writer;
// ==================================================
// Define row sampler
// --------------------------------------------------
RowSampler sampler(this->_options.sampling);
// ==================================================
// Loop through source data
// --------------------------------------------------
// titles is populated by parsed line if user provides a titles row, otherwise indices are used
std::vector<std::string> titles;
StringSplitter parser;
// Counters used to keep track of line reads if reshaping is requested by user
unsigned int counter = 0;
unsigned int counterSinceLastParsing = 0;
std::string lineToReshape = "";
// DataVector contains the parsed data from each line.
// It's size will get set on the first successful parsing.
DataVector data;
DataVector dataMasked;
bool reading = true;
while (reading)
{
// ==================================================
// Extract current line
// --------------------------------------------------
std::string line = StatisticsApp::readline(*source);
if (!(*source).good())
{
LOG_MESSAGE(Logger::Level::DETAIL, "End of file found. Exiting.");
break;
}
// ==================================================
// Check if line is empty and if we need to exit
// --------------------------------------------------
if (line.size() == 0)
{
if (this->_options.blankEOF)
{
LOG_MESSAGE(Logger::Level::DETAIL, "Blank line found. Exiting.");
break;
}
else
{
LOG_MESSAGE(Logger::Level::DETAIL, "Blank line found. Skipping.");
continue;
}
}
// ==================================================
// Check if row is comment and needs to be skipped
// --------------------------------------------------
if (line.compare(0,1,this->_options.comment.c_str()) == 0) continue;
// ==================================================
// Check if row needs to be reshaped into column
// --------------------------------------------------
// If yes, then append current line to previous
// lines with delimiter and continue to next read
counterSinceLastParsing++;
lineToReshape += (counterSinceLastParsing == 1 ? "" : this->_options.delimiter) + line;
if (counterSinceLastParsing < this->_options.numLinesToReshape) continue;
// Prepare line and counter for parsing
line = lineToReshape;
counter++;
// Reset counter and appended line for next read
counterSinceLastParsing = 0;
lineToReshape = "";
// ==================================================
// Extract header titles
// --------------------------------------------------
if (this->_options.headerRow == counter)
{
parser.initialize(line, this->_options.delimiter, this->_options.removeDuplicates, this->_options.filterColumns);
titles = parser.tokens();
continue;
}
// ==================================================
// Skip header rows
// --------------------------------------------------
if (counter <= this->_options.numLinesToSkip)
{
LOG_MESSAGE(Logger::Level::INFO, "Skipping header line.");
continue;
}
// ==================================================
// Skip unneeded rows
// --------------------------------------------------
if (counter > (this->_options.numLinesToSkip + this->_options.numLinesToKeep))
{
LOG_MESSAGE(Logger::Level::INFO, "Skipping remaining lines.");
break;
}
// ==================================================
// Skip unsampled rows
// --------------------------------------------------
if (!sampler.sample())
{
LOG_MESSAGE(Logger::Level::DETAIL, "Row not sampled. Skipping");
continue;
}
// ==================================================
// Parse current line
// --------------------------------------------------
parser.initialize(line, this->_options.delimiter, this->_options.removeDuplicates);
StringSplitter::size_type numTokens = parser.size();
LOG_MESSAGE(Logger::Level::DETAIL, "Line = " << counter << " - content =\"" << line << "\"");
// ==================================================
// Check and compute source data dimensions
// --------------------------------------------------
bool isDimSet = numDim > 0;
if (!isDimSet)
{
numDim = (int) numTokens;
data.resize(numDim);
// Make sure we only keep column filters if they are within actual number of columns
this->_options.filterColumns.resize(numDim, (this->_options.filterColumns.size() == 0));
// Compute how many columns are masked out
numDimMask = std::accumulate(this->_options.filterColumns.begin(), this->_options.filterColumns.end(), 0);
dataMasked.resize(numDimMask);
LOG_MESSAGE(Logger::Level::INFO, "Data dimensions set to " << numDim);
LOG_MESSAGE(Logger::Level::INFO, "Mask dimensions set to " << numDimMask);
}
bool isDimFailed = (numDim != (int) numTokens);
if (isDimFailed)
{
LOG_MESSAGE(Logger::Level::WARNING, "Line = " << counter << " - Statistics dimensions does not equal data dimensions." << (this->_options.strictParsing ? " Skipping." : ""));
if (this->_options.strictParsing)
{
continue;
}
}
LOG_MESSAGE(Logger::Level::DEBUG, "Line = " << counter << " - Number of tokens found: " << numTokens);
// ==================================================
// Apply string filters
// --------------------------------------------------
bool isStringFiltered = this->_options.filterRows.isFiltered(parser.get());
if (!isStringFiltered)
{
LOG_MESSAGE(Logger::Level::DEBUG, "Line = " << counter << " - filtered out by string filter");
continue;
}
// ==================================================
// Convert tokens into data array
// --------------------------------------------------
for (StringSplitter::size_type i = 0; i < (StringSplitter::size_type) numDim; ++i)
{
if (numTokens <= i) break;
data.at(i).active = parser.toValue<double>(i, data.at(i).value);
LOG_MESSAGE(Logger::Level::DETAIL, "Line = " << counter << " - " << (data.at(i).active ? "Valid token" : "Invalid token") << " = " << parser.at(i));
}
// ==================================================
// Apply numeric filters
// --------------------------------------------------
bool isNumericFiltered = this->_options.filterRows.isFiltered(data);
if (!isNumericFiltered)
{
LOG_MESSAGE(Logger::Level::DEBUG, "Line = " << counter << " - filtered out by numeric filter");
continue;
}
// ==================================================
// Apply column filters
// --------------------------------------------------
DataVector::copy(data, numDim, dataMasked, numDimMask, this->_options.filterColumns, numDim);
// ==================================================
// Write current data
// --------------------------------------------------
if (this->_options.showFilteredData)
{
writer.writeData(*this->_outputStream, dataMasked);
}
// ==================================================
// Update statistics with current data
// --------------------------------------------------
this->_tracker.update(dataMasked);
// Since the data vector is preallocated, we deactivate all entries in case they don't exist in the next parsed line
// This way they don't get inadvertently included in the next line's statistics
data.deactivate();
}
// ==================================================
// Update statistics names
// --------------------------------------------------
if (numDimMask != (long)titles.size())
{
// Show error message if user provided a bad header row
if (this->_options.headerRow > 0)
{
LOG_MESSAGE(Logger::Level::ERROR, "Size of header titles does not match data dimensions so using indices as header titles.");
}
titles.resize(numDimMask,"");
for (long i = 0; i < numDimMask; i++)
{
titles.at(i) = StringParser::parseNumber<long>(i+1);
}
}
for (long i = 0; i < numDimMask && i < this->_tracker.getDimension(); i++)
{
this->_tracker.setName(i, titles.at(i));
}
LOG_MESSAGE(Logger::Level::INFO, ApplicationProperties::NAME << " is complete");
return 0;
}
/**
* Dispaly output statistics
* @return True if statistics displayed successfully otherwise false
*/
bool
display()
{
// ==================================================
// Write output to stream
// --------------------------------------------------
StatisticsWriter writer;
// Show statistics
if (this->_options.showStatistics)
{
writer.writeStatistics(*this->_outputStream, this->_tracker);
}
// Show covariance
if (this->_options.showCovariance)
{
writer.writeMatrix<double>(*this->_outputStream, this->_tracker, "Covariance", &MultivariateTracker::getCovariance);
}
// Show correlation
if (this->_options.showCorrelation)
{
writer.writeMatrix<double>(*this->_outputStream, this->_tracker, "Correlation", &MultivariateTracker::getCorrelation);
}
// Show least squares fit offset
if (this->_options.showLeastSquaresOffset)
{
writer.writeMatrix<double>(*this->_outputStream, this->_tracker, "Offset", &MultivariateTracker::getLeastSquaresOffset);
}
// Show least squares fit slope
if (this->_options.showLeastSquaresSlope)
{
writer.writeMatrix<double>(*this->_outputStream, this->_tracker, "Slope", &MultivariateTracker::getLeastSquaresSlope);
}
// Show histogram
if (this->_options.showHistogram)
{
writer.writeHistograms(*this->_outputStream, this->_tracker);
}
return true;
}
private:
/**
* @brief Read current line from stream
* @param[in] stream Source stream
* @return Read line as string
*/
static
std::string
readline(std::istream & stream)
{
// Output line
std::string line;
// Get stream buffer and guard with sentry
std::istream::sentry guard(stream, true);
std::streambuf * buffer = stream.rdbuf();
// Iterate over source buffer, append new characters to
// destination string, and check for the following
// line endings:
// - LF = Linux
// - CR = Apple
// - CRLF = Windows
// - EOF = End-Of-file
while (true)
{
// Extract current character and bump stream pointer
int character = buffer->sbumpc();
// Check if current character is a line feed
if (character == StatisticsApp::LF)
{
return line;
}
// Check if current character is a carriage return
if (character == StatisticsApp::CR)
{
// Get current character without bumping stream pointer
character = buffer->sgetc();
if(character == StatisticsApp::LF)
{
// Remove line feed from stream and bump stream pointer
buffer->sbumpc();
}
return line;
}
// Check if current character is the end of file
if (character == StatisticsApp::EF)
{
if(line.empty())
{
stream.setstate(std::ios::eofbit);
}
return line;
}
// Append current character to destination string
line += (char) character;
}
return line;
}
private:
/**
* Line feed character
*/
static const int LF = '\n';
/**
* Carriage return character
*/
static const int CR = '\r';
/**
* End Of File character
*/
static const int EF = EOF;
private:
/**
* Options data delimiter
*/
CommandLineOptions _options;
/**
* Output file
*/
std::ofstream _outputFile;
/**
* Output stream
*/
std::ostream * _outputStream;
/**
* Statistics
*/
MultivariateTracker _tracker;
};
/**
* Application status codes
*/
namespace AppStatus
{
enum Status
{
SUCCESS = 0,
FAILED_PARSING,
FAILED_RUN,
FAILED_DISPLAY
};
}
/**
* @brief program driver
* @param[in] argc Number of arguments including executable path
* @param[in] argv Character array of arguments
* @return Exit status
* - 0 = Success
* - 1 = Argument parsing failed
* - 2 = Computing statistics failed
* - 3 = Displaying statistics failed
*/
int
pdrv(int argc,
char * argv[])
{
// ======================================================================
// Parse command line arguments
// ----------------------------------------------------------------------
CommandLineOptions options;
try
{
CommandLineParser parser(argc, argv);
if (parser.showUsage())
{
CommandLineParser::printUsage();
return AppStatus::SUCCESS;
}
else if (parser.showVersion())
{
CommandLineParser::printVersion();
return AppStatus::SUCCESS;
}
options = parser.options;
}
catch (std::exception & ex)
{
LOG_MESSAGE(Logger::Level::FATAL, ex.what());
return AppStatus::FAILED_PARSING;
}
// ======================================================================
// Launch application
// ----------------------------------------------------------------------
StatisticsApp application(options);
try
{
int status = application.run();
if (status != 0) return AppStatus::FAILED_RUN;
}
catch (std::exception & ex)
{
LOG_MESSAGE(Logger::Level::FATAL, ex.what());
return AppStatus::FAILED_RUN;
}
// ======================================================================
// Display results
// ----------------------------------------------------------------------
try
{
bool isDisplayValid = application.display();
if (!isDisplayValid) return AppStatus::FAILED_DISPLAY;
}
catch (std::exception & ex)
{
LOG_MESSAGE(Logger::Level::FATAL, ex.what());
return AppStatus::FAILED_DISPLAY;
}
return AppStatus::SUCCESS;
}
#ifndef _CLISTATS_TESTING
int
main(int argc,
char * argv[])
{
return pdrv(argc, argv);
}
#endif
| 33.210913 | 190 | 0.499584 | [
"vector",
"transform"
] |
36027093bc9aa2f253cf21d8c6b81e276f2420ba | 1,363 | cc | C++ | Str/68.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | Str/68.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | Str/68.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/text-justification/discuss/633915/Fast-and-thoroughly-explained-c%2B%2B-solution
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int w) {
vector<string> ans;
int j;
for (int i=0; i<words.size(); i=j){
string s(w,' ');
s.replace(0, words[i].size(), words[i]);
int remaining = w - words[i].size();
for (j=i+1; j<words.size() && remaining>words[j].size(); ++j){
remaining -= 1 + words[j].size();
}
int cnt = j - i - 1;
if (cnt){
int even_space = 1;
int uneven_space = 0;
if (j<words.size()){
even_space += remaining/cnt;
uneven_space += remaining%cnt;
}
int index = words[i].size() + even_space + (uneven_space-- >0);
for (int k=i+1; k<words.size() && index<w; ++k){
s.replace(index,words[k].size(),words[k]);
index += words[k].size() + even_space + (uneven_space-- >0);
}
}
ans.push_back(s);
}
return ans;
}
};
| 32.452381 | 113 | 0.414527 | [
"vector"
] |
3607e1b2a6592195026a1e734bd101a41f10d819 | 1,203 | hpp | C++ | src/include/Parser.hpp | TheLastBilly/cainit | 060bd4ee3dc953a2bbb4085c8ae059fc75d97287 | [
"BSD-2-Clause"
] | null | null | null | src/include/Parser.hpp | TheLastBilly/cainit | 060bd4ee3dc953a2bbb4085c8ae059fc75d97287 | [
"BSD-2-Clause"
] | 9 | 2020-02-14T17:51:22.000Z | 2020-03-04T22:10:18.000Z | src/include/Parser.hpp | TheLastBilly/cainit | 060bd4ee3dc953a2bbb4085c8ae059fc75d97287 | [
"BSD-2-Clause"
] | null | null | null | // cainit - Parser.cpp
//
// Copyright (c) 2019, TheLastBilly
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#pragma once
#include <iostream>
#include <vector>
#include "Cainit.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
class Parser
{
public:
Parser();
Parser( const Parser &parser );
~Parser();
Cainit::ErrorValue ParseFile( std::string path );
Cainit::file_v files;
std::string error_line;
private:
struct ParserBuffer
{
bool
has_file = false,
has_class = false;
int line_count = 0;
Cainit::class_v classes;
Cainit::header_v headers;
Cainit::File file;
};
Cainit::ErrorValue ParseLine( std::string line, ParserBuffer &buff );
//Varaibles and methods used by the parsing process
size_t pos = 0, end = 0, tar = 0;
static inline bool fil( std::string line, const char * find, size_t & pos);
static inline bool fil_l( std::string line, const char * find, size_t & pos);
std::string
param_b,
name_b,
type_b;
}; | 21.872727 | 81 | 0.631754 | [
"vector"
] |
362d1675d750649ac602108649c3cb0d716b3500 | 22,423 | cc | C++ | src/GaIA/pkgs/nmap/nmap-6.40/nse_main.cc | uninth/UNItools | c8b1fbfd5d3753b5b14fa19033e39737dedefc00 | [
"BSD-3-Clause"
] | null | null | null | src/GaIA/pkgs/nmap/nmap-6.40/nse_main.cc | uninth/UNItools | c8b1fbfd5d3753b5b14fa19033e39737dedefc00 | [
"BSD-3-Clause"
] | null | null | null | src/GaIA/pkgs/nmap/nmap-6.40/nse_main.cc | uninth/UNItools | c8b1fbfd5d3753b5b14fa19033e39737dedefc00 | [
"BSD-3-Clause"
] | 1 | 2021-06-08T15:59:26.000Z | 2021-06-08T15:59:26.000Z | #include "nmap.h"
#include "nbase.h"
#include "nmap_error.h"
#include "portlist.h"
#include "nsock.h"
#include "NmapOps.h"
#include "timing.h"
#include "Target.h"
#include "nmap_tty.h"
#include "xml.h"
#include "nse_main.h"
#include "nse_utility.h"
#include "nse_fs.h"
#include "nse_nsock.h"
#include "nse_nmaplib.h"
#include "nse_bit.h"
#include "nse_binlib.h"
#include "nse_pcrelib.h"
#include "nse_openssl.h"
#include "nse_debug.h"
#define NSE_MAIN "NSE_MAIN" /* the main function */
/* Script Scan phases */
#define NSE_PRE_SCAN "NSE_PRE_SCAN"
#define NSE_SCAN "NSE_SCAN"
#define NSE_POST_SCAN "NSE_POST_SCAN"
/* These are indices into the registry, for data shared with nse_main.lua. The
definitions here must match those in nse_main.lua. */
#define NSE_YIELD "NSE_YIELD"
#define NSE_BASE "NSE_BASE"
#define NSE_WAITING_TO_RUNNING "NSE_WAITING_TO_RUNNING"
#define NSE_DESTRUCTOR "NSE_DESTRUCTOR"
#define NSE_SELECTED_BY_NAME "NSE_SELECTED_BY_NAME"
#define NSE_CURRENT_HOSTS "NSE_CURRENT_HOSTS"
#define NSE_FORMAT_TABLE "NSE_FORMAT_TABLE"
#define NSE_FORMAT_XML "NSE_FORMAT_XML"
#ifndef MAXPATHLEN
# define MAXPATHLEN 2048
#endif
extern NmapOps o;
/* global object to store Pre-Scan and Post-Scan script results */
static ScriptResults script_scan_results;
static int timedOut (lua_State *L)
{
Target *target = nseU_gettarget(L, 1);
lua_pushboolean(L, target->timedOut(NULL));
return 1;
}
static int startTimeOutClock (lua_State *L)
{
Target *target = nseU_gettarget(L, 1);
if (!target->timeOutClockRunning())
target->startTimeOutClock(NULL);
return 0;
}
static int stopTimeOutClock (lua_State *L)
{
Target *target = nseU_gettarget(L, 1);
if (target->timeOutClockRunning())
target->stopTimeOutClock(NULL);
return 0;
}
static int next_port (lua_State *L)
{
lua_settop(L, 2);
lua_pushvalue(L, lua_upvalueindex(1));
lua_pushvalue(L, 2);
if (lua_next(L, -2) == 0)
return 0;
else {
lua_pop(L, 1); /* pop boolean value */
return 1;
}
}
static int ports (lua_State *L)
{
static const int states[] = {
PORT_OPEN,
PORT_OPENFILTERED,
PORT_UNFILTERED,
PORT_HIGHEST_STATE /* last one marks end */
};
Target *target = nseU_gettarget(L, 1);
PortList *plist = &(target->ports);
Port *current = NULL;
Port port;
lua_newtable(L);
for (int i = 0; states[i] != PORT_HIGHEST_STATE; i++)
while ((current = plist->nextPort(current, &port, TCPANDUDPANDSCTP,
states[i])) != NULL)
{
lua_newtable(L);
set_portinfo(L, target, current);
lua_pushboolean(L, 1);
lua_rawset(L, -3);
}
lua_pushcclosure(L, next_port, 1);
lua_pushnil(L);
lua_pushnil(L);
return 3;
}
static int script_set_output (lua_State *L)
{
ScriptResult sr;
sr.set_id(luaL_checkstring(L, 1));
sr.set_output_tab(L, 2);
if (!lua_isnil(L, 3)) {
lua_len(L, 3);
sr.set_output_str(luaL_checkstring(L, 3), luaL_checkint(L,-1));
}
script_scan_results.push_back(sr);
return 0;
}
static int host_set_output (lua_State *L)
{
ScriptResult sr;
Target *target = nseU_gettarget(L, 1);
sr.set_id(luaL_checkstring(L, 2));
sr.set_output_tab(L, 3);
if (!lua_isnil(L, 4)) {
lua_len(L, 4);
sr.set_output_str(luaL_checkstring(L, 4), luaL_checkint(L,-1));
}
target->scriptResults.push_back(sr);
return 0;
}
static int port_set_output (lua_State *L)
{
Port *p;
Port port;
ScriptResult sr;
Target *target = nseU_gettarget(L, 1);
p = nseU_getport(L, target, &port, 2);
sr.set_id(luaL_checkstring(L, 3));
sr.set_output_tab(L, 4);
if (!lua_isnil(L, 5)) {
lua_len(L, 5);
sr.set_output_str(luaL_checkstring(L, 5), luaL_checkint(L,-1));
}
target->ports.addScriptResult(p->portno, p->proto, sr);
target->ports.numscriptresults++;
return 0;
}
static int key_was_pressed (lua_State *L)
{
lua_pushboolean(L, keyWasPressed());
return 1;
}
static int scp (lua_State *L)
{
static const char * const ops[] = {"printStats", "printStatsIfNecessary",
"mayBePrinted", "endTask", NULL};
ScanProgressMeter *progress =
(ScanProgressMeter *) lua_touserdata(L, lua_upvalueindex(1));
switch (luaL_checkoption(L, 1, NULL, ops))
{
case 0: /* printStats */
progress->printStats((double) luaL_checknumber(L, 2), NULL);
break;
case 1:
progress->printStatsIfNecessary((double) luaL_checknumber(L, 2), NULL);
break;
case 2: /*mayBePrinted */
lua_pushboolean(L, progress->mayBePrinted(NULL));
return 1;
case 3: /* endTask */
progress->endTask(NULL, NULL);
delete progress;
break;
}
return 0;
}
static int scan_progress_meter (lua_State *L)
{
lua_pushlightuserdata(L, new ScanProgressMeter(luaL_checkstring(L, 1)));
lua_pushcclosure(L, scp, 1);
return 1;
}
/* This is like nmap.log_write, but doesn't append "NSE:" to the beginning of
messages. It is only used internally by nse_main.lua and is not available to
scripts. */
static int l_log_write(lua_State *L)
{
static const char *const ops[] = {"stdout", "stderr", NULL};
static const int logs[] = {LOG_STDOUT, LOG_STDERR};
int log = logs[luaL_checkoption(L, 1, NULL, ops)];
log_write(log, "%s", luaL_checkstring(L, 2));
return 0;
}
static int l_xml_start_tag(lua_State *L)
{
const char *name;
name = luaL_checkstring(L, 1);
xml_open_start_tag(name);
if (lua_isnoneornil(L, 2)) {
lua_newtable(L);
lua_replace(L, 2);
}
for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1))
xml_attribute(luaL_checkstring(L, -2), "%s", luaL_checkstring(L, -1));
xml_close_start_tag();
return 0;
}
static int l_xml_end_tag(lua_State *L)
{
xml_end_tag();
return 0;
}
static int l_xml_write_escaped(lua_State *L)
{
const char *text;
text = luaL_checkstring(L, 1);
xml_write_escaped("%s", text);
return 0;
}
static int l_xml_newline(lua_State *L)
{
xml_newline();
return 0;
}
static int l_protect_xml(lua_State *L)
{
const char *text;
size_t len;
std::string output;
text = luaL_checklstring(L, 1, &len);
output = protect_xml(std::string(text, len));
lua_pushlstring(L, output.c_str(), output.size());
return 1;
}
static int nse_fetch (lua_State *L, int (*fetch)(char *, size_t, const char *))
{
char path[MAXPATHLEN];
switch (fetch(path, sizeof(path), luaL_checkstring(L, 1)))
{
case 0: // no such path
lua_pushnil(L);
lua_pushfstring(L, "no path to file/directory: %s", lua_tostring(L, 1));
break;
case 1: // file returned
lua_pushliteral(L, "file");
lua_pushstring(L, path);
break;
case 2: // directory returned
lua_pushliteral(L, "directory");
lua_pushstring(L, path);
break;
default:
return luaL_error(L, "nse_fetch returned bad code");
}
return 2;
}
static bool filename_is_absolute(const char *file) {
if (file[0] == '/')
return true;
#ifdef WIN32
if ((file[0] != '\0' && file[1] == ':') || file[0] == '\\')
return true;
#endif
return false;
}
/* This is a modification of nmap_fetchfile that first looks for an
* absolute file name.
*/
static int nse_fetchfile_absolute(char *path, size_t path_len, const char *file) {
if (filename_is_absolute(file)) {
if (o.debugging > 1)
log_write(LOG_STDOUT, "%s: Trying absolute path %s\n", SCRIPT_ENGINE, file);
Strncpy(path, file, path_len);
return file_is_readable(file);
}
return nmap_fetchfile(path, path_len, file);
}
/* This is a modification of nmap_fetchfile specialized to look for files
* in the scripts subdirectory. If the path is absolute, it is always tried
* verbatim. Otherwise, the file is looked for under scripts/, and then finally
* in the current directory.
*/
static int nse_fetchscript(char *path, size_t path_len, const char *file) {
std::string scripts_path = std::string(SCRIPT_ENGINE_LUA_DIR) + std::string(file);
int type;
if (filename_is_absolute(file)) {
if (o.debugging > 1)
log_write(LOG_STDOUT, "%s: Trying absolute path %s\n", SCRIPT_ENGINE, file);
Strncpy(path, file, path_len);
return file_is_readable(file);
}
// lets look in <path>/scripts
type = nmap_fetchfile(path, path_len, scripts_path.c_str());
if (type == 0) {
// current directory
Strncpy(path, file, path_len);
return file_is_readable(file);
}
return type;
}
static int fetchscript (lua_State *L)
{
return nse_fetch(L, nse_fetchscript);
}
static int fetchfile_absolute (lua_State *L)
{
return nse_fetch(L, nse_fetchfile_absolute);
}
static void open_cnse (lua_State *L)
{
static const luaL_Reg nse[] = {
{"fetchfile_absolute", fetchfile_absolute},
{"fetchscript", fetchscript},
{"key_was_pressed", key_was_pressed},
{"scan_progress_meter", scan_progress_meter},
{"timedOut", timedOut},
{"startTimeOutClock", startTimeOutClock},
{"stopTimeOutClock", stopTimeOutClock},
{"ports", ports},
{"script_set_output", script_set_output},
{"host_set_output", host_set_output},
{"port_set_output", port_set_output},
{"log_write", l_log_write},
{"xml_start_tag", l_xml_start_tag},
{"xml_end_tag", l_xml_end_tag},
{"xml_write_escaped", l_xml_write_escaped},
{"xml_newline", l_xml_newline},
{"protect_xml", l_protect_xml},
{NULL, NULL}
};
luaL_newlib(L, nse);
/* Add some other fields */
nseU_setbfield(L, -1, "default", o.script == 1);
nseU_setbfield(L, -1, "scriptversion", o.scriptversion == 1);
nseU_setbfield(L, -1, "scriptupdatedb", o.scriptupdatedb == 1);
nseU_setbfield(L, -1, "scripthelp", o.scripthelp);
nseU_setsfield(L, -1, "script_dbpath", SCRIPT_ENGINE_DATABASE);
nseU_setsfield(L, -1, "scriptargs", o.scriptargs);
nseU_setsfield(L, -1, "scriptargsfile", o.scriptargsfile);
nseU_setsfield(L, -1, "NMAP_URL", NMAP_URL);
}
/* Global persistent Lua state used by the engine. */
static lua_State *L_NSE = NULL;
void ScriptResult::clear (void)
{
if (o.debugging > 3)
log_write(LOG_STDOUT, "ScriptResult::clear %d id %s\n", output_ref, get_id());
luaL_unref(L_NSE, LUA_REGISTRYINDEX, output_ref);
output_ref = LUA_NOREF;
}
void ScriptResult::set_output_tab (lua_State *L, int pos)
{
clear();
lua_pushvalue(L, pos);
output_ref = luaL_ref(L_NSE, LUA_REGISTRYINDEX);
if (o.debugging > 3)
log_write(LOG_STDOUT, "ScriptResult::set_output_tab %d id %s\n", output_ref, get_id());
}
void ScriptResult::set_output_str (const char *out)
{
output_str = std::string(out);
}
void ScriptResult::set_output_str (const char *out, size_t len)
{
output_str = std::string(out, len);
}
static std::string format_obj(lua_State *L, int pos)
{
std::string output;
pos = lua_absindex(L, pos);
/* Look up the FORMAT_TABLE function from nse_main.lua and call it. */
lua_getfield(L, LUA_REGISTRYINDEX, NSE_FORMAT_TABLE);
if (lua_isnil(L, -1)) {
log_write(LOG_STDOUT, "%s: Cannot find function _R[\"%s\"] that should be in nse_main.lua\n",
SCRIPT_ENGINE, NSE_FORMAT_TABLE);
lua_pop(L, 1);
return output;
}
lua_pushvalue(L, pos);
if (lua_pcall(L, 1, 1, 0) != 0) {
if (o.debugging)
log_write(LOG_STDOUT, "%s: Error in FORMAT_TABLE: %s\n", SCRIPT_ENGINE, lua_tostring(L, -1));
lua_pop(L, 1);
return output;
}
lua_len(L, -1);
output = std::string(lua_tostring(L, -2), luaL_checkint(L, -1));
lua_pop(L, 1);
return output;
}
std::string ScriptResult::get_output_str (void) const
{
std::string output;
/* Explicit string output? */
if (!output_str.empty())
return output_str;
/* Auto-formatted table output? */
lua_rawgeti(L_NSE, LUA_REGISTRYINDEX, output_ref);
if (!lua_isnil(L_NSE, -1))
output = format_obj(L_NSE, -1);
lua_pop(L_NSE, 1);
return output;
}
void ScriptResult::set_id (const char *ident)
{
id = std::string(ident);
}
const char *ScriptResult::get_id (void) const
{
return id.c_str();
}
ScriptResults *get_script_scan_results_obj (void)
{
return &script_scan_results;
}
static void format_xml(lua_State *L, int pos)
{
pos = lua_absindex(L, pos);
/* Look up the FORMAT_XML function from nse_main.lua and call it. */
lua_getfield(L, LUA_REGISTRYINDEX, NSE_FORMAT_XML);
if (lua_isnil(L, -1)) {
log_write(LOG_STDOUT, "%s: Cannot find function _R[\"%s\"] that should be in nse_main.lua\n",
SCRIPT_ENGINE, NSE_FORMAT_XML);
lua_pop(L, 1);
return;
}
lua_pushvalue(L, pos);
if (lua_pcall(L, 1, 1, 0) != 0) {
if (o.debugging)
log_write(LOG_STDOUT, "%s: Error in FORMAT_XML: %s\n", SCRIPT_ENGINE, lua_tostring(L, -1));
lua_pop(L, 1);
return;
}
}
void ScriptResult::write_xml() const
{
std::string output_str;
xml_open_start_tag("script");
xml_attribute("id", "%s", get_id());
output_str = get_output_str();
if (!output_str.empty())
xml_attribute("output", "%s", protect_xml(output_str).c_str());
/* Any table output? */
lua_rawgeti(L_NSE, LUA_REGISTRYINDEX, output_ref);
if (!lua_isnil(L_NSE, -1)) {
xml_close_start_tag();
format_xml(L_NSE, -1);
xml_end_tag();
} else {
xml_close_empty_tag();
}
lua_pop(L_NSE, 1);
}
/* int panic (lua_State *L)
*
* Panic function set via lua_atpanic().
*/
static int panic (lua_State *L)
{
const char *err = lua_tostring(L, 1);
fatal("Unprotected error in Lua:\n%s\n", err);
return 0;
}
static void set_nmap_libraries (lua_State *L)
{
static const luaL_Reg libs[] = {
{NSE_PCRELIBNAME, luaopen_pcrelib},
{NSE_NMAPLIBNAME, luaopen_nmap},
{NSE_BINLIBNAME, luaopen_binlib},
{BITLIBNAME, luaopen_bit},
{LFSLIBNAME, luaopen_lfs},
#ifdef HAVE_OPENSSL
{OPENSSLLIBNAME, luaopen_openssl},
#endif
{NULL, NULL}
};
for (int i = 0; libs[i].name; i++) {
luaL_requiref(L, libs[i].name, libs[i].func, 1);
lua_pop(L, 1);
}
}
static int init_main (lua_State *L)
{
char path[MAXPATHLEN];
std::vector<std::string> *rules = (std::vector<std::string> *)
lua_touserdata(L, 1);
/* Load some basic libraries */
luaL_openlibs(L);
set_nmap_libraries(L);
lua_newtable(L);
lua_setfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
if (nmap_fetchfile(path, sizeof(path), "nse_main.lua") != 1)
luaL_error(L, "could not locate nse_main.lua");
if (luaL_loadfile(L, path) != 0)
luaL_error(L, "could not load nse_main.lua: %s", lua_tostring(L, -1));
/* The first argument to the NSE Main Lua code is the private nse
* library table which exposes certain necessary C functions to
* the Lua engine.
*/
open_cnse(L); /* first argument */
/* The second argument is the script rules, including the
* files/directories/categories passed as the userdata to this function.
*/
lua_createtable(L, rules->size(), 0); /* second argument */
for (std::vector<std::string>::iterator si = rules->begin(); si != rules->end(); si++)
nseU_appendfstr(L, -1, "%s", si->c_str());
lua_call(L, 2, 1); /* returns the NSE main function */
lua_setfield(L, LUA_REGISTRYINDEX, NSE_MAIN);
return 0;
}
static int run_main (lua_State *L)
{
std::vector<Target *> *targets = (std::vector<Target*> *)
lua_touserdata(L, 1);
/* New host group */
lua_newtable(L);
lua_setfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
lua_getfield(L, LUA_REGISTRYINDEX, NSE_MAIN);
assert(lua_isfunction(L, -1));
/* The first argument to the NSE main function is the list of targets. This
* has all the target names, 1-N, in a list.
*/
lua_createtable(L, targets->size(), 0);
int targets_table = lua_gettop(L);
lua_getfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
int current_hosts = lua_gettop(L);
for (std::vector<Target *>::iterator ti = targets->begin(); ti != targets->end(); ti++)
{
Target *target = (Target *) *ti;
const char *TargetName = target->TargetName();
const char *targetipstr = target->targetipstr();
lua_newtable(L);
set_hostinfo(L, target);
lua_rawseti(L, targets_table, lua_rawlen(L, targets_table) + 1);
if (TargetName != NULL && strcmp(TargetName, "") != 0)
lua_pushstring(L, TargetName);
else
lua_pushstring(L, targetipstr);
lua_pushlightuserdata(L, target);
lua_rawset(L, current_hosts); /* add to NSE_CURRENT_HOSTS */
}
lua_settop(L, targets_table);
/* Push script scan phase type. Second argument to NSE main function */
switch (o.current_scantype)
{
case SCRIPT_PRE_SCAN:
lua_pushliteral(L, NSE_PRE_SCAN);
break;
case SCRIPT_SCAN:
lua_pushliteral(L, NSE_SCAN);
break;
case SCRIPT_POST_SCAN:
lua_pushliteral(L, NSE_POST_SCAN);
break;
default:
fatal("%s: failed to set the script scan phase.\n", SCRIPT_ENGINE);
}
lua_call(L, 2, 0);
return 0;
}
/* int nse_yield (lua_State *L, int ctx, lua_CFunction k) [-?, +?, e]
*
* This function will yield the running thread back to NSE, even across script
* auxiliary coroutines. All NSE initiated yields must use this function. The
* correct and only way to call is as a tail call:
* return nse_yield(L, 0, NULL);
*/
int nse_yield (lua_State *L, int ctx, lua_CFunction k)
{
lua_getfield(L, LUA_REGISTRYINDEX, NSE_YIELD);
lua_pushthread(L);
lua_call(L, 1, 1); /* returns NSE_YIELD_VALUE */
return lua_yieldk(L, 1, ctx, k); /* yield with NSE_YIELD_VALUE */
}
/* void nse_restore (lua_State *L, int number) [-, -, e]
*
* Restore the thread 'L' back into the running NSE queue. 'number' is the
* number of values on the stack to be passed when the thread is resumed. This
* function may cause a panic due to extraordinary and unavoidable
* circumstances.
*/
void nse_restore (lua_State *L, int number)
{
luaL_checkstack(L, 5, "nse_restore: stack overflow");
lua_pushthread(L);
lua_getfield(L, LUA_REGISTRYINDEX, NSE_WAITING_TO_RUNNING);
lua_insert(L, -(number+2)); /* move WAITING_TO_RUNNING down below the args */
lua_insert(L, -(number+1)); /* move thread above WAITING_TO_RUNNING */
/* Call WAITING_TO_RUNNING (defined in nse_main.lua) on the thread and any
other arguments. */
if (lua_pcall(L, number+1, 0, 0) != 0)
fatal("%s: WAITING_TO_RUNNING error!\n%s", __func__, lua_tostring(L, -1));
}
/* void nse_destructor (lua_State *L, char what) [-(1|2), +0, e]
*
* This function adds (what = 'a') or removes (what = 'r') a destructor from
* the Thread owning the running Lua thread (L). A destructor is called when
* the thread finishes for any reason (including error). A unique key is used
* to associate with the destructor so it is removable later.
*
* what == 'r', destructor key on stack
* what == 'a', destructor key and destructor function on stack
*/
void nse_destructor (lua_State *L, char what)
{
assert(what == 'a' || what == 'r');
lua_getfield(L, LUA_REGISTRYINDEX, NSE_DESTRUCTOR);
lua_pushstring(L, what == 'a' ? "add" : "remove");
lua_pushthread(L);
if (what == 'a')
{
lua_pushvalue(L, -5); /* destructor key */
lua_pushvalue(L, -5); /* destructor */
}
else
{
lua_pushvalue(L, -4); /* destructor key */
lua_pushnil(L); /* no destructor, we are removing */
}
if (lua_pcall(L, 4, 0, 0) != 0)
fatal("%s: NSE_DESTRUCTOR error!\n%s", __func__, lua_tostring(L, -1));
lua_pop(L, what == 'a' ? 2 : 1);
}
/* void nse_base (lua_State *L) [-0, +1, e]
*
* Returns the base Lua thread (coroutine) for the running thread. The base
* thread is resumed by NSE (runs the action function). Other coroutines being
* used by the base thread may be in a chain of resumes, we use the base thread
* as the "holder" of resources (for the Nsock binding in particular).
*/
void nse_base (lua_State *L)
{
lua_getfield(L, LUA_REGISTRYINDEX, NSE_BASE);
lua_call(L, 0, 1); /* returns base thread */
}
/* void nse_selectedbyname (lua_State *L) [-0, +1, e]
*
* Returns a boolean signaling whether the running script was selected by name
* on the command line (--script).
*/
void nse_selectedbyname (lua_State *L)
{
lua_getfield(L, LUA_REGISTRYINDEX, NSE_SELECTED_BY_NAME);
if (lua_isnil(L, -1)) {
lua_pushboolean(L, 0);
lua_replace(L, -2);
} else {
lua_call(L, 0, 1);
}
}
/* void nse_gettarget (lua_State *L) [-0, +1, -]
*
* Given the index to a string on the stack identifying the host, an ip or a
* targetname (host name specified on the command line, see Target.h), returns
* a lightuserdatum that points to the host's Target (see Target.h). If the
* host cannot be found, nil is returned.
*/
void nse_gettarget (lua_State *L, int index)
{
lua_pushvalue(L, index);
lua_getfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
lua_insert(L, -2);
lua_rawget(L, -2);
lua_replace(L, -2);
}
void open_nse (void)
{
if (L_NSE == NULL)
{
/*
Set the random seed value on behalf of scripts. Since Lua uses the
C rand and srand functions, which have a static seed for the entire
program, we don't want scripts doing this themselves.
*/
srand(get_random_uint());
const lua_Number *version = lua_version(NULL);
double major = (*version) / 100.0;
double minor = fmod(*version, 10.0);
if (o.debugging >= 1)
log_write(LOG_STDOUT, "%s: Using Lua %.0f.%.0f.\n", SCRIPT_ENGINE, major, minor);
if (*version < 502)
fatal("%s: This version of NSE only works with Lua 5.2 or greater.", SCRIPT_ENGINE);
if ((L_NSE = luaL_newstate()) == NULL)
fatal("%s: failed to open a Lua state!", SCRIPT_ENGINE);
lua_atpanic(L_NSE, panic);
lua_settop(L_NSE, 0);
lua_pushcfunction(L_NSE, nseU_traceback);
lua_pushcfunction(L_NSE, init_main);
lua_pushlightuserdata(L_NSE, &o.chosenScripts);
if (lua_pcall(L_NSE, 1, 0, 1))
fatal("%s: failed to initialize the script engine:\n%s\n", SCRIPT_ENGINE, lua_tostring(L_NSE, -1));
lua_settop(L_NSE, 0);
}
}
void script_scan (std::vector<Target *> &targets, stype scantype)
{
o.current_scantype = scantype;
assert(L_NSE != NULL);
lua_settop(L_NSE, 0); /* clear the stack */
lua_pushcfunction(L_NSE, nseU_traceback);
lua_pushcfunction(L_NSE, run_main);
lua_pushlightuserdata(L_NSE, &targets);
if (lua_pcall(L_NSE, 1, 0, 1))
error("%s: Script Engine Scan Aborted.\nAn error was thrown by the "
"engine: %s", SCRIPT_ENGINE, lua_tostring(L_NSE, -1));
lua_settop(L_NSE, 0);
}
void close_nse (void)
{
if (L_NSE != NULL)
{
lua_close(L_NSE);
L_NSE = NULL;
}
}
| 27.37851 | 105 | 0.672256 | [
"object",
"vector"
] |
15677348145bcbd7003b72d702664d650e4b5e95 | 1,327 | cpp | C++ | 牛客面试题/8-22tx-5.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | 牛客面试题/8-22tx-5.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | 牛客面试题/8-22tx-5.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <stdlib.h>
#include<string.h>
using namespace std;
#define int long long
#define INTMAX 0x7fffffffffffffff
signed main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n; cin>>n;
int a[n+10];
for(int i=0;i<n;i++){
cin>>a[i];
}
int ans=INTMAX;
for(int i=0;i<n;i++){
int start=i, end=i;
for(int j=i-1;j>=0;j--){
if(a[i]==a[j]){
start--;
} else {
break;
}
}
for(int j=i+1;j<n;j++){
if(a[i]==a[j]){
end++;
} else {
break;
}
}
int now=a[i], res=0;
while(start!=0 || end!=n-1){
int stdj = INTMAX,eddj = INTMAX;
if(start>0) {
stdj = abs(a[start-1]-now);
}
if(end<n-1) {
eddj = abs(a[end+1]-now);
}
if(stdj > eddj) {
now = a[end+1];
res+=eddj;
end++;
} else {
now = a[start-1];
res+=stdj;
start--;
}
}
ans = min(ans,res);
}
cout<<ans<<endl;
return 0;
}
| 22.491525 | 55 | 0.388093 | [
"vector"
] |
156ec061023202b09794e158273cf78fb3cebc03 | 736 | hpp | C++ | cpplib/math/polyOrigin.hpp | kuroni/cpplibforCP | f948d26120e1d19a182b290b43f54c959446991e | [
"MIT"
] | null | null | null | cpplib/math/polyOrigin.hpp | kuroni/cpplibforCP | f948d26120e1d19a182b290b43f54c959446991e | [
"MIT"
] | null | null | null | cpplib/math/polyOrigin.hpp | kuroni/cpplibforCP | f948d26120e1d19a182b290b43f54c959446991e | [
"MIT"
] | 1 | 2021-08-30T18:58:34.000Z | 2021-08-30T18:58:34.000Z | #pragma once
#include "poly.hpp"
#include "mod.hpp"
template<typename T>
class PolyBaseOrigin : public PolyBase<T> {
public:
using PolyBase<T>::PolyBase;
PolyBaseOrigin (const PolyBase<T> &x) : PolyBase<T>(x) {}
protected:
PolyBaseOrigin mul(const PolyBaseOrigin &rhs) const {
std::vector<T> ans(this->size() + rhs.size() - 1);
for (int i = 0, sn = this->size(); i < sn; ++i) {
for (int j = 0, rsn = rhs.size(); j < rsn; ++j) {
ans[i + j] += (*this)[i] * rhs[j];
}
}
return PolyBaseOrigin(ans);
}
};
// Origin Poly used for testing
constexpr int ORGM = 1e9 + 7;
using PolyOrigin = Poly<PolyBaseOrigin<MInt<ORGM>>, MInt<ORGM>>;
using PolyOriginDynamic = Poly<PolyBaseOrigin<ModInt>, ModInt>; | 29.44 | 64 | 0.630435 | [
"vector"
] |
157261164b0dc3a8621ed0ecba47999afefb2cc6 | 4,834 | hh | C++ | src/nexus/args.hh | project-arcana/nexus | 95429d94c9d90434f7feb27bb83f5a742c20e562 | [
"MIT"
] | 1 | 2020-12-09T13:54:59.000Z | 2020-12-09T13:54:59.000Z | src/nexus/args.hh | project-arcana/nexus | 95429d94c9d90434f7feb27bb83f5a742c20e562 | [
"MIT"
] | 7 | 2019-11-18T07:06:17.000Z | 2021-10-03T10:53:50.000Z | src/nexus/args.hh | project-arcana/nexus | 95429d94c9d90434f7feb27bb83f5a742c20e562 | [
"MIT"
] | null | null | null | #pragma once
#include <clean-core/function_ptr.hh>
#include <clean-core/span.hh>
#include <clean-core/string.hh>
#include <clean-core/string_view.hh>
#include <clean-core/vector.hh>
#include <nexus/detail/api.hh>
#include <nexus/detail/parse_arg.hh>
namespace nx
{
/// easy parsing of command line args for Nexus Apps
///
/// Supports almost all features desired in
/// https://attractivechaos.wordpress.com/2018/08/31/a-survey-of-argument-parsing-libraries-in-c-c/
///
/// TODO:
/// - generic deserialization
/// - parse(string_view) version
/// - define positional args
/// - get with optional return type
struct NX_API args
{
// setup
public:
args();
args(cc::string app_name, cc::string app_desc = "");
args& disable_help();
args& group(cc::string name);
template <class T>
args& add(T& v, cc::string name, cc::string desc)
{
auto& a = add_arg({cc::move(name)}, cc::move(desc));
a.register_var_parse(v);
return *this;
}
template <class T>
args& add(T& v, std::initializer_list<cc::string> names, cc::string desc)
{
auto& a = add_arg(names, cc::move(desc));
a.register_var_parse(v);
return *this;
}
template <class T = bool>
args& add(cc::string name, cc::string desc)
{
auto& a = add_arg({cc::move(name)}, cc::move(desc));
a.expect_val = !std::is_same_v<T, bool>;
return *this;
}
template <class T = bool>
args& add(std::initializer_list<cc::string> names, cc::string desc)
{
auto& a = add_arg(names, cc::move(desc));
a.expect_val = !std::is_same_v<T, bool>;
return *this;
}
args& version(cc::string v);
// parse
public:
bool parse(); ///< takes app args
bool parse(int argc, char const* const* argv);
void print_help() const;
// retrieval
public:
bool has(cc::string_view name) const;
int count_of(cc::string_view name) const;
int idx_of(cc::string_view name) const; // -1 if not found
template <class T>
T get_or(cc::string_view name, T const& def) const
{
for (auto const& a : _parsed_args)
for (auto const& n : a.a->names)
if (n == name)
{
T v;
static_assert(!std::is_same_v<decltype(nx::detail::parse_arg(v, a.value)), nx::detail::not_supported>, //
"argument type not supported");
if (nx::detail::parse_arg(v, a.value))
return v;
else
return def;
}
return def;
}
cc::vector<cc::string> positional_args() const;
private:
struct arg
{
bool expect_val = true;
cc::vector<cc::string> names;
cc::string description;
cc::string group;
void* target = nullptr;
cc::function_ptr<bool(void*, cc::string const&)> on_parse = nullptr;
template <class T>
void register_var_parse(T& v)
{
target = &v;
if constexpr (std::is_same_v<T, bool>)
{
expect_val = false;
on_parse = [](void* t, cc::string const&) -> bool {
*static_cast<bool*>(t) = true;
return true;
};
}
else
{
expect_val = true;
on_parse = [](void* t, cc::string const& s) -> bool {
T& vv = *static_cast<T*>(t);
static_assert(!std::is_same_v<decltype(nx::detail::parse_arg(vv, s)), nx::detail::not_supported>, "argument type not supported");
return nx::detail::parse_arg(vv, s);
};
}
}
};
struct pos_arg
{
int min_count = 0;
char metavar = 0;
cc::string description;
};
struct parsed_arg
{
arg const* a = nullptr;
cc::string value;
};
struct parsed_pos_arg
{
pos_arg const* a = nullptr;
cc::vector<cc::string> values;
};
arg& add_arg(std::initializer_list<cc::string> names, cc::string desc);
pos_arg& add_pos_arg(char n, cc::string desc);
bool _disable_help = false;
cc::string _version;
cc::string _app_name;
cc::string _app_desc;
cc::string _curr_group;
cc::vector<arg> _args;
cc::vector<pos_arg> _pos_args;
cc::vector<parsed_arg> _parsed_args;
cc::vector<parsed_pos_arg> _parsed_pos_args;
};
/// returns all command line arguments of the currently running test or app
NX_API cc::span<char const* const> get_cmd_args();
/// returns true if the current test or app was launched with the given command line argument
NX_API bool has_cmd_arg(cc::string_view arg);
}
| 27.622857 | 149 | 0.561026 | [
"vector"
] |
157b3b666362e82b9fa2f5f62e99120200f1da93 | 3,567 | cpp | C++ | srrg2_proslam/src/srrg2_proslam/mapping/mergers/merger_projective_depth_ekf_impl.cpp | srrg-sapienza/srrg2_proslam | 6321cd9f8c892c1949442abce6a934106954b2ae | [
"BSD-3-Clause"
] | 16 | 2020-03-11T14:27:38.000Z | 2021-12-08T13:05:29.000Z | srrg2_proslam/src/srrg2_proslam/mapping/mergers/merger_projective_depth_ekf_impl.cpp | srrg-sapienza/srrg2_proslam | 6321cd9f8c892c1949442abce6a934106954b2ae | [
"BSD-3-Clause"
] | 4 | 2020-05-21T11:59:27.000Z | 2021-09-08T03:59:24.000Z | srrg2_proslam/src/srrg2_proslam/mapping/mergers/merger_projective_depth_ekf_impl.cpp | srrg-sapienza/srrg2_proslam | 6321cd9f8c892c1949442abce6a934106954b2ae | [
"BSD-3-Clause"
] | 1 | 2020-11-30T08:17:23.000Z | 2020-11-30T08:17:23.000Z | #include "merger_projective_depth_ekf.h"
namespace srrg2_proslam {
using namespace srrg2_slam_interfaces;
using namespace srrg2_core;
template <typename TransformType_, typename FixedType_, typename MovingType_>
void MergerProjectiveDepthEKF_<TransformType_, FixedType_, MovingType_>::_precompute() {
using LandmarkEstimatorEKFType =
LandmarkEstimatorEKF_<typename MeasurementPointType::VectorType, ScenePointType>;
assert(BaseType::param_projector.value());
assert(BaseType::param_projector->cameraMatrix().norm() > 0);
assert(BaseType::param_landmark_estimator.value());
if (!param_unprojector.value()) {
throw std::runtime_error("MergerProjectiveDepthEKF_::_precompute|ERROR: unprojector not set");
}
assert(param_unprojector->cameraMatrix().norm() > 0);
if ((param_unprojector->cameraMatrix() - BaseType::param_projector->cameraMatrix()).norm() >
1e-5) {
throw std::runtime_error(
"MergerProjectiveDepthEKF_::_precompute|ERROR: mismatching camera matrices");
}
// ds TODO move this ugly bastard to initialization
std::shared_ptr<LandmarkEstimatorEKFType> landmark_estimator_ekf =
std::dynamic_pointer_cast<LandmarkEstimatorEKFType>(
BaseType::param_landmark_estimator.value());
assert(landmark_estimator_ekf);
assert(landmark_estimator_ekf->param_filter.value());
landmark_estimator_ekf->param_filter->setCameraMatrix(
param_unprojector->cameraMatrix().template cast<double>());
// ds transition estimate TODO enable proper covariance
// const TransformType_ measurement_in_scene = BaseType::_transform.inverse();
// Matrix3d transition_covariance(Matrix3d::Identity());
// transition_covariance *= measurement_in_scene.translation().norm();
// ds update landmark estimator with current global pose (landmark exist over local maps)
// ds and the transform to the local map (scene) coordinate frame
BaseType::param_landmark_estimator->setTransforms(BaseType::_measurement_in_world,
BaseType::_measurement_in_scene);
}
template <typename TransformType_, typename FixedType_, typename MovingType_>
bool MergerProjectiveDepthEKF_<TransformType_, FixedType_, MovingType_>::_isBetterForAddition(
const MeasurementPointType& point_a_,
const MeasurementPointType& point_b_) const {
assert(point_a_.coordinates()(2) >= 0);
assert(point_b_.coordinates()(2) >= 0);
// ds if the candidate depth is lower than the occupying one we prefer it
return (point_a_.coordinates()(2) < point_b_.coordinates()(2));
}
template <typename TransformType_, typename FixedType_, typename MovingType_>
void
MergerProjectiveDepthEKF_<TransformType_, FixedType_, MovingType_>::_adaptFromMeasurementToScene(
const MeasurementPointCloudType& points_in_measurement_space_,
ScenePointCloudType& points_in_scene_space_) const {
points_in_scene_space_.clear();
if (points_in_measurement_space_.empty()) {
return;
}
// ds unproject points in current left camera frame
assert(param_unprojector.value());
param_unprojector->compute(points_in_measurement_space_, points_in_scene_space_);
if (points_in_scene_space_.empty()) {
std::cerr << FG_RED("MergerProjectiveDepthEKF_::_adaptFromMeasurementToScene|WARNING: all "
"unprojections failed");
std::cerr << " (target: " << points_in_measurement_space_.size() << ")" << std::endl;
}
}
} // namespace srrg2_proslam
| 46.934211 | 100 | 0.736193 | [
"transform"
] |
157ef18dc0a169c2e25ca79a33f7188b11e83e01 | 3,485 | cpp | C++ | src/utils/transform_feedback.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | src/utils/transform_feedback.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | src/utils/transform_feedback.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | #include "chokoengine.hpp"
CE_BEGIN_NAMESPACE
namespace {
bool trycompile(GLuint& shad) {
glCompileShader(shad);
int compile_result;
glGetShaderiv(shad, GL_COMPILE_STATUS, &compile_result);
if (!compile_result) {
int info_log_length = 0;
glGetShaderiv(shad, GL_INFO_LOG_LENGTH, &info_log_length);
if (!!info_log_length) {
std::vector<char> shader_log(info_log_length);
glGetShaderInfoLog(shad, info_log_length, NULL, &shader_log[0]);
shad = 0;
Debug::Error("_TransformFeedback", std::string(shader_log.data(), info_log_length));
}
glDeleteShader(shad);
return false;
}
return true;
}
}
_TransformFeedback::_TransformFeedback(const std::string& shader, std::initializer_list<const char*> outNms)
: _TransformFeedback(shader, "", outNms) {}
_TransformFeedback::_TransformFeedback(const std::string& vert, const std::string& geom, std::initializer_list<const char*> outNms) {
const bool hasg = geom != "";
const char* cc[2] = { vert.c_str(), geom.c_str() };
GLuint _vshad = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(_vshad, 1, cc, nullptr);
if (!trycompile(_vshad)) {
return;
}
GLuint _gshad;
if (hasg) {
_gshad = glCreateShader(GL_GEOMETRY_SHADER);
glShaderSource(_gshad, 1, cc + 1, nullptr);
if (!trycompile(_gshad)) {
glDeleteShader(_vshad);
return;
}
}
_program = glCreateProgram();
glAttachShader(_program, _vshad);
if (hasg) {
glAttachShader(_program, _gshad);
}
glTransformFeedbackVaryings(_program, outNms.size(), outNms.begin(), GL_SEPARATE_ATTRIBS);
int link_result = 0;
glLinkProgram(_program);
glGetProgramiv(_program, GL_LINK_STATUS, &link_result);
if (!link_result) {
int info_log_length = 0;
glGetProgramiv(_program, GL_INFO_LOG_LENGTH, &info_log_length);
std::vector<char> program_log(info_log_length);
glGetProgramInfoLog(_program, info_log_length, NULL, &program_log[0]);
Debug::Error("_TransformFeedback", "Link error: " + std::string(program_log.data(), info_log_length));
glDeleteProgram(_program);
_program = 0;
return;
}
glDetachShader(_program, _vshad);
glDeleteShader(_vshad);
if (hasg) {
glDetachShader(_program, _gshad);
glDeleteShader(_gshad);
}
}
void _TransformFeedback::AddUniforms(std::initializer_list<const char*> nms) {
for (auto nm : nms) {
_uniforms.push_back(glGetUniformLocation(_program, nm));
}
}
GLint _TransformFeedback::Loc(int i) const {
return _uniforms[i];
}
void _TransformFeedback::Bind() {
glUseProgram(_program);
_vao->Bind();
for (int a = 0; a < _outputs.size(); a++) {
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, a, _outputs[a]->_pointer);
}
}
void _TransformFeedback::Unbind() {
for (int a = 0; a < _outputs.size(); a++) {
glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, a, 0);
}
glBindVertexArray(0);
glUseProgram(0);
}
void _TransformFeedback::Exec(int n, GLuint type) {
glEnable(GL_RASTERIZER_DISCARD);
glBeginTransformFeedback(type);
glDrawArrays(GL_POINTS, 0, (n > 0) ? n : _vao->buffer(0)->num() * 3);
glEndTransformFeedback();
glDisable(GL_RASTERIZER_DISCARD);
glFlush();
}
TransformFeedback TransformFeedback_New(const std::string& shader, std::initializer_list<const char*> outNms) {
return std::make_shared<_TransformFeedback>(shader, outNms);
}
TransformFeedback TransformFeedback_New(const std::string& vert, const std::string& geom, std::initializer_list<const char*> outNms) {
return std::make_shared<_TransformFeedback>(vert, geom, outNms);
}
CE_END_NAMESPACE | 29.533898 | 134 | 0.733142 | [
"vector"
] |
15911d63b9fad5c37b1764bd059ce50c310f7788 | 16,890 | cc | C++ | chrome/browser/search/ntp_icon_source.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/search/ntp_icon_source.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/search/ntp_icon_source.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 2018 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 "chrome/browser/search/ntp_icon_source.h"
#include <stddef.h>
#include <algorithm>
#include <cmath>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/hash/sha1.h"
#include "base/memory/ref_counted_memory.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "cc/paint/skia_paint_canvas.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/favicon/favicon_utils.h"
#include "chrome/browser/history/top_sites_factory.h"
#include "chrome/browser/image_fetcher/image_decoder_impl.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/suggestions/suggestions_service_factory.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/platform_locale_settings.h"
#include "components/favicon/core/fallback_url_util.h"
#include "components/favicon/core/favicon_service.h"
#include "components/favicon_base/favicon_types.h"
#include "components/favicon_base/favicon_util.h"
#include "components/history/core/browser/top_sites.h"
#include "components/image_fetcher/core/image_fetcher_impl.h"
#include "components/suggestions/proto/suggestions.pb.h"
#include "components/suggestions/suggestions_service.h"
#include "content/public/browser/storage_partition.h"
#include "extensions/common/image_util.h"
#include "net/base/escape.h"
#include "net/base/url_util.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/web_ui_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/favicon_size.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/native_theme/native_theme.h"
#include "url/gurl.h"
namespace {
const char kIconSourceUmaClientName[] = "NtpIconSource";
const char kShowFallbackMonogramParam[] = "show_fallback_monogram";
// The requested color of the icon in 8-digit Hex format (e.g., #757575FF).
const char kColorParam[] = "color";
// The requested size of the icon.
const char kSizeParam[] = "size";
// The URL for which to create an icon.
const char kUrlParam[] = "url";
// Size of the icon background (gray circle), in dp.
const int kIconSizeDip = 48;
// Size of the favicon fallback (letter + colored circle), in dp.
const int kFallbackSizeDip = 32;
// Maximum size of the icon, in dp.
const int kMaxIconSizeDip = 192;
// URL to the server favicon service. "alt=404" means the service will return a
// 404 if an icon can't be found.
const char kServerFaviconURL[] =
"https://s2.googleusercontent.com/s2/favicons?domain_url=%s&alt=404&sz=32";
// Used to parse the specification from the path.
struct ParsedNtpIconPath {
// The URL for which the icon is being requested.
GURL url;
// The requested color of the icon in 8-digit Hex format (e.g., #757575FF).
std::string color_rgba;
// The size of the requested icon in dip.
int size_in_dip = 0;
// The device scale factor of the requested icon.
float device_scale_factor = 1.0;
// Whether to show a circle + letter monogram if an icon is unable.
bool show_fallback_monogram = true;
};
float GetMaxDeviceScaleFactor() {
std::vector<float> favicon_scales = favicon_base::GetFaviconScales();
DCHECK(!favicon_scales.empty());
return favicon_scales.back();
}
// Parses the path after chrome-search://ntpicon/. Example path is
// "?size=24@2x&url=https%3A%2F%2Fcnn.com"
const ParsedNtpIconPath ParseNtpIconPath(const std::string& path) {
ParsedNtpIconPath parsed;
parsed.show_fallback_monogram = true;
parsed.size_in_dip = gfx::kFaviconSize;
parsed.url = GURL();
if (path.empty())
return parsed;
// NOTE(dbeam): can't start with an empty GURL() and use ReplaceComponents()
// because it's not allowed for invalid URLs.
GURL request = GURL(base::StrCat({chrome::kChromeSearchScheme, "://",
chrome::kChromeUINewTabIconHost}))
.Resolve(path);
for (net::QueryIterator it(request); !it.IsAtEnd(); it.Advance()) {
std::string key = it.GetKey();
if (key == kShowFallbackMonogramParam) {
parsed.show_fallback_monogram = it.GetUnescapedValue() != "false";
} else if (key == kColorParam) {
parsed.color_rgba = it.GetUnescapedValue();
} else if (key == kSizeParam) {
std::vector<std::string> pieces =
base::SplitString(it.GetUnescapedValue(), "@", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY);
if (pieces.empty() || pieces.size() > 2)
continue;
int size_in_dip = 0;
if (!base::StringToInt(pieces[0], &size_in_dip))
continue;
parsed.size_in_dip = std::min(size_in_dip, kMaxIconSizeDip);
if (pieces.size() > 1) {
float scale_factor = 0.0;
webui::ParseScaleFactor(pieces[1], &scale_factor);
// Do not exceed the maximum scale factor for the device.
parsed.device_scale_factor =
std::min(scale_factor, GetMaxDeviceScaleFactor());
}
} else if (key == kUrlParam) {
parsed.url = GURL(it.GetUnescapedValue());
}
}
return parsed;
}
// Will draw |bitmap| in the center of the |canvas| of a given |size|.
// |bitmap| keeps its size.
void DrawFavicon(const SkBitmap& bitmap, gfx::Canvas* canvas, int size) {
int x_origin = (size - bitmap.width()) / 2;
int y_origin = (size - bitmap.height()) / 2;
canvas->DrawImageInt(gfx::ImageSkia::CreateFromBitmap(bitmap, /*scale=*/1.f),
x_origin, y_origin);
}
} // namespace
struct NtpIconSource::NtpIconRequest {
NtpIconRequest(content::URLDataSource::GotDataCallback cb,
const GURL& path,
int icon_size_in_pixels,
std::string color_rgba,
float scale,
bool show_fallback_monogram)
: callback(std::move(cb)),
path(path),
icon_size_in_pixels(icon_size_in_pixels),
color_rgba(color_rgba),
device_scale_factor(scale),
show_fallback_monogram(show_fallback_monogram) {}
NtpIconRequest(NtpIconRequest&& other) = default;
NtpIconRequest& operator=(NtpIconRequest&& other) = default;
~NtpIconRequest() {}
content::URLDataSource::GotDataCallback callback;
GURL path;
int icon_size_in_pixels;
std::string color_rgba;
float device_scale_factor;
bool show_fallback_monogram;
};
NtpIconSource::NtpIconSource(Profile* profile)
: profile_(profile),
image_fetcher_(std::make_unique<image_fetcher::ImageFetcherImpl>(
std::make_unique<ImageDecoderImpl>(),
content::BrowserContext::GetDefaultStoragePartition(profile)
->GetURLLoaderFactoryForBrowserProcess())) {}
NtpIconSource::~NtpIconSource() = default;
std::string NtpIconSource::GetSource() {
return chrome::kChromeUINewTabIconHost;
}
void NtpIconSource::StartDataRequest(
const GURL& url,
const content::WebContents::Getter& wc_getter,
content::URLDataSource::GotDataCallback callback) {
favicon::FaviconService* favicon_service =
FaviconServiceFactory::GetForProfile(profile_,
ServiceAccessType::EXPLICIT_ACCESS);
const ParsedNtpIconPath parsed =
ParseNtpIconPath(content::URLDataSource::URLToRequestPath(url));
if (parsed.url.is_valid()) {
int icon_size_in_pixels =
std::ceil(parsed.size_in_dip * parsed.device_scale_factor);
NtpIconRequest request(std::move(callback), parsed.url, icon_size_in_pixels,
parsed.color_rgba, parsed.device_scale_factor,
parsed.show_fallback_monogram);
// Check if the requested URL is part of the prepopulated pages (currently,
// only the Web Store).
scoped_refptr<history::TopSites> top_sites =
TopSitesFactory::GetForProfile(profile_);
if (top_sites) {
for (const auto& prepopulated_page : top_sites->GetPrepopulatedPages()) {
if (parsed.url == prepopulated_page.most_visited.url) {
gfx::Image& image =
ui::ResourceBundle::GetSharedInstance().GetImageNamed(
prepopulated_page.favicon_id);
// Resize as necessary.
gfx::Size target_size(icon_size_in_pixels, icon_size_in_pixels);
if (!image.IsEmpty() && image.Size() != target_size) {
gfx::ImageSkia resized_image =
gfx::ImageSkiaOperations::CreateResizedImage(
image.AsImageSkia(), skia::ImageOperations::RESIZE_BEST,
target_size);
ReturnRenderedIconForRequest(std::move(request),
gfx::Image(resized_image).AsBitmap());
} else {
ReturnRenderedIconForRequest(std::move(request), image.AsBitmap());
}
return;
}
}
}
// This will query for a local favicon. If not found, will take alternative
// action in OnLocalFaviconAvailable.
const bool fallback_to_host = true;
favicon_service->GetRawFaviconForPageURL(
parsed.url, {favicon_base::IconType::kFavicon}, icon_size_in_pixels,
fallback_to_host,
base::BindOnce(&NtpIconSource::OnLocalFaviconAvailable,
weak_ptr_factory_.GetWeakPtr(), std::move(request)),
&cancelable_task_tracker_);
} else {
std::move(callback).Run(nullptr);
}
}
std::string NtpIconSource::GetMimeType(const std::string&) {
// NOTE: this may not always be correct for all possible types that this
// source will serve. Seems to work fine, however.
return "image/png";
}
bool NtpIconSource::ShouldServiceRequest(
const GURL& url,
content::BrowserContext* browser_context,
int render_process_id) {
if (url.SchemeIs(chrome::kChromeSearchScheme)) {
return InstantService::ShouldServiceRequest(url, browser_context,
render_process_id);
}
return URLDataSource::ShouldServiceRequest(url, browser_context,
render_process_id);
}
void NtpIconSource::OnLocalFaviconAvailable(
NtpIconRequest request,
const favicon_base::FaviconRawBitmapResult& bitmap_result) {
if (bitmap_result.is_valid()) {
// A local favicon was found. Decode it to an SkBitmap so it can eventually
// be passed as valid image data to ReturnRenderedIconForRequest.
SkBitmap bitmap;
bool result =
gfx::PNGCodec::Decode(bitmap_result.bitmap_data.get()->front(),
bitmap_result.bitmap_data.get()->size(), &bitmap);
DCHECK(result);
ReturnRenderedIconForRequest(std::move(request), bitmap);
} else {
// Since a local favicon was not found, attempt to fetch a server icon if
// the url is known to the server (this last check is important to avoid
// leaking private history to the server).
RequestServerFavicon(std::move(request));
}
}
bool NtpIconSource::IsRequestedUrlInServerSuggestions(const GURL& url) {
suggestions::SuggestionsService* suggestions_service =
suggestions::SuggestionsServiceFactory::GetForProfile(profile_);
if (!suggestions_service)
return false;
suggestions::SuggestionsProfile profile =
suggestions_service->GetSuggestionsDataFromCache().value_or(
suggestions::SuggestionsProfile());
auto position =
std::find_if(profile.suggestions().begin(), profile.suggestions().end(),
[url](const suggestions::ChromeSuggestion& suggestion) {
return suggestion.url() == url.spec();
});
return position != profile.suggestions().end();
}
void NtpIconSource::RequestServerFavicon(NtpIconRequest request) {
// Only fetch a server icon if the page url is known to the server. This check
// is important to avoid leaking private history to the server.
const GURL server_favicon_url =
GURL(base::StringPrintf(kServerFaviconURL, request.path.spec().c_str()));
if (!server_favicon_url.is_valid() ||
!IsRequestedUrlInServerSuggestions(request.path)) {
ReturnRenderedIconForRequest(std::move(request), SkBitmap());
return;
}
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("ntp_icon_source", R"(
semantics {
sender: "NTP Icon Source"
description:
"Retrieves icons for site suggestions based on the user's browsing "
"history, for use e.g. on the New Tab page."
trigger:
"Triggered when an icon for a suggestion is required (e.g. on "
"the New Tab page), no local icon is available and the URL is known "
"to the server (hence no private information is revealed)."
data: "The URL for which to retrieve an icon."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: NO
setting:
"Users cannot disable this feature. The feature is enabled by "
"default."
policy_exception_justification: "Not implemented."
})");
image_fetcher::ImageFetcherParams params(traffic_annotation,
kIconSourceUmaClientName);
params.set_frame_size(
gfx::Size(request.icon_size_in_pixels, request.icon_size_in_pixels));
image_fetcher_->FetchImage(
server_favicon_url,
base::BindOnce(&NtpIconSource::OnServerFaviconAvailable,
weak_ptr_factory_.GetWeakPtr(), std::move(request)),
std::move(params));
}
void NtpIconSource::OnServerFaviconAvailable(
NtpIconRequest request,
const gfx::Image& fetched_image,
const image_fetcher::RequestMetadata& metadata) {
// If a server icon was not found, |fetched_bitmap| will be empty and a
// fallback icon will be eventually drawn.
SkBitmap fetched_bitmap = fetched_image.AsBitmap();
if (!fetched_bitmap.empty()) {
// The received server icon bitmap may still be bigger than our desired
// size, so resize it.
fetched_bitmap = skia::ImageOperations::Resize(
fetched_bitmap, skia::ImageOperations::RESIZE_BEST,
request.icon_size_in_pixels, request.icon_size_in_pixels);
}
ReturnRenderedIconForRequest(std::move(request), fetched_bitmap);
}
void NtpIconSource::ReturnRenderedIconForRequest(NtpIconRequest request,
const SkBitmap& favicon) {
// Only use even pixel sizes to avoid issues when centering the fallback
// monogram.
const int icon_size =
std::round(kIconSizeDip * request.device_scale_factor * 0.5) * 2.0;
const int fallback_size =
std::round(kFallbackSizeDip * request.device_scale_factor * 0.5) * 2.0;
SkBitmap bitmap;
// If necessary, draw the colored fallback monogram.
if (favicon.empty() && request.show_fallback_monogram) {
bitmap = favicon::GenerateMonogramFavicon(request.path, icon_size,
fallback_size);
} else {
bitmap.allocN32Pixels(icon_size, icon_size, false);
cc::SkiaPaintCanvas paint_canvas(bitmap);
gfx::Canvas canvas(&paint_canvas, 1.f);
canvas.DrawColor(SK_ColorTRANSPARENT, SkBlendMode::kSrc);
if (favicon.empty()) {
const auto* default_favicon = favicon::GetDefaultFavicon().ToImageSkia();
const auto& rep =
default_favicon->GetRepresentation(request.device_scale_factor);
gfx::ImageSkia scaled_image(rep);
const auto resized = gfx::ImageSkiaOperations::CreateResizedImage(
scaled_image, skia::ImageOperations::RESIZE_BEST,
gfx::Size(fallback_size, fallback_size));
auto bitmap = *resized.bitmap();
SkColor color = 0;
if (extensions::image_util::ParseHexColorString(request.color_rgba,
&color)) {
bitmap = SkBitmapOperations::CreateColorMask(bitmap, color);
}
DrawFavicon(bitmap, &canvas, icon_size);
} else {
DrawFavicon(favicon, &canvas, icon_size);
}
}
std::vector<unsigned char> bitmap_data;
bool result = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &bitmap_data);
DCHECK(result);
std::move(request.callback)
.Run(base::RefCountedBytes::TakeVector(&bitmap_data));
}
| 38.738532 | 80 | 0.687271 | [
"geometry",
"vector"
] |
159468d80c0ea0ce074e310189a4dd200dc97c8e | 7,005 | hpp | C++ | engine/engine/alice/components/Random.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | null | null | null | engine/engine/alice/components/Random.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | null | null | null | engine/engine/alice/components/Random.hpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2022-01-28T16:37:51.000Z | 2022-01-28T16:37:51.000Z | /*
Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include <algorithm>
#include <cstdint>
#include <mutex>
#include <random>
#include <type_traits>
#include <vector>
#include "engine/alice/alice_codelet.hpp"
#include "engine/core/math/types.hpp"
namespace isaac {
namespace alice {
// Helper component to generate random numbers.
// FIXME(dweikersdorf) This should be a component, however currently configuration is not setup
// yet when the call to initialize happens.
class Random : public Codelet {
public:
void start() override;
// Return a random number using the given distribution.
template <typename T, template<typename> typename Distribution>
T sample(Distribution<T>& dist) {
std::unique_lock<std::mutex> lock(mutex_);
return dist(rng_);
}
// Return a random real using the range (min and max are included).
template <typename T>
T sampleUniformReal(T min, T max) {
static_assert(std::is_floating_point<T>::value, "sampleUniformReal expects a real number type");
std::unique_lock<std::mutex> lock(mutex_);
return std::uniform_real_distribution<T>(min, max)(rng_);
}
template <typename T>
T sampleUniformReal(const Vector2<T>& range) {
return sampleUniformReal(range[0], range[1]);
}
// Return a random integer using the range (min and max are included).
template <typename I>
I sampleUniformInt(I min, I max) {
static_assert(std::is_integral<I>::value, "sampleUniformInt expects an integer type");
std::unique_lock<std::mutex> lock(mutex_);
return std::uniform_int_distribution<I>(min, max)(rng_);
}
template <typename I>
I sampleUniformInt(const Vector2<I>& range) {
return sampleUniformInt(range[0], range[1]);
}
// Returns a random integer `index` such that: 0 <= index < count.
template <typename I>
I sampleUniformIndex(I count) {
static_assert(std::is_integral<I>::value, "sampleUniformInt expects an integer type");
ASSERT(count > 0, "`count` (%s) must be positive", std::to_string(count).c_str());
std::unique_lock<std::mutex> lock(mutex_);
return std::uniform_int_distribution<I>(0, count - 1)(rng_);
}
// Samples a vector in which element is within the corresponding interval defined by the given
// vectors min and max.
template <typename K, int N>
Vector<K, N> sampleUniformRealVector(const Vector<K, N>& min, const Vector<K, N>& max) {
Vector<K, N> result;
for (int i = 0; i < N; i++) {
result[i] = sampleUniformReal(min[i], max[i]);
}
return result;
}
// Samples a vector in which element is within the corresponding interval defined by
// [-range|range]. In different words this is identical to
// sampleUniformRealVector(-range, +range)
template <typename K, int N>
Vector<K, N> sampleUniformRealVector(const Vector<K, N>& range) {
Vector<K, N> result;
for (int i = 0; i < N; i++) {
result[i] = sampleUniformReal(-range[i], +range[i]);
}
return result;
}
// Shuffles the given object using the range iterator
template <typename Iterator>
void shuffle(Iterator start, Iterator end) {
std::unique_lock<std::mutex> lock(mutex_);
std::shuffle(start, end, rng_);
}
// Returns a random unsigned 32 bits integer
uint32_t sampleSeed() {
std::unique_lock<std::mutex> lock(mutex_);
return rng_();
}
// Returns a sample from a normal distribution
template <typename K>
K sampleGaussian(K standard_deviation) {
static_assert(std::is_floating_point<K>::value,
"sampleGaussianVector expects a real number type");
std::unique_lock<std::mutex> lock(mutex_);
return std::normal_distribution<K>(K(0), standard_deviation)(rng_);
}
// Returns a vector of the same side as the one provided by std_deviation containing random value
// following a gaussian distribution of the given standard deviation.
template <typename K, int N>
Vector<K, N> sampleGaussianVector(const Vector<K, N>& std_deviation) {
static_assert(std::is_floating_point<K>::value,
"sampleGaussianVector expects a real number type");
static_assert(N > 0, "sampleGaussianVector expects a compile time sized Vector");
std::unique_lock<std::mutex> lock(mutex_);
Vector<K, N> samples;
for (int i = 0; i < N; ++i) {
samples(i) = std::normal_distribution<K>(K(0), std_deviation(i))(rng_);
}
return samples;
}
// Samples a coin flip, i.e. returns a random Boolean
bool sampleCoin() {
return sampleUniformInt(0, 1) == 0;
}
// Samples a coin flip for a biased coin, i.e. returns true if a random sample from unit interval
// is smaller than the given probability.
bool sampleCoin(double probability) {
return sampleUniformReal(0.0, 1.0) < probability;
}
// Picks a random element from a list with equal probability
template <typename K>
const K& sampleChoice(const std::vector<K>& choices) {
ASSERT(!choices.empty(), "must have at least one option");
return choices[sampleUniformIndex(choices.size())];
}
// Weighted random sampling of an element from a discrete probability density function.
// The index of the chosen element is returned. This functions needs a copy of `pdf` to compute
// the CDF. Use `sampleChoiceCdf` instead if you have the CDF available. It is an error to pass
// an empty PDF.
template <typename K>
size_t sampleDiscretePdf(std::vector<K> pdf) {
// Compute CDF
for (size_t i = 1; i < pdf.size(); i++) {
pdf[i] += pdf[i - 1];
}
return sampleDiscreteCdf(pdf);
}
// Weighted random sampling of an element from a cumulative distribution function.
// The index of the chosen element is returned. It is an error to pass an empty CDF.
template <typename K>
size_t sampleDiscreteCdf(const std::vector<K>& cdf) {
ASSERT(!cdf.empty(), "cdf must have at least one element");
const K value = sampleUniformReal(K(0), cdf.back());
const auto it = std::lower_bound(cdf.begin(), cdf.end(), value);
if (it == cdf.end()) return cdf.size() - 1;
return std::distance(cdf.begin(), it);
}
// Returns the underlying random number generator
std::mt19937& rng() { return rng_; }
// The seed used by the random engine. If use_random_seed is set to true, this seed will be
// ignored.
ISAAC_PARAM(int, seed, 0);
// Whether or not using the default seed or use a random seed that will change from one execution
// to another.
ISAAC_PARAM(bool, use_random_seed, false);
private:
std::mt19937 rng_;
std::mutex mutex_;
};
} // namespace alice
} // namespace isaac
ISAAC_ALICE_REGISTER_CODELET(isaac::alice::Random)
| 36.484375 | 100 | 0.699643 | [
"object",
"vector"
] |
1594d1e0c7255c386bc51bffdfe47d2329a5d392 | 956 | hpp | C++ | coding-interviews/min_number_in_rotate_array_6.hpp | lonelyhentai/nowcoder-collection | db795a5349b59f8cbb69e974adbb90ad30912558 | [
"WTFPL"
] | 1 | 2020-03-08T13:54:54.000Z | 2020-03-08T13:54:54.000Z | coding-interviews/min_number_in_rotate_array_6.hpp | lonelyhentai/nowcoder-collection | db795a5349b59f8cbb69e974adbb90ad30912558 | [
"WTFPL"
] | null | null | null | coding-interviews/min_number_in_rotate_array_6.hpp | lonelyhentai/nowcoder-collection | db795a5349b59f8cbb69e974adbb90ad30912558 | [
"WTFPL"
] | null | null | null | // [旋转数组的最小数字](https://www.nowcoder.com/practice/9f3231a991af4f55b95579b44b7a01ba)
#pragma once
#include <vector>
namespace task6 {
using namespace std;
#define let const auto
class Solution {
public:
// s < m < e
// s< m > e
// s > m< e
int minNumberInRotateArray(const vector<int> &rotateArray) {
if (rotateArray.empty()) return 0;
int left = 0, right = rotateArray.size() - 1;
while (left < right) {
if (rotateArray[left] < rotateArray[right]) return rotateArray[left];
int mid = left + (right - left) / 2;
if (rotateArray[left] < rotateArray[mid])
left = mid + 1;
else if (rotateArray[mid] < rotateArray[right])
right = mid;
else {
++left;
}
}
return rotateArray[left];
}
};
} | 28.969697 | 85 | 0.493724 | [
"vector"
] |
159669e19b29ebd335bedd30fc0354c48efd1a65 | 7,944 | cpp | C++ | tests/core/program_arguments.cpp | swallat/hal | 98b08ac69448c2d7067f1bdd53ba428548c87cc9 | [
"MIT"
] | 1 | 2019-05-13T17:14:35.000Z | 2019-05-13T17:14:35.000Z | tests/core/program_arguments.cpp | swallat/hal | 98b08ac69448c2d7067f1bdd53ba428548c87cc9 | [
"MIT"
] | null | null | null | tests/core/program_arguments.cpp | swallat/hal | 98b08ac69448c2d7067f1bdd53ba428548c87cc9 | [
"MIT"
] | 1 | 2020-01-09T23:38:55.000Z | 2020-01-09T23:38:55.000Z | #include "test_def.h"
#include "gtest/gtest.h"
#include <core/log.h>
#include <core/program_arguments.h>
#include <iostream>
class program_arguments_test : public ::testing::Test
{
protected:
virtual void SetUp()
{
}
virtual void TearDown()
{
}
};
/**
* Testing the access on the original arguments, which were handed over he constructor
*
* Functions: constructor, get_original_arguments
*/
TEST_F(program_arguments_test, check_get_original_arguments){TEST_START
// ########################
// POSITIVE TESTS
// ########################
{// Call the constructor with some arguments and get them after
const char * args[] = {"arg_0", "arg_1"};
program_arguments p_args(2, args);
int ret_argc;
const char** ret_argv;
p_args.get_original_arguments(&ret_argc, &ret_argv);
EXPECT_EQ(ret_argc, 2);
EXPECT_EQ(ret_argv[0], args[0]);
EXPECT_EQ(ret_argv[1], args[1]);
}
TEST_END
}
/**
* Testing the creation of options with stand-alone flags as well as flags with
* equivalent descriptions. Moreover the access of the passed parameters is being tested.
*
* Functions: set_option, get_parameter, get_parameters, is_option_set
*/
TEST_F(program_arguments_test, check_flags_and_parameters)
{
TEST_START
// ########################
// POSITIVE TESTS
// ########################
{
// Set a single flag with a set of parameters
program_arguments p_args;
std::vector<std::string> flag_params = {"param_0", "param_1"};
p_args.set_option("flag_0", flag_params);
EXPECT_TRUE(p_args.is_option_set("flag_0"));
EXPECT_EQ(p_args.get_parameters("flag_0")[0], "param_0");
EXPECT_EQ(p_args.get_parameters("flag_0")[1], "param_1");
}
{
// Set multiple flags with a set of parameters (found_flag part of flag-list)
program_arguments p_args;
std::set<std::string> flags_with_flag_0 = {"flag_0", "flag_1", "flag_2"};
std::vector<std::string> flag_params_1 = {"param_0", "param_1"};
p_args.set_option("flag_0", flags_with_flag_0, flag_params_1);
EXPECT_TRUE(p_args.is_option_set("flag_0"));
EXPECT_TRUE(p_args.is_option_set("flag_1"));
EXPECT_TRUE(p_args.is_option_set("flag_2"));
EXPECT_EQ(p_args.get_parameters("flag_0")[1], "param_1");
EXPECT_EQ(p_args.get_parameters("flag_1")[1], "param_1");
EXPECT_EQ(p_args.get_parameters("flag_2")[1], "param_1");
EXPECT_EQ(p_args.get_set_options()[0], "flag_0");
}
{
// Set multiple flags with a set of parameters (found_flag not part of flag-list)
program_arguments p_args;
std::set<std::string> flags_without_flag_0 = {"flag_1", "flag_2"};
std::vector<std::string> flag_params = {"param_0", "param_1"};
p_args.set_option("flag_0", flags_without_flag_0, flag_params);
EXPECT_TRUE(p_args.is_option_set("flag_0"));
EXPECT_TRUE(p_args.is_option_set("flag_1"));
EXPECT_TRUE(p_args.is_option_set("flag_2"));
EXPECT_EQ(p_args.get_parameters("flag_0")[1], "param_1");
EXPECT_EQ(p_args.get_parameters("flag_1")[1], "param_1");
EXPECT_EQ(p_args.get_parameters("flag_2")[1], "param_1");
EXPECT_EQ(p_args.get_set_options()[0], "flag_0");
}
{
// Set multiple valid options
program_arguments p_args;
std::vector<std::string> flag_params_0 = {"param_0_0"};
p_args.set_option("flag_0", flag_params_0);
std::vector<std::string> flag_params_1 = {"param_1_0", "param_1_1"};
p_args.set_option("flag_1", flag_params_1);
std::vector<std::string> flag_params_2 = {"param_2_0"};
p_args.set_option("flag_2", {"flag_2_1", "flag_2_2"}, flag_params_2);
EXPECT_TRUE(p_args.is_option_set("flag_0"));
EXPECT_TRUE(p_args.is_option_set("flag_1"));
EXPECT_TRUE(p_args.is_option_set("flag_2"));
EXPECT_EQ(p_args.get_parameters("flag_0"), flag_params_0);
EXPECT_EQ(p_args.get_parameters("flag_1"), flag_params_1);
EXPECT_EQ(p_args.get_parameters("flag_2"), flag_params_2);
EXPECT_EQ(p_args.get_parameters("flag_2_1"), flag_params_2);
}
// ########################
// NEGATIVE TESTS
// ########################
{
// Get parameter/-s with unknown flag
NO_COUT_TEST_BLOCK;
program_arguments p_args;
std::vector<std::string> unknown_flag_params = p_args.get_parameters("unknown_flag");
std::string unknown_flag_param = p_args.get_parameter("unknown_flag");
EXPECT_TRUE(unknown_flag_params.empty());
EXPECT_EQ(unknown_flag_param, "");
}
{
// Overwrite a given flag
program_arguments p_args;
std::vector<std::string> flag_params_0 = {"param_0"};
std::vector<std::string> flag_params_1 = {"param_1"};
p_args.set_option("flag", flag_params_0);
p_args.set_option("flag", flag_params_1);
EXPECT_EQ(p_args.get_parameters("flag"), flag_params_1);
}
{
// Overwrite a given flag via alias
program_arguments p_args;
std::vector<std::string> flag_params_0 = {"param_0"};
std::vector<std::string> flag_params_1 = {"param_1"};
p_args.set_option("flag", {"alternate_flag"}, flag_params_0);
p_args.set_option("alternate_flag", flag_params_1);
EXPECT_TRUE(p_args.is_option_set("flag"));
EXPECT_TRUE(p_args.is_option_set("alternate_flag"));
EXPECT_EQ(p_args.get_parameters("flag"), flag_params_1);
}
{
// Set two options with partially overlapping flags
NO_COUT_TEST_BLOCK;
program_arguments p_args;
p_args.set_option("flag_0", {"alternative_flag_0"}, {"param_0"});
bool suc = p_args.set_option("flag_1", {"alternative_flag_0"}, {"param_1"});
EXPECT_FALSE(suc);
EXPECT_TRUE(p_args.is_option_set("flag_0"));
EXPECT_EQ(p_args.get_parameter("flag_0"), "param_0");
EXPECT_FALSE(p_args.is_option_set("flag_1"));
}
{
// Set an options with flags of two different options
NO_COUT_TEST_BLOCK;
program_arguments p_args;
p_args.set_option("flag_0", {"alternative_flag_0"}, {"param_0"});
p_args.set_option("flag_1", {"alternative_flag_1"}, {"param_1"});
bool suc = p_args.set_option("flag_1", {"alternative_flag_0"}, {"param_2"});
EXPECT_FALSE(suc);
EXPECT_TRUE(p_args.is_option_set("flag_0"));
EXPECT_TRUE(p_args.is_option_set("flag_1"));
EXPECT_EQ(p_args.get_parameter("flag_0"), "param_0");
EXPECT_EQ(p_args.get_parameter("flag_1"), "param_1");
}
{
// set an existing option but specify more flags than "last time"
NO_COUT_TEST_BLOCK;
program_arguments p_args;
p_args.set_option("flag", {"alternative_flag_0"}, {});
bool suc = p_args.set_option("flag", {"alternative_flag_0", "alternative_flag_1"}, {});
EXPECT_FALSE(suc);
EXPECT_TRUE(p_args.is_option_set("flag"));
EXPECT_TRUE(p_args.is_option_set("alternative_flag_0"));
EXPECT_FALSE(p_args.is_option_set("alternative_flag_1"));
}
{
// Set a flag with empty parameters
NO_COUT_TEST_BLOCK;
program_arguments p_args;
std::vector<std::string> flag_params = {};
p_args.set_option("flag", flag_params);
std::string param = p_args.get_parameter("flag");
std::vector<std::string> params = p_args.get_parameters("flag");
EXPECT_EQ(param, "");
EXPECT_TRUE(params.empty());
}
TEST_END
}
| 39.522388 | 124 | 0.616566 | [
"vector"
] |
15a00bc72e5b014ecf976f867c88f1674da8dff7 | 32,426 | cxx | C++ | TransformProcessor/MRML/vtkMRMLTransformProcessorNode.cxx | cpinter/SlicerIGT | 85265b6f70c1e499d4996e21854581683a874b89 | [
"BSD-3-Clause"
] | 1 | 2019-07-10T02:43:48.000Z | 2019-07-10T02:43:48.000Z | TransformProcessor/MRML/vtkMRMLTransformProcessorNode.cxx | rprueckl/SlicerIGT | 00ff9bf070d538d5c713bfc375f544ee4e8033bc | [
"BSD-3-Clause"
] | null | null | null | TransformProcessor/MRML/vtkMRMLTransformProcessorNode.cxx | rprueckl/SlicerIGT | 00ff9bf070d538d5c713bfc375f544ee4e8033bc | [
"BSD-3-Clause"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Franklin King, PerkLab, Queen's University
and was supported through the Applied Cancer Research Unit program of Cancer Care
Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care
==============================================================================*/
#include "vtkMRMLTransformProcessorNode.h"
// VTK includes
#include <vtkNew.h>
#include <vtkCommand.h>
#include <vtkObjectFactory.h>
// MRML includes
#include <vtkMRMLScene.h>
#include <vtkMRMLLinearTransformNode.h>
#include <sstream>
//----------------------------------------------------------------------------
// constant strings for MRML reference roles
// these should not be used outside of this class
// (further note: Do *not* put spaces in these names -
// will wreak havok when trying to load from XML)
const char* ROLE_INPUT_COMBINE_TRANSFORM = "InputCombineTransform";
const char* ROLE_INPUT_FROM_TRANSFORM = "InputFromTransform";
const char* ROLE_INPUT_TO_TRANSFORM = "InputToTransform";
const char* ROLE_INPUT_INITIAL_TRANSFORM = "InputInitialTransform";
const char* ROLE_INPUT_CHANGED_TRANSFORM = "InputChangedTransform";
const char* ROLE_INPUT_ANCHOR_TRANSFORM = "InputAnchorTransform";
const char* ROLE_INPUT_FORWARD_TRANSFORM = "InputForwardTransform";
const char* ROLE_OUTPUT_TRANSFORM = "OutputTransform";
//----------------------------------------------------------------------------
vtkMRMLNodeNewMacro( vtkMRMLTransformProcessorNode );
//----------------------------------------------------------------------------
vtkMRMLTransformProcessorNode::vtkMRMLTransformProcessorNode()
{
vtkNew<vtkIntArray> events;
events->InsertNextValue( vtkMRMLTransformNode::TransformModifiedEvent );
this->AddNodeReferenceRole( ROLE_INPUT_COMBINE_TRANSFORM, NULL, events.GetPointer() );
this->AddNodeReferenceRole( ROLE_INPUT_FROM_TRANSFORM, NULL, events.GetPointer() );
this->AddNodeReferenceRole( ROLE_INPUT_TO_TRANSFORM, NULL, events.GetPointer() );
this->AddNodeReferenceRole( ROLE_INPUT_INITIAL_TRANSFORM, NULL, events.GetPointer() );
this->AddNodeReferenceRole( ROLE_INPUT_CHANGED_TRANSFORM, NULL, events.GetPointer() );
this->AddNodeReferenceRole( ROLE_INPUT_ANCHOR_TRANSFORM, NULL, events.GetPointer() );
this->AddNodeReferenceRole( ROLE_INPUT_FORWARD_TRANSFORM, NULL, events.GetPointer() );
this->AddNodeReferenceRole( ROLE_OUTPUT_TRANSFORM );
//Parameters
this->UpdatesPerSecond = 60;
this->ProcessingMode = PROCESSING_MODE_QUATERNION_AVERAGE;
this->UpdateMode = UPDATE_MODE_MANUAL;
this->CopyTranslationComponents[ 0 ] = true;
this->CopyTranslationComponents[ 1 ] = true;
this->CopyTranslationComponents[ 2 ] = true;
this->RotationMode = ROTATION_MODE_COPY_ALL_AXES;
this->PrimaryAxisLabel = AXIS_LABEL_Z;
this->DependentAxesMode = DEPENDENT_AXES_MODE_FROM_PIVOT;
this->SecondaryAxisLabel = AXIS_LABEL_Y;
}
//----------------------------------------------------------------------------
vtkMRMLTransformProcessorNode::~vtkMRMLTransformProcessorNode()
{
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::ReadXMLAttributes( const char** atts )
{
Superclass::ReadXMLAttributes(atts);
const char* attName;
const char* attValue;
while ( *atts != NULL )
{
attName = *( atts++ );
attValue = *( atts++ );
if ( strcmp( attName, "UpdatesPerSecond" ) == 0 )
{
std::stringstream ss;
ss << attValue;
ss >> this->UpdatesPerSecond;
continue;
}
else if ( strcmp( attName, "UpdateMode" ) == 0 )
{
int modeAsInt = this->GetUpdateModeFromString( attValue );
if ( modeAsInt >= 0 && modeAsInt < UPDATE_MODE_LAST)
{
this->UpdateMode = modeAsInt;
}
else
{
vtkWarningMacro("Unrecognized update mode read from MRML node: " << attValue << ". Setting to manual update.")
this->UpdateMode = UPDATE_MODE_MANUAL;
}
}
else if ( strcmp( attName, "ProcessingMode" ) == 0 )
{
int modeAsInt = this->GetProcessingModeFromString( attValue );
if ( modeAsInt >= 0 && modeAsInt < PROCESSING_MODE_LAST)
{
this->ProcessingMode = modeAsInt;
}
else
{
vtkWarningMacro("Unrecognized processing mode read from MRML node: " << attValue << ". Setting to quaternion average.")
this->ProcessingMode = PROCESSING_MODE_QUATERNION_AVERAGE;
}
}
else if ( strcmp( attName, "RotationMode" ) == 0 )
{
int modeAsInt = this->GetRotationModeFromString( attValue );
if ( modeAsInt >= 0 && modeAsInt < ROTATION_MODE_LAST)
{
this->RotationMode = modeAsInt;
}
else
{
vtkWarningMacro("Unrecognized rotation mode read from MRML node: " << attValue << ". Setting to copy all axes.")
this->RotationMode = ROTATION_MODE_COPY_ALL_AXES;
}
}
else if ( strcmp( attName, "PrimaryAxisLabel" ) == 0 )
{
int labelAsInt = this->GetAxisLabelFromString( attValue );
if ( labelAsInt >= 0 && labelAsInt < AXIS_LABEL_LAST)
{
this->PrimaryAxisLabel = labelAsInt;
}
else
{
vtkWarningMacro("Unrecognized primary axis label read from MRML node: " << attValue << ". Setting to z.")
this->PrimaryAxisLabel = AXIS_LABEL_Z;
}
}
else if ( strcmp( attName, "DependentAxesMode" ) == 0 )
{
int modeAsInt = this->GetDependentAxesModeFromString( attValue );
if ( modeAsInt >= 0 && modeAsInt < DEPENDENT_AXES_MODE_LAST)
{
this->DependentAxesMode = modeAsInt;
}
else
{
vtkWarningMacro("Unrecognized dependent axes mode read from MRML node: " << attValue << ". Setting to pivot.")
this->DependentAxesMode = DEPENDENT_AXES_MODE_FROM_PIVOT;
}
}
else if ( strcmp( attName, "SecondaryAxisLabel" ) == 0 )
{
int labelAsInt = this->GetAxisLabelFromString( attValue );
if ( labelAsInt >= 0 && labelAsInt < AXIS_LABEL_LAST)
{
this->SecondaryAxisLabel = labelAsInt;
}
else
{
vtkWarningMacro("Unrecognized secondary axis label read from MRML node: " << attValue << ". Setting to y.")
this->SecondaryAxisLabel = AXIS_LABEL_Y;
}
}
else if ( strcmp( attName, "CopyTranslationX" ) == 0 )
{
bool isTrue = !strcmp( attValue, "true" );
this->SetCopyTranslationX( isTrue );
}
else if ( strcmp( attName, "CopyTranslationY" ) == 0 )
{
bool isTrue = !strcmp( attValue, "true" );
this->SetCopyTranslationY( isTrue );
}
else if ( strcmp( attName, "CopyTranslationZ" ) == 0 )
{
bool isTrue = !strcmp( attValue, "true" );
this->SetCopyTranslationZ( isTrue );
}
}
this->Modified();
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::WriteXML( ostream& of, int nIndent )
{
Superclass::WriteXML( of, nIndent );
vtkIndent indent( nIndent );
of << indent << " UpdatesPerSecond=\"" << this->UpdatesPerSecond << "\"";
of << indent << " UpdateMode=\"" << this->GetUpdateModeAsString( this->UpdateMode ) << "\"";
of << indent << " ProcessingMode=\"" << this->GetProcessingModeAsString( this->ProcessingMode ) << "\"";
of << indent << " RotationMode=\"" << this->GetRotationModeAsString( this->RotationMode ) << "\"";
of << indent << " PrimaryAxisLabel=\"" << this->GetAxisLabelAsString( this->PrimaryAxisLabel ) << "\"";
of << indent << " DependentAxesMode=\"" << this->GetDependentAxesModeAsString( this->DependentAxesMode ) << "\"";
of << indent << " SecondaryAxisLabel=\"" << this->GetAxisLabelAsString( this->SecondaryAxisLabel ) << "\"";
of << indent << " CopyTranslationX=\"" << ( this->CopyTranslationComponents[ 0 ] ? "true" : "false" ) << "\"";
of << indent << " CopyTranslationY=\"" << ( this->CopyTranslationComponents[ 1 ] ? "true" : "false" ) << "\"";
of << indent << " CopyTranslationZ=\"" << ( this->CopyTranslationComponents[ 2 ] ? "true" : "false" ) << "\"";
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::PrintSelf( ostream& os, vtkIndent indent )
{
Superclass::PrintSelf( os, indent );
os << indent << " UpdatesPerSecond = " << this->UpdatesPerSecond << "\n";
os << indent << " UpdateMode = " << this->GetUpdateModeAsString( this->UpdateMode ) << "\n";
os << indent << " ProcessingMode = " << this->GetProcessingModeAsString( this->ProcessingMode ) << "\n";
os << indent << " RotationMode = " << this->GetRotationModeAsString( this->RotationMode ) << "\n";
os << indent << " PrimaryAxisLabel = " << this->GetAxisLabelAsString( this->PrimaryAxisLabel ) << "\n";
os << indent << " DependentAxesMode = " << this->GetDependentAxesModeAsString( this->DependentAxesMode ) << "\n";
os << indent << " SecondaryAxisLabel = " << this->GetAxisLabelAsString( this->SecondaryAxisLabel ) << "\n";
os << indent << " CopyTranslationX = " << ( this->CopyTranslationComponents[ 0 ] ? "true" : "false" ) << "\n";
os << indent << " CopyTranslationY = " << ( this->CopyTranslationComponents[ 1 ] ? "true" : "false" ) << "\n";
os << indent << " CopyTranslationZ = " << ( this->CopyTranslationComponents[ 2 ] ? "true" : "false" ) << "\n";
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::Copy( vtkMRMLNode *anode )
{
Superclass::Copy( anode );
vtkMRMLTransformProcessorNode *node = vtkMRMLTransformProcessorNode::SafeDownCast( anode );
int wasModifying = node->StartModify();
this->UpdatesPerSecond = node->UpdatesPerSecond;
this->UpdateMode = node->UpdateMode;
this->ProcessingMode = node->ProcessingMode;
this->RotationMode = node->RotationMode;
this->PrimaryAxisLabel = node->PrimaryAxisLabel;
this->DependentAxesMode = node->DependentAxesMode;
this->SecondaryAxisLabel = node->SecondaryAxisLabel;
this->CopyTranslationComponents[0] = node->CopyTranslationComponents[0];
this->CopyTranslationComponents[1] = node->CopyTranslationComponents[1];
this->CopyTranslationComponents[2] = node->CopyTranslationComponents[2];
node->EndModify( wasModifying );
}
//------------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::ProcessMRMLEvents( vtkObject* caller, unsigned long event, void* callData )
{
Superclass::ProcessMRMLEvents( caller, event, callData );
vtkMRMLNode* callerNode = vtkMRMLNode::SafeDownCast( caller );
if ( callerNode == NULL )
{
return;
}
// Make sure that the calling node is one of the inputs
bool callerNodeIsAnInputTransform = ( callerNode == this->GetInputAnchorTransformNode() ||
callerNode == this->GetInputChangedTransformNode() ||
callerNode == this->GetInputInitialTransformNode() ||
callerNode == this->GetInputFromTransformNode() ||
callerNode == this->GetInputToTransformNode() ||
callerNode == this->GetInputForwardTransformNode() );
// Also check the "InputCombine" transforms:
if ( !callerNodeIsAnInputTransform ) // don't need to check if we already know the caller node is an input transform
{
int numberOfInputCombineTransformNodes = GetNumberOfInputCombineTransformNodes();
for ( int inputCombineTransformIndex = 0; inputCombineTransformIndex < numberOfInputCombineTransformNodes; inputCombineTransformIndex++ )
{
if ( callerNode == GetNthInputCombineTransformNode( inputCombineTransformIndex ) )
{
callerNodeIsAnInputTransform = true;
break;
}
}
}
if ( callerNodeIsAnInputTransform == true )
{
if ( event == vtkMRMLTransformNode::TransformModifiedEvent )
{
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
}
}
//------------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetProcessingMode( int newProcessingMode )
{
bool validMode = ( newProcessingMode >= 0 && newProcessingMode < PROCESSING_MODE_LAST );
if ( validMode == false )
{
vtkWarningMacro( "Input new processing mode " << newProcessingMode << " is not a valid option. No change will be done." )
return;
}
if ( this->ProcessingMode == newProcessingMode )
{
// no change
return;
}
this->ProcessingMode = newProcessingMode;
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetUpdateMode( int newUpdateMode )
{
bool validMode = ( newUpdateMode >= 0 && newUpdateMode < UPDATE_MODE_LAST );
if ( validMode == false )
{
vtkWarningMacro( "Input new update mode " << newUpdateMode << " is not a valid option. No change will be done." )
return;
}
if ( this->UpdateMode == newUpdateMode )
{
// no change
return;
}
this->UpdateMode = newUpdateMode;
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
const bool* vtkMRMLTransformProcessorNode::GetCopyTranslationComponents()
{
return ( const bool* )this->CopyTranslationComponents;
}
//----------------------------------------------------------------------------
bool vtkMRMLTransformProcessorNode::GetCopyTranslationX()
{
return this->CopyTranslationComponents[ 0 ];
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetCopyTranslationX( bool enabled )
{
if ( this->CopyTranslationComponents[ 0 ] == enabled )
{
// no change
return;
}
this->CopyTranslationComponents[ 0 ] = enabled;
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
bool vtkMRMLTransformProcessorNode::GetCopyTranslationY()
{
return this->CopyTranslationComponents[ 1 ];
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetCopyTranslationY( bool enabled )
{
if ( this->CopyTranslationComponents[ 1 ] == enabled )
{
// no change
return;
}
this->CopyTranslationComponents[ 1 ] = enabled;
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
bool vtkMRMLTransformProcessorNode::GetCopyTranslationZ()
{
return this->CopyTranslationComponents[ 2 ];
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetCopyTranslationZ( bool enabled )
{
if ( this->CopyTranslationComponents[ 2 ] == enabled )
{
// no change
return;
}
this->CopyTranslationComponents[ 2 ] = enabled;
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetRotationMode( int newRotationMode )
{
bool validMode = ( newRotationMode >= 0 && newRotationMode < ROTATION_MODE_LAST );
if ( validMode == false )
{
vtkWarningMacro( "Input new rotation mode " << newRotationMode << " is not a valid option. No change will be done." )
return;
}
if ( this->RotationMode == newRotationMode )
{
// no change
return;
}
this->RotationMode = newRotationMode;
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetDependentAxesMode( int newDependentAxesMode )
{
bool validMode = ( newDependentAxesMode >= 0 && newDependentAxesMode < DEPENDENT_AXES_MODE_LAST );
if ( validMode == false )
{
vtkWarningMacro( "Input new dependent axes mode " << newDependentAxesMode << " is not a valid option. No change will be done." )
return;
}
if ( this->DependentAxesMode == newDependentAxesMode )
{
// no change
return;
}
this->DependentAxesMode = newDependentAxesMode;
// if there are other modes that need to check for duplicate axes, these should be added below:
if ( this->DependentAxesMode == vtkMRMLTransformProcessorNode::DEPENDENT_AXES_MODE_FROM_SECONDARY_AXIS )
{
this->CheckAndCorrectForDuplicateAxes();
}
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetPrimaryAxisLabel( int newAxisLabel )
{
bool validMode = ( newAxisLabel >= 0 && newAxisLabel < AXIS_LABEL_LAST );
if ( validMode == false )
{
vtkWarningMacro( "Input primary axis " << newAxisLabel << " is not a valid option. No change will be done." )
return;
}
if ( this->PrimaryAxisLabel == newAxisLabel )
{
// no change
return;
}
this->PrimaryAxisLabel = newAxisLabel;
if ( this->DependentAxesMode == vtkMRMLTransformProcessorNode::DEPENDENT_AXES_MODE_FROM_SECONDARY_AXIS )
{
this->CheckAndCorrectForDuplicateAxes();
}
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetSecondaryAxisLabel( int newAxisLabel )
{
bool validMode = ( newAxisLabel >= 0 && newAxisLabel < AXIS_LABEL_LAST );
if ( validMode == false )
{
vtkWarningMacro( "Input secondary axis " << newAxisLabel << " is not a valid option. No change will be done." )
return;
}
if ( this->SecondaryAxisLabel == newAxisLabel )
{
// no change
return;
}
this->SecondaryAxisLabel = newAxisLabel;
if ( this->DependentAxesMode == vtkMRMLTransformProcessorNode::DEPENDENT_AXES_MODE_FROM_SECONDARY_AXIS )
{
this->CheckAndCorrectForDuplicateAxes();
}
this->Modified();
this->InvokeCustomModifiedEvent( InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::CheckAndCorrectForDuplicateAxes()
{
if (this->PrimaryAxisLabel == this->SecondaryAxisLabel )
{
if ( this->PrimaryAxisLabel == vtkMRMLTransformProcessorNode::AXIS_LABEL_Z )
{
this->SecondaryAxisLabel = vtkMRMLTransformProcessorNode::AXIS_LABEL_Y;
vtkWarningMacro( "Duplicate axes for primary and secondary axes. Changing secondary axis to y." );
}
else if ( this->PrimaryAxisLabel == vtkMRMLTransformProcessorNode::AXIS_LABEL_Y ||
this->PrimaryAxisLabel == vtkMRMLTransformProcessorNode::AXIS_LABEL_X )
{
this->SecondaryAxisLabel = vtkMRMLTransformProcessorNode::AXIS_LABEL_Z;
vtkWarningMacro( "Duplicate axes for primary and secondary axes. Changing secondary axis to z." );
}
}
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetNthTransformNodeInRole( const char* role, int n )
{
vtkMRMLNode* node = this->GetNthNodeReference( role, n );
if ( node == NULL )
{
// If necessary a verbose flag should be added. In some cases it is normal for the node to be null (for instance, if it hasn't been set yet)
//vtkWarningMacro( "Failed to find a node in the role " << role << " at index " << n << ". Returning NULL." );
return NULL;
}
vtkMRMLLinearTransformNode* linearTransformNode = vtkMRMLLinearTransformNode::SafeDownCast( node );
if ( linearTransformNode == NULL )
{
vtkWarningMacro( "Failed to downcast vtkMRMLNode to vtkLinearTransformNode in the role " << role << " at index " << n << ". Returning NULL." );
}
return linearTransformNode;
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveTransformNodeInRole( const char* role, vtkMRMLLinearTransformNode* node )
{
if ( node == this->GetTransformNodeInRole( role ) )
{
// if the node is the same, then no need to do anything
return;
}
// We want only one transform as input when this function is called.
// Remove all existing input transforms before setting
this->RemoveNodeReferenceIDs( role );
const char* nodeID = NULL;
if ( node )
{
nodeID = node->GetID();
}
int indexOfNodeID = 0; // This function sets it to the first (and theoretically only) slot
this->SetAndObserveNthNodeReferenceID( role, indexOfNodeID, nodeID );
this->InvokeCustomModifiedEvent( vtkMRMLTransformProcessorNode::InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::AddAndObserveTransformNodeInRole( const char* role, vtkMRMLLinearTransformNode* node )
{
// adding null does nothing, so just return in this case
if ( node == NULL )
{
return;
}
// need to iterate over existing inputs, make sure we are not adding a duplicate
for ( int n = 0; n < this->GetNumberOfTransformNodesInRole( role ); n++ )
{
if ( node == this->GetNthTransformNodeInRole( role, n ) )
{
return;
}
}
const char* nodeID = node->GetID();
this->AddAndObserveNodeReferenceID( role, nodeID );
this->InvokeCustomModifiedEvent( vtkMRMLTransformProcessorNode::InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::RemoveNthTransformNodeInRole( const char* role, int n )
{
this->RemoveNthNodeReferenceID( role, n );
this->InvokeCustomModifiedEvent( vtkMRMLTransformProcessorNode::InputDataModifiedEvent );
}
//----------------------------------------------------------------------------
int vtkMRMLTransformProcessorNode::GetNumberOfTransformNodesInRole( const char* role )
{
return this->GetNumberOfNodeReferences( role );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetTransformNodeInRole( const char* role )
{
return this->GetNthTransformNodeInRole( role, 0 );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetNthInputCombineTransformNode( int n )
{
return this->GetNthTransformNodeInRole( ROLE_INPUT_COMBINE_TRANSFORM, n );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::AddAndObserveInputCombineTransformNode( vtkMRMLLinearTransformNode* node )
{
this->AddAndObserveTransformNodeInRole( ROLE_INPUT_COMBINE_TRANSFORM, node );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::RemoveNthInputCombineTransformNode( int n )
{
this->RemoveNthTransformNodeInRole( ROLE_INPUT_COMBINE_TRANSFORM, n );
}
//----------------------------------------------------------------------------
int vtkMRMLTransformProcessorNode::GetNumberOfInputCombineTransformNodes()
{
return this->GetNumberOfTransformNodesInRole( ROLE_INPUT_COMBINE_TRANSFORM );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetInputFromTransformNode()
{
return this->GetTransformNodeInRole( ROLE_INPUT_FROM_TRANSFORM );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveInputFromTransformNode( vtkMRMLLinearTransformNode* node )
{
this->SetAndObserveTransformNodeInRole( ROLE_INPUT_FROM_TRANSFORM, node );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetInputToTransformNode()
{
return GetTransformNodeInRole( ROLE_INPUT_TO_TRANSFORM );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveInputToTransformNode( vtkMRMLLinearTransformNode* node )
{
this->SetAndObserveTransformNodeInRole( ROLE_INPUT_TO_TRANSFORM, node );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetInputInitialTransformNode()
{
return GetTransformNodeInRole( ROLE_INPUT_INITIAL_TRANSFORM );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveInputInitialTransformNode( vtkMRMLLinearTransformNode* node )
{
this->SetAndObserveTransformNodeInRole( ROLE_INPUT_INITIAL_TRANSFORM, node );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetInputChangedTransformNode()
{
return GetTransformNodeInRole( ROLE_INPUT_CHANGED_TRANSFORM );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveInputChangedTransformNode( vtkMRMLLinearTransformNode* node )
{
this->SetAndObserveTransformNodeInRole( ROLE_INPUT_CHANGED_TRANSFORM, node );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetInputAnchorTransformNode()
{
return GetTransformNodeInRole( ROLE_INPUT_ANCHOR_TRANSFORM );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveInputAnchorTransformNode( vtkMRMLLinearTransformNode* node )
{
this->SetAndObserveTransformNodeInRole( ROLE_INPUT_ANCHOR_TRANSFORM, node );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetInputForwardTransformNode()
{
return GetTransformNodeInRole( ROLE_INPUT_FORWARD_TRANSFORM );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveInputForwardTransformNode( vtkMRMLLinearTransformNode* node )
{
this->SetAndObserveTransformNodeInRole( ROLE_INPUT_FORWARD_TRANSFORM, node );
}
//----------------------------------------------------------------------------
vtkMRMLLinearTransformNode* vtkMRMLTransformProcessorNode::GetOutputTransformNode()
{
return GetTransformNodeInRole( ROLE_OUTPUT_TRANSFORM );
}
//----------------------------------------------------------------------------
void vtkMRMLTransformProcessorNode::SetAndObserveOutputTransformNode( vtkMRMLLinearTransformNode* node )
{
this->SetAndObserveTransformNodeInRole( ROLE_OUTPUT_TRANSFORM, node );
}
//----------------------------------------------------------------------------
std::string vtkMRMLTransformProcessorNode::GetProcessingModeAsString( int mode )
{
switch ( mode )
{
case PROCESSING_MODE_QUATERNION_AVERAGE:
return "Quaternion Average";
case PROCESSING_MODE_COMPUTE_SHAFT_PIVOT:
return "Compute Shaft Pivot";
case PROCESSING_MODE_COMPUTE_ROTATION:
return "Compute Rotation Only";
case PROCESSING_MODE_COMPUTE_TRANSLATION:
return "Compute Translation Only";
case PROCESSING_MODE_COMPUTE_FULL_TRANSFORM:
return "Compute Full Transform";
case PROCESSING_MODE_COMPUTE_INVERSE:
return "Compute Inverse";
default:
vtkGenericWarningMacro("Unknown processing mode provided as input to GetProcessingModeAsString: " << mode << ". Returning \"Unknown Processing Mode\"");
return "Unknown Processing Mode";
}
}
//----------------------------------------------------------------------------
int vtkMRMLTransformProcessorNode::GetProcessingModeFromString( std::string name )
{
for ( int i = 0; i < PROCESSING_MODE_LAST; i++ )
{
if ( name == GetProcessingModeAsString( i ) )
{
// found a matching name
return i;
}
}
// unknown name
return -1;
}
//----------------------------------------------------------------------------
std::string vtkMRMLTransformProcessorNode::GetUpdateModeAsString( int mode )
{
switch ( mode )
{
case UPDATE_MODE_MANUAL:
return "Manual Update";
case UPDATE_MODE_AUTO:
return "Auto-Update";
default:
vtkGenericWarningMacro("Unknown update mode provided as input to GetUpdateModeAsString: " << mode << ". Returning \"Unknown Update Mode\"");
return "Unknown Update Mode";
}
}
//----------------------------------------------------------------------------
int vtkMRMLTransformProcessorNode::GetUpdateModeFromString( std::string name )
{
for ( int i = 0; i < UPDATE_MODE_LAST; i++ )
{
if ( name == vtkMRMLTransformProcessorNode::GetUpdateModeAsString( i ) )
{
// found a matching name
return i;
}
}
// unknown name
return -1;
}
//----------------------------------------------------------------------------
std::string vtkMRMLTransformProcessorNode::GetRotationModeAsString( int mode )
{
switch ( mode )
{
case ROTATION_MODE_COPY_ALL_AXES:
return "Copy All Axes";
case ROTATION_MODE_COPY_SINGLE_AXIS:
return "Copy Single Axis";
default:
vtkGenericWarningMacro("Unknown rotation mode provided as input to GetRotationModeAsString: " << mode << ". Returning \"Unknown Rotation Mode\"");
return "Unknown Rotation Mode";
}
}
//----------------------------------------------------------------------------
int vtkMRMLTransformProcessorNode::GetRotationModeFromString( std::string name )
{
for ( int i = 0; i < ROTATION_MODE_LAST; i++ )
{
if ( name == vtkMRMLTransformProcessorNode::GetRotationModeAsString( i ) )
{
// found a matching name
return i;
}
}
// unknown name
return -1;
}
//----------------------------------------------------------------------------
std::string vtkMRMLTransformProcessorNode::GetDependentAxesModeAsString( int mode )
{
switch ( mode )
{
case DEPENDENT_AXES_MODE_FROM_PIVOT:
return "From Pivot";
case DEPENDENT_AXES_MODE_FROM_SECONDARY_AXIS:
return "From Secondary Axis";
default:
vtkGenericWarningMacro("Unknown dependent axes mode provided as input to GetRotationDependentAxesModeAsString: " << mode << ". Returning \"Unknown Dependent Axes Mode\"");
return "Unknown Dependent Axes Mode";
}
}
//----------------------------------------------------------------------------
int vtkMRMLTransformProcessorNode::GetDependentAxesModeFromString( std::string name )
{
for ( int i = 0; i < DEPENDENT_AXES_MODE_LAST; i++ )
{
if ( name == vtkMRMLTransformProcessorNode::GetDependentAxesModeAsString( i ) )
{
// found a matching name
return i;
}
}
// unknown name
return -1;
}
//----------------------------------------------------------------------------
std::string vtkMRMLTransformProcessorNode::GetAxisLabelAsString( int label )
{
switch ( label )
{
case AXIS_LABEL_X:
return "X Axis";
case AXIS_LABEL_Y:
return "Y Axis";
case AXIS_LABEL_Z:
return "Z Axis";
default:
vtkGenericWarningMacro("Unknown axis provided as input to GetAxisLabelAsString: " << label << ". Returning \"Unknown Axis\"");
return "Unknown Axis";
}
}
//----------------------------------------------------------------------------
int vtkMRMLTransformProcessorNode::GetAxisLabelFromString( std::string name )
{
for ( int i = 0; i < AXIS_LABEL_LAST; i++ )
{
if ( name == vtkMRMLTransformProcessorNode::GetAxisLabelAsString( i ) )
{
// found a matching name
return i;
}
}
// unknown name
return -1;
}
| 37.357143 | 175 | 0.613551 | [
"transform",
"3d"
] |
15a721ec7c979ffcb6b41c096107b69dbe76b91b | 331 | cpp | C++ | src/scene/Scene.cpp | lejonmcgowan/JohnnyTracer2 | 41d2378b5ee81dc0332e4a87379f2ce6338a915a | [
"MIT"
] | null | null | null | src/scene/Scene.cpp | lejonmcgowan/JohnnyTracer2 | 41d2378b5ee81dc0332e4a87379f2ce6338a915a | [
"MIT"
] | null | null | null | src/scene/Scene.cpp | lejonmcgowan/JohnnyTracer2 | 41d2378b5ee81dc0332e4a87379f2ce6338a915a | [
"MIT"
] | null | null | null | //
// Created by lejonmcgowan on 1/3/17.
//
#include "Scene.h"
Scene::Scene(std::shared_ptr<IPrimitive> aggregate, const std::vector<std::shared_ptr<ILight>>& lights)
: lights(lights), aggregate(aggregate) {
// Scene Constructor Implementation
worldBound = aggregate->worldBound();
//todo add lights to the scene
} | 30.090909 | 103 | 0.703927 | [
"vector"
] |
15a7d2afdb64328f1e0808f1559de73d9b925d46 | 866 | cpp | C++ | demos/overload.cpp | hbursk/matchine | 28b814343a5317c053dddc46fa2d40b971f32662 | [
"MIT"
] | 70 | 2018-11-21T14:46:17.000Z | 2021-12-15T19:51:52.000Z | demos/overload.cpp | hbursk/matchine | 28b814343a5317c053dddc46fa2d40b971f32662 | [
"MIT"
] | 4 | 2019-02-09T07:33:47.000Z | 2020-12-03T17:57:53.000Z | demos/overload.cpp | hbursk/matchine | 28b814343a5317c053dddc46fa2d40b971f32662 | [
"MIT"
] | 6 | 2019-02-22T11:09:06.000Z | 2020-12-01T18:37:49.000Z | //
// MIT License
//
// Copyright © 2018
// Native Instruments
//
// For more detailed information, please read the LICENSE in the root directory.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >8
#include <ni/functional/overload.h>
#include <vector>
#include <variant>
#include <string>
#include <iostream>
int main()
{
struct MyType {};
using var_t = std::variant<double, int, MyType>;
std::vector<var_t> vars = { var_t{3.14}, var_t{1337}, var_t{MyType{}} };
for (auto const& var : vars)
{
auto visitor = ni::overload
( [](double x) { return "float: " + std::to_string(x); }
, [](int n) { return "int: " + std::to_string(n); }
, [](auto) { return std::string("<unknown type>"); }
);
std::cout << std::visit(visitor, var) << std::endl;
}
}
| 25.470588 | 81 | 0.516166 | [
"vector"
] |
15bbaa3e64c23c5204db2bb834316be6b9838129 | 5,581 | cpp | C++ | tech/Game/Mountable.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | tech/Game/Mountable.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | tech/Game/Mountable.cpp | nbtdev/teardrop | fa9cc8faba03a901d1d14f655a04167e14cd08ee | [
"MIT"
] | null | null | null | /******************************************************************************
Copyright (c) 2015 Teardrop Games
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 "Mountable.h"
#include "Game/Component_Render.h"
#include "Game/Component_EquipmentSlot.h"
#include "Math/Transform.h"
#include "Util/Environment.h"
using namespace Teardrop;
//---------------------------------------------------------------------------
TD_CLASS_IMPL(Mountable);
static Transform s_transform(Transform(
Vector4(0,0,0,0), Quaternion(1,0,0,0), Vector4(1,1,1,1)));
//---------------------------------------------------------------------------
Mountable::Mountable()
{
m_pSlot = 0;
}
//---------------------------------------------------------------------------
Mountable::~Mountable()
{
}
//---------------------------------------------------------------------------
bool Mountable::initialize()
{
if (Object::initialize())
{
// initialize components
for (Components::iterator it = m_components.begin();
it != m_components.end(); ++it)
{
Component* pComp = it->second;
if(!pComp->getServerComponent() && Environment::get().isServer)
continue;
pComp->initialize();
}
return _initialize();
}
return false;
}
//---------------------------------------------------------------------------
bool Mountable::destroy()
{
_destroy();
// clear out all components
for (Components::iterator it = m_components.begin();
it != m_components.end(); ++it)
{
it->second->destroy();
delete it->second;
}
m_components.clear();
return Object::destroy();
}
//---------------------------------------------------------------------------
Reflection::Object* Mountable::clone() const
{
// leverage the base functionality...
Reflection::Object* obj = Reflection::Object::clone();
// and then do our components as well...
ComponentHost* pHost = dynamic_cast<ComponentHost*>(obj);
if (pHost) {
// since we are also a component host, we need to clone our components
// as well as the base properties
int nComps = getComponents(0, 0);
std::vector<Component*> compvec(nComps);
Component** comps = &compvec[0];
nComps = getComponents(comps, nComps);
for (int i=0; i<nComps; ++i)
{
Component* pComp = comps[i];
if(!pComp->getServerComponent() && Environment::get().isServer)
continue;
Component* pNewComp = static_cast<Component*>(pComp->clone());
if (pNewComp)
{
pHost->addComponent(pNewComp);
}
}
}
return obj;
}
//---------------------------------------------------------------------------
bool Mountable::update(float deltaT)
{
return _update(deltaT);
}
//---------------------------------------------------------------------------
const Transform& Mountable::getTransformWS()
{
if (m_pSlot)
return m_pSlot->getParentTransformWS();
return s_transform; // static Transform is IDENTITY
}
//---------------------------------------------------------------------------
void Mountable::setBoundingBox(const AABB& /*aabb*/)
{
}
//---------------------------------------------------------------------------
bool Mountable::isOfType(Reflection::ClassDef* pClassDef)
{
const Reflection::ClassDef* pDerived = getDerivedClassDef();
while (pDerived)
{
if (pDerived == pClassDef)
return true;
pDerived = pDerived->getBaseClass();
}
return false;
}
//---------------------------------------------------------------------------
void Mountable::notifyMounted(EquipmentSlotComponent* pSlot)
{
m_pSlot = pSlot;
}
//---------------------------------------------------------------------------
void Mountable::notifyUnmounted()
{
m_pSlot = 0;
}
//---------------------------------------------------------------------------
void Mountable::queueForRendering(Gfx::Renderer* pRend)
{
ComponentList list;
findComponents(RenderComponent::getClassDef(), list);
for (ComponentList::iterator it = list.begin(); it != list.end(); ++it)
{
RenderComponent* pComp = static_cast<RenderComponent*>(*it);
pComp->queueForRendering(pRend);
}
}
//---------------------------------------------------------------------------
bool Mountable::isMounted() const
{
return m_pSlot != 0;
}
//---------------------------------------------------------------------------
bool Mountable::_initialize()
{
return true;
}
//---------------------------------------------------------------------------
bool Mountable::_destroy()
{
return true;
}
//---------------------------------------------------------------------------
bool Mountable::_update(float /*deltaT*/)
{
return true;
}
| 29.68617 | 79 | 0.531267 | [
"object",
"vector",
"transform"
] |
15be7d475d45f50ff790eb00822ab4f0828362a0 | 5,541 | cpp | C++ | src/Native/natsu.fcall.cpp | dotnetGame/natsu-clr | 1334aa1b8ff4af2819750417c54f76fe4784e6f8 | [
"MIT"
] | 73 | 2018-06-08T09:00:02.000Z | 2022-03-30T10:22:03.000Z | src/Native/natsu.fcall.cpp | dotnetGame/natsu-clr | 1334aa1b8ff4af2819750417c54f76fe4784e6f8 | [
"MIT"
] | null | null | null | src/Native/natsu.fcall.cpp | dotnetGame/natsu-clr | 1334aa1b8ff4af2819750417c54f76fe4784e6f8 | [
"MIT"
] | 4 | 2020-04-18T13:34:04.000Z | 2021-03-09T07:46:34.000Z | #include "Chino.Kernel.h"
#include "System.Console.h"
#include <cmath>
#include <random>
#ifdef WIN32
#include <Windows.h>
#endif
using namespace natsu;
using namespace System_Private_CoreLib;
using namespace System_Private_CoreLib::System;
using namespace System_Private_CoreLib::System::Diagnostics;
using namespace System_Private_CoreLib::System::Runtime;
using namespace System_Private_CoreLib::System::Runtime::CompilerServices;
using namespace System_Private_CoreLib::System::Runtime::InteropServices;
using namespace System_Private_CoreLib::System::Threading;
using namespace Chino_Threading;
gc_obj_ref<Type> Object::GetType(::natsu::gc_obj_ref<Object> _this)
{
check_null_obj_ref(_this);
return _this.header().vtable_->runtime_type();
}
gc_obj_ref<MulticastDelegate> MulticastDelegate::_s_CreateDelegateLike(gc_obj_ref<MulticastDelegate> delegate, gc_obj_ref<SZArray_1<Delegate>> invocationList)
{
auto d_len = invocationList->length();
if (d_len == 0)
{
return nullptr;
}
else if (d_len == 1)
{
return invocationList->get(0).cast<MulticastDelegate>();
}
else
{
auto d = gc_alloc(*delegate.header().vtable_, sizeof(MulticastDelegate)).cast<MulticastDelegate>();
d->_invocationList = invocationList;
return d;
}
}
void RuntimeImports::_s_GetRandomBytes(gc_ptr<uint8_t> buffer, int32_t length)
{
std::mt19937 rbe;
std::generate_n(buffer.get(), length, std::ref(rbe));
}
void RuntimeImports::_s_RhZeroMemory(gc_ptr<void> b, uint64_t byteLength)
{
std::memset(b.ptr_, 0, byteLength);
}
int32_t RuntimeHelpers::_s_GetHashCode(::natsu::gc_obj_ref<::System_Private_CoreLib::System::Object> o)
{
return (int32_t)o.ptr_;
}
void Debugger::_s_BreakInternal()
{
#ifdef WIN32
DebugBreak();
#else
assert(false);
#endif
}
bool Debugger::_s_get_IsAttached()
{
#ifdef WIN32
return IsDebuggerPresent();
#else
return false;
#endif
}
bool Debugger::_s_LaunchInternal()
{
#ifdef WIN32
while (IsDebuggerPresent())
DebugBreak();
return true;
#else
return false;
#endif
}
void Debugger::_s_CustomNotification(gc_obj_ref<ICustomDebuggerNotification> data)
{
}
void Environment::_s__Exit(int32_t exitCode)
{
exit(exitCode);
}
int32_t Environment::_s_get_TickCount()
{
return (int32_t)_s_get_TickCount64();
}
int64_t Environment::_s_get_TickCount64()
{
auto scheduler = Chino::Threading::Scheduler::_s_get_Current();
return (int64_t)Chino::Threading::Scheduler::get_TickCount(scheduler);
}
void Marshal::_s_CopyToNative(gc_obj_ref<Object> source, int32_t startIndex, IntPtr destination, int32_t length)
{
check_null_obj_ref(source);
check_null_obj_ref(destination._value);
auto src = source.cast<RawSzArrayData>();
auto element_size = source.header().vtable_->ElementSize;
if ((startIndex + length) > (intptr_t)src->Count)
throw_index_out_of_range_exception();
std::memmove(destination._value, &src->Data + (size_t)startIndex * element_size, (size_t)length * element_size);
}
void Marshal::_s_CopyToManaged(IntPtr source, gc_obj_ref<Object> destination, int32_t startIndex, int32_t length)
{
check_null_obj_ref(source._value);
check_null_obj_ref(destination);
auto dest = destination.cast<RawSzArrayData>();
auto element_size = destination.header().vtable_->ElementSize;
if ((startIndex + length) > (intptr_t)dest->Count)
throw_index_out_of_range_exception();
std::memmove(&dest->Data + (size_t)startIndex * element_size, source._value, (size_t)length * element_size);
}
namespace
{
uint32_t get_current_thread_id()
{
return Chino::Threading::Scheduler::_s_get_CurrentThreadId();
}
}
void Monitor::_s_Enter(gc_obj_ref<Object> obj)
{
bool lock_taken = false;
_s_ReliableEnter(obj, lock_taken);
}
void Monitor::_s_ReliableEnter(gc_obj_ref<Object> obj, gc_ref<bool> lockTaken)
{
check_null_obj_ref(obj);
auto thread_id = get_current_thread_id();
auto &sync_header = obj.header().sync_header_;
uint32_t expected = 0;
while (true)
{
if (sync_header.lock_taken.compare_exchange_strong(expected, thread_id))
{
Volatile::_s_Write(*lockTaken, true);
break;
}
Thread::_s_Sleep(1);
}
}
void Monitor::_s_Exit(::natsu::gc_obj_ref<Object> obj)
{
check_null_obj_ref(obj);
auto &sync_header = obj.header().sync_header_;
sync_header.lock_taken.store(0);
}
void Monitor::_s_ReliableEnterTimeout(gc_obj_ref<Object> obj, int32_t timeout, gc_ref<bool> lockTaken)
{
pure_call();
}
bool Monitor::_s_IsEnteredNative(gc_obj_ref<Object> obj)
{
check_null_obj_ref(obj);
auto thread_id = get_current_thread_id();
auto &sync_header = obj.header().sync_header_;
return sync_header.lock_taken.load() == thread_id;
}
bool Monitor::_s_ObjWait(bool exitContext, int32_t millisecondsTimeout, gc_obj_ref<Object> obj)
{
pure_call();
}
void Monitor::_s_ObjPulse(gc_obj_ref<Object> obj)
{
pure_call();
}
void Monitor::_s_ObjPulseAll(gc_obj_ref<Object> obj)
{
pure_call();
}
int64_t Monitor::_s_GetLockContentionCount()
{
return 0;
}
void Thread::_s_SleepInternal(int32_t millisecondsTimeout)
{
Chino::Threading::Scheduler::_s_Delay(TimeSpan::_s_FromMilliseconds(millisecondsTimeout));
}
bool Thread::_s_YieldInternal()
{
Chino::Threading::Scheduler::_s_Delay(TimeSpan::_s_FromTicks(0));
return true;
}
int32_t Thread::_s_GetOptimalMaxSpinWaitsPerSpinIterationInternal()
{
return 1;
}
| 24.847534 | 158 | 0.730193 | [
"object"
] |
15c01362b938ce3a85a7ee174f49bcaf617cd2f9 | 1,612 | cpp | C++ | Teaching/ControllerManager.cpp | ryhanai/teachingplugin | a495885899eaa36ea00ba8ab89057cd4d3f36350 | [
"MIT"
] | 2 | 2020-07-21T06:08:42.000Z | 2020-07-21T06:08:44.000Z | Teaching/ControllerManager.cpp | ryhanai/teachingplugin | a495885899eaa36ea00ba8ab89057cd4d3f36350 | [
"MIT"
] | null | null | null | Teaching/ControllerManager.cpp | ryhanai/teachingplugin | a495885899eaa36ea00ba8ab89057cd4d3f36350 | [
"MIT"
] | null | null | null | #include "ControllerManager.h"
#include "TeachingUtil.h"
#include "LoggerUtil.h"
namespace teaching {
ControllerManager* ControllerManager::instance() {
static ControllerManager* handler = new ControllerManager();
return handler;
}
ControllerManager::ControllerManager() {
}
ControllerManager::~ControllerManager() {
}
void ControllerManager::registController(string controllerName, ControllerBase* controller) {
DDEBUG_V("ControllerManager::registController: %s", controllerName.c_str());
ControllerInfo param;
param.controllerName = controllerName;
param.controller = controller;
controllerList_.push_back(param);
if(SettingManager::getInstance().getController()==controllerName) {
controller->initialize(); // R.Hanai
stateView_->createStateCommands();
taskView_->loadTaskInfo();
}
}
void ControllerManager::initialize() {
}
vector<string> ControllerManager::getControllerNameList() {
vector<string> result;
for(ControllerInfo target : controllerList_) {
result.push_back(target.controllerName);
}
return result;
}
ControllerBase* ControllerManager::getController(string controllerName) {
for(ControllerInfo target : controllerList_) {
if(target.controllerName == controllerName) {
return target.controller;
}
}
return controllerList_[0].controller;
}
void ControllerManager::setStateMachineView(StateMachineViewImpl* view) {
stateView_ = view;
}
void ControllerManager::setTaskInstanceView(TaskInstanceViewImpl* view) {
taskView_ = view;
}
bool ControllerManager::isExistController() {
return 0 < controllerList_.size();
}
} | 24.424242 | 93 | 0.760546 | [
"vector"
] |
15c9a57d57a95cd9ae6a33cef22b3f99176087c8 | 26,983 | cpp | C++ | examples/thumbnail/app.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 23 | 2021-08-25T10:40:40.000Z | 2022-03-28T13:02:05.000Z | examples/thumbnail/app.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 2 | 2021-12-04T12:50:44.000Z | 2021-12-14T14:55:00.000Z | examples/thumbnail/app.cpp | sketchbooks99/PRayGround | 07d1779f2e36ad9ed5fd6df457cdc515b9017300 | [
"MIT"
] | 1 | 2021-04-15T13:13:17.000Z | 2021-04-15T13:13:17.000Z | #include "app.h"
#define INTERACTIVE 1
static void streamProgress(int frame, int max_frame, float elapsed_time, int bar_length)
{
cout << "\rRendering: [";
int progress = static_cast<int>( ( (float)(frame) / max_frame) * bar_length );
for (int i = 0; i < progress; i++)
cout << "+";
for (int i = progress; i < bar_length; i++)
cout << " ";
cout << "]";
cout << " [" << fixed << setprecision(2) << elapsed_time << "s]";
float percent = (float)(frame) / max_frame;
cout << " (" << fixed << setprecision(2) << (float)(percent * 100.0f) << "%, ";
cout << "Samples: " << frame << " / " << max_frame << ")" << flush;
if (frame == max_frame)
cout << endl;
}
void App::initResultBufferOnDevice()
{
params.subframe_index = 0;
result_bitmap.allocateDevicePtr();
accum_bitmap.allocateDevicePtr();
params.result_buffer = reinterpret_cast<uchar4*>(result_bitmap.devicePtr());
params.accum_buffer = reinterpret_cast<float4*>(accum_bitmap.devicePtr());
CUDA_SYNC_CHECK();
}
void App::handleCameraUpdate()
{
if (!camera_update)
return;
camera_update = false;
float3 U, V, W;
camera.UVWFrame(U, V, W);
RaygenRecord* rg_record = reinterpret_cast<RaygenRecord*>(sbt.raygenRecord());
RaygenData rg_data;
rg_data.camera =
{
.origin = camera.origin(),
.lookat = camera.lookat(),
.U = U,
.V = V,
.W = W,
.fov = camera.fov(),
.aspect = camera.aspect(),
.aperture = camera.aperture(),
.focus_distance = camera.focusDistance(),
.farclip = camera.farClip()
};
CUDA_CHECK(cudaMemcpy(
reinterpret_cast<void*>(&rg_record->data),
&rg_data, sizeof(RaygenData),
cudaMemcpyHostToDevice
));
initResultBufferOnDevice();
}
// ----------------------------------------------------------------
void App::setup()
{
// Initialize CUDA
stream = 0;
CUDA_CHECK(cudaFree(0));
// Initialize OptixDeviceContext
OPTIX_CHECK(optixInit());
context.disableValidation();
context.create();
// Initialize instance acceleration structure
scene_ias = InstanceAccel{InstanceAccel::Type::Instances};
// Pipeline settings
pipeline.setLaunchVariableName("params");
pipeline.setDirectCallableDepth(5);
pipeline.setContinuationCallableDepth(5);
pipeline.setNumPayloads(5);
pipeline.setNumAttributes(6);
// Create modules from cuda source file
Module raygen_module, miss_module, hitgroups_module, textures_module, surfaces_module;
raygen_module = pipeline.createModuleFromCudaFile(context, "cuda/raygen.cu");
miss_module = pipeline.createModuleFromCudaFile(context, "cuda/miss.cu");
hitgroups_module = pipeline.createModuleFromCudaFile(context, "cuda/hitgroups.cu");
textures_module = pipeline.createModuleFromCudaFile(context, "cuda/textures.cu");
surfaces_module = pipeline.createModuleFromCudaFile(context, "cuda/surfaces.cu");
// Initialize bitmaps to store rendered results
result_bitmap.allocate(PixelFormat::RGBA, pgGetWidth(), pgGetHeight());
accum_bitmap.allocate(PixelFormat::RGBA, pgGetWidth(), pgGetHeight());
// Configuration of launch parameters
params.width = result_bitmap.width();
params.height = result_bitmap.height();
params.samples_per_launch = 1;
params.max_depth = 10;
params.white = 1.0f;
initResultBufferOnDevice();
// Camera settings
camera.setOrigin(-47.7f, 10.0f, 64.0f);
camera.setLookat(-7, -4.5, 12.3);
camera.setUp(0.0f, 1.0f, 0.0f);
camera.setFarClip(5000);
camera.setFov(40.0f);
camera.setAspect(static_cast<float>(params.width) / params.height);
camera.setAperture(2.0f);
camera.setFocusDistance(60);
camera.enableTracking(pgGetCurrentWindow());
float3 U, V, W;
camera.UVWFrame(U, V, W);
// Raygen program
ProgramGroup raygen_prg = pipeline.createRaygenProgram(context, raygen_module, "__raygen__pinhole");
// Shader binding table data for raygen program
RaygenRecord raygen_record;
raygen_prg.recordPackHeader(&raygen_record);
raygen_record.data.camera =
{
.origin = camera.origin(),
.lookat = camera.lookat(),
.U = U,
.V = V,
.W = W,
.fov = camera.fov(),
.aspect = camera.aspect(),
.aperture = camera.aperture(),
.focus_distance = camera.focusDistance(),
.farclip = camera.farClip()
};
sbt.setRaygenRecord(raygen_record);
auto setupCallable = [&](const Module& module, const std::string& dc, const std::string& cc)
{
EmptyRecord callable_record = {};
auto [prg, id] = pipeline.createCallablesProgram(context, module, dc, cc);
prg.recordPackHeader(&callable_record);
sbt.addCallablesRecord(callable_record);
return id;
};
// Callable programs for textures
uint32_t constant_prg_id = setupCallable(textures_module, DC_FUNC_STR("constant"), "");
uint32_t checker_prg_id = setupCallable(textures_module, DC_FUNC_STR("checker"), "");
uint32_t bitmap_prg_id = setupCallable(textures_module, DC_FUNC_STR("bitmap"), "");
// Callable programs for surfaces
// Diffuse
uint32_t diffuse_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_diffuse"), CC_FUNC_STR("bsdf_diffuse"));
uint32_t diffuse_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_diffuse"), "");
// Conductor
uint32_t conductor_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_conductor"), CC_FUNC_STR("bsdf_conductor"));
uint32_t conductor_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_conductor"), "");
// Dielectric
uint32_t dielectric_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_dielectric"), CC_FUNC_STR("bsdf_dielectric"));
uint32_t dielectric_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_dielectric"), "");
// Disney
uint32_t disney_sample_bsdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("sample_disney"), CC_FUNC_STR("bsdf_disney"));
uint32_t disney_pdf_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("pdf_disney"), "");
// AreaEmitter
uint32_t area_emitter_prg_id = setupCallable(surfaces_module, DC_FUNC_STR("area_emitter"), "");
// Callable program for direct sampling of area emitter
uint32_t plane_sample_pdf_prg_id = setupCallable(hitgroups_module, DC_FUNC_STR("rnd_sample_plane"), CC_FUNC_STR("pdf_plane"));
textures.emplace("env", new FloatBitmapTexture("resources/image/christmas_photo_studio_01_4k.exr", bitmap_prg_id));
env = EnvironmentEmitter{textures.at("env")};
env.copyToDevice();
// Miss program
ProgramGroup miss_prg = pipeline.createMissProgram(context, miss_module, MS_FUNC_STR("envmap"));
// Shader binding table data for miss program
MissRecord miss_record;
miss_prg.recordPackHeader(&miss_record);
miss_record.data.env_data = env.devicePtr();
sbt.setMissRecord(miss_record);
// Hitgroup program
// Plane
auto plane_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("plane"), IS_FUNC_STR("plane"));
auto plane_alpha_discard_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("plane"), IS_FUNC_STR("plane"), AH_FUNC_STR("alpha_discard"));
// Sphere
auto sphere_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("sphere"), IS_FUNC_STR("sphere"));
auto sphere_alpha_discard_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("sphere"), IS_FUNC_STR("sphere"), AH_FUNC_STR("alpha_discard"));
// Box
auto box_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("box"), IS_FUNC_STR("box"));
// Cylinder
auto cylinder_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("cylinder"), IS_FUNC_STR("cylinder"));
// Triangle mesh
auto mesh_prg = pipeline.createHitgroupProgram(context, hitgroups_module, CH_FUNC_STR("mesh"));
struct Primitive
{
shared_ptr<Shape> shape;
shared_ptr<Material> material;
uint32_t sample_bsdf_id;
uint32_t pdf_id;
};
uint32_t sbt_idx = 0;
uint32_t sbt_offset = 0;
uint32_t instance_id = 0;
using SurfaceP = variant<shared_ptr<Material>, shared_ptr<AreaEmitter>>;
auto addHitgroupRecord = [&](ProgramGroup& prg, shared_ptr<Shape> shape, SurfaceP surface, uint32_t sample_bsdf_id, uint32_t pdf_id, shared_ptr<Texture> alpha_texture = nullptr)
{
const bool is_mat = holds_alternative<shared_ptr<Material>>(surface);
if (alpha_texture) alpha_texture->copyToDevice();
// Copy data to GPU
shape->copyToDevice();
shape->setSbtIndex(sbt_idx);
if (is_mat)
std::get<shared_ptr<Material>>(surface)->copyToDevice();
else
std::get<shared_ptr<AreaEmitter>>(surface)->copyToDevice();
// Register data to shader binding table
HitgroupRecord record;
prg.recordPackHeader(&record);
record.data =
{
.shape_data = shape->devicePtr(),
.surface_info =
{
.data = is_mat ? std::get<shared_ptr<Material>>(surface)->devicePtr() : std::get<shared_ptr<AreaEmitter>>(surface)->devicePtr(),
.sample_id = sample_bsdf_id,
.bsdf_id = sample_bsdf_id,
.pdf_id = pdf_id,
.type = is_mat ? std::get<shared_ptr<Material>>(surface)->surfaceType() : SurfaceType::AreaEmitter,
},
.alpha_texture =
{
alpha_texture ? alpha_texture->devicePtr() : nullptr,
alpha_texture ? alpha_texture->programId() : bitmap_prg_id
}
};
sbt.addHitgroupRecord(record);
sbt_idx++;
};
auto createGAS = [&](shared_ptr<Shape> shape, const Matrix4f& transform, uint32_t num_sbt=1)
{
// Build GAS and add it to IAS
ShapeInstance instance{shape->type(), shape, transform};
instance.allowCompaction();
instance.buildAccel(context, stream);
instance.setSBTOffset(sbt_offset);
instance.setId(instance_id);
scene_ias.addInstance(instance);
instance_id++;
sbt_offset += ThumbnailSBT::NRay * num_sbt;
};
auto setupPrimitive = [&](ProgramGroup& prg, const Primitive& p, const Matrix4f& transform, shared_ptr<Texture> alpha_texture = nullptr)
{
addHitgroupRecord(prg, p.shape, p.material, p.sample_bsdf_id, p.pdf_id, alpha_texture);
createGAS(p.shape, transform);
};
vector<AreaEmitterInfo> area_emitter_infos;
auto setupAreaEmitter = [&](
ProgramGroup& prg,
shared_ptr<Shape> shape,
shared_ptr<AreaEmitter> area, Matrix4f transform,
uint32_t sample_pdf_id,
shared_ptr<Texture> alpha_texture = nullptr
)
{
ASSERT(dynamic_pointer_cast<Plane>(shape) || dynamic_pointer_cast<Sphere>(shape), "The shape of area emitter must be a plane or sphere.");
addHitgroupRecord(prg, shape, area, area_emitter_prg_id, area_emitter_prg_id, alpha_texture);
createGAS(shape, transform);
AreaEmitterInfo area_emitter_info =
{
.shape_data = shape->devicePtr(),
.objToWorld = transform,
.worldToObj = transform.inverse(),
.sample_id = sample_pdf_id,
.pdf_id = sample_pdf_id
};
area_emitter_infos.push_back(area_emitter_info);
};
// Scene ==========================================================================
auto logo_alpha = make_shared<BitmapTexture>("resources/image/PRayGround_white.png", bitmap_prg_id);
auto logo_aspect = (float)logo_alpha->width() / logo_alpha->height();
textures.emplace("logo_alpha", logo_alpha);
textures.emplace("white", new ConstantTexture(make_float3(1.0f), constant_prg_id));
textures.emplace("black", new ConstantTexture(make_float3(0.0f), constant_prg_id));
textures.emplace("bright_gray", new ConstantTexture(make_float3(0.6f), constant_prg_id));
textures.emplace("orange", new ConstantTexture(make_float3(0.8f, 0.7f, 0.3f), constant_prg_id));
textures.emplace("green", new ConstantTexture(make_float3(0.05f, 0.8f, 0.6f), constant_prg_id));
textures.emplace("yellow", new ConstantTexture(make_float3(0.8f, 0.8f, 0.05f), constant_prg_id));
textures.emplace("wine_red", new ConstantTexture(make_float3(0.5f, 0.15f, 0.4f), constant_prg_id));
textures.emplace("checker", new CheckerTexture(make_float3(0.8f), make_float3(0.3f), 100, checker_prg_id));
textures.emplace("rtRest", new BitmapTexture("examples/rayTracingRestOfYourLife/rtRestOfYourLife.jpg", bitmap_prg_id));
textures.emplace("brick", new BitmapTexture("resources/image/brick_wall_001_diffuse_4k.jpg", bitmap_prg_id));
textures.emplace("alpha_checker", new CheckerTexture(make_float4(1.0), make_float4(0.0f), 20, checker_prg_id));
textures.emplace("wood", new BitmapTexture("resources/image/plywood_diff_1k.jpg", bitmap_prg_id));
materials.emplace("black_diffuse", new Diffuse(textures.at("black")));
materials.emplace("white_diffuse", new Diffuse(textures.at("white")));
materials.emplace("floor", new Diffuse(textures.at("checker")));
materials.emplace("brick", new Diffuse(textures.at("brick")));
materials.emplace("alpha_checker", new Diffuse(textures.at("alpha_checker")));
materials.emplace("orange", new Diffuse(textures.at("orange")));
materials.emplace("green", new Diffuse(textures.at("green")));
materials.emplace("silver_metal", new Conductor(textures.at("bright_gray")));
materials.emplace("gold", new Conductor(textures.at("yellow")));
materials.emplace("glass", new Dielectric(textures.at("white"), 1.5f));
auto aniso_disney = make_shared<Disney>(textures.at("wine_red"));
aniso_disney->setRoughness(0.3f);
aniso_disney->setSubsurface(0.0f);
aniso_disney->setMetallic(0.9f);
aniso_disney->setAnisotropic(0.8f);
materials.emplace("aniso_disney", aniso_disney);
materials.emplace("image_diffuse", new Diffuse(textures.at("rtRest")));
auto wooden_disney = make_shared<Disney>(textures.at("wood"));
wooden_disney->setMetallic(0.9f);
wooden_disney->setRoughness(0.02f);
materials.emplace("wooden_disney", wooden_disney);
lights.emplace("logo1", new AreaEmitter( textures.at("orange"), 150.0f, true ));
lights.emplace("logo2", new AreaEmitter( textures.at("white"), 300.0f, true ));
shapes.emplace("plane", new Plane(make_float2(-0.5f), make_float2(0.5f)));
shapes.emplace("sphere", new Sphere(make_float3(0.0f), 1.0f));
shapes.emplace("cylinder", new Cylinder(0.5f, 1.0f));
shapes.emplace("box", new Box(make_float3(-0.5f), make_float3(0.5f)));
auto dragon = make_shared<TriangleMesh>("resources/model/dragon.obj");
auto bunny = make_shared<TriangleMesh>("resources/model/bunny.obj");
auto buddha = make_shared<TriangleMesh>("resources/model/happy_vrip_res3.ply");
auto teapot = make_shared<TriangleMesh>("resources/model/teapot_normal_merged.obj");
auto armadillo = make_shared<TriangleMesh>("resources/model/Armadillo.ply");
shared_ptr<TriangleMesh> mitsuba(new TriangleMesh());
vector<Attributes> mitsuba_mat_attribs;
mitsuba->loadWithMtl("resources/model/mitsuba-sphere.obj", mitsuba_mat_attribs);
dragon->smooth();
bunny->smooth();
buddha->smooth();
teapot->smooth();
armadillo->smooth();
mitsuba->smooth();
shapes.emplace("dragon", dragon);
shapes.emplace("bunny", bunny);
shapes.emplace("buddha", buddha);
shapes.emplace("teapot", teapot);
shapes.emplace("armadillo", armadillo);
shapes.emplace("mitsuba", mitsuba);
float x = -logo_aspect * 10 / 2 + 10;
// Ground plane
Primitive p1{ shapes.at("plane"), materials.at("floor"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(plane_prg, p1, Matrix4f::translate(0, -5, 0) * Matrix4f::scale(500));
// Dragon
Primitive p3{ shapes.at("dragon"), materials.at("glass"), dielectric_sample_bsdf_prg_id, dielectric_pdf_prg_id };
setupPrimitive(mesh_prg, p3, Matrix4f::translate(-logo_aspect * 10 / 2 + 10, -0.75, 15) *Matrix4f::rotate(math::pi/2, {0, 1, 0})* Matrix4f::scale(15));
// Bunny
Primitive p4{ shapes.at("bunny"), materials.at("white_diffuse"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(mesh_prg, p4, Matrix4f::translate(0, -7.5, 15)* Matrix4f::scale(75));
// Buddha
Primitive p5{ shapes.at("buddha"), materials.at("gold"), conductor_sample_bsdf_prg_id, conductor_pdf_prg_id };
setupPrimitive(mesh_prg, p5, Matrix4f::translate(logo_aspect * 10 / 2 - 10, -10, 15)* Matrix4f::scale(100));
// Teapot
Primitive p6{ shapes.at("teapot"), materials.at("orange"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(mesh_prg, p6, Matrix4f::translate(-logo_aspect * 10 / 2 + 10, -5, 30)* Matrix4f::scale(3));
// Armadillo
Primitive p7{ shapes.at("armadillo"), materials.at("green"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(mesh_prg, p7, Matrix4f::translate(logo_aspect * 10 / 2 - 10, 0.5, 30)* Matrix4f::rotate(math::pi, { 0, 1, 0 }) * Matrix4f::scale(0.1));
// Mitsuba
for (auto& attrib : mitsuba_mat_attribs)
{
if (attrib.name == "inside") {
materials.emplace("inside", new Diffuse(textures.at("white")));
addHitgroupRecord(mesh_prg, shapes.at("mitsuba"), materials.at("inside"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id);
}
else if (attrib.name == "case")
{
textures.emplace("case", new ConstantTexture(attrib.findOneFloat3("diffuse", make_float3(0.3, 0.8, 0.7)), constant_prg_id));
auto case_disney = make_shared<Disney>(textures.at("case"));
case_disney->setRoughness(0.3f);
case_disney->setSubsurface(0.0f);
case_disney->setMetallic(0.9f);
case_disney->setAnisotropic(0.8f);
materials.emplace("case", case_disney);
addHitgroupRecord(mesh_prg, shapes.at("mitsuba"), materials.at("case"), disney_sample_bsdf_prg_id, disney_pdf_prg_id);
}
}
createGAS(shapes.at("mitsuba"), Matrix4f::translate(0, -4.8, 30) * Matrix4f::scale(5), 2);
// Sphere1
Primitive p9{ shapes.at("sphere"), materials.at("brick"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(sphere_prg, p9, Matrix4f::translate(x, 0, 0)* Matrix4f::scale(5));
// Sphere2
Primitive p10{ shapes.at("sphere"), materials.at("black_diffuse"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(sphere_alpha_discard_prg, p10, Matrix4f::translate(0, 0, 0)* Matrix4f::scale(5), textures.at("alpha_checker"));
// Sphere3
Primitive p11{ shapes.at("sphere"), materials.at("aniso_disney"), disney_sample_bsdf_prg_id, disney_pdf_prg_id };
setupPrimitive(sphere_prg, p11, Matrix4f::translate(-x, 0, 0)* Matrix4f::scale(5));
// Cylinder
Primitive p12{ shapes.at("cylinder"), materials.at("white_diffuse"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id };
setupPrimitive(cylinder_prg, p12, Matrix4f::translate(x, -1, -15)* Matrix4f::scale(8));
// Box
Primitive p13{ shapes.at("box"), materials.at("wooden_disney"), disney_sample_bsdf_prg_id, disney_pdf_prg_id };
setupPrimitive(box_prg, p13, Matrix4f::translate(0, -0.9f, -15) * Matrix4f::rotate(math::pi / 6, {0, 1, 0}) * Matrix4f::scale(8));
// Plane
Primitive p14{ shapes.at("plane"), materials.at("image_diffuse"), diffuse_sample_bsdf_prg_id, diffuse_pdf_prg_id};
setupPrimitive(plane_prg, p14, Matrix4f::translate(-x, 1, -15) * Matrix4f::rotate(math::pi / 2, { 1,0,0 }) * Matrix4f::rotate(-math::pi / 12, { 0, 1, 0 }) * Matrix4f::scale(10));
setupAreaEmitter(plane_alpha_discard_prg, shapes.at("plane"), lights.at("logo1"),
Matrix4f::translate(0, 12.5f, -20) * Matrix4f::rotate(math::pi * 2 / 3, { 1.0f, 0.0f, 0.0f })* Matrix4f::scale(make_float3(logo_aspect * 10, 1, 10)),
plane_sample_pdf_prg_id, textures.at("logo_alpha"));
setupAreaEmitter(plane_alpha_discard_prg, shapes.at("plane"), lights.at("logo2"),
Matrix4f::translate(0, 12.5f, 80) * Matrix4f::rotate(math::pi * 1 / 3, { 1.0f, 0.0f, 0.0f }) * Matrix4f::scale(make_float3(logo_aspect * 10, 1, 10)),
plane_sample_pdf_prg_id, textures.at("logo_alpha"));
// Copy light infomation to device
CUDABuffer<AreaEmitterInfo> d_area_emitter_infos;
d_area_emitter_infos.copyToDevice(area_emitter_infos);
params.lights = d_area_emitter_infos.deviceData();
params.num_lights = static_cast<int>(area_emitter_infos.size());
CUDA_CHECK(cudaStreamCreate(&stream));
scene_ias.build(context, stream);
sbt.createOnDevice();
params.handle = scene_ias.handle();
pipeline.create(context);
d_params.allocate(sizeof(LaunchParams));
#if INTERACTIVE
// GUI setting
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
const char* glsl_version = "#version 150";
ImGui::StyleColorsDark();
ImGui_ImplGlfw_InitForOpenGL(pgGetCurrentWindow()->windowPtr(), true);
ImGui_ImplOpenGL3_Init(glsl_version);
#else
float start_time = pgGetElapsedTimef();
constexpr int num_samples = 100000;
for (int frame = 0; frame < num_samples; frame += params.samples_per_launch)
{
d_params.copyToDeviceAsync(¶ms, sizeof(LaunchParams), stream);
OPTIX_CHECK(optixLaunch(
static_cast<OptixPipeline>(pipeline),
stream,
d_params.devicePtr(),
sizeof(LaunchParams),
&sbt.sbt(),
params.width,
params.height,
1
));
CUDA_CHECK(cudaStreamSynchronize(stream));
CUDA_SYNC_CHECK();
params.subframe_index = frame + 1;
streamProgress(params.subframe_index, num_samples, pgGetElapsedTimef() - start_time, 20);
}
result_bitmap.copyFromDevice();
result_bitmap.write(pgPathJoin(pgAppDir(), "thumbnail.jpg"));
pgExit();
#endif
}
// ----------------------------------------------------------------
void App::update()
{
handleCameraUpdate();
d_params.copyToDeviceAsync(¶ms, sizeof(LaunchParams), stream);
float start_time = pgGetElapsedTimef();
optixLaunch(
static_cast<OptixPipeline>(pipeline),
stream,
d_params.devicePtr(),
sizeof(LaunchParams),
&sbt.sbt(),
params.width,
params.height,
1
);
CUDA_CHECK(cudaStreamSynchronize(stream));
CUDA_SYNC_CHECK();
render_time = pgGetElapsedTimef() - start_time;
params.subframe_index++;
result_bitmap.copyFromDevice();
}
// ----------------------------------------------------------------
void App::draw()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::Begin("Path tracing GUI");
ImGui::SliderFloat("White", ¶ms.white, 0.01f, 1.0f);
ImGui::Text("Camera info:");
ImGui::Text("Origin: %f %f %f", camera.origin().x, camera.origin().y, camera.origin().z);
ImGui::Text("Lookat: %f %f %f", camera.lookat().x, camera.lookat().y, camera.lookat().z);
ImGui::Text("Up: %f %f %f", camera.up().x, camera.up().y, camera.up().z);
float farclip = camera.farClip();
ImGui::SliderFloat("far clip", &farclip, 500.0f, 10000.0f);
if (farclip != camera.farClip()) {
camera.setFarClip(farclip);
camera_update = true;
}
float aperture = camera.aperture();
ImGui::SliderFloat("Aperture", &aperture, 0.01f, 4.0f);
if (aperture != camera.aperture()) {
camera.setAperture(aperture);
initResultBufferOnDevice();
}
float focus_dist = camera.focusDistance();
ImGui::SliderFloat("Focus distance", &focus_dist, 1.0f, 100.0f);
if (focus_dist != camera.focusDistance()) {
camera.setFocusDistance(focus_dist);
initResultBufferOnDevice();
}
auto& light1 = lights.at("logo1");
float intensity1 = light1->intensity();
ImGui::SliderFloat("Emittance (light1)", &intensity1, 1.0f, 1000.0f);
if (intensity1 != light1->intensity())
{
light1->setIntensity(intensity1);
light1->copyToDevice();
initResultBufferOnDevice();
}
auto& light2 = lights.at("logo2");
float intensity2 = light2->intensity();
ImGui::SliderFloat("Emittance (light2)", &intensity2, 1.0f, 1000.0f);
if (intensity2 != light2->intensity())
{
light2->setIntensity(intensity2);
light2->copyToDevice();
initResultBufferOnDevice();
}
ImGui::Text("Frame rate: %.3f ms/frame (%.2f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("Render time: %.3f ms/frame", render_time * 1000.0f);
ImGui::Text("Subframe index: %d", params.subframe_index);
ImGui::End();
ImGui::Render();
result_bitmap.draw(0, 0);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
if (params.subframe_index == 20000) {
result_bitmap.write(pgPathJoin(pgAppDir(), "thumbnail.jpg"));
pgExit();
}
}
// ----------------------------------------------------------------
void App::close()
{
env.free();
for (auto& it : shapes) it.second->free();
for (auto& it : materials) it.second->free();
for (auto& it : textures) it.second->free();
for (auto& it : lights) it.second->free();
pipeline.destroy();
context.destroy();
#if INTERACTIVE
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
#endif
}
// ----------------------------------------------------------------
void App::mouseDragged(float x, float y, int button)
{
if (button != MouseButton::Middle) return;
camera_update = true;
}
// ----------------------------------------------------------------
void App::mouseScrolled(float xoffset, float yoffset)
{
camera_update = true;
}
| 42.095164 | 183 | 0.646296 | [
"mesh",
"render",
"shape",
"vector",
"model",
"transform"
] |
15d70341100014c9a02ce7c3314a146b2c21df3c | 1,604 | cpp | C++ | dayten.cpp | seanlowjk/aoc-2020-cpp | 74b0b58362bd082beeff1295118c15551547771e | [
"MIT"
] | null | null | null | dayten.cpp | seanlowjk/aoc-2020-cpp | 74b0b58362bd082beeff1295118c15551547771e | [
"MIT"
] | null | null | null | dayten.cpp | seanlowjk/aoc-2020-cpp | 74b0b58362bd082beeff1295118c15551547771e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
// Avoids synchro with input stream
std::ios_base::sync_with_stdio(false);
// Guarentees the flushing of cout before cin
std::cin.tie(NULL);
std::string input;
std::vector<long> voltages;
while (std::getline(std::cin, input))
{
if (!input.empty())
voltages.push_back(stol(input));
}
std::sort(voltages.begin(), voltages.end(), [](int i, int j) { return i < j; });
long one_differences = 0;
long three_differences = 1;
if (voltages[0] == 1)
one_differences++;
else if (voltages[0] == 3)
three_differences++;
for (int i = 0; i < voltages.size() - 1; i++)
{
if (voltages[i + 1] - voltages[i] == 1)
one_differences++;
else
three_differences++;
}
long multi_differences = one_differences * three_differences;
long dp[voltages.back() + 1];
for (int i = 0; i <= voltages.back(); i++)
dp[i] = 0;
dp[0] = 1;
for (int i = 0; i < voltages.size(); i++)
{
int voltage_value = voltages[i];
if (voltage_value == 1)
dp[1] = 1;
else if (voltage_value == 2)
dp[2] = 2;
else
dp[voltage_value] = dp[voltage_value - 1] + dp[voltage_value - 2] + dp[voltage_value - 3];
}
long long num_ways = dp[voltages.back()];
std::cout << "Part One\n";
std::cout << multi_differences << "\n";
std::cout << "Part Two\n";
std::cout << num_ways << std::endl;
} | 23.246377 | 102 | 0.543017 | [
"vector"
] |
15e4a17e0b9b95db04a19b7e363aa0ad11de6019 | 459 | cpp | C++ | engine/modules/net/editor/http_client_editor.cpp | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 58 | 2018-05-10T17:06:42.000Z | 2019-01-24T13:42:22.000Z | engine/modules/net/editor/http_client_editor.cpp | blab-liuliang/echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 290 | 2018-01-24T16:29:42.000Z | 2019-01-24T07:11:16.000Z | engine/modules/net/editor/http_client_editor.cpp | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 9 | 2018-08-26T04:06:21.000Z | 2019-01-14T03:47:39.000Z | #include "http_client_editor.h"
#include "engine/core/editor/editor.h"
#include "engine/core/main/Engine.h"
namespace Echo
{
#ifdef ECHO_EDITOR_MODE
HttpClientEditor::HttpClientEditor(Object* object)
: ObjectEditor(object)
{
}
HttpClientEditor::~HttpClientEditor()
{
}
ImagePtr HttpClientEditor::getThumbnail() const
{
return Image::loadFromFile(Engine::instance()->getRootPath() + "engine/modules/net/editor/icon/httpclient.png");
}
#endif
}
| 19.956522 | 114 | 0.751634 | [
"object"
] |
15f070c3397adb5d6adc8c6578e6490104f483dd | 3,575 | cpp | C++ | core/silkworm/trie/node.cpp | gelfand/silkworm | cc995126e45c48a5c45d6be287a8515f843e602a | [
"Apache-2.0"
] | null | null | null | core/silkworm/trie/node.cpp | gelfand/silkworm | cc995126e45c48a5c45d6be287a8515f843e602a | [
"Apache-2.0"
] | null | null | null | core/silkworm/trie/node.cpp | gelfand/silkworm | cc995126e45c48a5c45d6be287a8515f843e602a | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2021 The Silkworm Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "node.hpp"
#include <bitset>
#include <silkworm/common/endian.hpp>
namespace silkworm::trie {
Node::Node(uint16_t state_mask, uint16_t tree_mask, uint16_t hash_mask, std::vector<evmc::bytes32> hashes,
std::optional<evmc::bytes32> root_hash)
: state_mask_{state_mask},
tree_mask_{tree_mask},
hash_mask_{hash_mask},
hashes_{std::move(hashes)},
root_hash_{std::move(root_hash)} {
assert_subset(tree_mask_, state_mask_);
assert_subset(hash_mask_, state_mask_);
assert(std::bitset<16>(hash_mask_).count() == hashes_.size());
}
void Node::set_root_hash(std::optional<evmc::bytes32> root_hash) { root_hash_ = std::move(root_hash); }
bool operator==(const Node& a, const Node& b) {
return a.state_mask() == b.state_mask() && a.tree_mask() == b.tree_mask() && a.hash_mask() == b.hash_mask() &&
a.hashes() == b.hashes() && a.root_hash() == b.root_hash();
}
Bytes marshal_node(const Node& n) {
size_t buf_size{/* 3 masks state/tree/hash 2 bytes each */ 6 +
/* root hash */ (n.root_hash().has_value() ? kHashLength : 0u) +
/* hashes */ n.hashes().size() * kHashLength};
Bytes buf(buf_size, '\0');
size_t pos{0};
endian::store_big_u16(&buf[pos], n.state_mask());
pos += 2;
endian::store_big_u16(&buf[pos], n.tree_mask());
pos += 2;
endian::store_big_u16(&buf[pos], n.hash_mask());
pos += 2;
if (n.root_hash().has_value()) {
std::memcpy(&buf[pos], n.root_hash()->bytes, kHashLength);
pos += kHashLength;
}
for (const auto& hash : n.hashes()) {
std::memcpy(&buf[pos], hash.bytes, kHashLength);
pos += kHashLength;
}
return buf;
}
std::optional<Node> unmarshal_node(ByteView v) {
if (v.length() < 6) {
// At least state/tree/hash masks need to be present
return std::nullopt;
} else {
// Beyond the 6th byte the length must be a multiple of kHashLength
if ((v.length() - 6) % kHashLength != 0) {
return std::nullopt;
}
}
const auto state_mask{endian::load_big_u16(v.data())};
v.remove_prefix(2);
const auto tree_mask{endian::load_big_u16(v.data())};
v.remove_prefix(2);
const auto hash_mask{endian::load_big_u16(v.data())};
v.remove_prefix(2);
std::optional<evmc::bytes32> root_hash{std::nullopt};
if (std::bitset<16>(hash_mask).count() + 1 == v.length() / kHashLength) {
root_hash = evmc::bytes32{};
std::memcpy(root_hash->bytes, v.data(), kHashLength);
v.remove_prefix(kHashLength);
}
const size_t num_hashes{v.length() / kHashLength};
std::vector<evmc::bytes32> hashes(num_hashes);
for (size_t i{0}; i < num_hashes; ++i) {
std::memcpy(hashes[i].bytes, v.data(), kHashLength);
v.remove_prefix(kHashLength);
}
return Node{state_mask, tree_mask, hash_mask, hashes, root_hash};
}
} // namespace silkworm::trie
| 32.5 | 114 | 0.638881 | [
"vector"
] |
15f403492bc3ac6aa91a40e3cb8e1dbe685fa3ca | 16,907 | cpp | C++ | Code/Projects/Rosa/src/rosawardrobe.cpp | dphrygian/zeta | 2b32760558cf2b20c626cf46fcf2a382924988fe | [
"Zlib",
"Unlicense"
] | 6 | 2022-01-22T02:18:07.000Z | 2022-02-14T09:30:53.000Z | Code/Projects/Rosa/src/rosawardrobe.cpp | dphrygian/zeta | 2b32760558cf2b20c626cf46fcf2a382924988fe | [
"Zlib",
"Unlicense"
] | null | null | null | Code/Projects/Rosa/src/rosawardrobe.cpp | dphrygian/zeta | 2b32760558cf2b20c626cf46fcf2a382924988fe | [
"Zlib",
"Unlicense"
] | null | null | null | #include "core.h"
#include "rosawardrobe.h"
#include "mathfunc.h"
#include "configmanager.h"
#include "idatastream.h"
#include "hsv.h"
RosaWardrobe::RosaWardrobe()
: m_Wardrobes()
, m_Bodies()
, m_Skins()
, m_Hairs()
, m_Eyes()
, m_Heads()
, m_Outfits()
, m_Styles()
, m_Schemes()
, m_Pieces()
, m_Options()
, m_Accessories()
{
}
RosaWardrobe::~RosaWardrobe()
{
}
RosaWardrobe::SCostume RosaWardrobe::CreateCostume( const HashedString& WardrobeTag, const EBodyGender BodyGender, const bool IsHuman )
{
SCostume Costume;
Costume.m_IsValid = true;
Costume.m_IsHuman = IsHuman;
const SWardrobe& Wardrobe = GetWardrobe( WardrobeTag );
Costume.m_Wardrobe = WardrobeTag;
if( BodyGender == EBG_Woman && !Wardrobe.m_FemaleBodies.Empty() )
{
Costume.m_Body = Math::ArrayRandom( Wardrobe.m_FemaleBodies );
}
else if( BodyGender == EBG_Man && !Wardrobe.m_MaleBodies.Empty() )
{
Costume.m_Body = Math::ArrayRandom( Wardrobe.m_MaleBodies );
}
else
{
Costume.m_Body = Math::ArrayRandom( Wardrobe.m_Bodies );
}
const SBody& Body = GetBody( Costume.m_Body );
Costume.m_Scale = Math::Random( Body.m_ScaleMin, Body.m_ScaleMax );
Costume.m_Skin = Math::ArrayRandom( Body.m_Skins );
Costume.m_Head = Body.m_Heads.Empty() ? HashedString::NullString : Math::ArrayRandom( Body.m_Heads );
const SSkin& Skin = GetSkin( Costume.m_Skin );
Costume.m_Hair = Skin.m_Hairs.Empty() ? HashedString::NullString : Math::ArrayRandom( Skin.m_Hairs );
Costume.m_Eyes = Skin.m_Eyes.Empty() ? HashedString::NullString : Math::ArrayRandom( Skin.m_Eyes );
if( Body.m_Outfits.Empty() )
{
// Skip all of that stuff
}
else
{
const HashedString& OutfitTag = Math::ArrayRandom( Body.m_Outfits );
const SOutfit& Outfit = GetOutfit( OutfitTag );
Costume.m_Style = Outfit.m_Styles.Empty() ? HashedString::NullString : Math::ArrayRandom( Outfit.m_Styles );
Costume.m_Accessory = Outfit.m_Accessories.Empty() ? HashedString::NullString : Math::ArrayRandom( Outfit.m_Accessories );
Costume.m_Scheme = Outfit.m_Schemes.Empty() ? HashedString::NullString : Math::ArrayRandom( Outfit.m_Schemes );
// HACKHACK: Disable the accessory if hairstyle disallows it (because hats)
// ROSATODO: For Zeta, revisit this so that we can instead hide hair when a helmet is equipped?
const bool AllowAccessory = ConfigManager::GetInheritedBool( Costume.m_Accessory, true, Costume.m_Style );
Costume.m_Accessory = AllowAccessory ? Costume.m_Accessory : HashedString::NullString;
FOR_EACH_ARRAY( PieceIter, Outfit.m_Pieces, HashedString )
{
const HashedString& PieceTag = PieceIter.GetValue();
const SPiece& Piece = GetPiece( PieceTag );
const HashedString& OptionTag = Math::ArrayRandom( Piece.m_Options );
Costume.m_Options.PushBack( OptionTag );
}
}
return Costume;
}
const RosaWardrobe::SWardrobe& RosaWardrobe::GetWardrobe( const HashedString& Tag )
{
Map<HashedString, SWardrobe>::Iterator Iter = m_Wardrobes.Search( Tag );
if( Iter.IsValid() )
{
return Iter.GetValue();
}
SWardrobe& Wardrobe = m_Wardrobes[ Tag ];
STATICHASH( NumBodies );
const uint NumBodies = ConfigManager::GetInheritedInt( sNumBodies, 0, Tag );
for( uint Index = 0; Index < NumBodies; ++Index )
{
Wardrobe.m_Bodies.PushBack( ConfigManager::GetInheritedSequenceHash( "Body%d", Index, HashedString::NullString, Tag ) );
}
STATICHASH( NumMaleBodies );
const uint NumMaleBodies = ConfigManager::GetInheritedInt( sNumMaleBodies, 0, Tag );
for( uint Index = 0; Index < NumMaleBodies; ++Index )
{
const HashedString Body = ConfigManager::GetInheritedSequenceHash( "MaleBody%d", Index, HashedString::NullString, Tag );
Wardrobe.m_Bodies.PushBack( Body );
Wardrobe.m_MaleBodies.PushBack( Body );
}
STATICHASH( NumFemaleBodies );
const uint NumFemaleBodies = ConfigManager::GetInheritedInt( sNumFemaleBodies, 0, Tag );
for( uint Index = 0; Index < NumFemaleBodies; ++Index )
{
const HashedString Body = ConfigManager::GetInheritedSequenceHash( "FemaleBody%d", Index, HashedString::NullString, Tag );
Wardrobe.m_Bodies.PushBack( Body );
Wardrobe.m_FemaleBodies.PushBack( Body );
}
STATICHASH( CastsShadows );
Wardrobe.m_CastsShadows = ConfigManager::GetInheritedBool( sCastsShadows, true, Tag );
STATICHASH( CastsSelfShadows );
Wardrobe.m_CastsSelfShadows = ConfigManager::GetInheritedBool( sCastsSelfShadows, true, Tag );
return Wardrobe;
}
RosaWardrobe::EBodyGender RosaWardrobe::GetBodyGender( const HashedString& BodyGender ) const
{
STATIC_HASHED_STRING( Woman );
if( BodyGender == sWoman ) { return EBG_Woman; }
STATIC_HASHED_STRING( Man );
if( BodyGender == sMan ) { return EBG_Man; }
// This case is not invalid; some enemy types may not be
// gendered (whereas currently all actors are gendered).
return EBG_None;
}
const RosaWardrobe::SBody& RosaWardrobe::GetBody( const HashedString& Tag )
{
Map<HashedString, SBody>::Iterator BodyIter = m_Bodies.Search( Tag );
if( BodyIter.IsValid() )
{
return BodyIter.GetValue();
}
SBody& Body = m_Bodies[ Tag ];
STATICHASH( Mesh );
Body.m_Mesh = ConfigManager::GetInheritedString( sMesh, "", Tag );
STATICHASH( Gender );
Body.m_Gender = GetBodyGender( ConfigManager::GetInheritedHash( sGender, HashedString::NullString, Tag ) );
STATICHASH( Voice );
const SimpleString DefaultVoice = ConfigManager::GetInheritedString( sVoice, "", Tag );
STATICHASH( HumanVoice );
Body.m_HumanVoice = ConfigManager::GetInheritedString( sHumanVoice, DefaultVoice.CStr(), Tag );
STATICHASH( VampireVoice );
Body.m_VampireVoice = ConfigManager::GetInheritedString( sVampireVoice, DefaultVoice.CStr(), Tag );
STATICHASH( Scale );
const float Scale = ConfigManager::GetInheritedFloat( sScale, 1.0f, Tag );
STATICHASH( ScaleMin );
Body.m_ScaleMin = ConfigManager::GetInheritedFloat( sScaleMin, Scale, Tag );
STATICHASH( ScaleMax );
Body.m_ScaleMax = ConfigManager::GetInheritedFloat( sScaleMax, Scale, Tag );
DEVASSERT( Body.m_ScaleMin <= Body.m_ScaleMax );
STATICHASH( NumSkins );
const uint NumSkins = ConfigManager::GetInheritedInt( sNumSkins, 0, Tag );
for( uint Index = 0; Index < NumSkins; ++Index )
{
Body.m_Skins.PushBack( ConfigManager::GetInheritedSequenceHash( "Skin%d", Index, HashedString::NullString, Tag ) );
}
STATICHASH( NumHeads );
const uint NumHeads = ConfigManager::GetInheritedInt( sNumHeads, 0, Tag );
for( uint Index = 0; Index < NumHeads; ++Index )
{
Body.m_Heads.PushBack( ConfigManager::GetInheritedSequenceHash( "Head%d", Index, HashedString::NullString, Tag ) );
}
// ZETATODO: Clean up the stuff I no longer want here, make it easier to build creature variations.
STATICHASH( NumOutfits );
const uint NumOutfits = ConfigManager::GetInheritedInt( sNumOutfits, 0, Tag );
for( uint Index = 0; Index < NumOutfits; ++Index )
{
Body.m_Outfits.PushBack( ConfigManager::GetInheritedSequenceHash( "Outfit%d", Index, HashedString::NullString, Tag ) );
}
return Body;
}
const RosaWardrobe::SSkin& RosaWardrobe::GetSkin( const HashedString& Tag )
{
Map<HashedString, SSkin>::Iterator SkinIter = m_Skins.Search( Tag );
if( SkinIter.IsValid() )
{
return SkinIter.GetValue();
}
SSkin& Skin = m_Skins[ Tag ];
const Vector DefaultColorHSV = HSV::GetConfigHSV( "Color", Tag, Vector() );
// ROSANOTE: Human alpha defaults to 0, which is the skin bit (see character shader)
Skin.m_HumanColorHSV = HSV::GetConfigHSVA( "HumanColor", Tag, Vector4( DefaultColorHSV, 0.0f ) );
// ROSANOTE: Vampire alpha defaults to 1, which is the no-skin bit (see character shader)
Skin.m_VampireColorHSV = HSV::GetConfigHSVA( "VampireColor", Tag, Vector4( DefaultColorHSV, 1.0f ) );
STATICHASH( NumHairs );
const uint NumHairs = ConfigManager::GetInheritedInt( sNumHairs, 0, Tag );
for( uint Index = 0; Index < NumHairs; ++Index )
{
Skin.m_Hairs.PushBack( ConfigManager::GetInheritedSequenceHash( "Hair%d", Index, HashedString::NullString, Tag ) );
}
STATICHASH( NumEyes );
const uint NumEyes = ConfigManager::GetInheritedInt( sNumEyes, 0, Tag );
for( uint Index = 0; Index < NumEyes; ++Index )
{
Skin.m_Eyes.PushBack( ConfigManager::GetInheritedSequenceHash( "Eyes%d", Index, HashedString::NullString, Tag ) );
}
return Skin;
}
const RosaWardrobe::SHair& RosaWardrobe::GetHair( const HashedString& Tag )
{
Map<HashedString, SHair>::Iterator HairIter = m_Hairs.Search( Tag );
if( HairIter.IsValid() )
{
return HairIter.GetValue();
}
SHair& Hair = m_Hairs[ Tag ];
Hair.m_ColorHSV = HSV::GetConfigHSV( "Color", Tag, Vector() );
return Hair;
}
const RosaWardrobe::SEyes& RosaWardrobe::GetEyes( const HashedString& Tag )
{
Map<HashedString, SEyes>::Iterator EyesIter = m_Eyes.Search( Tag );
if( EyesIter.IsValid() )
{
return EyesIter.GetValue();
}
SEyes& Eyes = m_Eyes[ Tag ];
Eyes.m_ColorHSV = HSV::GetConfigHSV( "Color", Tag, Vector() );
return Eyes;
}
const RosaWardrobe::SHead& RosaWardrobe::GetHead( const HashedString& Tag )
{
Map<HashedString, SHead>::Iterator HeadIter = m_Heads.Search( Tag );
if( HeadIter.IsValid() )
{
return HeadIter.GetValue();
}
SHead& Head = m_Heads[ Tag ];
STATICHASH( Mesh );
const SimpleString DefaultMesh = ConfigManager::GetInheritedString( sMesh, "", Tag );
STATICHASH( HumanMesh );
Head.m_HumanMesh = ConfigManager::GetInheritedString( sHumanMesh, DefaultMesh.CStr(), Tag );
STATICHASH( VampireMesh );
Head.m_VampireMesh = ConfigManager::GetInheritedString( sVampireMesh, DefaultMesh.CStr(), Tag );
return Head;
}
const RosaWardrobe::SOutfit& RosaWardrobe::GetOutfit( const HashedString& Tag )
{
Map<HashedString, SOutfit>::Iterator Iter = m_Outfits.Search( Tag );
if( Iter.IsValid() )
{
return Iter.GetValue();
}
SOutfit& Outfit = m_Outfits[ Tag ];
STATICHASH( NumStyles );
const uint NumStyles = ConfigManager::GetInheritedInt( sNumStyles, 0, Tag );
for( uint Index = 0; Index < NumStyles; ++Index )
{
Outfit.m_Styles.PushBack( ConfigManager::GetInheritedSequenceHash( "Style%d", Index, HashedString::NullString, Tag ) );
}
STATICHASH( NumSchemes );
const uint NumSchemes = ConfigManager::GetInheritedInt( sNumSchemes, 0, Tag );
for( uint Index = 0; Index < NumSchemes; ++Index )
{
Outfit.m_Schemes.PushBack( ConfigManager::GetInheritedSequenceHash( "Scheme%d", Index, HashedString::NullString, Tag ) );
}
STATICHASH( NumPieces );
const uint NumPieces = ConfigManager::GetInheritedInt( sNumPieces, 0, Tag );
for( uint Index = 0; Index < NumPieces; ++Index )
{
Outfit.m_Pieces.PushBack( ConfigManager::GetInheritedSequenceHash( "Piece%d", Index, HashedString::NullString, Tag ) );
}
STATICHASH( NumAccessories );
const uint NumAccessories = ConfigManager::GetInheritedInt( sNumAccessories, 0, Tag );
for( uint Index = 0; Index < NumAccessories; ++Index )
{
Outfit.m_Accessories.PushBack( ConfigManager::GetInheritedSequenceHash( "Accessory%d", Index, HashedString::NullString, Tag ) );
}
return Outfit;
}
const RosaWardrobe::SStyle& RosaWardrobe::GetStyle( const HashedString& Tag )
{
Map<HashedString, SStyle>::Iterator StyleIter = m_Styles.Search( Tag );
if( StyleIter.IsValid() )
{
return StyleIter.GetValue();
}
SStyle& Style = m_Styles[ Tag ];
STATICHASH( Mesh );
Style.m_Mesh = ConfigManager::GetInheritedString( sMesh, "", Tag );
return Style;
}
const RosaWardrobe::SScheme& RosaWardrobe::GetScheme( const HashedString& Tag )
{
Map<HashedString, SScheme>::Iterator SchemeIter = m_Schemes.Search( Tag );
if( SchemeIter.IsValid() )
{
return SchemeIter.GetValue();
}
SScheme& Scheme = m_Schemes[ Tag ];
Scheme.m_PrimaryColorHSV = HSV::GetConfigHSV( "PrimaryColor", Tag, Vector() );
Scheme.m_SecondaryColorHSV = HSV::GetConfigHSV( "SecondaryColor", Tag, Vector() );
Scheme.m_AccentColorHSV = HSV::GetConfigHSV( "AccentColor", Tag, Vector() );
return Scheme;
}
const RosaWardrobe::SPiece& RosaWardrobe::GetPiece( const HashedString& Tag )
{
Map<HashedString, SPiece>::Iterator Iter = m_Pieces.Search( Tag );
if( Iter.IsValid() )
{
return Iter.GetValue();
}
SPiece& Piece = m_Pieces[ Tag ];
STATICHASH( NumOptions );
const uint NumOptions = ConfigManager::GetInheritedInt( sNumOptions, 0, Tag );
for( uint Index = 0; Index < NumOptions; ++Index )
{
Piece.m_Options.PushBack( ConfigManager::GetInheritedSequenceHash( "Option%d", Index, HashedString::NullString, Tag ) );
}
return Piece;
}
const RosaWardrobe::SOption& RosaWardrobe::GetOption( const HashedString& Tag )
{
Map<HashedString, SOption>::Iterator OptionIter = m_Options.Search( Tag );
if( OptionIter.IsValid() )
{
return OptionIter.GetValue();
}
SOption& Option = m_Options[ Tag ];
STATICHASH( Mesh );
Option.m_Mesh = ConfigManager::GetInheritedString( sMesh, "", Tag );
return Option;
}
const RosaWardrobe::SAccessory& RosaWardrobe::GetAccessory( const HashedString& Tag )
{
Map<HashedString, SAccessory>::Iterator AccessoryIter = m_Accessories.Search( Tag );
if( AccessoryIter.IsValid() )
{
return AccessoryIter.GetValue();
}
SAccessory& Accessory = m_Accessories[ Tag ];
STATICHASH( Mesh );
Accessory.m_Mesh = ConfigManager::GetInheritedString( sMesh, "", Tag );
STATICHASH( Bone );
Accessory.m_Bone = ConfigManager::GetInheritedHash( sBone, HashedString::NullString, Tag );
STATICHASH( OffsetX );
Accessory.m_LocationOffset.x = ConfigManager::GetInheritedFloat( sOffsetX, 0.0f, Tag );
STATICHASH( OffsetY );
Accessory.m_LocationOffset.y = ConfigManager::GetInheritedFloat( sOffsetY, 0.0f, Tag );
STATICHASH( OffsetZ );
Accessory.m_LocationOffset.z = ConfigManager::GetInheritedFloat( sOffsetZ, 0.0f, Tag );
STATICHASH( OffsetPitch );
Accessory.m_OrientationOffset.Pitch = ConfigManager::GetInheritedFloat( sOffsetPitch, 0.0f, Tag );
STATICHASH( OffsetRoll );
Accessory.m_OrientationOffset.Roll = ConfigManager::GetInheritedFloat( sOffsetRoll, 0.0f, Tag );
STATICHASH( OffsetYaw );
Accessory.m_OrientationOffset.Yaw = ConfigManager::GetInheritedFloat( sOffsetYaw, 0.0f, Tag );
return Accessory;
}
#define VERSION_EMPTY 0
#define VERSION_BASE 1
#define VERSION_ISVALID 2
#define VERSION_ACCESSORY 3
#define VERSION_HAIRSTYLE 4
#define VERSION_SCALE 5
#define VERSION_EYES 6
#define VERSION_ISHUMAN 7
#define VERSION_WARDROBE 8
#define VERSION_CURRENT 8
uint RosaWardrobe::GetCostumeSerializationSize( const SCostume& Costume )
{
uint Size = 0;
Size += 4; // Version
Size += 1; // m_IsValid
Size += 1; // m_IsHuman
Size += 4; // m_Scale
Size += sizeof( HashedString ); // m_Wardrobe
Size += sizeof( HashedString ); // m_Body
Size += sizeof( HashedString ); // m_Skin
Size += sizeof( HashedString ); // m_Hair
Size += sizeof( HashedString ); // m_Eyes
Size += sizeof( HashedString ); // m_Head
Size += sizeof( HashedString ); // m_Style
Size += sizeof( HashedString ); // m_Accessory
Size += sizeof( HashedString ); // m_Scheme
Size += 4; // m_Options.Size()
Size += sizeof( HashedString ) * Costume.m_Options.Size(); // m_Options
return Size;
}
void RosaWardrobe::SaveCostume( const SCostume& Costume, const IDataStream& Stream )
{
Stream.WriteUInt32( VERSION_CURRENT );
Stream.WriteBool( Costume.m_IsValid );
Stream.WriteBool( Costume.m_IsHuman );
Stream.WriteFloat( Costume.m_Scale );
Stream.Write<HashedString>( Costume.m_Wardrobe );
Stream.Write<HashedString>( Costume.m_Body );
Stream.Write<HashedString>( Costume.m_Skin );
Stream.Write<HashedString>( Costume.m_Hair );
Stream.Write<HashedString>( Costume.m_Eyes );
Stream.Write<HashedString>( Costume.m_Head );
Stream.Write<HashedString>( Costume.m_Style );
Stream.Write<HashedString>( Costume.m_Accessory );
Stream.Write<HashedString>( Costume.m_Scheme );
Stream.WriteArray<HashedString>( Costume.m_Options );
}
void RosaWardrobe::LoadCostume( SCostume& Costume, const IDataStream& Stream )
{
XTRACE_FUNCTION;
const uint Version = Stream.ReadUInt32();
if( Version >= VERSION_ISVALID )
{
Costume.m_IsValid = Stream.ReadBool();
}
if( Version >= VERSION_ISHUMAN )
{
Costume.m_IsHuman = Stream.ReadBool();
}
Costume.m_Scale = ( Version >= VERSION_SCALE ) ? Stream.ReadFloat() : 1.0f;
if( Version >= VERSION_BASE )
{
if( Version >= VERSION_WARDROBE )
{
Costume.m_Wardrobe = Stream.Read<HashedString>();
}
Costume.m_Body = Stream.Read<HashedString>();
Costume.m_Skin = Stream.Read<HashedString>();
if( Version >= VERSION_HAIRSTYLE )
{
Costume.m_Hair = Stream.Read<HashedString>();
}
if( Version >= VERSION_EYES )
{
Costume.m_Eyes = Stream.Read<HashedString>();
}
Costume.m_Head = Stream.Read<HashedString>();
if( Version >= VERSION_HAIRSTYLE )
{
Costume.m_Style = Stream.Read<HashedString>();
}
if( Version >= VERSION_ACCESSORY )
{
Costume.m_Accessory = Stream.Read<HashedString>();
}
Costume.m_Scheme = Stream.Read<HashedString>();
Stream.ReadArray<HashedString>( Costume.m_Options );
}
}
| 30.463063 | 135 | 0.72396 | [
"mesh",
"vector"
] |
15f94bbdcd0fb623f8d1148d4e44d099b8554239 | 1,299 | c++ | C++ | algorithms_and_data_structures-develop/0_1_knapsack_problems.c++ | Nirj2004/data_structures_and_algorithms | 50879a589e9fa979de47b38f183fdf148378b486 | [
"Apache-2.0"
] | 2 | 2022-02-27T11:01:44.000Z | 2022-02-27T11:04:06.000Z | algorithms_and_data_structures-develop/0_1_knapsack_problems.c++ | Nirj2004/data_structures_and_algorithms | 50879a589e9fa979de47b38f183fdf148378b486 | [
"Apache-2.0"
] | null | null | null | algorithms_and_data_structures-develop/0_1_knapsack_problems.c++ | Nirj2004/data_structures_and_algorithms | 50879a589e9fa979de47b38f183fdf148378b486 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <cctype>
#include <math>
int maximum_possible_loot_value(const std::vector<int>& weights,
const std::vector<int>& values, const int capacity)
{
int items_count = values.size();
std::vector<std::vector<int>>loots(items_count + 1, std::vector<int>(capacity + 1));
for (int i = 0; i <= items_count; ++i) {
for (int w = 0; w <= capacity; ++w) {
if ( i == 0 || w == 0 ) {
loots[i][w] = 0;
}
else if (weights[i-1] <= w) {
loots[i][w] = loots[i-1][w];
}
}
}
return loots[items_count][capacity];
}
void print_vector(const std::vector<int>& vec) {
for (auto v : vec) {
std::cout << v << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> values{40, 10, 90};
std::vector<int> weights{20, 40, 60};
int capacity = 190;
std::cout << "Weights of items: ";
print_vector(values);
std::cout << " Capacity :" << capacity << std::endl;
std::cout << "Maximum possible loot value for capacity" << capacity
<< " : " << maximum_possible_loot_value(weights, values, capacity) << std::endl;
return 0;
} | 28.866667 | 89 | 0.529638 | [
"vector"
] |
15f9e03b738c6dc048f40aa48a1929b083fa0f24 | 28,055 | cpp | C++ | Source/ui_win32/Debugger.cpp | literalmente-game/Play- | c7cb9b12c751aadf105c6e05f36dbd647e7f9d2c | [
"BSD-2-Clause"
] | null | null | null | Source/ui_win32/Debugger.cpp | literalmente-game/Play- | c7cb9b12c751aadf105c6e05f36dbd647e7f9d2c | [
"BSD-2-Clause"
] | null | null | null | Source/ui_win32/Debugger.cpp | literalmente-game/Play- | c7cb9b12c751aadf105c6e05f36dbd647e7f9d2c | [
"BSD-2-Clause"
] | null | null | null | #include "../iop/IopBios.h"
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <iostream>
#include "../AppConfig.h"
#include "../MIPSAssembler.h"
#include "../Ps2Const.h"
#include "../ee/PS2OS.h"
#include "../MipsFunctionPatternDb.h"
#include "StdStream.h"
#include "win32/AcceleratorTableGenerator.h"
#include "win32/InputBox.h"
#include "win32/DpiUtils.h"
#include "xml/Parser.h"
#include "Debugger.h"
#include "resource.h"
#include "string_cast.h"
#include "string_format.h"
#define CLSNAME _T("CDebugger")
#define WM_EXECUNLOAD (WM_USER + 0)
#define WM_EXECCHANGE (WM_USER + 1)
#define PREF_DEBUGGER_MEMORYVIEW_BYTEWIDTH "debugger.memoryview.bytewidth"
#define FIND_MAX_ADDRESS 0x02000000
CDebugger::CDebugger(CPS2VM& virtualMachine)
: m_virtualMachine(virtualMachine)
{
RegisterPreferences();
if(!DoesWindowClassExist(CLSNAME))
{
WNDCLASSEX wc;
memset(&wc, 0, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH);
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLSNAME;
wc.lpfnWndProc = CWindow::WndProc;
RegisterClassEx(&wc);
}
Create(NULL, CLSNAME, _T(""), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, Framework::Win32::CRect(0, 0, 640, 480), NULL, NULL);
SetClassPtr();
SetMenu(LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_DEBUGGER)));
CreateClient(NULL);
//Show(SW_MAXIMIZE);
//ELF View Initialization
m_pELFView = new CELFView(m_pMDIClient->m_hWnd);
m_pELFView->Show(SW_HIDE);
//Functions View Initialization
m_pFunctionsView = new CFunctionsView(m_pMDIClient->m_hWnd);
m_pFunctionsView->Show(SW_HIDE);
m_pFunctionsView->OnFunctionDblClick.connect(boost::bind(&CDebugger::OnFunctionsViewFunctionDblClick, this, _1));
m_pFunctionsView->OnFunctionsStateChange.connect(boost::bind(&CDebugger::OnFunctionsViewFunctionsStateChange, this));
//Threads View Initialization
m_threadsView = new CThreadsViewWnd(m_pMDIClient->m_hWnd, m_virtualMachine);
m_threadsView->Show(SW_HIDE);
m_threadsView->OnGotoAddress.connect(boost::bind(&CDebugger::OnThreadsViewAddressDblClick, this, _1));
//Address List View Initialization
m_addressListView = new CAddressListViewWnd(m_pMDIClient->m_hWnd);
m_addressListView->Show(SW_HIDE);
m_addressListView->AddressSelected.connect([&](uint32 address) { OnFindCallersAddressDblClick(address); });
//Debug Views Initialization
m_nCurrentView = -1;
memset(m_pView, 0, sizeof(m_pView));
m_pView[DEBUGVIEW_EE] = new CDebugView(m_pMDIClient->m_hWnd, m_virtualMachine, &m_virtualMachine.m_ee->m_EE,
std::bind(&CPS2VM::StepEe, &m_virtualMachine), m_virtualMachine.m_ee->m_os, "EmotionEngine");
m_pView[DEBUGVIEW_VU0] = new CDebugView(m_pMDIClient->m_hWnd, m_virtualMachine, &m_virtualMachine.m_ee->m_VU0,
std::bind(&CPS2VM::StepVu0, &m_virtualMachine), nullptr, "Vector Unit 0", CDisAsmWnd::DISASM_VU);
m_pView[DEBUGVIEW_VU1] = new CDebugView(m_pMDIClient->m_hWnd, m_virtualMachine, &m_virtualMachine.m_ee->m_VU1,
std::bind(&CPS2VM::StepVu1, &m_virtualMachine), nullptr, "Vector Unit 1", CDisAsmWnd::DISASM_VU);
m_pView[DEBUGVIEW_IOP] = new CDebugView(m_pMDIClient->m_hWnd, m_virtualMachine, &m_virtualMachine.m_iop->m_cpu,
std::bind(&CPS2VM::StepIop, &m_virtualMachine), m_virtualMachine.m_iop->m_bios.get(), "IO Processor");
m_virtualMachine.m_ee->m_os->OnExecutableChange.connect(boost::bind(&CDebugger::OnExecutableChange, this));
m_virtualMachine.m_ee->m_os->OnExecutableUnloading.connect(boost::bind(&CDebugger::OnExecutableUnloading, this));
ActivateView(DEBUGVIEW_EE);
LoadSettings();
if(GetDisassemblyWindow()->IsVisible())
{
GetDisassemblyWindow()->SetFocus();
}
CreateAccelerators();
}
CDebugger::~CDebugger()
{
OnExecutableUnloadingMsg();
DestroyAccelerators();
SaveSettings();
//Destroy explicitly since we're keeping the window alive
//artificially by handling WM_SYSCOMMAND
Destroy();
for(unsigned int i = 0; i < DEBUGVIEW_MAX; i++)
{
delete m_pView[i];
}
delete m_pELFView;
delete m_pFunctionsView;
}
HACCEL CDebugger::GetAccelerators()
{
return m_nAccTable;
}
void CDebugger::RegisterPreferences()
{
CAppConfig& config(CAppConfig::GetInstance());
config.RegisterPreferenceInteger("debugger.disasm.posx", 0);
config.RegisterPreferenceInteger("debugger.disasm.posy", 0);
config.RegisterPreferenceInteger("debugger.disasm.sizex", 0);
config.RegisterPreferenceInteger("debugger.disasm.sizey", 0);
config.RegisterPreferenceBoolean("debugger.disasm.visible", true);
config.RegisterPreferenceInteger("debugger.regview.posx", 0);
config.RegisterPreferenceInteger("debugger.regview.posy", 0);
config.RegisterPreferenceInteger("debugger.regview.sizex", 0);
config.RegisterPreferenceInteger("debugger.regview.sizey", 0);
config.RegisterPreferenceBoolean("debugger.regview.visible", true);
config.RegisterPreferenceInteger("debugger.memoryview.posx", 0);
config.RegisterPreferenceInteger("debugger.memoryview.posy", 0);
config.RegisterPreferenceInteger("debugger.memoryview.sizex", 0);
config.RegisterPreferenceInteger("debugger.memoryview.sizey", 0);
config.RegisterPreferenceBoolean("debugger.memoryview.visible", true);
config.RegisterPreferenceInteger(PREF_DEBUGGER_MEMORYVIEW_BYTEWIDTH, 0);
config.RegisterPreferenceInteger("debugger.callstack.posx", 0);
config.RegisterPreferenceInteger("debugger.callstack.posy", 0);
config.RegisterPreferenceInteger("debugger.callstack.sizex", 0);
config.RegisterPreferenceInteger("debugger.callstack.sizey", 0);
config.RegisterPreferenceBoolean("debugger.callstack.visible", true);
}
void CDebugger::UpdateTitle()
{
std::tstring sTitle(_T("Play! - Debugger"));
if(GetCurrentView() != NULL)
{
sTitle +=
_T(" - [ ") +
string_cast<std::tstring>(GetCurrentView()->GetName()) +
_T(" ]");
}
SetText(sTitle.c_str());
}
void CDebugger::LoadSettings()
{
LoadViewLayout();
LoadBytesPerLine();
}
void CDebugger::SaveSettings()
{
SaveViewLayout();
SaveBytesPerLine();
}
void CDebugger::SerializeWindowGeometry(CWindow* pWindow, const char* sPosX, const char* sPosY, const char* sSizeX, const char* sSizeY, const char* sVisible)
{
CAppConfig& config(CAppConfig::GetInstance());
RECT rc = pWindow->GetWindowRect();
ScreenToClient(m_pMDIClient->m_hWnd, (POINT*)&rc + 0);
ScreenToClient(m_pMDIClient->m_hWnd, (POINT*)&rc + 1);
config.SetPreferenceInteger(sPosX, rc.left);
config.SetPreferenceInteger(sPosY, rc.top);
if(sSizeX != NULL && sSizeY != NULL)
{
config.SetPreferenceInteger(sSizeX, (rc.right - rc.left));
config.SetPreferenceInteger(sSizeY, (rc.bottom - rc.top));
}
config.SetPreferenceBoolean(sVisible, pWindow->IsVisible());
}
void CDebugger::UnserializeWindowGeometry(CWindow* pWindow, const char* sPosX, const char* sPosY, const char* sSizeX, const char* sSizeY, const char* sVisible)
{
CAppConfig& config(CAppConfig::GetInstance());
pWindow->SetPosition(config.GetPreferenceInteger(sPosX), config.GetPreferenceInteger(sPosY));
pWindow->SetSize(config.GetPreferenceInteger(sSizeX), config.GetPreferenceInteger(sSizeY));
if(!config.GetPreferenceBoolean(sVisible))
{
pWindow->Show(SW_HIDE);
}
else
{
pWindow->Show(SW_SHOW);
}
}
void CDebugger::Resume()
{
m_virtualMachine.Resume();
}
void CDebugger::StepCPU()
{
if(m_virtualMachine.GetStatus() == CVirtualMachine::RUNNING)
{
MessageBeep(-1);
return;
}
if(::GetParent(GetFocus()) != GetDisassemblyWindow()->m_hWnd)
{
GetDisassemblyWindow()->SetFocus();
}
GetCurrentView()->Step();
}
void CDebugger::FindWordValue(uint32 mask)
{
Framework::Win32::CInputBox input(_T("Find Value in Memory"), _T("Enter value to find:"), _T("00000000"));
auto valueString = input.GetValue(m_hWnd);
if(!valueString) return;
uint32 targetValue = 0;
auto scanned = _stscanf(valueString, _T("%x"), &targetValue);
if(scanned == 0) return;
auto context = GetCurrentView()->GetContext();
auto title = string_format(_T("Search results for 0x%08X"), targetValue);
auto refs = FindWordValueRefs(context, targetValue & mask, mask);
m_addressListView->SetTitle(std::move(title));
m_addressListView->SetAddressList(std::move(refs));
m_addressListView->Show(SW_SHOW);
m_addressListView->SetFocus();
}
void CDebugger::AssembleJAL()
{
Framework::Win32::CInputBox InputTarget(_T("Assemble JAL"), _T("Enter jump target:"), _T("00000000"));
Framework::Win32::CInputBox InputAssemble(_T("Assemble JAL"), _T("Enter address to assemble JAL to:"), _T("00000000"));
const TCHAR* sTarget = InputTarget.GetValue(m_hWnd);
if(sTarget == NULL) return;
const TCHAR* sAssemble = InputAssemble.GetValue(m_hWnd);
if(sAssemble == NULL) return;
uint32 nValueTarget = 0, nValueAssemble = 0;
_stscanf(sTarget, _T("%x"), &nValueTarget);
_stscanf(sAssemble, _T("%x"), &nValueAssemble);
*(uint32*)&m_virtualMachine.m_ee->m_ram[nValueAssemble] = 0x0C000000 | (nValueTarget / 4);
}
void CDebugger::ReanalyzeEe()
{
if(m_virtualMachine.m_ee->m_os->GetELF() == nullptr) return;
auto executableRange = m_virtualMachine.m_ee->m_os->GetExecutableRange();
uint32 minAddr = executableRange.first;
uint32 maxAddr = executableRange.second & ~0x03;
auto getAddress =
[this](const TCHAR* prompt, uint32& address) {
Framework::Win32::CInputBox addressInputBox(_T("Analyze EE"), prompt,
string_format(_T("0x%08X"), address).c_str());
auto addrValue = addressInputBox.GetValue(m_hWnd);
if(addrValue == nullptr) return false;
uint32 addrValueTemp = 0;
int cvtCount = _stscanf(addrValue, _T("%x"), &addrValueTemp);
if(cvtCount != 0)
{
address = addrValueTemp & ~0x3;
}
return true;
};
if(!getAddress(_T("Start Address:"), minAddr)) return;
if(!getAddress(_T("End Address:"), maxAddr)) return;
if(minAddr > maxAddr)
{
MessageBox(m_hWnd, _T("Start address is larger than end address."), _T("Analyze EE"), MB_ICONERROR);
return;
}
minAddr = std::min<uint32>(minAddr, PS2::EE_RAM_SIZE);
maxAddr = std::min<uint32>(maxAddr, PS2::EE_RAM_SIZE);
m_virtualMachine.m_ee->m_EE.m_analysis->Clear();
m_virtualMachine.m_ee->m_EE.m_analysis->Analyse(minAddr, maxAddr);
}
void CDebugger::FindEeFunctions()
{
if(m_virtualMachine.m_ee->m_os->GetELF() == nullptr) return;
auto executableRange = m_virtualMachine.m_ee->m_os->GetExecutableRange();
uint32 minAddr = executableRange.first;
uint32 maxAddr = executableRange.second & ~0x03;
{
Framework::CStdStream patternStream("ee_functions.xml", "rb");
boost::scoped_ptr<Framework::Xml::CNode> document(Framework::Xml::CParser::ParseDocument(patternStream));
CMipsFunctionPatternDb patternDb(document.get());
for(auto patternIterator(std::begin(patternDb.GetPatterns()));
patternIterator != std::end(patternDb.GetPatterns()); ++patternIterator)
{
auto pattern = *patternIterator;
for(uint32 address = minAddr; address <= maxAddr; address += 4)
{
uint32* text = reinterpret_cast<uint32*>(m_virtualMachine.m_ee->m_ram + address);
uint32 textSize = (maxAddr - address);
if(pattern.Matches(text, textSize))
{
m_virtualMachine.m_ee->m_EE.m_Functions.InsertTag(address, pattern.name.c_str());
break;
}
}
}
}
{
//Identify functions that reference special string literals (TODO: Move that inside a file)
static const std::map<std::string, std::string> stringFuncs =
{
{"SceSifrpcBind", "SifBindRpc"},
{"SceSifrpcCall", "SifCallRpc"},
{"SceStdioOpenSema", "Open"},
{"SceStdioCloseSema", "Close"},
{"SceStdioLseekSema", "Lseek"},
{"SceStdioReadSema", "Read"},
{"SceStdioWriteSema", "Write"},
{"SceStdioIoctlSema", "Ioctl"},
{"SceStdioIoctl2Sema", "Ioctl2"},
{"SceStdioMkdirSema", "Mkdir"},
{"call cdread cmd\n", "CdRead"},
{"N cmd wait\n", "CdSync"},
{"S cmd wait\n", "CdSyncS"},
{"Scmd fail sema cur_cmd:%d keep_cmd:%d\n", "CdCheckSCmd"},
{"sceGsExecLoadImage: DMA Ch.2 does not terminate\r\n", "GsExecLoadImage"},
{"sceGsExecStoreImage: DMA Ch.1 does not terminate\r\n", "GsExecStoreImage"},
{"sceGsPutDrawEnv: DMA Ch.2 does not terminate\r\n", "GsPutDrawEnv"},
{"sceGsSetDefLoadImage: too big size\r\n", "GsSetDefLoadImage"},
{"sceGsSyncPath: DMA Ch.1 does not terminate\r\n", "GsSyncPath"},
{"libpad: buffer addr is not 64 byte align. %08x\n", "PadPortOpen"},
{"sceDbcReceiveData: rpc error\n", "DbcReceiveData"},
{"sceDbcSendData: rpc error\n", "DbcSendData"},
{"sceDbcSendData2: rpc error\n", "DbcSendData2"},
{"The size of work area is too small", "MpegCreate"},
{"Need to re-setup libipu since sceMpegGetPicture was aborted\n", "_MpegInternalFct"},
{"image buffer needs to be aligned to 64byte boundary(0x%08x)", "_MpegInternalFct"},
};
{
auto& eeFunctions = m_virtualMachine.m_ee->m_EE.m_Functions;
const auto& eeComments = m_virtualMachine.m_ee->m_EE.m_Comments;
const auto& eeAnalysis = m_virtualMachine.m_ee->m_EE.m_analysis;
for(auto tagIterator = eeComments.GetTagsBegin();
tagIterator != eeComments.GetTagsEnd(); tagIterator++)
{
const auto& tag = *tagIterator;
auto subroutine = eeAnalysis->FindSubroutine(tag.first);
if(subroutine == nullptr) continue;
auto stringFunc = stringFuncs.find(tag.second);
if(stringFunc == std::end(stringFuncs)) continue;
eeFunctions.InsertTag(subroutine->start, stringFunc->second.c_str());
}
}
}
m_virtualMachine.m_ee->m_EE.m_Functions.OnTagListChange();
}
void CDebugger::Layout1024()
{
auto disassemblyWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(0, 0, 700, 435));
auto registerViewWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(700, 0, 324, 572));
auto memoryViewWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(0, 435, 700, 265));
auto callStackWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(700, 572, 324, 128));
GetDisassemblyWindow()->SetSizePosition(disassemblyWindowRect);
GetDisassemblyWindow()->Show(SW_SHOW);
GetRegisterViewWindow()->SetSizePosition(registerViewWindowRect);
GetRegisterViewWindow()->Show(SW_SHOW);
GetMemoryViewWindow()->SetSizePosition(memoryViewWindowRect);
GetMemoryViewWindow()->Show(SW_SHOW);
GetCallStackWindow()->SetSizePosition(callStackWindowRect);
GetCallStackWindow()->Show(SW_SHOW);
}
void CDebugger::Layout1280()
{
auto disassemblyWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(0, 0, 900, 540));
auto registerViewWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(900, 0, 380, 784));
auto memoryViewWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(0, 540, 900, 416));
auto callStackWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(900, 784, 380, 172));
GetDisassemblyWindow()->SetSizePosition(disassemblyWindowRect);
GetDisassemblyWindow()->Show(SW_SHOW);
GetRegisterViewWindow()->SetSizePosition(registerViewWindowRect);
GetRegisterViewWindow()->Show(SW_SHOW);
GetMemoryViewWindow()->SetSizePosition(memoryViewWindowRect);
GetMemoryViewWindow()->Show(SW_SHOW);
GetCallStackWindow()->SetSizePosition(callStackWindowRect);
GetCallStackWindow()->Show(SW_SHOW);
}
void CDebugger::Layout1600()
{
auto disassemblyWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(0, 0, 1094, 725));
auto registerViewWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(1094, 0, 506, 725));
auto memoryViewWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(0, 725, 1094, 407));
auto callStackWindowRect = Framework::Win32::PointsToPixels(Framework::Win32::MakeRectPositionSize(1094, 725, 506, 407));
GetDisassemblyWindow()->SetSizePosition(disassemblyWindowRect);
GetDisassemblyWindow()->Show(SW_SHOW);
GetRegisterViewWindow()->SetSizePosition(registerViewWindowRect);
GetRegisterViewWindow()->Show(SW_SHOW);
GetMemoryViewWindow()->SetSizePosition(memoryViewWindowRect);
GetMemoryViewWindow()->Show(SW_SHOW);
GetCallStackWindow()->SetSizePosition(callStackWindowRect);
GetCallStackWindow()->Show(SW_SHOW);
}
void CDebugger::InitializeConsole()
{
#ifdef _DEBUG
AllocConsole();
CONSOLE_SCREEN_BUFFER_INFO ScreenBufferInfo;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &ScreenBufferInfo);
ScreenBufferInfo.dwSize.Y = 1000;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), ScreenBufferInfo.dwSize);
(*stdout) = *_fdopen(_open_osfhandle(
reinterpret_cast<intptr_t>(GetStdHandle(STD_OUTPUT_HANDLE)),
_O_TEXT),
"w");
setvbuf(stdout, NULL, _IONBF, 0);
std::ios::sync_with_stdio();
#endif
}
void CDebugger::ActivateView(unsigned int nView)
{
if(m_nCurrentView == nView) return;
if(m_nCurrentView != -1)
{
SaveBytesPerLine();
SaveViewLayout();
GetCurrentView()->Hide();
}
m_findCallersRequestConnection.disconnect();
m_nCurrentView = nView;
LoadViewLayout();
LoadBytesPerLine();
UpdateTitle();
{
auto biosDebugInfoProvider = GetCurrentView()->GetBiosDebugInfoProvider();
m_pFunctionsView->SetContext(GetCurrentView()->GetContext(), biosDebugInfoProvider);
m_threadsView->SetContext(GetCurrentView()->GetContext(), biosDebugInfoProvider);
}
if(GetDisassemblyWindow()->IsVisible())
{
GetDisassemblyWindow()->SetFocus();
}
m_findCallersRequestConnection = GetCurrentView()->GetDisassemblyWindow()->GetDisAsm()->FindCallersRequested.connect(
[&](uint32 address) { OnFindCallersRequested(address); });
}
void CDebugger::SaveViewLayout()
{
SerializeWindowGeometry(GetDisassemblyWindow(),
"debugger.disasm.posx",
"debugger.disasm.posy",
"debugger.disasm.sizex",
"debugger.disasm.sizey",
"debugger.disasm.visible");
SerializeWindowGeometry(GetRegisterViewWindow(),
"debugger.regview.posx",
"debugger.regview.posy",
"debugger.regview.sizex",
"debugger.regview.sizey",
"debugger.regview.visible");
SerializeWindowGeometry(GetMemoryViewWindow(),
"debugger.memoryview.posx",
"debugger.memoryview.posy",
"debugger.memoryview.sizex",
"debugger.memoryview.sizey",
"debugger.memoryview.visible");
SerializeWindowGeometry(GetCallStackWindow(),
"debugger.callstack.posx",
"debugger.callstack.posy",
"debugger.callstack.sizex",
"debugger.callstack.sizey",
"debugger.callstack.visible");
}
void CDebugger::LoadViewLayout()
{
UnserializeWindowGeometry(GetDisassemblyWindow(),
"debugger.disasm.posx",
"debugger.disasm.posy",
"debugger.disasm.sizex",
"debugger.disasm.sizey",
"debugger.disasm.visible");
UnserializeWindowGeometry(GetRegisterViewWindow(),
"debugger.regview.posx",
"debugger.regview.posy",
"debugger.regview.sizex",
"debugger.regview.sizey",
"debugger.regview.visible");
UnserializeWindowGeometry(GetMemoryViewWindow(),
"debugger.memoryview.posx",
"debugger.memoryview.posy",
"debugger.memoryview.sizex",
"debugger.memoryview.sizey",
"debugger.memoryview.visible");
UnserializeWindowGeometry(GetCallStackWindow(),
"debugger.callstack.posx",
"debugger.callstack.posy",
"debugger.callstack.sizex",
"debugger.callstack.sizey",
"debugger.callstack.visible");
}
void CDebugger::SaveBytesPerLine()
{
auto memoryView = GetMemoryViewWindow()->GetMemoryView();
auto bytesPerLine = memoryView->GetBytesPerLine();
CAppConfig::GetInstance().SetPreferenceInteger(PREF_DEBUGGER_MEMORYVIEW_BYTEWIDTH, bytesPerLine);
}
void CDebugger::LoadBytesPerLine()
{
auto bytesPerLine = CAppConfig::GetInstance().GetPreferenceInteger(PREF_DEBUGGER_MEMORYVIEW_BYTEWIDTH);
auto memoryView = GetMemoryViewWindow()->GetMemoryView();
memoryView->SetBytesPerLine(bytesPerLine);
}
CDebugView* CDebugger::GetCurrentView()
{
if(m_nCurrentView == -1) return NULL;
return m_pView[m_nCurrentView];
}
CMIPS* CDebugger::GetContext()
{
return GetCurrentView()->GetContext();
}
CDisAsmWnd* CDebugger::GetDisassemblyWindow()
{
return GetCurrentView()->GetDisassemblyWindow();
}
CMemoryViewMIPSWnd* CDebugger::GetMemoryViewWindow()
{
return GetCurrentView()->GetMemoryViewWindow();
}
CRegViewWnd* CDebugger::GetRegisterViewWindow()
{
return GetCurrentView()->GetRegisterViewWindow();
}
CCallStackWnd* CDebugger::GetCallStackWindow()
{
return GetCurrentView()->GetCallStackWindow();
}
std::vector<uint32> CDebugger::FindCallers(CMIPS* context, uint32 address)
{
std::vector<uint32> callers;
for(uint32 i = 0; i < FIND_MAX_ADDRESS; i += 4)
{
uint32 opcode = context->m_pMemoryMap->GetInstruction(i);
uint32 ea = context->m_pArch->GetInstructionEffectiveAddress(context, i, opcode);
if(ea == address)
{
callers.push_back(i);
}
}
return callers;
}
std::vector<uint32> CDebugger::FindWordValueRefs(CMIPS* context, uint32 targetValue, uint32 valueMask)
{
std::vector<uint32> refs;
for(uint32 i = 0; i < FIND_MAX_ADDRESS; i += 4)
{
uint32 valueAtAddress = context->m_pMemoryMap->GetWord(i);
if((valueAtAddress & valueMask) == targetValue)
{
refs.push_back(i);
}
}
return refs;
}
void CDebugger::CreateAccelerators()
{
Framework::Win32::CAcceleratorTableGenerator generator;
generator.Insert(ID_VIEW_FUNCTIONS, 'F', FCONTROL | FVIRTKEY);
generator.Insert(ID_VIEW_THREADS, 'T', FCONTROL | FVIRTKEY);
generator.Insert(ID_VM_STEP, VK_F10, FVIRTKEY);
generator.Insert(ID_VM_RESUME, VK_F5, FVIRTKEY);
generator.Insert(ID_VIEW_CALLSTACK, 'A', FCONTROL | FVIRTKEY);
generator.Insert(ID_VIEW_EEVIEW, '1', FALT | FVIRTKEY);
generator.Insert(ID_VIEW_VU0VIEW, '2', FALT | FVIRTKEY);
generator.Insert(ID_VIEW_VU1VIEW, '3', FALT | FVIRTKEY);
generator.Insert(ID_VIEW_IOPVIEW, '4', FALT | FVIRTKEY);
m_nAccTable = generator.Create();
}
void CDebugger::DestroyAccelerators()
{
DestroyAcceleratorTable(m_nAccTable);
}
long CDebugger::OnCommand(unsigned short nID, unsigned short nMsg, HWND hFrom)
{
switch(nID)
{
case ID_VM_STEP:
StepCPU();
break;
case ID_VM_RESUME:
Resume();
break;
case ID_VM_DUMPINTCHANDLERS:
m_virtualMachine.DumpEEIntcHandlers();
break;
case ID_VM_DUMPDMACHANDLERS:
m_virtualMachine.DumpEEDmacHandlers();
break;
case ID_VM_ASMJAL:
AssembleJAL();
break;
case ID_VM_REANALYZE_EE:
ReanalyzeEe();
break;
case ID_VM_FINDEEFUNCTIONS:
FindEeFunctions();
break;
case ID_VM_FINDWORDVALUE:
FindWordValue(~0);
break;
case ID_VM_FINDWORDLOWHALFVALUE:
FindWordValue(0xFFFF);
break;
case ID_VIEW_MEMORY:
GetMemoryViewWindow()->Show(SW_SHOW);
GetMemoryViewWindow()->SetFocus();
return FALSE;
break;
case ID_VIEW_CALLSTACK:
GetCallStackWindow()->Show(SW_SHOW);
GetCallStackWindow()->SetFocus();
return FALSE;
break;
case ID_VIEW_FUNCTIONS:
m_pFunctionsView->Show(SW_SHOW);
m_pFunctionsView->SetFocus();
return FALSE;
break;
case ID_VIEW_ELF:
m_pELFView->Show(SW_SHOW);
m_pELFView->SetFocus();
return FALSE;
break;
case ID_VIEW_THREADS:
m_threadsView->Show(SW_SHOW);
m_threadsView->SetFocus();
return FALSE;
break;
case ID_VIEW_DISASSEMBLY:
GetDisassemblyWindow()->Show(SW_SHOW);
GetDisassemblyWindow()->SetFocus();
return FALSE;
break;
case ID_VIEW_EEVIEW:
ActivateView(DEBUGVIEW_EE);
break;
case ID_VIEW_VU0VIEW:
ActivateView(DEBUGVIEW_VU0);
break;
case ID_VIEW_VU1VIEW:
ActivateView(DEBUGVIEW_VU1);
break;
case ID_VIEW_IOPVIEW:
ActivateView(DEBUGVIEW_IOP);
break;
case ID_WINDOW_CASCAD:
m_pMDIClient->Cascade();
return FALSE;
break;
case ID_WINDOW_TILEHORIZONTAL:
m_pMDIClient->TileHorizontal();
return FALSE;
break;
case ID_WINDOW_TILEVERTICAL:
m_pMDIClient->TileVertical();
return FALSE;
break;
case ID_WINDOW_LAYOUT1024:
Layout1024();
return FALSE;
break;
case ID_WINDOW_LAYOUT1280:
Layout1280();
return FALSE;
break;
case ID_WINDOW_LAYOUT1600:
Layout1600();
return FALSE;
break;
}
return TRUE;
}
long CDebugger::OnSysCommand(unsigned int nCmd, LPARAM lParam)
{
switch(nCmd)
{
case SC_CLOSE:
Show(SW_HIDE);
return FALSE;
case SC_KEYMENU:
return FALSE;
}
return TRUE;
}
LRESULT CDebugger::OnWndProc(unsigned int nMsg, WPARAM wParam, LPARAM lParam)
{
switch(nMsg)
{
case WM_EXECUNLOAD:
OnExecutableUnloadingMsg();
return FALSE;
break;
case WM_EXECCHANGE:
OnExecutableChangeMsg();
return FALSE;
break;
}
return CMDIFrame::OnWndProc(nMsg, wParam, lParam);
}
void CDebugger::OnFunctionsViewFunctionDblClick(uint32 address)
{
GetDisassemblyWindow()->GetDisAsm()->SetAddress(address);
}
void CDebugger::OnFunctionsViewFunctionsStateChange()
{
GetDisassemblyWindow()->Refresh();
}
void CDebugger::OnThreadsViewAddressDblClick(uint32 address)
{
auto disAsm = GetDisassemblyWindow()->GetDisAsm();
disAsm->SetCenterAtAddress(address);
disAsm->SetSelectedAddress(address);
}
void CDebugger::OnExecutableChange()
{
SendMessage(m_hWnd, WM_EXECCHANGE, 0, 0);
}
void CDebugger::OnExecutableUnloading()
{
SendMessage(m_hWnd, WM_EXECUNLOAD, 0, 0);
}
void CDebugger::OnFindCallersRequested(uint32 address)
{
auto context = GetCurrentView()->GetContext();
auto callers = FindCallers(context, address);
auto title =
[&]() {
auto functionName = context->m_Functions.Find(address);
if(functionName)
{
return string_format(_T("Find Callers For '%s' (0x%08X)"),
string_cast<std::tstring>(functionName).c_str(), address);
}
else
{
return string_format(_T("Find Callers For 0x%08X"), address);
}
}();
m_addressListView->SetAddressList(std::move(callers));
m_addressListView->SetTitle(std::move(title));
m_addressListView->Show(SW_SHOW);
m_addressListView->SetFocus();
}
void CDebugger::OnFindCallersAddressDblClick(uint32 address)
{
auto disAsm = GetDisassemblyWindow()->GetDisAsm();
disAsm->SetCenterAtAddress(address);
disAsm->SetSelectedAddress(address);
}
void CDebugger::OnExecutableChangeMsg()
{
m_pELFView->SetELF(m_virtualMachine.m_ee->m_os->GetELF());
// m_pFunctionsView->SetELF(m_virtualMachine.m_os->GetELF());
LoadDebugTags();
GetDisassemblyWindow()->Refresh();
m_pFunctionsView->Refresh();
}
void CDebugger::OnExecutableUnloadingMsg()
{
SaveDebugTags();
m_pELFView->SetELF(NULL);
// m_pFunctionsView->SetELF(NULL);
}
void CDebugger::LoadDebugTags()
{
#ifdef DEBUGGER_INCLUDED
m_virtualMachine.LoadDebugTags(m_virtualMachine.m_ee->m_os->GetExecutableName());
#endif
}
void CDebugger::SaveDebugTags()
{
#ifdef DEBUGGER_INCLUDED
if(m_virtualMachine.m_ee->m_os->GetELF() != NULL)
{
m_virtualMachine.SaveDebugTags(m_virtualMachine.m_ee->m_os->GetExecutableName());
}
#endif
}
| 31.276477 | 159 | 0.709891 | [
"vector"
] |
c60a886a0ecfe0221200bb6ae783cc0dd504d93c | 1,140 | cc | C++ | ext/v8/backref.cc | stereobooster/therubyracer | 09e4d4025144b04ea66e4111b539a2483991f846 | [
"Unlicense",
"MIT"
] | null | null | null | ext/v8/backref.cc | stereobooster/therubyracer | 09e4d4025144b04ea66e4111b539a2483991f846 | [
"Unlicense",
"MIT"
] | null | null | null | ext/v8/backref.cc | stereobooster/therubyracer | 09e4d4025144b04ea66e4111b539a2483991f846 | [
"Unlicense",
"MIT"
] | null | null | null | #include "rr.h"
namespace rr {
VALUE Backref::Storage;
ID Backref::_new;
ID Backref::object;
void Backref::Init() {
Storage = rb_eval_string("Ref::WeakReference");
rb_gc_register_address(&Storage);
_new = rb_intern("new");
object = rb_intern("object");
}
Backref::Backref(VALUE initial) {
allocate(initial);
}
Backref::~Backref() {
deallocate();
}
void Backref::allocate(VALUE data) {
this->storage = rb_funcall(Storage, _new, 1, data);
rb_gc_register_address(&storage);
}
void Backref::deallocate() {
rb_gc_unregister_address(&storage);
}
VALUE Backref::get() {
return rb_funcall(storage, object, 0);
}
VALUE Backref::set(VALUE data) {
deallocate();
allocate(data);
return data;
}
v8::Handle<v8::Value> Backref::toExternal() {
v8::Local<v8::Value> wrapper = v8::External::Wrap(this);
v8::Persistent<v8::Value>::New(wrapper).MakeWeak(this, &release);
return wrapper;
}
void Backref::release(v8::Persistent<v8::Value> handle, void* data) {
handle.Dispose();
Backref* backref = (Backref*)data;
delete backref;
}
} | 21.111111 | 71 | 0.642105 | [
"object"
] |
c60e2ace6318619b1d131a2b700f662c3864eeb5 | 10,906 | cpp | C++ | snippets/cpp/VS_Snippets_Winforms/System.Drawing.ClassicStringFormatExamples/CPP/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 834 | 2017-06-24T10:40:36.000Z | 2022-03-31T19:48:51.000Z | snippets/cpp/VS_Snippets_Winforms/System.Drawing.ClassicStringFormatExamples/CPP/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 7,042 | 2017-06-23T22:34:47.000Z | 2022-03-31T23:05:23.000Z | snippets/cpp/VS_Snippets_Winforms/System.Drawing.ClassicStringFormatExamples/CPP/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 1,640 | 2017-06-23T22:31:39.000Z | 2022-03-31T02:45:37.000Z | #using <System.Data.dll>
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
using namespace System::Data;
/// <summary>
/// Summary description for Form1.
/// </summary>
public ref class Form1: public System::Windows::Forms::Form
{
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container^ components;
public:
Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if ( components != nullptr )
{
delete components;
}
}
private:
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent()
{
this->components = gcnew System::ComponentModel::Container;
this->Size = System::Drawing::Size( 300, 300 );
this->Text = "Form1";
}
// Snippet for: M:System.Drawing.StringFormat.GetTabStops(System.Single@)
// <snippet1>
public:
void GetSetTabStopsExample1( PaintEventArgs^ e )
{
Graphics^ g = e->Graphics;
// Tools used for drawing, painting.
Pen^ redPen = gcnew Pen( Color::FromArgb( 255, 255, 0, 0 ) );
SolidBrush^ blueBrush = gcnew SolidBrush( Color::FromArgb( 255, 0, 0, 255 ) );
// Layout and format for text.
System::Drawing::Font^ myFont = gcnew System::Drawing::Font( "Times New Roman",12 );
StringFormat^ myStringFormat = gcnew StringFormat;
Rectangle enclosingRectangle = Rectangle(20,20,500,100);
array<Single>^tabStops = {150.0f,100.0f,100.0f};
// Text with tabbed columns.
String^ myString = "Name\tTab 1\tTab 2\tTab 3\nGeorge Brown\tOne\tTwo\tThree";
// Set the tab stops, paint the text specified by myString, and draw the
// rectangle that encloses the text.
myStringFormat->SetTabStops( 0.0f, tabStops );
g->DrawString( myString, myFont, blueBrush, enclosingRectangle, myStringFormat );
g->DrawRectangle( redPen, enclosingRectangle );
// Get the tab stops.
float firstTabOffset;
array<Single>^tabStopsObtained = myStringFormat->GetTabStops( firstTabOffset );
for ( int j = 0; j < tabStopsObtained->Length; j++ )
{
// Inspect or use the value in tabStopsObtained[j].
Console::WriteLine( "\n Tab stop {0} = {1}", j, tabStopsObtained[ j ] );
}
}
// </snippet1>
// Snippet for: M:System.Drawing.StringFormat.SetDigitSubstitution(System.Int32,System.Drawing.StringDigitSubstitute)
// <snippet2>
public:
void SetDigitSubExample( PaintEventArgs^ e )
{
Graphics^ g = e->Graphics;
SolidBrush^ blueBrush = gcnew SolidBrush( Color::FromArgb( 255, 0, 0, 255 ) );
System::Drawing::Font^ myFont = gcnew System::Drawing::Font( "Courier New",12 );
StringFormat^ myStringFormat = gcnew StringFormat;
String^ myString = "0 1 2 3 4 5 6 7 8 9";
// Arabic (0x0C01) digits.
// Use National substitution method.
myStringFormat->SetDigitSubstitution( 0x0C01, StringDigitSubstitute::National );
g->DrawString( String::Format( "Arabic:\nMethod of substitution = National: {0}", myString ), myFont, blueBrush, PointF(10.0f,20.0f), myStringFormat );
// Use Traditional substitution method.
myStringFormat->SetDigitSubstitution( 0x0C01, StringDigitSubstitute::Traditional );
g->DrawString( String::Format( "Method of substitution = Traditional: {0}", myString ), myFont, blueBrush, PointF(10.0f,55.0f), myStringFormat );
// Thai (0x041E) digits.
// Use National substitution method.
myStringFormat->SetDigitSubstitution( 0x041E, StringDigitSubstitute::National );
g->DrawString( String::Format( "Thai:\nMethod of substitution = National: {0}", myString ), myFont, blueBrush, PointF(10.0f,85.0f), myStringFormat );
// Use Traditional substitution method.
myStringFormat->SetDigitSubstitution( 0x041E, StringDigitSubstitute::Traditional );
g->DrawString( String::Format( "Method of substitution = Traditional: {0}", myString ), myFont, blueBrush, PointF(10.0f,120.0f), myStringFormat );
}
// </snippet2>
// Snippet for: M:System.Drawing.StringFormat.SetMeasurableCharacterRanges(System.Drawing.CharacterRange[])
// <snippet3>
void SetMeasCharRangesExample( PaintEventArgs^ e )
{
Graphics^ g = e->Graphics;
SolidBrush^ redBrush = gcnew SolidBrush( Color::FromArgb( 50, 255, 0, 0 ) );
// Layout rectangles, font, and string format used for displaying string.
Rectangle layoutRectA = Rectangle(20,20,165,80);
Rectangle layoutRectB = Rectangle(20,110,165,80);
Rectangle layoutRectC = Rectangle(20,200,240,80);
System::Drawing::Font^ tnrFont = gcnew System::Drawing::Font( "Times New Roman",16 );
StringFormat^ strFormat = gcnew StringFormat;
// Ranges of character positions within a string.
array<CharacterRange>^ charRanges = {CharacterRange(3,5),CharacterRange(15,2),CharacterRange(30,15)};
// Each region specifies the area occupied by the characters within a
// range of positions. the values are obtained by using a method that
// measures the character ranges.
array<System::Drawing::Region^>^charRegions = gcnew array<System::Drawing::Region^>(charRanges->Length);
// String to be displayed.
String^ str = "The quick, brown fox easily jumps over the lazy dog.";
// Set the char ranges for the string format.
strFormat->SetMeasurableCharacterRanges( charRanges );
// loop counter (unsigned 8-bit integer)
Byte i;
// Measure the char ranges for a given string and layout rectangle. Each
// area occupied by the characters in a range is stored as a region. Then
// draw the string and layout rectangle, and paint the regions.
charRegions = g->MeasureCharacterRanges( str, tnrFont, layoutRectA, strFormat );
g->DrawString( str, tnrFont, Brushes::Blue, layoutRectA, strFormat );
g->DrawRectangle( Pens::Black, layoutRectA );
// Paint the regions.
for ( i = 0; i < charRegions->Length; i++ )
g->FillRegion( redBrush, charRegions[ i ] );
// Repeat the above steps, but include trailing spaces in the char
// range measurement by setting the appropriate string format flag.
strFormat->FormatFlags = StringFormatFlags::MeasureTrailingSpaces;
charRegions = g->MeasureCharacterRanges( str, tnrFont, layoutRectB, strFormat );
g->DrawString( str, tnrFont, Brushes::Blue, layoutRectB, strFormat );
g->DrawRectangle( Pens::Black, layoutRectB );
for ( i = 0; i < charRegions->Length; i++ )
g->FillRegion( redBrush, charRegions[ i ] );
// Clear all the format flags.
strFormat->FormatFlags = StringFormatFlags(0);
// Repeat the steps, but use a different layout rectangle. the dimensions
// of the layout rectangle and the size of the font both affect the
// character range measurement.
charRegions = g->MeasureCharacterRanges( str, tnrFont, layoutRectC, strFormat );
g->DrawString( str, tnrFont, Brushes::Blue, layoutRectC, strFormat );
g->DrawRectangle( Pens::Black, layoutRectC );
// Paint the regions.
for ( i = 0; i < charRegions->Length; i++ )
g->FillRegion( redBrush, charRegions[ i ] );
}
// </snippet3>
// Snippet for: M:System.Drawing.StringFormat.SetTabStops(System.Single,System.Single[])
// <snippet4>
void GetSetTabStopsExample2( PaintEventArgs^ e )
{
Graphics^ g = e->Graphics;
// Tools used for drawing, painting.
Pen^ redPen = gcnew Pen( Color::FromArgb( 255, 255, 0, 0 ) );
SolidBrush^ blueBrush = gcnew SolidBrush( Color::FromArgb( 255, 0, 0, 255 ) );
// Layout and format for text.
System::Drawing::Font^ myFont = gcnew System::Drawing::Font( "Times New Roman",12 );
StringFormat^ myStringFormat = gcnew StringFormat;
Rectangle enclosingRectangle = Rectangle(20,20,500,100);
array<Single>^tabStops = {150.0f,100.0f,100.0f};
// Text with tabbed columns.
String^ myString = "Name\tTab 1\tTab 2\tTab 3\nGeorge Brown\tOne\tTwo\tThree";
// Set the tab stops, paint the text specified by myString, draw the
// rectangle that encloses the text.
myStringFormat->SetTabStops( 0.0f, tabStops );
g->DrawString( myString, myFont, blueBrush, enclosingRectangle, myStringFormat );
g->DrawRectangle( redPen, enclosingRectangle );
// Get the tab stops.
float firstTabOffset;
array<Single>^tabStopsObtained = myStringFormat->GetTabStops( firstTabOffset );
for ( int j = 0; j < tabStopsObtained->Length; j++ )
{
// Inspect or use the value in tabStopsObtained[j].
Console::WriteLine( "\n Tab stop {0} = {1}", j, tabStopsObtained[ j ] );
}
}
// </snippet4>
// Snippet for: M:System.Drawing.StringFormat.ToString
// <snippet5>
void ToStringExample( PaintEventArgs^ e )
{
Graphics^ g = e->Graphics;
SolidBrush^ blueBrush = gcnew SolidBrush( Color::FromArgb( 255, 0, 0, 255 ) );
System::Drawing::Font^ myFont = gcnew System::Drawing::Font( "Times New Roman",14 );
StringFormat^ myStringFormat = gcnew StringFormat;
// String variable to hold the values of the StringFormat object.
String^ strFmtString;
// Convert the string format object to a string (only certain information
// in the object is converted) and display the string.
strFmtString = myStringFormat->ToString();
g->DrawString( String::Format( "Before changing properties: {0}", myStringFormat ), myFont, blueBrush, 20, 40 );
// Change some properties of the string format
myStringFormat->Trimming = StringTrimming::None;
myStringFormat->FormatFlags = (StringFormatFlags)(StringFormatFlags::NoWrap | StringFormatFlags::NoClip);
// Convert the string format object to a string and display the string.
// The string will be different because the properties of the string
// format have changed.
strFmtString = myStringFormat->ToString();
g->DrawString( String::Format( "After changing properties: {0}", myStringFormat ), myFont, blueBrush, 20, 70 );
}
// </snippet5>
};
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
int main()
{
Application::Run( gcnew Form1 );
}
| 39.80292 | 161 | 0.666789 | [
"object"
] |
723ab0ab3f15e718a2aecedaef8ba4eaca9678bf | 2,415 | hpp | C++ | cmd/Command.hpp | Tchernobil21/ExtendedCommandParser | 161207ae983dc0b3014fb8bb07b3f7cb94974f01 | [
"MIT"
] | 1 | 2015-04-19T17:52:35.000Z | 2015-04-19T17:52:35.000Z | cmd/Command.hpp | Tchernobil21/ExtendedCommandParser | 161207ae983dc0b3014fb8bb07b3f7cb94974f01 | [
"MIT"
] | null | null | null | cmd/Command.hpp | Tchernobil21/ExtendedCommandParser | 161207ae983dc0b3014fb8bb07b3f7cb94974f01 | [
"MIT"
] | null | null | null | #ifndef COMMAND_H
#define COMMAND_H
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include "Argument.hpp"
#include "Minus.hpp"
#include "Plus.hpp"
#include "Target.hpp"
#include "DependenceTree.hpp"
namespace cmd
{
class Command
{
public:
Command(const std::string name, const std::string description, const std::string author, const std::string version);
void addPossiblePlus(Plus * plus);
void addPossiblePlus(const std::string name, const std::string shortcut, const std::string description);
void addPossibleMinus(Minus * minus);
void addPossibleMinus(const std::string name, const std::string shortcut, const std::string description, Validator * validator);
void addPossibleTarget(Target * target);
void addPossibleTarget(const std::string name, const std::string description, Validator * validator);
void addDependence(const std::string argumentNameOrShortcut, DependenceTree * dependenceTree);
void addDependence(const std::string argumentNameOrShortcut, const std::string booleanDependences);
void allowRemainingTargets(bool state);
Argument * getArgument(const std::string argumentNameOrShortcut) const;
template<typename T>
T * get(const std::string plusNameOrShortcut) const
{
try
{
T * arg = dynamic_cast<T*>(this->getArgument(plusNameOrShortcut));
return arg;
}
catch(const std::string & ex)
{
return 0;
}
}
std::vector<std::string> getRemainingTargets() const;
void parse(int argc, const char ** argv);
bool isValid() const;
std::string help() const;
~Command();
private:
std::string extractArgumentName(const std::string argumentNameOrShortcut) const;
void expandArgs(std::vector<std::string> & args) const;
void parseArgs(std::vector<std::string> & args);
void checkDependences() const;
std::string name;
std::string description;
std::string author;
std::string version;
std::map<std::string, Argument*> arguments;
std::map<std::string, std::string> argumentsShortcutsToNames;
std::map<std::string, std::string> argumentsNamesToShortcuts;
std::vector<std::string> targetsNames;
std::vector<std::string> remainingTargets;
bool remainingTargetsAllowed;
std::map<std::string, DependenceTree*> dependences;
std::set<std::string> validArgumentsNames;
bool cmdIsValid;
};
}
#endif /* end of include guard: COMMAND_H */
| 32.635135 | 131 | 0.722981 | [
"vector"
] |
723eaecce79df074571aa20a820013fbc8518795 | 8,274 | hpp | C++ | src/lib/clxx/info/platform_query.hpp | ptomulik/clxx | 9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8 | [
"MIT"
] | 1 | 2015-08-12T13:11:35.000Z | 2015-08-12T13:11:35.000Z | src/lib/clxx/info/platform_query.hpp | ptomulik/clxx | 9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8 | [
"MIT"
] | 67 | 2015-01-03T10:11:13.000Z | 2015-10-21T11:03:06.000Z | src/lib/clxx/info/platform_query.hpp | ptomulik/clxx | 9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8 | [
"MIT"
] | null | null | null | // @COPYRIGHT@
// Licensed under MIT license (LICENSE.txt)
// clxx/info/platform_query.hpp
/** // doc: clxx/info/platform_query.hpp {{{
* \file clxx/info/platform_query.hpp
* \brief Provides the clxx::platform_query class.
*
* This file contains definition of clxx::platform_query class, which
* configures queries to OpenCL platforms.
*/ // }}}
#ifndef CLXX_INFO_PLATFORM_QUERY_HPP_INCLUDED
#define CLXX_INFO_PLATFORM_QUERY_HPP_INCLUDED
namespace clxx {
/** // doc: class platform_query {{{
* \ingroup clxx_info
* \brief Indicate what information to retrieve from an OpenCL platform.
*
* This class encapsulates several boolean flags which indicate what
* information should be retrieved from an OpenCL platform when performing
* a platform info query. Objects of type #platform_query are used
* together with #query_platform_info() function and #clxx::platform_info to
* query several parmeters describing local OpenCL platform(s) at once.
*
* For each platform info parameter \em xxx two methods are provided by the
* class:
*
* - \em xxx_selected() - to check if attribute \em xxx is selected for query,
* - \em select_xxx() - to select or deselect attribute \em xxx.
*/ // }}}
class platform_query
{
template <class Archive>
friend void _serialize(Archive&, platform_query&, const unsigned int);
public:
/** // doc: class_version {{{
* \brief Class version number
*
* Used by the serialization machinery (see \ref clxx_s11n)
*/ // }}}
static constexpr unsigned int class_version = 0x000001;
public:
/** // doc: ~platform_query() {{{
* \brief Destructor
*/ // }}}
virtual ~platform_query() noexcept;
/** // doc: platform_query() {{{
* \brief Default constructor
*
* Selects all attributes to be queried.
*/ // }}}
platform_query() noexcept;
/** // doc: platform_query(flag) {{{
* \brief Constructor
* \param flag Determines, whether attributes shall be initially selected or
* deselected (\c true - selected, \c false - deselected)
*/ // }}}
platform_query(bool flag) noexcept;
/** // doc: select_all() {{{
* \brief Select all the platform attributes
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
platform_query& select_all() noexcept;
/** // doc: select_none() {{{
* \brief Deselect all the platform attributes
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
platform_query& select_none() noexcept;
/** // doc: select_default() {{{
* \brief Make a default selection
*
* By default all attributes are selected. It's guaranteed, that default
* selections is same as that after object initialization by default
* constructor.
*
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
platform_query& select_default() noexcept;
// getters {{{
/** // {{{
* \brief Whether \ref clxx::platform_info::id "id" attribute is selected
* \returns \c true if \ref clxx::platform_info::id "id" is selected or \c false if not
*/ // }}}
inline bool id_selected() const noexcept
{
return this->_id;
}
/** // {{{
* \brief Whether \ref clxx::platform_info::profile "profile" attribute is selected
* \returns \c true if \ref clxx::platform_info::profile "profile" is selected or \c false if not
*/ // }}}
inline bool profile_selected() const noexcept
{
return this->_profile;
}
/** // {{{
* \brief Whether \ref clxx::platform_info::version "version" attribute is selected
* \returns \c true if \ref clxx::platform_info::version "version" is selected or \c false if not
*/ // }}}
inline bool version_selected() const noexcept
{
return this->_version;
}
/** // {{{
* \brief Whether \ref clxx::platform_info::name "name" attribute is selected
* \returns \c true if \ref clxx::platform_info::name "name" is selected or \c false if not
*/ // }}}
inline bool name_selected() const noexcept
{
return this->_name;
}
/** // {{{
* \brief Whether \ref clxx::platform_info::vendor "vendor" attribute is selected
* \returns \c true if \ref clxx::platform_info::vendor "vendor" is selected or \c false if not
*/ // }}}
inline bool vendor_selected() const noexcept
{
return this->_vendor;
}
/** // {{{
* \brief Whether \ref clxx::platform_info::extensions "extensions" attribute is selected
* \returns \c true if \ref clxx::platform_info::extensions "extensions" is selected or \c false if not
*/ // }}}
inline bool extensions_selected() const noexcept
{
return this->_extensions;
}
// }}}
// selectors {{{
/** // {{{
* \brief Select or deselect the \ref clxx::platform_info::id "id" attribute
* \param flag \c true to select, \c false to deselected
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
inline platform_query& select_id(bool flag = true) noexcept
{
this->_id = flag;
return *this;
}
/** // {{{
* \brief Select or deselect the \ref clxx::platform_info::profile "profile" attribute
* \param flag \c true to select, \c false to deselected
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
inline platform_query& select_profile(bool flag = true) noexcept
{
this->_profile = flag;
return *this;
}
/** // {{{
* \brief Select or deselect the \ref clxx::platform_info::version "version" attribute
* \param flag \c true to select, \c false to deselected
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
inline platform_query& select_version(bool flag = true) noexcept
{
this->_version = flag;
return *this;
}
/** // {{{
* \brief Select or deselect the \ref clxx::platform_info::name "name" attribute
* \param flag \c true to select, \c false to deselected
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
inline platform_query& select_name(bool flag = true) noexcept
{
this->_name = flag;
return *this;
}
/** // {{{
* \brief Select or deselect the \ref clxx::platform_info::vendor "vendor" attribute
* \param flag \c true to select, \c false to deselected
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
inline platform_query& select_vendor(bool flag = true) noexcept
{
this->_vendor = flag;
return *this;
}
/** // {{{
* \brief Select or deselect the \ref clxx::platform_info::extensions "extensions" attribute
* \param flag \c true to select, \c false to deselected
* \returns A mutable reference to the modified #platform_query object.
*/ // }}}
inline platform_query& select_extensions(bool flag = true) noexcept
{
this->_extensions = flag;
return *this;
}
// }}}
private:
void _select(bool flag) noexcept;
void _init(bool flag) noexcept;
// Attributes {{{
bool _id;
bool _profile;
bool _version;
bool _name;
bool _vendor;
bool _extensions;
// }}}
};
/** \addtogroup clxx_info
* @{ */
/** // doc: operator==(platform_query, platform_query) {{{
* \brief Compare two \ref clxx::platform_query "platform_queries"
*
* Two \ref clxx::platform_query "platform_queries" are equal if and only if
* their selections are identical.
*
* \param a Left hand side operand to comparison
* \param b Right hand side operand to comparison
* \returns \c true if two queries are equal or \c false otherwise
*/ // }}}
bool operator==(platform_query const& a, platform_query const& b) noexcept;
/** // doc: operator==(platform_query, platform_query) {{{
* \brief Compare two \ref clxx::platform_query "platform_queries"
*
* Two \ref clxx::platform_query "platform_queries" are equal if and only if
* their selections are identical.
*
* \param a Left hand side operand to comparison
* \param b Right hand side operand to comparison
* \returns \c true if two queries are equal or \c false otherwise
*/ // }}}
inline bool operator!=(platform_query const& a, platform_query const& b) noexcept
{ return !(a == b); }
/** @} */
} // end namespace clxx
#endif /* CLXX_INFO_PLATFORM_QUERY_HPP_INCLUDED */
// vim: set expandtab tabstop=2 shiftwidth=2:
// vim: set foldmethod=marker foldcolumn=4:
| 35.208511 | 105 | 0.675973 | [
"object"
] |
723f74202eeb1347892c21a09e0ce5e3f58886f0 | 2,306 | cpp | C++ | client/ModelGenerated/createaccount.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 1 | 2015-08-23T11:03:58.000Z | 2015-08-23T11:03:58.000Z | client/ModelGenerated/createaccount.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | null | null | null | client/ModelGenerated/createaccount.cpp | vorushin/moodbox_aka_risovaska | 5943452e4c7fc9e3c828f62f565cd2da9a040e92 | [
"MIT"
] | 3 | 2016-12-05T02:43:52.000Z | 2021-06-30T21:35:46.000Z | #include "listwrapperobjects.h"
#include "createaccount.h"
namespace MoodBox
{
CreateAccountData::CreateAccountData() : QSharedData()
{
}
CreateAccountData::CreateAccountData(UserAccount userAccount, QString inviteCode) : QSharedData()
{
this->userAccount = userAccount;
this->inviteCode = inviteCode;
}
CreateAccountData::~CreateAccountData()
{
}
CreateAccount::CreateAccount() : TransportableObject()
{
}
CreateAccount::CreateAccount(UserAccount userAccount, QString inviteCode) : TransportableObject()
{
d = new CreateAccountData(userAccount, inviteCode);
}
CreateAccount::~CreateAccount()
{
}
UserAccount CreateAccount::getUserAccount() const
{
Q_ASSERT_X(!isNull(), "CreateAccount::getUserAccount", "Getter call on object which isNull");
return this->d->userAccount;
}
void CreateAccount::setUserAccount(UserAccount value)
{
Q_ASSERT_X(!isNull(), "CreateAccount::setUserAccount", "Setter call on object which isNull");
this->d->userAccount = value;
}
QString CreateAccount::getInviteCode() const
{
Q_ASSERT_X(!isNull(), "CreateAccount::getInviteCode", "Getter call on object which isNull");
return this->d->inviteCode;
}
void CreateAccount::setInviteCode(QString value)
{
Q_ASSERT_X(!isNull(), "CreateAccount::setInviteCode", "Setter call on object which isNull");
this->d->inviteCode = value;
}
qint32 CreateAccount::getRepresentedTypeId()
{
return 10003;
}
qint32 CreateAccount::getTypeId() const
{
return 10003;
}
void CreateAccount::writeProperties(PropertyWriter *writer)
{
TransportableObject::writeProperties(writer);
writer->writeProperty(this, 1, &this->d->userAccount);
writer->writeProperty(this, 2, this->d->inviteCode);
}
PropertyReadResult CreateAccount::readProperty(qint32 propertyId, qint32 typeId, PropertyReader *reader)
{
PropertyReadResult result = TransportableObject::readProperty(propertyId, typeId, reader);
if(result.getIsPropertyFound())
return result;
switch(propertyId)
{
case 1:
this->d->userAccount = UserAccount::empty();
return PropertyReadResult(&this->d->userAccount);
case 2:
this->d->inviteCode = reader->readString();
return PropertyReadResult(true);
}
return PropertyReadResult(false);
}
}
| 25.910112 | 104 | 0.724198 | [
"object"
] |
723fdd16b0236ec49317ff0f779efac7f8712936 | 2,946 | hpp | C++ | CouplingManager.hpp | FluiditLtd/caddies-caflood | e43521a47665209454af7fa1b4ee8c280486f969 | [
"MIT"
] | 2 | 2021-12-23T09:02:14.000Z | 2021-12-23T09:04:24.000Z | CouplingManager.hpp | FluiditLtd/caddies-caflood | e43521a47665209454af7fa1b4ee8c280486f969 | [
"MIT"
] | null | null | null | CouplingManager.hpp | FluiditLtd/caddies-caflood | e43521a47665209454af7fa1b4ee8c280486f969 | [
"MIT"
] | null | null | null | /*
* CouplingManager.hpp
*
* Created on: Jun 15, 2021
* Author: sunelma
*/
#ifndef _COUPLINGMANAGER_HPP_
#define _COUPLINGMANAGER_HPP_
#include"ca2D.hpp"
#include"BaseTypes.hpp"
#include"Box.hpp"
#include<string>
#include<vector>
//! Structure with the configuration value that define an inflow of
//! water event in the CA2D model. The time is in seconds and the
//! inflow is in cubic meters per second. The specific inflow at a
//! specific time is given by linear interpolation between the
//! previous and next values.
struct ICoupling
{
public:
std::string name; //!< Coupling component.
CA::Real x; //!< X coordinate of the coupling point
CA::Real y; //!< Y coordinate of the coupling point
CA::Real head; //!< CAFLOOD simulated head
CA::Real flow; //!< Net flow calculated by the hydraulic simulator (+ to surface, - to network)
CA::Real prevFlow; //!< Net flow calculated by the hydraulic simulator (+ to surface, - to network)
CA::Box box_area; //!< The box of the area where the flow is set.
ICoupling():
box_area(CA::Box::Empty()) {
}
};
//! Initialise the inflow event structure usign a CSV file.
//! Each row represents a new "variable" where the
//! first column is the name of the element
//! and the following columns have the multiple/single values.
//! \attention The order of elements is not important.
//! \param[in] filename This is the file where the data is read.
//! \param[out] setup The structure containing the read data.
//! \return A non zero value if there was an error.
int initICouplingsFromCSV(const std::string& filename, std::vector<ICoupling>& couplings);
class CouplingManager {
private:
//! Reference to the grid.
CA::Grid& grid;
//! Reference to the List of inflow events
std::vector<ICoupling>& coupling;
int port;
int sockfd;
CA::Real time_start;
CA::Real time_end;
CA::Real readValuesUntil;
CA::Real previousValuesUntil;
CA::Real networkWaitingUntil;
bool inputEnded = false;
bool stopped = false;
public:
CouplingManager(CA::Grid& GRID, std::vector<ICoupling>& aCoupling, CA::Real time_start, CA::Real time_end, int port);
~CouplingManager();
inline bool isStopped() { return stopped; }
void createBoxes();
void input(CA::Real t);
void output(CA::Real time, CA::CellBuffReal& WD, CA::CellBuffReal& ELV);
void add(CA::CellBuffReal& WD, CA::CellBuffState& MASK, CA::Real t, CA::Real dt);
void end();
CA::Real potentialVA(CA::Real t, CA::Real period_time_dt);
CA::Real volume(CA::Real period_time_dt) {
double volume = 0;
for (auto i = coupling.begin(); i != coupling.end(); i++) {
volume += (*i).flow;
}
return (CA::Real)(volume * period_time_dt);
}
CA::Real endTime();
private:
void write(std::string line);
std::string read();
};
#endif
| 29.168317 | 122 | 0.661914 | [
"vector",
"model"
] |
7240c54fc80e7d28a6d81de6e0802437e6061806 | 17,388 | hpp | C++ | include/trafo/data_layout/variable_declaration.hpp | flwende/code_transformation | 07603c562d9acda3ae801e2f9ebb7d5f87cf6fb7 | [
"BSD-2-Clause"
] | 3 | 2019-08-27T10:25:41.000Z | 2020-04-16T22:17:52.000Z | include/trafo/data_layout/variable_declaration.hpp | flwende/code_transformation | 07603c562d9acda3ae801e2f9ebb7d5f87cf6fb7 | [
"BSD-2-Clause"
] | null | null | null | include/trafo/data_layout/variable_declaration.hpp | flwende/code_transformation | 07603c562d9acda3ae801e2f9ebb7d5f87cf6fb7 | [
"BSD-2-Clause"
] | 1 | 2020-05-13T20:57:10.000Z | 2020-05-13T20:57:10.000Z | // Copyright (c) 2017-2019 Florian Wende (flwende@gmail.com)
//
// Distributed under the BSD 2-clause Software License
// (See accompanying file LICENSE)
#if !defined(TRAFO_DATA_LAYOUT_VARIABLE_DECLARATION_HPP)
#define TRAFO_DATA_LAYOUT_VARIABLE_DECLARATION_HPP
#include <cstdint>
#include <iostream>
#include <vector>
#include <misc/ast_helper.hpp>
#if !defined(TRAFO_NAMESPACE)
#define TRAFO_NAMESPACE fw
#endif
namespace TRAFO_NAMESPACE
{
namespace internal
{
class Declaration
{
std::string getDataTypeName(const clang::QualType& dataType)
{
if (const clang::Type* const type = dataType.getTypePtrOrNull())
{
if (type->isClassType() || type->isStructureType())
{
const clang::CXXRecordDecl& decl = *(type->getAsCXXRecordDecl());
return decl.getNameAsString();
}
}
return dataType.getAsString();
}
public:
const clang::VarDecl& decl;
const clang::SourceRange sourceRange;
const clang::QualType elementDataType;
const std::string elementDataTypeName;
std::string elementDataTypeNamespace;
protected:
Declaration(const clang::VarDecl& decl, const clang::QualType elementDataType)
:
decl(decl),
sourceRange(getSourceRangeWithClosingCharacter(decl.getSourceRange(), std::string(";"), decl.getASTContext(), true)),
elementDataType(elementDataType),
elementDataTypeName(getDataTypeName(elementDataType))
{
if (!elementDataType.isNull())
{
const std::string fullElementTypeName = elementDataType->getCanonicalTypeInternal().getAsString();
const std::size_t startPosElementTypeName = fullElementTypeName.find(elementDataTypeName);
const std::size_t startPosElementTypeNamespace = fullElementTypeName.rfind(' ', startPosElementTypeName) + 1;
elementDataTypeNamespace = fullElementTypeName.substr(startPosElementTypeNamespace, (startPosElementTypeName - startPosElementTypeNamespace));
}
else
{
elementDataTypeNamespace = std::string("");
}
}
public:
virtual ~Declaration() { ; }
virtual bool isScalarTypeDeclaration() const { return true; }
virtual std::uint32_t getNestingLevel() const { return 0; }
virtual const std::vector<std::size_t>& getExtent() const = 0;
virtual const std::vector<std::string>& getExtentString() const = 0;
virtual void printInfo(const clang::SourceManager& sourceManager, const std::string indent = std::string("")) const
{
std::cout << indent << "* variable name: " << decl.getNameAsString() << std::endl;
std::cout << indent << "* range: " << sourceRange.printToString(sourceManager) << std::endl;
std::cout << indent << "* element data type: " << elementDataType.getAsString();
if (elementDataType.getAsString() != elementDataTypeName)
{
std::cout << " (" << elementDataTypeNamespace << elementDataTypeName << ")";
}
std::cout << std::endl;
}
};
class ConstantArrayDeclaration : public Declaration
{
using Base = Declaration;
public:
using Base::decl;
using Base::sourceRange;
using Base::elementDataType;
using Base::elementDataTypeName;
using Base::elementDataTypeNamespace;
const clang::QualType arrayType;
const bool isNested;
const std::uint32_t nestingLevel;
const std::vector<std::size_t> extent;
const std::vector<std::string> extentString;
ConstantArrayDeclaration(const clang::VarDecl& decl, const bool isNested, const std::uint32_t nestingLevel, const clang::QualType elementDataType, const std::vector<std::size_t>& extent, const std::vector<std::string>& extentString)
:
Base(decl, elementDataType),
arrayType(decl.getType()),
isNested(isNested),
nestingLevel(nestingLevel),
extent(extent),
extentString(extentString)
{ ; }
~ConstantArrayDeclaration() { ; }
bool isScalarTypeDeclaration() const { return true; }
std::uint32_t getNestingLevel() const { return nestingLevel; }
const std::vector<std::size_t>& getExtent() const { return extent; }
const std::vector<std::string>& getExtentString() const { return extentString; }
static ConstantArrayDeclaration make(const clang::VarDecl& decl, clang::ASTContext& context)
{
clang::QualType elementDataType;
bool isNested = false;
std::uint32_t nestingLevel = 0;
std::vector<std::size_t> extent;
std::vector<std::string> extentString;
if (const clang::Type* type = decl.getType().getTypePtrOrNull())
{
if (type->isConstantArrayType())
{
do
{
// in all cases
const clang::ConstantArrayType* arrayType = reinterpret_cast<const clang::ConstantArrayType*>(type);
clang::QualType qualType = arrayType->getElementType();
//extent.push_back(arrayType->getSize().getLimitedValue());
std::size_t value = arrayType->getSize().getLimitedValue();
extent.insert(extent.begin(), value);
extentString.insert(extentString.begin(), std::to_string(value));
type = qualType.getTypePtrOrNull();
if (type->isConstantArrayType())
{
isNested |= true;
++nestingLevel;
continue;
}
elementDataType = qualType;
break;
}
while (type);
}
else
{
std::cerr << "error: this is not a constant array declaration" << std::endl;
}
}
return ConstantArrayDeclaration(decl, isNested, nestingLevel, elementDataType, extent, extentString);
}
virtual void printInfo(const clang::SourceManager& sourceManager, const std::string indent = std::string("")) const
{
std::cout << indent << "CONSTANT ARRAY DECLARATION" << std::endl;
Base::printInfo(sourceManager, indent + std::string("\t"));
std::cout << indent << "\t\t+-> declaration: " << decl.getSourceRange().printToString(sourceManager) << std::endl;
std::cout << indent << "\t\t+-> type: " << arrayType.getAsString() << std::endl;
std::cout << indent << "\t\t+-> extent: ";
for (std::size_t i = 0; i < extent.size(); ++i)
{
std::cout << "[" << (extent[i] > 0 ? std::to_string(extent[i]) : std::string("-")) << "]";
}
std::cout << " -> ";
for (std::size_t i = 0; i < extentString.size(); ++i)
{
std::cout << "[" << extentString[i] << "]";
}
std::cout << std::endl;
std::cout << indent << "\t\t+-> nested: " << (isNested ? "yes" : "no") << std::endl;
if (isNested)
{
std::cout << indent << "\t\t\t+-> nesting level: " << nestingLevel << std::endl;
}
}
};
class ContainerDeclaration : public Declaration
{
using Base = Declaration;
public:
using Base::decl;
using Base::sourceRange;
using Base::elementDataType;
using Base::elementDataTypeName;
using Base::elementDataTypeNamespace;
const clang::QualType containerType;
const bool isNested;
const std::uint32_t nestingLevel;
const std::vector<std::size_t> extent;
const std::vector<std::string> extentString;
ContainerDeclaration(const clang::VarDecl& decl, const bool isNested, const std::uint32_t nestingLevel, const clang::QualType elementDataType, const std::vector<std::size_t>& extent, const std::vector<std::string>& extentString)
:
Base(decl, elementDataType),
containerType(decl.getType()),
isNested(isNested),
nestingLevel(nestingLevel),
extent(extent),
extentString(extentString)
{ ; }
~ContainerDeclaration() { ; }
bool isScalarTypeDeclaration() const { return true; }
std::uint32_t getNestingLevel() const { return nestingLevel; }
const std::vector<std::size_t>& getExtent() const { return extent; }
const std::vector<std::string>& getExtentString() const { return extentString; }
static ContainerDeclaration make(const clang::VarDecl& decl, clang::ASTContext& context, const std::vector<std::string>& containerNames)
{
clang::QualType elementDataType;
const clang::SourceRange sourceRange = getSourceRangeWithClosingCharacter(decl.getSourceRange(), std::string(";"), decl.getASTContext(), true);
std::string fullName = decl.getType().getAsString();
std::string name = decl.getType()->getAsRecordDecl()->getNameAsString();
const clang::Type* type = decl.getType().getTypePtrOrNull();
bool isNested = false;
std::uint32_t nestingLevel = 0;
std::vector<std::size_t> extent;
std::vector<std::string> extentString;
// check for nested container declaration
// note: in the first instance 'type' is either a class or structur type (it is the container type itself)
while (type)
{
// we can do this as any variable declaration of the container is a specialzation of containerType<T,..>
if (const clang::TemplateSpecializationType* const tsType = type->getAs<clang::TemplateSpecializationType>())
{
// if the container is an array of fixed size...
std::size_t value = 0;
std::string valueString("");
if (name == std::string("array"))
{
// get the extent: 2nd template parameter
if (tsType->getArg(1).getKind() == clang::TemplateArgument::ArgKind::Integral)
{
value = tsType->getArg(1).getAsIntegral().getExtValue();
}
else if (tsType->getArg(1).getKind() == clang::TemplateArgument::ArgKind::Expression)
{
const clang::Expr* const expr = tsType->getArg(1).getAsExpr();
value = (expr ? expr->EvaluateKnownConstInt(context).getExtValue() : 0);
}
valueString = std::to_string(value);
}
else if (name == std::string("vector"))
{
std::string declString = dumpSourceRangeToString(sourceRange, decl.getASTContext().getSourceManager());
std::size_t firstArgumentBeginPos = declString.find('(', declString.find(decl.getNameAsString()));
std::size_t firstArgumentEndPos = declString.find(',', firstArgumentBeginPos);
if (firstArgumentEndPos == std::string::npos)
{
firstArgumentEndPos = declString.find(')', firstArgumentBeginPos);
}
if (firstArgumentBeginPos != std::string::npos && firstArgumentEndPos != std::string::npos)
{
value = 1; // TODO: remove that! this is just to indicate that there is an argument
valueString = declString.substr(firstArgumentBeginPos + 1, firstArgumentEndPos - firstArgumentBeginPos - 1);
}
}
extent.insert(extent.begin(), value);
extentString.insert(extentString.begin(), valueString);
// the first template argument is the type of the content of the container
clang::QualType taQualType = tsType->getArg(0).getAsType();
if (const clang::Type* const taType = taQualType.getTypePtrOrNull())
{
// if it is a class or structure type, check for it being a containerType
// TEST: if (taType->isRecordType())
if (taType->isClassType() || taType->isStructureType())
{
// if it is a container, get nesting information and continue the loop execution
if (const clang::CXXRecordDecl* const cxxRecordDecl = taType->getAsCXXRecordDecl())
{
// if it is a container, get nesting information and continue the loop execution
bool isContainerType = false;
for (const auto& containerName : containerNames)
{
name = cxxRecordDecl->getNameAsString();
if (name == containerName)
{
isNested |= true;
++nestingLevel;
type = taType;
isContainerType = true;
break;
}
}
if (isContainerType) continue;
}
}
}
// this point is reached if the a non-vector type has been encountered
elementDataType = taQualType;
}
// break condition for the outer loop!
// this point is reached only if the current template argument type is not the specified container type
type = nullptr;
}
return ContainerDeclaration(decl, isNested, nestingLevel, elementDataType, extent, extentString);
}
virtual void printInfo(const clang::SourceManager& sourceManager, const std::string indent = std::string("")) const
{
std::cout << indent << "CONTAINER DECLARATION" << std::endl;
Base::printInfo(sourceManager, indent + std::string("\t"));
std::cout << indent << "\t* container type: " << containerType.getAsString() << std::endl;
std::cout << indent << "\t\t+-> declaration: " << decl.getSourceRange().printToString(sourceManager) << std::endl;
std::cout << indent << "\t\t+-> extent: ";
for (std::size_t i = 0; i < extent.size(); ++i)
{
std::cout << "[" << (extent[i] > 0 ? std::to_string(extent[i]) : std::string("-")) << "]";
}
for (std::size_t i = 0; i < extentString.size(); ++i)
{
std::cout << "[" << extentString[i] << "]";
}
std::cout << std::endl;
std::cout << indent << "\t\t+-> nested: " << (isNested ? "yes" : "no") << std::endl;
if (isNested)
{
std::cout << indent << "\t\t\t+-> nesting level: " << nestingLevel << std::endl;
}
}
};
}
}
#endif | 46.491979 | 244 | 0.489878 | [
"vector"
] |
7242bf31679f1a2c154e58d684ee51bd9359ce19 | 19,930 | cpp | C++ | libJumpropes/Common/HttpClient.cpp | partouf/Crosscables | cf621ae938e69cc63e37d4d32a7cbdc32486787b | [
"MIT"
] | 6 | 2019-11-18T01:58:33.000Z | 2022-01-02T04:00:51.000Z | libJumpropes/Common/HttpClient.cpp | partouf/Crosscables | cf621ae938e69cc63e37d4d32a7cbdc32486787b | [
"MIT"
] | 5 | 2016-12-30T14:20:34.000Z | 2020-09-22T23:59:38.000Z | libJumpropes/Common/HttpClient.cpp | partouf/Crosscables | cf621ae938e69cc63e37d4d32a7cbdc32486787b | [
"MIT"
] | null | null | null |
#include "HttpClient.h"
#include <Groundfloor/Bookshelfs/BValue.h>
#include <Groundfloor/Materials/Functions.h>
#include "../Functions.h"
#ifdef GF_OS_LINUX
#include <cstring>
#include <cstdlib>
#endif
const char crlf[] = {13,10,0};
const char crlfcrlf[] = {13,10,13,10,0};
const char space[] = " ";
const char contentLenNeedle[] = "Content-Length: ";
const char contentTypeNeedle[] = "Content-Type: ";
const char locationNeedle[] = "Location: ";
const char connectionNeedle[] = "Connection: ";
const char httpNeedle[] = "HTTP/";
const char setcookieNeedle[] = "Set-Cookie: ";
const char sendgetNeedle[] = "GET ";
const char sendpostNeedle[] = "POST ";
const char sendhttpNeedle[] = " HTTP/";
const char hostNeedle[] = "Host: ";
const char useragentNeedle[] = "User-Agent: ";
const char refererNeedle[] = "Referrer: ";
const char cookieNeedle[] = "Cookie: ";
const char acceptrangeNeedle[] = "Accept-Ranges: ";
const char contentdispNeedle[] = "Content-Disposition: ";
const char transferencNeedle[] = "Transfer-Encoding: ";
const char rangeNeedle[] = "Range: ";
const char chunkedNeedle[] = "chunked";
void DEBUG_Range( const char *sName, StringVectorRange *range ) {
printf( "range (%s): [%d, %d] - [%d, %d]\n", sName, range->start_ind, range->start_pos, range->end_ind, range->end_pos );
}
void DEBUG_Str( const char *sName, const char *sStr ) {
printf( "str (%s): [%s]\n", sName, sStr );
}
//----------------------------------------------------------------------------
/*
GET /SkypeSetup.exe HTTP/1.1
Host: download.skype.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; nl; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*//*;q=0.5
Accept-Language: nl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://tweakers.net/meuktracker/17066/skype-for-windows-360248.html
Cookie: SC=CC=:CCY=:LC=:TM=1201808799:TS=1201808799:TZ=:VER=0/3.6.0.244/
*/
JumpropesCommon::HttpHeader::HttpHeader() : Freeable() {
resetVars();
}
JumpropesCommon::HttpHeader::~HttpHeader() {
resetVars();
}
void JumpropesCommon::HttpHeader::resetVars() {
contentlength = -1;
httpversion = 0.0;
httpstatus = -1;
chunked = false;
cookies.clear();
statusstring.setValue( "", 0 );
location.setValue( "", 0 );
contenttype.setValue( "", 0 );
connection.setValue( "", 0 );
allvars.deleteAndClear();
}
// TODO: rewrite met split()
void JumpropesCommon::HttpHeader::parse( const String *sHeader ) {
int iPosStart;
int iPosEnd;
int iValStart;
int iValLen;
int iSpacePos;
String tmp;
String dbg;
resetVars();
int iCrlfLen = strlen(crlf);
// "HTTP/1.0 301 Moved Permanently\r\n"
iPosStart = sHeader->pos( 0, httpNeedle, strlen(httpNeedle) );
if ( iPosStart != -1 ) {
iPosEnd = sHeader->pos( iPosStart, crlf, iCrlfLen );
if ( iPosEnd == -1 ) {
iPosEnd = sHeader->getLength();
}
iValStart = iPosStart + strlen( httpNeedle );
iValLen = iPosEnd - iValStart;
tmp.setValue( sHeader->getPointer( iValStart ), iValLen );
// tmp="1.0 301 Moved Permanently"
char *ptr = tmp.getValue();
iSpacePos = tmp.pos( 0, space, strlen(space) );
ptr[iSpacePos] = 0;
httpversion = atof( ptr );
int iStatPos = iSpacePos + 1;
iSpacePos = tmp.pos( 0, space, strlen(space) );
ptr[iSpacePos] = 0;
httpstatus = atoi( tmp.getPointer( iStatPos ) );
statusstring.setValue( tmp.getPointer( iSpacePos + 1 ), tmp.getLength() - iSpacePos - 1 );
}
iPosStart = sHeader->pos( 0, contentLenNeedle, strlen(contentLenNeedle) );
if ( iPosStart != -1 ) {
iPosEnd = sHeader->pos( iPosStart, crlf, iCrlfLen );
if ( iPosEnd == -1 ) {
iPosEnd = sHeader->getLength();
}
iValStart = iPosStart + strlen( contentLenNeedle );
iValLen = iPosEnd - iValStart;
tmp.setValue( sHeader->getPointer( iValStart ), iValLen );
contentlength = atoi( tmp.getValue() );
}
iPosStart = sHeader->pos( 0, contentTypeNeedle, strlen(contentTypeNeedle) );
if ( iPosStart != -1 ) {
iPosEnd = sHeader->pos( iPosStart, crlf, iCrlfLen );
if ( iPosEnd == -1 ) {
iPosEnd = sHeader->getLength();
}
iValStart = iPosStart + strlen( contentTypeNeedle );
iValLen = iPosEnd - iValStart;
tmp.setValue( sHeader->getPointer( iValStart ), iValLen );
contenttype.setValue( &tmp );
}
iPosStart = sHeader->pos( 0, locationNeedle, strlen(locationNeedle) );
if ( iPosStart != -1 ) {
iPosEnd = sHeader->pos( iPosStart, crlf, iCrlfLen );
if ( iPosEnd == -1 ) {
iPosEnd = sHeader->getLength();
}
iValStart = iPosStart + strlen( locationNeedle );
iValLen = iPosEnd - iValStart;
tmp.setValue( sHeader->getPointer( iValStart ), iValLen );
location.setValue( &tmp );
}
iPosStart = sHeader->pos( 0, connectionNeedle, strlen(connectionNeedle) );
if ( iPosStart != -1 ) {
iPosEnd = sHeader->pos( iPosStart, crlf, iCrlfLen );
if ( iPosEnd == -1 ) {
iPosEnd = sHeader->getLength();
}
iValStart = iPosStart + strlen( connectionNeedle );
iValLen = iPosEnd - iValStart;
tmp.setValue( sHeader->getPointer( iValStart ), iValLen );
connection.setValue( &tmp );
}
iPosStart = sHeader->pos( 0, transferencNeedle, strlen(transferencNeedle) );
if ( iPosStart != -1 ) {
iPosEnd = sHeader->pos( iPosStart, crlf, iCrlfLen );
if ( iPosEnd == -1 ) {
iPosEnd = sHeader->getLength();
}
iValStart = iPosStart + strlen( transferencNeedle );
iValLen = iPosEnd - iValStart;
tmp.setValue( sHeader->getPointer( iValStart ), iValLen );
chunked = tmp.match( chunkedNeedle, strlen(chunkedNeedle) );
}
if ( chunked ) {
contentlength = -1;
}
int iSetCookies = 0;
int iSearchPos = 0;
iPosStart = 0;
while ( iPosStart != -1 ) {
iPosStart = sHeader->pos( iSearchPos, setcookieNeedle, strlen(setcookieNeedle) );
if ( iPosStart != -1 ) {
iPosEnd = sHeader->pos( iPosStart, crlf, iCrlfLen );
if ( iPosEnd == -1 ) {
iPosEnd = sHeader->getLength();
}
iSearchPos = iPosEnd + strlen(crlf);
iValStart = iPosStart + strlen( setcookieNeedle );
iValLen = iPosEnd - iValStart;
iSetCookies++;
tmp.setValue( sHeader->getPointer( iValStart ), iValLen );
String *cookie = new String();
cookie->setValue( &tmp );
cookies.addElement( cookie );
}
}
Vector completeList;
Groundfloor::split_p(&completeList, sHeader, crlf);
size_t c = completeList.size();
for (size_t i = 0; i < c; ++i)
{
String *keyvalue = static_cast<String *>(completeList.elementAt(i));
int colonpos = keyvalue->pos_ansi(":");
if (colonpos != -1) {
String key, value;
key.setValue(keyvalue->getValue(), colonpos);
key.rtrim_ansi();
value.setValue(keyvalue->getPointer(colonpos + 1));
value.ltrim_ansi();
BValue *val = new BValue();
val->setString(&value);
allvars.addObjectByString(key.getValue(), val);
}
}
}
JumpropesCommon::HttpClient::HttpClient( LookupBase *pLookupBase ) : Thread() {
this->pLookupBase = pLookupBase;
socket = NULL;
connection = NULL;
useHttpVersion.set( 1.0 );
cookie.setValue( "", 0 );
referer.setValue( "", 0 );
useragent.setValue( "", 0 );
reset();
}
JumpropesCommon::HttpClient::~HttpClient() {
reset();
}
void JumpropesCommon::HttpClient::reset() {
if ( connection != NULL ) {
if ( bAlternateSocketUsed ) {
connection->setSocket( NULL );
} else {
socket = NULL;
}
delete connection;
connection = NULL;
}
if ( (!bAlternateSocketUsed) && (socket != NULL) ) {
delete socket;
socket = NULL;
}
bAlternateSocketUsed = false;
port = 80;
bHeaderParsed = false;
iHeaderSize = 0;
iChunkScanLastSize = -1;
bWaitForChunk = false;
lastChunkRange.start_ind = 0;
lastChunkRange.start_pos = 0;
lastChunkRange.end_ind = 0;
lastChunkRange.end_pos = 0;
rLastSend.start_ind = 0;
rLastSend.start_pos = 0;
rLastSend.end_ind = 0;
rLastSend.end_pos = 0;
iChunkCount = 0;
}
void JumpropesCommon::HttpClient::get( const URI *uri, bool bBlocking, BaseSocket *anAlternateSocket ) {
reset();
this->host.setValue( &uri->host );
if ( this->host.size() == 0 ) {
if ( pLookupBase != NULL ) {
pLookupBase->lookupHost( &this->host );
} else {
JRresolveAll( &this->host );
}
}
this->path.setValue( &uri->path );
this->port = uri->port.get();
if ( !this->path.startsWith( "/", 1 ) ) {
this->path.prepend( "/", 1 );
}
if ( uri->query.getLength() > 0 ) {
this->path.append( "?", 1 );
this->path.append( &uri->query );
}
IPAddress *aDefaultIp = this->host.getAddress();
if ( aDefaultIp != NULL ) {
if ( anAlternateSocket != NULL ) {
socket = anAlternateSocket;
bAlternateSocketUsed = true;
} else {
socket = new ClientSocket();
}
socket->getRemoteAddress()->setValue( aDefaultIp );
socket->remotePort.set( this->port );
if ( socket->connect() ) {
connection = new HttpConnection( socket );
connection->start();
start();
onStatusUpdate.execute( JRHTTPSTATUS_CONNECTED );
sendGet();
if ( bBlocking ) {
while ( isRunning() ) {
GFMillisleep( 50 );
}
}
} else {
reset();
onStatusUpdate.execute( JRHTTPSTATUS_ERROR );
}
} else {
reset();
onStatusUpdate.execute( JRHTTPSTATUS_ERROR );
}
}
void JumpropesCommon::HttpClient::post( const URI *uri, const String *sDataType, const String *sData, bool bBlocking, BaseSocket *anAlternateSocket ) {
reset();
this->host.setValue( &uri->host );
if ( this->host.size() == 0 ) {
if ( pLookupBase != NULL ) {
pLookupBase->lookupHost( &this->host );
} else {
JRresolveAll( &this->host );
}
}
this->path.setValue( &uri->path );
this->port = uri->port.get();
if ( !this->path.startsWith( "/", 1 ) ) {
this->path.prepend( "/", 1 );
}
if ( uri->query.getLength() > 0 ) {
this->path.append( "?", 1 );
this->path.append( &uri->query );
}
IPAddress *aDefaultIp = this->host.getAddress();
if ( aDefaultIp != NULL ) {
if ( anAlternateSocket != NULL ) {
socket = anAlternateSocket;
bAlternateSocketUsed = true;
} else {
socket = new ClientSocket();
}
socket->getRemoteAddress()->setValue( aDefaultIp );
socket->remotePort.set( this->port );
if ( socket->connect() ) {
connection = new HttpConnection( socket );
connection->start();
start();
onStatusUpdate.execute( JRHTTPSTATUS_CONNECTED );
sendPost( sDataType, sData );
if ( bBlocking ) {
while ( isRunning() ) {
GFMillisleep( 50 );
}
}
} else {
reset();
onStatusUpdate.execute( JRHTTPSTATUS_ERROR );
}
} else {
reset();
onStatusUpdate.execute( JRHTTPSTATUS_ERROR );
}
}
void JumpropesCommon::HttpClient::sendGet() {
BValue val;
int iCrlfLen = strlen(crlf);
String *sCmd = new String();
sCmd->append( sendgetNeedle, strlen(sendgetNeedle) );
sCmd->append( &this->path );
sCmd->append( sendhttpNeedle, strlen(sendhttpNeedle) );
val.precision.set( 1 );
val.setDouble( useHttpVersion.get() );
sCmd->append( val.asString() );
sCmd->append( crlf, iCrlfLen );
sCmd->append( hostNeedle, strlen(hostNeedle) );
sCmd->append( &this->host.name );
sCmd->append( crlf, iCrlfLen );
if ( useragent.getLength() > 0 ) {
sCmd->append( useragentNeedle, strlen(useragentNeedle) );
sCmd->append( &this->useragent );
sCmd->append( crlf, iCrlfLen );
}
if ( referer.getLength() > 0 ) {
sCmd->append( refererNeedle, strlen(refererNeedle) );
sCmd->append( &this->referer );
sCmd->append( crlf, iCrlfLen );
}
if ( cookie.getLength() > 0 ) {
sCmd->append( cookieNeedle, strlen(cookieNeedle) );
sCmd->append( &this->cookie );
sCmd->append( crlf, iCrlfLen );
}
sCmd->append( crlf, iCrlfLen );
socket->send( sCmd );
delete sCmd;
}
void JumpropesCommon::HttpClient::sendPost( const String *sDataType, const String *sData ) {
BValue val;
int iCrlfLen = strlen(crlf);
String *sCmd = new String();
sCmd->append( sendpostNeedle, strlen(sendpostNeedle) );
sCmd->append( &this->path );
sCmd->append( sendhttpNeedle, strlen(sendhttpNeedle) );
val.precision.set( 1 );
val.setDouble( useHttpVersion.get() );
sCmd->append( val.asString() );
sCmd->append( crlf, iCrlfLen );
sCmd->append( hostNeedle, strlen(hostNeedle) );
sCmd->append( &this->host.name );
sCmd->append( crlf, iCrlfLen );
if ( useragent.getLength() > 0 ) {
sCmd->append( useragentNeedle, strlen(useragentNeedle) );
sCmd->append( &this->useragent );
sCmd->append( crlf, iCrlfLen );
}
if ( referer.getLength() > 0 ) {
sCmd->append( refererNeedle, strlen(refererNeedle) );
sCmd->append( &this->referer );
sCmd->append( crlf, iCrlfLen );
}
if ( cookie.getLength() > 0 ) {
sCmd->append( cookieNeedle, strlen(cookieNeedle) );
sCmd->append( &this->cookie );
sCmd->append( crlf, iCrlfLen );
}
sCmd->append( contentTypeNeedle, strlen(contentTypeNeedle) );
sCmd->append( sDataType );
sCmd->append( crlf, iCrlfLen );
val.setInteger( sData->getLength() );
sCmd->append( contentLenNeedle, strlen(contentLenNeedle) );
sCmd->append( val.asString() );
sCmd->append( crlf, iCrlfLen );
sCmd->append( crlf, iCrlfLen );
socket->send( sCmd );
socket->send( sData );
delete sCmd;
}
void JumpropesCommon::HttpClient::done() {
parseReceivedData();
stop();
onStatusUpdate.execute( JRHTTPSTATUS_DONE );
}
void JumpropesCommon::HttpClient::locateAndParseHeader() {
connection->bufferlock.lockWhenAvailable( GFLOCK_INFINITEWAIT );
StringVectorRange *tmpRange = new StringVectorRange(0,0);
bool bPos = connection->receivedData.pos( tmpRange, crlfcrlf, strlen(crlfcrlf) );
if ( bPos ) {
lastChunkRange.copyValues( tmpRange );
lastChunkRange.start_ind = 0;
lastChunkRange.start_pos = 0;
rHeader.copyValues( &lastChunkRange );
lastChunkRange.end_pos++;
String *sHeaderData = connection->receivedData.copy( &rHeader );
iHeaderSize = sHeaderData->getLength();
header.parse( sHeaderData );
parsedHeader.setValue( sHeaderData );
delete sHeaderData;
rLastSend.start_pos = iHeaderSize;
rLastSend.end_pos = iHeaderSize;
bHeaderParsed = true;
if ( !bHeaderParsed ) {
stop();
onStatusUpdate.execute( JRHTTPSTATUS_ERROR );
} else {
onStatusUpdate.execute( JRHTTPSTATUS_HEADER );
}
}
delete tmpRange;
connection->bufferlock.unlock();
}
void JumpropesCommon::HttpClient::execute() {
if ( !connection->isRunning() ) {
done();
} else {
if ( !bHeaderParsed ) {
locateAndParseHeader();
} else {
if ( header.contentlength != -1 ) {
connection->bufferlock.lockWhenAvailable( GFLOCK_INFINITEWAIT );
unsigned long iDataReceived = connection->receivedData.getLength( 0 );
if ( static_cast<unsigned long>(iDataReceived - iHeaderSize) >= header.contentlength ) {
connection->stopAndWait();
}
if ( iDataReceived > rLastSend.end_pos ) {
rLastSend.start_pos = rLastSend.end_pos;
rLastSend.end_pos = iDataReceived;
String *sData = connection->receivedData.copy( 0, rLastSend.start_pos, rLastSend.end_pos - rLastSend.start_pos );
onContent.execute( sData );
delete sData;
}
connection->bufferlock.unlock();
}
if ( header.chunked ) {
// check on 0 bytes remaining
if ( isEndOfChunkedData() ) {
connection->stopAndWait();
}
}
}
}
}
void JumpropesCommon::HttpClient::parseReceivedData() {
if ( bHeaderParsed ) {
if ( !header.chunked ) {
int iStart = iHeaderSize;
connection->bufferlock.lockWhenAvailable( GFLOCK_INFINITEWAIT );
if ( header.contentlength == -1 ) {
header.contentlength = connection->receivedData.getLength( 0 ) - iStart;
String *sData = connection->receivedData.copy( 0, iStart, header.contentlength );
onContent.execute( sData );
delete sData;
} else {
unsigned long iDataReceived = connection->receivedData.getLength( 0 );
if ( iDataReceived > rLastSend.end_pos ) {
rLastSend.start_pos = rLastSend.end_pos;
rLastSend.end_pos = iDataReceived;
String *sData = connection->receivedData.copy( 0, rLastSend.start_pos, rLastSend.end_pos - rLastSend.start_pos );
onContent.execute( sData );
delete sData;
}
}
connection->bufferlock.unlock();
}
}
}
bool JumpropesCommon::HttpClient::isEndOfChunkedData() {
if ( iChunkScanLastSize == 0 ) {
return true;
}
StringVectorRange searchRange;
// nog geen chunklength string gevonden
if ( iChunkScanLastSize == -1 ) {
bWaitForChunk = true;
searchRange.start_ind = lastChunkRange.end_ind;
searchRange.start_pos = lastChunkRange.end_pos;
connection->bufferlock.lockWhenAvailable( GFLOCK_INFINITEWAIT );
bool bPos = connection->receivedData.pos( &searchRange, crlf, strlen(crlf) );
if ( bPos ) {
bWaitForChunk = false;
StringVectorRange tmpRange;
tmpRange.start_ind = lastChunkRange.end_ind;
tmpRange.start_pos = lastChunkRange.end_pos;
tmpRange.end_ind = searchRange.start_ind;
tmpRange.end_pos = searchRange.start_pos;
connection->receivedData.endMinusOne( &tmpRange );
lastChunkRange.end_ind = searchRange.end_ind;
lastChunkRange.end_pos = searchRange.end_pos + 1;
String *tmp = connection->receivedData.copy( &tmpRange );
tmp->ltrim_ansi();
tmp->uppercase_ansi();
iChunkScanLastSize = HexToInt( tmp );
delete tmp;
}
connection->bufferlock.unlock();
}
if ( iChunkScanLastSize == 0 ) {
return true;
}
if ( !bWaitForChunk ) {
// do stuff
connection->bufferlock.lockWhenAvailable( GFLOCK_INFINITEWAIT );
if ( ( connection->receivedData.getLength( lastChunkRange.end_ind ) - lastChunkRange.end_pos ) >= iChunkScanLastSize ) {
String *tmpData = connection->receivedData.copy( lastChunkRange.end_ind, lastChunkRange.end_pos, iChunkScanLastSize );
onContent.execute( tmpData );
delete tmpData;
lastChunkRange.end_pos += iChunkScanLastSize + strlen(crlf);
iChunkScanLastSize = -1;
}
connection->bufferlock.unlock();
}
return false;
}
/*
String *JumpropesCommon::HttpClient::getParsedData() {
return &parsedData;
}
*/
String *JumpropesCommon::HttpClient::getHeader() {
return &parsedHeader;
}
| 27.30137 | 151 | 0.606372 | [
"vector"
] |
724e07e0668139d95446ddd7ab4209249e6e1542 | 9,219 | cpp | C++ | third_party/skia_m84/third_party/externals/angle2/src/common/PoolAlloc.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 20 | 2019-04-18T07:37:34.000Z | 2022-02-02T21:43:47.000Z | third_party/skia_m84/third_party/externals/angle2/src/common/PoolAlloc.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 11 | 2019-10-21T13:39:41.000Z | 2021-11-05T08:11:54.000Z | third_party/skia_m84/third_party/externals/angle2/src/common/PoolAlloc.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 1 | 2021-12-03T18:11:36.000Z | 2021-12-03T18:11:36.000Z | //
// Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// PoolAlloc.cpp:
// Implements the class methods for PoolAllocator and Allocation classes.
//
#include "common/PoolAlloc.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "common/angleutils.h"
#include "common/debug.h"
#include "common/mathutil.h"
#include "common/platform.h"
#include "common/tls.h"
namespace angle
{
//
// Implement the functionality of the PoolAllocator class, which
// is documented in PoolAlloc.h.
//
PoolAllocator::PoolAllocator(int growthIncrement, int allocationAlignment)
: mAlignment(allocationAlignment),
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
mPageSize(growthIncrement),
mFreeList(0),
mInUseList(0),
mNumCalls(0),
mTotalBytes(0),
#endif
mLocked(false)
{
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
if (mAlignment == 1)
{
// This is a special fast-path where fastAllocation() is enabled
mAlignmentMask = 0;
mHeaderSkip = sizeof(Header);
}
else
{
#endif
//
// Adjust mAlignment to be at least pointer aligned and
// power of 2.
//
size_t minAlign = sizeof(void *);
mAlignment &= ~(minAlign - 1);
if (mAlignment < minAlign)
mAlignment = minAlign;
mAlignment = gl::ceilPow2(static_cast<unsigned int>(mAlignment));
mAlignmentMask = mAlignment - 1;
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
//
// Align header skip
//
mHeaderSkip = minAlign;
if (mHeaderSkip < sizeof(Header))
{
mHeaderSkip = rx::roundUpPow2(sizeof(Header), mAlignment);
}
}
//
// Don't allow page sizes we know are smaller than all common
// OS page sizes.
//
if (mPageSize < 4 * 1024)
mPageSize = 4 * 1024;
//
// A large mCurrentPageOffset indicates a new page needs to
// be obtained to allocate memory.
//
mCurrentPageOffset = mPageSize;
#else // !defined(ANGLE_DISABLE_POOL_ALLOC)
mStack.push_back({});
#endif
}
PoolAllocator::~PoolAllocator()
{
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
while (mInUseList)
{
Header *next = mInUseList->nextPage;
mInUseList->~Header();
delete[] reinterpret_cast<char *>(mInUseList);
mInUseList = next;
}
// We should not check the guard blocks
// here, because we did it already when the block was
// placed into the free list.
//
while (mFreeList)
{
Header *next = mFreeList->nextPage;
delete[] reinterpret_cast<char *>(mFreeList);
mFreeList = next;
}
#else // !defined(ANGLE_DISABLE_POOL_ALLOC)
for (auto &allocs : mStack)
{
for (auto alloc : allocs)
{
free(alloc);
}
}
mStack.clear();
#endif
}
//
// Check a single guard block for damage
//
void Allocation::checkGuardBlock(unsigned char *blockMem,
unsigned char val,
const char *locText) const
{
#if defined(ANGLE_POOL_ALLOC_GUARD_BLOCKS)
for (size_t x = 0; x < kGuardBlockSize; x++)
{
if (blockMem[x] != val)
{
char assertMsg[80];
// We don't print the assert message. It's here just to be helpful.
snprintf(assertMsg, sizeof(assertMsg),
"PoolAlloc: Damage %s %zu byte allocation at 0x%p\n", locText, mSize, data());
assert(0 && "PoolAlloc: Damage in guard block");
}
}
#endif
}
void PoolAllocator::push()
{
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
AllocState state = {mCurrentPageOffset, mInUseList};
mStack.push_back(state);
//
// Indicate there is no current page to allocate from.
//
mCurrentPageOffset = mPageSize;
#else // !defined(ANGLE_DISABLE_POOL_ALLOC)
mStack.push_back({});
#endif
}
//
// Do a mass-deallocation of all the individual allocations
// that have occurred since the last push(), or since the
// last pop(), or since the object's creation.
//
// The deallocated pages are saved for future allocations.
//
void PoolAllocator::pop()
{
if (mStack.size() < 1)
return;
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
Header *page = mStack.back().page;
mCurrentPageOffset = mStack.back().offset;
while (mInUseList != page)
{
// invoke destructor to free allocation list
mInUseList->~Header();
Header *nextInUse = mInUseList->nextPage;
if (mInUseList->pageCount > 1)
delete[] reinterpret_cast<char *>(mInUseList);
else
{
mInUseList->nextPage = mFreeList;
mFreeList = mInUseList;
}
mInUseList = nextInUse;
}
mStack.pop_back();
#else // !defined(ANGLE_DISABLE_POOL_ALLOC)
for (auto &alloc : mStack.back())
{
free(alloc);
}
mStack.pop_back();
#endif
}
//
// Do a mass-deallocation of all the individual allocations
// that have occurred.
//
void PoolAllocator::popAll()
{
while (mStack.size() > 0)
pop();
}
void *PoolAllocator::allocate(size_t numBytes)
{
ASSERT(!mLocked);
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
//
// Just keep some interesting statistics.
//
++mNumCalls;
mTotalBytes += numBytes;
// If we are using guard blocks, all allocations are bracketed by
// them: [guardblock][allocation][guardblock]. numBytes is how
// much memory the caller asked for. allocationSize is the total
// size including guard blocks. In release build,
// kGuardBlockSize=0 and this all gets optimized away.
size_t allocationSize = Allocation::AllocationSize(numBytes) + mAlignment;
// Detect integer overflow.
if (allocationSize < numBytes)
return 0;
//
// Do the allocation, most likely case first, for efficiency.
// This step could be moved to be inline sometime.
//
if (allocationSize <= mPageSize - mCurrentPageOffset)
{
//
// Safe to allocate from mCurrentPageOffset.
//
unsigned char *memory = reinterpret_cast<unsigned char *>(mInUseList) + mCurrentPageOffset;
mCurrentPageOffset += allocationSize;
mCurrentPageOffset = (mCurrentPageOffset + mAlignmentMask) & ~mAlignmentMask;
return initializeAllocation(mInUseList, memory, numBytes);
}
if (allocationSize > mPageSize - mHeaderSkip)
{
//
// Do a multi-page allocation. Don't mix these with the others.
// The OS is efficient in allocating and freeing multiple pages.
//
size_t numBytesToAlloc = allocationSize + mHeaderSkip;
// Detect integer overflow.
if (numBytesToAlloc < allocationSize)
return 0;
Header *memory = reinterpret_cast<Header *>(::new char[numBytesToAlloc]);
if (memory == 0)
return 0;
// Use placement-new to initialize header
new (memory) Header(mInUseList, (numBytesToAlloc + mPageSize - 1) / mPageSize);
mInUseList = memory;
mCurrentPageOffset = mPageSize; // make next allocation come from a new page
// No guard blocks for multi-page allocations (yet)
void *unalignedPtr =
reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(memory) + mHeaderSkip);
return std::align(mAlignment, numBytes, unalignedPtr, allocationSize);
}
unsigned char *newPageAddr =
static_cast<unsigned char *>(allocateNewPage(numBytes, allocationSize));
return initializeAllocation(mInUseList, newPageAddr, numBytes);
#else // !defined(ANGLE_DISABLE_POOL_ALLOC)
void *alloc = malloc(numBytes + mAlignmentMask);
mStack.back().push_back(alloc);
intptr_t intAlloc = reinterpret_cast<intptr_t>(alloc);
intAlloc = (intAlloc + mAlignmentMask) & ~mAlignmentMask;
return reinterpret_cast<void *>(intAlloc);
#endif
}
#if !defined(ANGLE_DISABLE_POOL_ALLOC)
void *PoolAllocator::allocateNewPage(size_t numBytes, size_t allocationSize)
{
//
// Need a simple page to allocate from.
//
Header *memory;
if (mFreeList)
{
memory = mFreeList;
mFreeList = mFreeList->nextPage;
}
else
{
memory = reinterpret_cast<Header *>(::new char[mPageSize]);
if (memory == 0)
return 0;
}
// Use placement-new to initialize header
new (memory) Header(mInUseList, 1);
mInUseList = memory;
unsigned char *ret = reinterpret_cast<unsigned char *>(mInUseList) + mHeaderSkip;
mCurrentPageOffset = (mHeaderSkip + allocationSize + mAlignmentMask) & ~mAlignmentMask;
return ret;
}
#endif
void PoolAllocator::lock()
{
ASSERT(!mLocked);
mLocked = true;
}
void PoolAllocator::unlock()
{
ASSERT(mLocked);
mLocked = false;
}
//
// Check all allocations in a list for damage by calling check on each.
//
void Allocation::checkAllocList() const
{
for (const Allocation *alloc = this; alloc != 0; alloc = alloc->mPrevAlloc)
alloc->check();
}
} // namespace angle
| 27.519403 | 99 | 0.6338 | [
"object"
] |
7254e62b333d85982d71b8a62ada72fc6075557a | 6,949 | hpp | C++ | c++/include/objtools/readers/reader_base.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/include/objtools/readers/reader_base.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/include/objtools/readers/reader_base.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | /* $Id: reader_base.hpp 352777 2012-02-09 12:01:52Z ludwigf $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Frank Ludwig
*
* File Description:
* Basic reader interface
*
*/
#ifndef OBJTOOLS_READERS___READERBASE__HPP
#define OBJTOOLS_READERS___READERBASE__HPP
#include <corelib/ncbistd.hpp>
#include <objects/seq/Seq_annot.hpp>
#include <util/format_guess.hpp>
#include <objtools/readers/line_error.hpp>
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
class IErrorContainer;
class CObjReaderLineException;
class CTrackData;
// ----------------------------------------------------------------------------
/// Defines and provides stubs for a general interface to a variety of file
/// readers. These readers are assumed to read information in some foreign
/// format from an input stream, and render it as an NCBI Genbank object.
///
class NCBI_XOBJREAD_EXPORT CReaderBase
// ----------------------------------------------------------------------------
{
public:
/// Customization flags that are relevant to all CReaderBase derived readers.
///
enum EFlags {
fNormal = 0,
///< numeric identifiers are local IDs
fNumericIdsAsLocal = 1<0,
///< all identifiers are local IDs
fAllIdsAsLocal = 1<1,
fNextInLine = 1<2,
};
enum ObjectType {
OT_UNKNOWN,
OT_SEQANNOT,
OT_SEQENTRY
};
protected:
/// Protected constructor. Use GetReader() to get an actual reader object.
CReaderBase(
unsigned int flags =0); //flags
public:
virtual ~CReaderBase();
/// Allocate a CReaderBase derived reader object based on the given
/// file format.
/// @param format
/// format specifier as defined in the class CFormatGuess
/// @param flags
/// bit flags as defined in EFlags
///
static CReaderBase* GetReader(
CFormatGuess::EFormat format,
unsigned int flags =0 );
/// Read an object from a given input stream, render it as the most
/// appropriate Genbank object.
/// @param istr
/// input stream to read from.
/// @param pErrors
/// pointer to optional error container object.
///
virtual CRef< CSerialObject >
ReadObject(
CNcbiIstream& istr,
IErrorContainer* pErrors=0 );
/// Read an object from a given line reader, render it as the most
/// appropriate Genbank object.
/// This is the only function that does not come with a default
/// implementation. That is, an implementation must be provided in the
/// derived class.
/// @param lr
/// line reader to read from.
/// @param pErrors
/// pointer to optional error container object.
///
virtual CRef< CSerialObject >
ReadObject(
ILineReader& lr,
IErrorContainer* pErrors=0 ) =0;
/// Read an object from a given input stream, render it as a single
/// Seq-annot. Return empty Seq-annot otherwise.
/// @param istr
/// input stream to read from.
/// @param pErrors
/// pointer to optional error container object.
///
virtual CRef< CSeq_annot >
ReadSeqAnnot(
CNcbiIstream& istr,
IErrorContainer* pErrors=0 );
/// Read an object from a given line reader, render it as a single
/// Seq-annot, if possible. Return empty Seq-annot otherwise.
/// @param lr
/// line reader to read from.
/// @param pErrors
/// pointer to optional error container object.
///
virtual CRef< CSeq_annot >
ReadSeqAnnot(
ILineReader& lr,
IErrorContainer* pErrors=0 );
/// Read an object from a given input stream, render it as a single
/// Seq-entry, if possible. Return empty Seq-entry otherwise.
/// @param istr
/// input stream to read from.
/// @param pErrors
/// pointer to optional error container object.
///
virtual CRef< CSeq_entry >
ReadSeqEntry(
CNcbiIstream& istr,
IErrorContainer* pErrors=0 );
/// Read an object from a given line reader, render it as a single
/// Seq-entry, if possible. Return empty Seq-entry otherwise.
/// @param lr
/// line reader to read from.
/// @param pErrors
/// pointer to optional error container object.
///
virtual CRef< CSeq_entry >
ReadSeqEntry(
ILineReader& lr,
IErrorContainer* pErrors=0 );
protected:
virtual void x_AssignTrackData(
CRef<CSeq_annot>& );
virtual bool x_ParseBrowserLine(
const string&,
CRef<CSeq_annot>& );
virtual bool x_ParseTrackLine(
const string&,
CRef<CSeq_annot>& );
virtual void x_SetBrowserRegion(
const string&,
CAnnot_descr& );
virtual void x_SetTrackData(
CRef<CSeq_annot>&,
CRef<CUser_object>&,
const string&,
const string& );
virtual void x_AddConversionInfo(
CRef< CSeq_annot >&,
IErrorContainer* );
virtual void x_AddConversionInfo(
CRef< CSeq_entry >&,
IErrorContainer* );
virtual CRef<CUser_object> x_MakeAsnConversionInfo(
IErrorContainer* );
void
ProcessError(
CObjReaderLineException&,
IErrorContainer* );
void
ProcessError(
CLineError&,
IErrorContainer* );
//
// Data:
//
unsigned int m_uLineNumber;
int m_iFlags;
CTrackData* m_pTrackDefaults;
};
END_objects_SCOPE
END_NCBI_SCOPE
#endif // OBJTOOLS_READERS___READERBASE__HPP
| 30.884444 | 81 | 0.607569 | [
"render",
"object"
] |
7256b1bcd5f31c404386b39020b50c665e8c6cc7 | 3,851 | hpp | C++ | include/MasterServer/MessageHandler_--c__DisplayClass77_0_1.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/MasterServer/MessageHandler_--c__DisplayClass77_0_1.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/MasterServer/MessageHandler_--c__DisplayClass77_0_1.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: MasterServer.MessageHandler
#include "MasterServer/MessageHandler.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: MasterServer
namespace MasterServer {
// Forward declaring type: IMasterServerReliableRequest
class IMasterServerReliableRequest;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
}
// Completed forward declares
// Type namespace: MasterServer
namespace MasterServer {
// WARNING Size may be invalid!
// Autogenerated type: MasterServer.MessageHandler/<>c__DisplayClass77_0`1
// [CompilerGeneratedAttribute] Offset: DEF85C
template<typename T>
class MessageHandler::$$c__DisplayClass77_0_1 : public ::Il2CppObject {
public:
// public MasterServer.MessageHandler <>4__this
// Size: 0x8
// Offset: 0x0
MasterServer::MessageHandler* $$4__this;
// Field size check
static_assert(sizeof(MasterServer::MessageHandler*) == 0x8);
// public System.Action`2<T,MasterServer.MessageHandler/MessageOrigin> customHandler
// Size: 0x8
// Offset: 0x0
System::Action_2<T, MasterServer::MessageHandler::MessageOrigin>* customHandler;
// Field size check
static_assert(sizeof(System::Action_2<T, MasterServer::MessageHandler::MessageOrigin>*) == 0x8);
// Creating value type constructor for type: $$c__DisplayClass77_0_1
$$c__DisplayClass77_0_1(MasterServer::MessageHandler* $$4__this_ = {}, System::Action_2<T, MasterServer::MessageHandler::MessageOrigin>* customHandler_ = {}) noexcept : $$4__this{$$4__this_}, customHandler{customHandler_} {}
// System.Void <CustomResponseHandler>b__0(T packet, MasterServer.MessageHandler/MessageOrigin origin)
// Offset: 0xFFFFFFFF
void $CustomResponseHandler$b__0(T packet, MasterServer::MessageHandler::MessageOrigin origin) {
static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::MessageHandler::$$c__DisplayClass77_0_1::<CustomResponseHandler>b__0");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "<CustomResponseHandler>b__0", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(packet), ::il2cpp_utils::ExtractType(origin)})));
::il2cpp_utils::RunMethodThrow<void, false>(this, ___internal__method, packet, origin);
}
// public System.Void .ctor()
// Offset: 0xFFFFFFFF
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MessageHandler::$$c__DisplayClass77_0_1<T>* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("MasterServer::MessageHandler::$$c__DisplayClass77_0_1::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MessageHandler::$$c__DisplayClass77_0_1<T>*, creationType>()));
}
}; // MasterServer.MessageHandler/<>c__DisplayClass77_0`1
// Could not write size check! Type: MasterServer.MessageHandler/<>c__DisplayClass77_0`1 is generic, or has no fields that are valid for size checks!
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(MasterServer::MessageHandler::$$c__DisplayClass77_0_1, "MasterServer", "MessageHandler/<>c__DisplayClass77_0`1");
| 55.811594 | 258 | 0.744482 | [
"object",
"vector"
] |
7260ed53844728357ebff17e58bf3f9582b8420b | 4,378 | c++ | C++ | src/extern/inventor/apps/samples/lod/details.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/extern/inventor/apps/samples/lod/details.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/extern/inventor/apps/samples/lod/details.c++ | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
#include <stdlib.h>
#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/Xt/SoXt.h>
#include <Inventor/Xt/viewers/SoXtExaminerViewer.h>
// #include <Inventor/nodes/SoLevelOfDetail.h>
#include <Inventor/nodes/SoLOD.h>
#include <Inventor/nodes/SoSeparator.h>
void
main(int argc, char *argv[])
{
char *filename = "lod.iv";
if (argc < 2) {
fprintf(stderr, "NOTE: You can specify your own geometry file.\n");
fprintf(stderr, "Run: %s inputFile.\n", argv[0]);
fprintf(stderr, "Running with the default geometry, %s.\n", filename);
} else {
filename = argv[1];
}
// Initialize Inventor and Xt
Widget mainWindow = SoXt::init(argv[0]);
// Read the geometry from the file
SoInput in;
SoNode *fileGeom;
if (! in.openFile(filename))
exit(1);
if(! SoDB::read(&in, fileGeom) || fileGeom == NULL)
exit(1);
// Create the root node and the empty LevelOfDetail node
SoSeparator *root = new SoSeparator;
root->ref();
// Using the SoLOD node is the recommended way of doing
// level-of-detail switching in Inventor 2.1 - it's faster
// than the old SoLevelOfDetail
SoLOD *lod = new SoLOD;
root->addChild(lod);
lod->range.set1Value(0, 25);
lod->range.set1Value(1, 50);
lod->range.set1Value(2, 100);
lod->center.setValue(0,0,0);
// Pre-2.1 programs must use the SoLevelOfDetail node
// SoLevelOfDetail *lod = new SoLevelOfDetail;
// root->addChild(lod);
// lod->screenArea.set1Value(0, 110000.);
// lod->screenArea.set1Value(1, 20000.);
// lod->screenArea.set1Value(2, 3000.);
// lod->screenArea.set1Value(3, 1000.);
// Search for the different levels by name, and insert
// into the level-of-detail group
SoSeparator *level1 = (SoSeparator *)fileGeom->getByName("Level1");
if (level1 != NULL &&
level1->isOfType(SoSeparator::getClassTypeId())) {
lod->addChild(level1);
}
SoSeparator *level2 = (SoSeparator *)fileGeom->getByName("Level2");
if (level2 != NULL &&
level2->isOfType(SoSeparator::getClassTypeId())) {
lod->addChild(level2);
}
SoSeparator *level3 = (SoSeparator *)fileGeom->getByName("Level3");
if (level3 != NULL &&
level3->isOfType(SoSeparator::getClassTypeId())) {
lod->addChild(level3);
}
SoSeparator *level4 = (SoSeparator *)fileGeom->getByName("Level4");
if (level4 != NULL &&
level4->isOfType(SoSeparator::getClassTypeId())) {
lod->addChild(level4);
}
fprintf(stderr, "\nUse the left&middle mouse buttons to zoom\n");
// Create the viewer
SoXtExaminerViewer *viewer = new SoXtExaminerViewer(mainWindow);
viewer->setDecoration(FALSE);
viewer->setTitle("Details, details");
viewer->setSceneGraph(root);
viewer->show();
// Loop forever
SoXt::show(mainWindow);
SoXt::mainLoop();
}
| 33.166667 | 77 | 0.678392 | [
"geometry"
] |
726221925a6b5144836593253bbd447b9891add8 | 16,502 | hpp | C++ | include/VROSC/PreferencesPanelUI.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/PreferencesPanelUI.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/PreferencesPanelUI.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: VROSC
namespace VROSC {
// Forward declaring type: SpectatorCameraUI
class SpectatorCameraUI;
// Forward declaring type: UIHoldButton
class UIHoldButton;
// Forward declaring type: UISlider
class UISlider;
// Forward declaring type: UISlideToggle
class UISlideToggle;
// Forward declaring type: UIButton
class UIButton;
// Forward declaring type: PassthroughManager
class PassthroughManager;
// Forward declaring type: UserDataControllers
class UserDataControllers;
// Forward declaring type: InputDevice
class InputDevice;
// Forward declaring type: ClickData
class ClickData;
}
// Completed forward declares
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: PreferencesPanelUI
class PreferencesPanelUI;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::PreferencesPanelUI);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::PreferencesPanelUI*, "VROSC", "PreferencesPanelUI");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x60
#pragma pack(push, 1)
// Autogenerated type: VROSC.PreferencesPanelUI
// [TokenAttribute] Offset: FFFFFFFF
class PreferencesPanelUI : public ::UnityEngine::MonoBehaviour {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private VROSC.SpectatorCameraUI _spectatorCameraUI
// Size: 0x8
// Offset: 0x18
::VROSC::SpectatorCameraUI* spectatorCameraUI;
// Field size check
static_assert(sizeof(::VROSC::SpectatorCameraUI*) == 0x8);
// private VROSC.UIHoldButton _resetAllButton
// Size: 0x8
// Offset: 0x20
::VROSC::UIHoldButton* resetAllButton;
// Field size check
static_assert(sizeof(::VROSC::UIHoldButton*) == 0x8);
// private VROSC.UISlider _volumeSlider
// Size: 0x8
// Offset: 0x28
::VROSC::UISlider* volumeSlider;
// Field size check
static_assert(sizeof(::VROSC::UISlider*) == 0x8);
// private VROSC.UISlideToggle _audioWhenUnfocusedButton
// Size: 0x8
// Offset: 0x30
::VROSC::UISlideToggle* audioWhenUnfocusedButton;
// Field size check
static_assert(sizeof(::VROSC::UISlideToggle*) == 0x8);
// private VROSC.UISlideToggle _useClassicControls
// Size: 0x8
// Offset: 0x38
::VROSC::UISlideToggle* useClassicControls;
// Field size check
static_assert(sizeof(::VROSC::UISlideToggle*) == 0x8);
// private VROSC.UIButton _resetMalletsButton
// Size: 0x8
// Offset: 0x40
::VROSC::UIButton* resetMalletsButton;
// Field size check
static_assert(sizeof(::VROSC::UIButton*) == 0x8);
// private VROSC.UISlideToggle _autoDimLasersToggle
// Size: 0x8
// Offset: 0x48
::VROSC::UISlideToggle* autoDimLasersToggle;
// Field size check
static_assert(sizeof(::VROSC::UISlideToggle*) == 0x8);
// private System.Boolean _spectatorCameraEnabled
// Size: 0x1
// Offset: 0x50
bool spectatorCameraEnabled;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: spectatorCameraEnabled and: passthroughManager
char __padding7[0x7] = {};
// private VROSC.PassthroughManager _passthroughManager
// Size: 0x8
// Offset: 0x58
::VROSC::PassthroughManager* passthroughManager;
// Field size check
static_assert(sizeof(::VROSC::PassthroughManager*) == 0x8);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private VROSC.SpectatorCameraUI _spectatorCameraUI
::VROSC::SpectatorCameraUI*& dyn__spectatorCameraUI();
// Get instance field reference: private VROSC.UIHoldButton _resetAllButton
::VROSC::UIHoldButton*& dyn__resetAllButton();
// Get instance field reference: private VROSC.UISlider _volumeSlider
::VROSC::UISlider*& dyn__volumeSlider();
// Get instance field reference: private VROSC.UISlideToggle _audioWhenUnfocusedButton
::VROSC::UISlideToggle*& dyn__audioWhenUnfocusedButton();
// Get instance field reference: private VROSC.UISlideToggle _useClassicControls
::VROSC::UISlideToggle*& dyn__useClassicControls();
// Get instance field reference: private VROSC.UIButton _resetMalletsButton
::VROSC::UIButton*& dyn__resetMalletsButton();
// Get instance field reference: private VROSC.UISlideToggle _autoDimLasersToggle
::VROSC::UISlideToggle*& dyn__autoDimLasersToggle();
// Get instance field reference: private System.Boolean _spectatorCameraEnabled
bool& dyn__spectatorCameraEnabled();
// Get instance field reference: private VROSC.PassthroughManager _passthroughManager
::VROSC::PassthroughManager*& dyn__passthroughManager();
// public System.Boolean get_IsOpen()
// Offset: 0x8FFCE8
bool get_IsOpen();
// protected System.Void Awake()
// Offset: 0x8FFD0C
void Awake();
// private System.Void OnDestroy()
// Offset: 0x900210
void OnDestroy();
// private System.Void OnEnable()
// Offset: 0x900580
void OnEnable();
// private System.Void UserDataLoaded(VROSC.UserDataControllers user)
// Offset: 0x9005D4
void UserDataLoaded(::VROSC::UserDataControllers* user);
// private System.Void SetVolume(System.Single volume)
// Offset: 0x90074C
void SetVolume(float volume);
// public System.Void Open()
// Offset: 0x9007F8
void Open();
// public System.Void Close()
// Offset: 0x900820
void Close();
// private System.Void ResetAllButtonPressed()
// Offset: 0x900848
void ResetAllButtonPressed();
// private System.Void AudioWhenUnfocusedToggled(VROSC.InputDevice inputDevice, System.Boolean state)
// Offset: 0x90084C
void AudioWhenUnfocusedToggled(::VROSC::InputDevice* inputDevice, bool state);
// private System.Void UseClassicControlsToggled(VROSC.InputDevice inputDevice, System.Boolean state)
// Offset: 0x9008B4
void UseClassicControlsToggled(::VROSC::InputDevice* inputDevice, bool state);
// private System.Void ResetMalletsToDefault(VROSC.ClickData obj)
// Offset: 0x90091C
void ResetMalletsToDefault(::VROSC::ClickData* obj);
// private System.Void AutoDimLaserToggled(VROSC.InputDevice device, System.Boolean active)
// Offset: 0x900974
void AutoDimLaserToggled(::VROSC::InputDevice* device, bool active);
// private System.Void TogglePassthrough(VROSC.InputDevice device, System.Boolean active)
// Offset: 0x9009D4
void TogglePassthrough(::VROSC::InputDevice* device, bool active);
// public System.Void .ctor()
// Offset: 0x900AA4
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PreferencesPanelUI* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::PreferencesPanelUI::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PreferencesPanelUI*, creationType>()));
}
}; // VROSC.PreferencesPanelUI
#pragma pack(pop)
static check_size<sizeof(PreferencesPanelUI), 88 + sizeof(::VROSC::PassthroughManager*)> __VROSC_PreferencesPanelUISizeCheck;
static_assert(sizeof(PreferencesPanelUI) == 0x60);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::get_IsOpen
// Il2CppName: get_IsOpen
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (VROSC::PreferencesPanelUI::*)()>(&VROSC::PreferencesPanelUI::get_IsOpen)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "get_IsOpen", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)()>(&VROSC::PreferencesPanelUI::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)()>(&VROSC::PreferencesPanelUI::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::OnEnable
// Il2CppName: OnEnable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)()>(&VROSC::PreferencesPanelUI::OnEnable)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "OnEnable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::UserDataLoaded
// Il2CppName: UserDataLoaded
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)(::VROSC::UserDataControllers*)>(&VROSC::PreferencesPanelUI::UserDataLoaded)> {
static const MethodInfo* get() {
static auto* user = &::il2cpp_utils::GetClassFromName("VROSC", "UserDataControllers")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "UserDataLoaded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{user});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::SetVolume
// Il2CppName: SetVolume
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)(float)>(&VROSC::PreferencesPanelUI::SetVolume)> {
static const MethodInfo* get() {
static auto* volume = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "SetVolume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{volume});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::Open
// Il2CppName: Open
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)()>(&VROSC::PreferencesPanelUI::Open)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "Open", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::Close
// Il2CppName: Close
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)()>(&VROSC::PreferencesPanelUI::Close)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "Close", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::ResetAllButtonPressed
// Il2CppName: ResetAllButtonPressed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)()>(&VROSC::PreferencesPanelUI::ResetAllButtonPressed)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "ResetAllButtonPressed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::AudioWhenUnfocusedToggled
// Il2CppName: AudioWhenUnfocusedToggled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)(::VROSC::InputDevice*, bool)>(&VROSC::PreferencesPanelUI::AudioWhenUnfocusedToggled)> {
static const MethodInfo* get() {
static auto* inputDevice = &::il2cpp_utils::GetClassFromName("VROSC", "InputDevice")->byval_arg;
static auto* state = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "AudioWhenUnfocusedToggled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inputDevice, state});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::UseClassicControlsToggled
// Il2CppName: UseClassicControlsToggled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)(::VROSC::InputDevice*, bool)>(&VROSC::PreferencesPanelUI::UseClassicControlsToggled)> {
static const MethodInfo* get() {
static auto* inputDevice = &::il2cpp_utils::GetClassFromName("VROSC", "InputDevice")->byval_arg;
static auto* state = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "UseClassicControlsToggled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inputDevice, state});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::ResetMalletsToDefault
// Il2CppName: ResetMalletsToDefault
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)(::VROSC::ClickData*)>(&VROSC::PreferencesPanelUI::ResetMalletsToDefault)> {
static const MethodInfo* get() {
static auto* obj = &::il2cpp_utils::GetClassFromName("VROSC", "ClickData")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "ResetMalletsToDefault", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::AutoDimLaserToggled
// Il2CppName: AutoDimLaserToggled
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)(::VROSC::InputDevice*, bool)>(&VROSC::PreferencesPanelUI::AutoDimLaserToggled)> {
static const MethodInfo* get() {
static auto* device = &::il2cpp_utils::GetClassFromName("VROSC", "InputDevice")->byval_arg;
static auto* active = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "AutoDimLaserToggled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{device, active});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::TogglePassthrough
// Il2CppName: TogglePassthrough
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::PreferencesPanelUI::*)(::VROSC::InputDevice*, bool)>(&VROSC::PreferencesPanelUI::TogglePassthrough)> {
static const MethodInfo* get() {
static auto* device = &::il2cpp_utils::GetClassFromName("VROSC", "InputDevice")->byval_arg;
static auto* active = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::PreferencesPanelUI*), "TogglePassthrough", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{device, active});
}
};
// Writing MetadataGetter for method: VROSC::PreferencesPanelUI::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 50.310976 | 192 | 0.738638 | [
"object",
"vector"
] |
72648598b775e88f62f653d939e3db5b55d891d3 | 4,753 | cpp | C++ | android-30/java/util/logging/LogRecord.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/util/logging/LogRecord.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/util/logging/LogRecord.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JArray.hpp"
#include "../../../JObjectArray.hpp"
#include "../../io/ObjectInputStream.hpp"
#include "../../io/ObjectOutputStream.hpp"
#include "../../../JString.hpp"
#include "../../../JThrowable.hpp"
#include "../../time/Instant.hpp"
#include "../ResourceBundle.hpp"
#include "../concurrent/atomic/AtomicLong.hpp"
#include "./Level.hpp"
#include "./LogRecord.hpp"
namespace java::util::logging
{
// Fields
// QJniObject forward
LogRecord::LogRecord(QJniObject obj) : JObject(obj) {}
// Constructors
LogRecord::LogRecord(java::util::logging::Level arg0, JString arg1)
: JObject(
"java.util.logging.LogRecord",
"(Ljava/util/logging/Level;Ljava/lang/String;)V",
arg0.object(),
arg1.object<jstring>()
) {}
// Methods
java::time::Instant LogRecord::getInstant() const
{
return callObjectMethod(
"getInstant",
"()Ljava/time/Instant;"
);
}
java::util::logging::Level LogRecord::getLevel() const
{
return callObjectMethod(
"getLevel",
"()Ljava/util/logging/Level;"
);
}
JString LogRecord::getLoggerName() const
{
return callObjectMethod(
"getLoggerName",
"()Ljava/lang/String;"
);
}
jlong LogRecord::getLongThreadID() const
{
return callMethod<jlong>(
"getLongThreadID",
"()J"
);
}
JString LogRecord::getMessage() const
{
return callObjectMethod(
"getMessage",
"()Ljava/lang/String;"
);
}
jlong LogRecord::getMillis() const
{
return callMethod<jlong>(
"getMillis",
"()J"
);
}
JObjectArray LogRecord::getParameters() const
{
return callObjectMethod(
"getParameters",
"()[Ljava/lang/Object;"
);
}
java::util::ResourceBundle LogRecord::getResourceBundle() const
{
return callObjectMethod(
"getResourceBundle",
"()Ljava/util/ResourceBundle;"
);
}
JString LogRecord::getResourceBundleName() const
{
return callObjectMethod(
"getResourceBundleName",
"()Ljava/lang/String;"
);
}
jlong LogRecord::getSequenceNumber() const
{
return callMethod<jlong>(
"getSequenceNumber",
"()J"
);
}
JString LogRecord::getSourceClassName() const
{
return callObjectMethod(
"getSourceClassName",
"()Ljava/lang/String;"
);
}
JString LogRecord::getSourceMethodName() const
{
return callObjectMethod(
"getSourceMethodName",
"()Ljava/lang/String;"
);
}
jint LogRecord::getThreadID() const
{
return callMethod<jint>(
"getThreadID",
"()I"
);
}
JThrowable LogRecord::getThrown() const
{
return callObjectMethod(
"getThrown",
"()Ljava/lang/Throwable;"
);
}
void LogRecord::setInstant(java::time::Instant arg0) const
{
callMethod<void>(
"setInstant",
"(Ljava/time/Instant;)V",
arg0.object()
);
}
void LogRecord::setLevel(java::util::logging::Level arg0) const
{
callMethod<void>(
"setLevel",
"(Ljava/util/logging/Level;)V",
arg0.object()
);
}
void LogRecord::setLoggerName(JString arg0) const
{
callMethod<void>(
"setLoggerName",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
java::util::logging::LogRecord LogRecord::setLongThreadID(jlong arg0) const
{
return callObjectMethod(
"setLongThreadID",
"(J)Ljava/util/logging/LogRecord;",
arg0
);
}
void LogRecord::setMessage(JString arg0) const
{
callMethod<void>(
"setMessage",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
void LogRecord::setMillis(jlong arg0) const
{
callMethod<void>(
"setMillis",
"(J)V",
arg0
);
}
void LogRecord::setParameters(JObjectArray arg0) const
{
callMethod<void>(
"setParameters",
"([Ljava/lang/Object;)V",
arg0.object<jobjectArray>()
);
}
void LogRecord::setResourceBundle(java::util::ResourceBundle arg0) const
{
callMethod<void>(
"setResourceBundle",
"(Ljava/util/ResourceBundle;)V",
arg0.object()
);
}
void LogRecord::setResourceBundleName(JString arg0) const
{
callMethod<void>(
"setResourceBundleName",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
void LogRecord::setSequenceNumber(jlong arg0) const
{
callMethod<void>(
"setSequenceNumber",
"(J)V",
arg0
);
}
void LogRecord::setSourceClassName(JString arg0) const
{
callMethod<void>(
"setSourceClassName",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
void LogRecord::setSourceMethodName(JString arg0) const
{
callMethod<void>(
"setSourceMethodName",
"(Ljava/lang/String;)V",
arg0.object<jstring>()
);
}
void LogRecord::setThreadID(jint arg0) const
{
callMethod<void>(
"setThreadID",
"(I)V",
arg0
);
}
void LogRecord::setThrown(JThrowable arg0) const
{
callMethod<void>(
"setThrown",
"(Ljava/lang/Throwable;)V",
arg0.object<jthrowable>()
);
}
} // namespace java::util::logging
| 19.640496 | 76 | 0.660635 | [
"object"
] |
7269662c3211fdb62b7228f2dd344766f0d51696 | 3,174 | cpp | C++ | src/engine/resource_manager.cpp | Gaetz/SDL-OpenGL | ee0d8bf49c143f973c81cde973f7261c44bb1df2 | [
"MIT"
] | 13 | 2020-01-03T12:19:47.000Z | 2022-01-02T08:22:56.000Z | src/engine/resource_manager.cpp | Gaetz/cpp-Tetris | ee0d8bf49c143f973c81cde973f7261c44bb1df2 | [
"MIT"
] | null | null | null | src/engine/resource_manager.cpp | Gaetz/cpp-Tetris | ee0d8bf49c143f973c81cde973f7261c44bb1df2 | [
"MIT"
] | 3 | 2021-12-07T21:08:02.000Z | 2022-03-22T04:33:08.000Z | #include "resource_manager.h"
#include "log.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
// Instantiate static variables
std::map<std::string, Texture2D> ResourceManager::textures;
std::map<std::string, Shader> ResourceManager::shaders;
Shader ResourceManager::loadShader(const std::string& vShaderFile, const std::string& fShaderFile, const std::string& gShaderFile, const std::string& name)
{
shaders[name] = loadShaderFromFile(vShaderFile, fShaderFile, gShaderFile);
return shaders[name];
}
Shader ResourceManager::getShader(const std::string& name)
{
return shaders[name];
}
Texture2D ResourceManager::loadTexture(const std::string& file, const std::string& name)
{
textures[name] = loadTextureFromFile(file.c_str());
return textures[name];
}
Texture2D ResourceManager::getTexture(const std::string& name)
{
return textures[name];
}
void ResourceManager::clear()
{
// (Properly) delete all shaders
for (auto iter : shaders)
glDeleteProgram(iter.second.id);
// (Properly) delete all textures
for (auto iter : textures)
glDeleteTextures(1, &iter.second.id);
}
Shader ResourceManager::loadShaderFromFile(const std::string& vShaderFile, const std::string& fShaderFile, const std::string& gShaderFile)
{
// 1. Retrieve the vertex/fragment source code from filePath
std::string vertexCode;
std::string fragmentCode;
std::string geometryCode;
try
{
// Open files
std::ifstream vertexShaderFile(vShaderFile);
std::ifstream fragmentShaderFile(fShaderFile);
std::stringstream vShaderStream, fShaderStream;
// Read file's buffer contents into streams
vShaderStream << vertexShaderFile.rdbuf();
fShaderStream << fragmentShaderFile.rdbuf();
// close file handlers
vertexShaderFile.close();
fragmentShaderFile.close();
// Convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
// If geometry shader path is present, also load a geometry shader
if (gShaderFile != "")
{
std::ifstream geometryShaderFile(gShaderFile);
std::stringstream gShaderStream;
gShaderStream << geometryShaderFile.rdbuf();
geometryShaderFile.close();
geometryCode = gShaderStream.str();
}
}
catch (std::exception e)
{
std::ostringstream loadError;
std::string geomShaderFile = "";
if (gShaderFile != "")
geomShaderFile = gShaderFile;
loadError << "ERROR::SHADER: Failed to read shader files " << vShaderFile << " " << fShaderFile << " " << geomShaderFile << "\n"
<< "\n -- --------------------------------------------------- -- "
<< std::endl;
LOG(Error) << loadError.str();
}
const GLchar *vShaderCode = vertexCode.c_str();
const GLchar *fShaderCode = fragmentCode.c_str();
const GLchar *gShaderCode = geometryCode.c_str();
// 2. Now create shader object from source code
Shader shader;
shader.compile(vShaderCode, fShaderCode, gShaderFile != "" ? gShaderCode : nullptr);
return shader;
}
Texture2D ResourceManager::loadTextureFromFile(const std::string& file)
{
// Create Texture object
Texture2D texture;
texture.load(file);
// Now generate texture
texture.generate();
// And finally return texture
return texture;
} | 29.663551 | 155 | 0.720542 | [
"geometry",
"object"
] |
726aeac3ec80745b146a128e822ad8df6bca7068 | 728 | hpp | C++ | Engine/Mesh/OpenGLMesh.hpp | FeikoJoosten/GameEngineFramework | 09017f92270db6d0fc649949a2960f9a14d5db0e | [
"MIT"
] | 5 | 2019-02-16T18:55:40.000Z | 2019-07-30T09:07:11.000Z | Engine/Mesh/OpenGLMesh.hpp | FeikoJoosten/GameEngineFramework | 09017f92270db6d0fc649949a2960f9a14d5db0e | [
"MIT"
] | null | null | null | Engine/Mesh/OpenGLMesh.hpp | FeikoJoosten/GameEngineFramework | 09017f92270db6d0fc649949a2960f9a14d5db0e | [
"MIT"
] | null | null | null | #pragma once
#include "Engine/Utility/Defines.hpp"
#ifdef USING_OPENGL
#include "Engine/Mesh/Mesh.hpp"
#include <ThirdParty/glew-2.1.0/include/GL/glew.h>
namespace Engine
{
/// <summary>
/// This object is used to store data regarding a mesh. NOTE: only the resource manager is allowed to create a mesh.
/// </summary>
class ENGINE_API OpenGLMesh : public Mesh
{
friend class ResourceManager;
OpenGLMesh() = delete;
OpenGLMesh(eastl::vector<Vertex> vertices, eastl::vector<unsigned> indices);
OpenGLMesh(OpenGLMesh const &other) = default;
//OpenGLMesh(OpenGLMesh &&other) noexcept = default;
public:
~OpenGLMesh() noexcept = default;
private:
void SetUpMesh() override;
};
} // namespace Engine
#endif | 26 | 117 | 0.729396 | [
"mesh",
"object",
"vector"
] |
726c523700a4de30daa203e9c6d5eead7c0a2ded | 949 | cpp | C++ | Leetcode/L14-longestCommonPrefix.cpp | Yvettre/Cpp-practice | 711985f27789cd442962a004293ac4ef2ce5029c | [
"MIT"
] | null | null | null | Leetcode/L14-longestCommonPrefix.cpp | Yvettre/Cpp-practice | 711985f27789cd442962a004293ac4ef2ce5029c | [
"MIT"
] | null | null | null | Leetcode/L14-longestCommonPrefix.cpp | Yvettre/Cpp-practice | 711985f27789cd442962a004293ac4ef2ce5029c | [
"MIT"
] | null | null | null | /***************************************************************
Leetcode-easy-14: My runtime is 4ms.
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
All given inputs are in lowercase letters a-z.
URL: https://leetcode.com/problems/longest-common-prefix/
****************************************************************/
#pragma once
#include<vector>
#include<string>
using namespace std;
string longestCommonPrefix(vector<string>& strs) {
if (strs.size() == 0) { return ""; }
if (strs.size() == 1) { return strs[0]; }
size_t commonLen = strs[0].size();
for (auto s : strs) {
commonLen = s.size() < commonLen ? s.size() : commonLen;
}
for (size_t i = 0; i < commonLen; ++i) {
for (size_t j = 1; j < strs.size(); ++j) {
if (strs[0][i] != strs[j][i]) {
return strs[0].substr(0, i);
}
}
}
return strs[0].substr(0, commonLen);
} | 29.65625 | 86 | 0.561644 | [
"vector"
] |
727e22f137fa7739f3f8e507e216cb9567685a91 | 34,418 | hpp | C++ | SU2-Quantum/SU2_CFD/include/output/COutput.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/include/output/COutput.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | null | null | null | SU2-Quantum/SU2_CFD/include/output/COutput.hpp | Agony5757/SU2-Quantum | 16e7708371a597511e1242f3a7581e8c4187f5b2 | [
"Apache-2.0"
] | 1 | 2021-12-03T06:40:08.000Z | 2021-12-03T06:40:08.000Z | /*!
* \file COutput.hpp
* \brief Headers of the output class.
* \author T.Albring
* \version 7.0.6 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <fstream>
#include <cmath>
#include <map>
#include <sstream>
#include <iomanip>
#include <limits>
#include <vector>
#include "../../../Common/include/toolboxes/printing_toolbox.hpp"
#include "tools/CWindowingTools.hpp"
#include "../../../Common/include/option_structure.hpp"
class CGeometry;
class CSolver;
class CFileWriter;
class CParallelDataSorter;
class CConfig;
using namespace std;
/*!
* \class COutput
* \brief Class for writing the convergence history and to write solution data to file.
* \author T.Albring
*/
class COutput {
protected:
/*----------------------------- General ----------------------------*/
int rank, /*!< \brief MPI Rank. */
size; /*!< \brief MPI Size. */
unsigned short nDim; /*!< \brief Physical Dimension */
bool multiZone, /*!< \brief Boolean to store whether we are running a multizone problem */
gridMovement, /*!< \brief Boolean to store whether we have grid movement enabled */
femOutput; /*!< \brief Boolean to store whether we should use the FEM routines */
/*----------------------------- Screen and history output ----------------------------*/
string historySep; /*!< \brief Character which separates values in the history file */
unsigned short fieldWidth; /*!< \brief Width of each column for the screen output (hardcoded for now) */
bool noWriting; /*!< \brief Boolean indicating whether a screen/history output should be written */
unsigned long curTimeIter, /*!< \brief Current value of the time iteration index */
curAbsTimeIter, /*!< \brief Current value of the time iteration index */
curOuterIter, /*!< \brief Current value of the outer iteration index */
curInnerIter; /*!< \brief Current value of the inner iteration index */
string historyFilename; /*!< \brief The history filename*/
char char_histfile[200]; /*! \brief Temporary variable to store the history filename */
ofstream histFile; /*! \brief Output file stream for the history */
/** \brief Enum to identify the screen output format. */
enum class ScreenOutputFormat {
INTEGER, /*!< \brief Integer format. Example: 34 */
FIXED, /*!< \brief Format with fixed precision for floating point values. Example: 344.54 */
SCIENTIFIC, /*!< \brief Scientific format for floating point values. Example: 3.4454E02 */
PERCENT /*!< \brief Format with fixed precision for floating point values with a % signs. Example: 99.52% */
};
/** \brief Enum to identify the screen/history field type. */
enum class HistoryFieldType {
RESIDUAL, /*!< \brief A user-defined residual field type*/
AUTO_RESIDUAL, /*!< \brief An automatically generated residual field type */
COEFFICIENT, /*!< \brief User defined coefficient field type */
AUTO_COEFFICIENT, /*!< \brief Automatically generated coefficient field type */
DEFAULT /*!< \brief Default field type */
};
/** \brief Structure to store information for a history output field.
*
* The stored information is printed to the history file and to screen.
* Each individual instance represents a single field (i.e. column) in the history file or on screen.
*/
struct HistoryOutputField {
/*! \brief The name of the field, i.e. the name that is printed in the screen or file header.*/
string fieldName = "";
/*! \brief The value of the field. */
su2double value = 0.0;
/*! \brief The format that is used to print this value to screen. */
ScreenOutputFormat screenFormat = ScreenOutputFormat::FIXED;
/*! \brief The group this field belongs to. */
string outputGroup ="";
/*! \brief The field type*/
HistoryFieldType fieldType = HistoryFieldType::DEFAULT;
/*! \brief String containing the description of the field */
string description = "";
/*! \brief Default constructor. */
HistoryOutputField() {}
/*! \brief Constructor to initialize all members. */
HistoryOutputField(string fieldName_, ScreenOutputFormat screenFormat_, string OutputGroup_,
HistoryFieldType fieldType_, string description_):
fieldName(std::move(fieldName_)), value(0.0), screenFormat(screenFormat_),
outputGroup(std::move(OutputGroup_)), fieldType(fieldType_), description(std::move(description_)){}
};
/*! \brief Associative map to access data stored in the history output fields by a string identifier. */
std::map<string, HistoryOutputField > historyOutput_Map;
/*! \brief Vector that contains the keys of the ::historyOutput_Map in the order of their insertion. */
std::vector<string> historyOutput_List;
/*! \brief Associative map to access data stored in the history per surface output fields by a string identifier. */
std::map<string, vector<HistoryOutputField> > historyOutputPerSurface_Map;
/*! \brief Vector that contains the keys of the ::historyOutputPerSurface_Map in the order of their insertion. */
std::vector<string> historyOutputPerSurface_List;
/*! \brief Requested history field names in the config file. */
std::vector<string> requestedHistoryFields;
/*! \brief Number of requested history field names in the config file. */
unsigned short nRequestedHistoryFields;
/*! \brief Requested screen field names in the config file. */
std::vector<string> requestedScreenFields;
/*! \brief Number of requested screen field names in the config file. */
unsigned short nRequestedScreenFields;
PrintingToolbox::CTablePrinter* convergenceTable; //!< Convergence output table structure
PrintingToolbox::CTablePrinter* multiZoneHeaderTable; //!< Multizone header output structure
PrintingToolbox::CTablePrinter* historyFileTable; //!< Table structure for writing to history file
PrintingToolbox::CTablePrinter* fileWritingTable; //!< File writing header
std::string multiZoneHeaderString; //!< Multizone header string
bool headerNeeded; //!< Boolean that stores whether a screen header is needed
//! Structure to store the value of the running averages
map<string, CWindowedAverage> windowedTimeAverages;
//! Structure to store the value initial residuals for relative residual computation
std::map<string, su2double> initialResiduals;
/*----------------------------- Volume output ----------------------------*/
CParallelDataSorter* volumeDataSorter; //!< Volume data sorter
CParallelDataSorter* surfaceDataSorter; //!< Surface data sorter
vector<string> volumeFieldNames; //!< Vector containing the volume field names
unsigned short nVolumeFields; /*!< \brief Number of fields in the volume output */
string volumeFilename, //!< Volume output filename
surfaceFilename, //!< Surface output filename
restartFilename; //!< Restart output filename
/** \brief Structure to store information for a volume output field.
*
* The stored information is used to create the volume solution file.
*/
struct VolumeOutputField {
/*! \brief The name of the field, i.e. the name that is printed in the file header.*/
string fieldName;
/*! \brief This value identifies the position of the values of this field at each node in the ::Local_Data array. */
short offset;
/*! \brief The group this field belongs to. */
string outputGroup;
/*! \brief String containing the description of the field */
string description;
/*! \brief Default constructor. */
VolumeOutputField () {}
/*! \brief Constructor to initialize all members. */
VolumeOutputField(string fieldName_, int offset_, string volumeOutputGroup_, string description_):
fieldName(std::move(fieldName_)), offset(std::move(offset_)),
outputGroup(std::move(volumeOutputGroup_)), description(std::move(description_)){}
};
/*! \brief Associative map to access data stored in the volume output fields by a string identifier. */
std::map<string, VolumeOutputField > volumeOutput_Map;
/*! \brief Vector that contains the keys of the ::volumeOutput_Map in the order of their insertion. */
std::vector<string> volumeOutput_List;
/*! \brief Vector to cache the positions of the field in the data array */
std::vector<short> fieldIndexCache;
/*! \brief Current value of the cache index */
unsigned short cachePosition;
/*! \brief Boolean to store whether the field index cache should be build. */
bool buildFieldIndexCache;
/*! \brief Vector to cache the positions of the field in the data array */
std::vector<short> fieldGetIndexCache;
/*! \brief Current value of the cache index */
unsigned short curGetFieldIndex;
/*! \brief Requested volume field names in the config file. */
std::vector<string> requestedVolumeFields;
/*! \brief Number of requested volume field names in the config file. */
unsigned short nRequestedVolumeFields;
/*----------------------------- Convergence monitoring ----------------------------*/
su2double cauchyValue, /*!< \brief Summed value of the convergence indicator. */
cauchyFunc; /*!< \brief Current value of the convergence indicator at one iteration. */
unsigned short Cauchy_Counter; /*!< \brief Number of elements of the Cauchy serial. */
vector<vector<su2double> > cauchySerie; /*!< \brief Complete Cauchy serial. */
unsigned long nCauchy_Elems; /*!< \brief Total number of cauchy elems to monitor */
su2double cauchyEps; /*!< \brief Defines the threshold when to stop the solver. */
su2double minLogResidual; /*!< \brief Minimum value of the residual to reach */
vector<su2double> oldFunc, /*!< \brief Old value of the coefficient. */
newFunc; /*!< \brief Current value of the coefficient. */
bool convergence; /*!< \brief To indicate if the solver has converged or not. */
su2double initResidual; /*!< \brief Initial value of the residual to evaluate the convergence level. */
vector<string> convFields; /*!< \brief Name of the field to be monitored for convergence. */
/*----------------------------- Adaptive CFL ----------------------------*/
su2double rhoResNew, /*!< New value of the residual for adaptive CFL routine. */
rhoResOld; /*!< Old value of the residual for adaptive CFL routine. */
/*----------------------------- Time Convergence monitoring ----------------------------*/
vector<string> wndConvFields; /*!< \brief Name of the field to be monitored for convergence. */
vector<vector<su2double> > WndCauchy_Serie; /*!< \brief Complete Cauchy serial. */
unsigned long nWndCauchy_Elems; /*!< \brief Total number of cauchy elems to monitor */
su2double wndCauchyEps; /*!< \brief Defines the threshold when to stop the solver. */
vector<su2double> WndOld_Func; /*!< \brief Old value of the objective function (the function which is monitored). */
vector<su2double> WndNew_Func; /*!< \brief Current value of the objective function (the function which is monitored). */
su2double WndCauchy_Func; /*!< \brief Current value of the convergence indicator at one iteration. */
su2double WndCauchy_Value; /*!< \brief Summed value of the convergence indicator. */
bool TimeConvergence; /*!< \brief To indicate, if the windowed time average of the time loop has converged*/
public:
/*----------------------------- Public member functions ----------------------------*/
/*!
* \brief Constructor of the class.
*/
COutput(CConfig *config, unsigned short nDim, bool femOutput);
/*!
* \brief Preprocess the volume output by setting the requested volume output fields.
* \param[in] config - Definition of the particular problem.
*/
void PreprocessVolumeOutput(CConfig *config);
/*!
* \brief Load the data from the solvers into the data sorters and sort it for the linear partitioning.
*
* \param[in] config - Definition of the particular problem.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver_container - The container holding all solution data.
*/
void Load_Data(CGeometry *geometry, CConfig *config, CSolver **solver_container);
/*!
* \brief Preprocess the history output by setting the history fields and opening the history file.
* \param[in] config - Definition of the particular problem.
* \param[in] wrt - If <TRUE> prepares history file for writing.
*/
void PreprocessHistoryOutput(CConfig *config, bool wrt = true);
/*!
* \brief Preprocess the history output by setting the history fields and opening the history file.
* \param[in] output - Container holding the output instances per zone.
* \param[in] config - Definition of the particular problem per zone.
* \param[in] wrt - If <TRUE> prepares history file for writing.
*/
void PreprocessMultizoneHistoryOutput(COutput **output, CConfig **config, CConfig *driver_config, bool wrt = true);
/*!
* \brief Collects history data from the solvers, monitors the convergence and writes to screen and history file.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver_container - Container vector with all the solutions.
* \param[in] config - Definition of the particular problem.
* \param[in] TimeIter - Value of the time iteration index
* \param[in] OuterIter - Value of outer iteration index
* \param[in] InnerIter - Value of the inner iteration index
*/
void SetHistory_Output(CGeometry *geometry, CSolver **solver_container, CConfig *config,
unsigned long TimeIter, unsigned long OuterIter, unsigned long InnerIter);
/*!
* \brief Collects history data from the solvers and monitors the convergence. Does not write to screen or file.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver_container - Container vector with all the solutions.
* \param[in] config - Definition of the particular problem.
*/
void SetHistory_Output(CGeometry *geometry, CSolver **solver_container, CConfig *config);
/*!
* Collects history data from the individual output per zone,
* monitors the convergence and writes to screen and history file.
* \param[in] output - Container holding the output instances per zone.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] config - Definition of the particular problem per zone.
* \param[in] driver_config - Base definition of the particular problem.
* \param[in] TimeIter - Value of the time iteration index
* \param[in] OuterIter - Value of outer iteration index
*/
void SetMultizoneHistory_Output(COutput** output, CConfig **config, CConfig *driver_config,
unsigned long TimeIter, unsigned long OuterIter);
/*!
* \brief Sets the volume output filename
* \param[in] filename - the new filename
*/
inline void SetVolume_Filename(string filename) {volumeFilename = filename;}
/*!
* \brief Sets the surface output filename
* \param[in] filename - the new filename
*/
inline void SetSurface_Filename(string filename) {surfaceFilename = filename;}
/*!
* \brief Returns the current volume filename
* \return - The current volume filename
*/
inline string GetVolume_Filename() {return volumeFilename;}
/*!
* \brief Returns the current surface filename
* \return - The current surface filename
*/
inline string GetSurface_Filename() {return surfaceFilename;}
/*!
* \brief Sets the restart filename
* \param[in] filename - the new filename
*/
inline void SetRestart_Filename(string filename) {restartFilename = filename;}
/*!
* \brief Returns the current restart filename
* \return - The current restart filename
*/
inline string GetRestart_Filename() {return restartFilename;}
/*!
* \brief Set the current iteration indices
* \param[in] TimeIter - Timer iteration index
* \param[in] OuterIter - Outer iteration index
* \param[in] InnerIter - Inner iteration index
*/
inline void SetIteration(unsigned long TimeIter, unsigned long OuterIter, unsigned long InnerIter){
curTimeIter = TimeIter;
curOuterIter = OuterIter;
curInnerIter = InnerIter;
}
/*!
* \brief Get the value of particular history output field
* \param[in] field - Name of the field
* \return Value of the field
*/
su2double GetHistoryFieldValue(string field){
return historyOutput_Map.at(field).value;
}
su2double GetHistoryFieldValuePerSurface(string field, unsigned short iMarker){
return historyOutputPerSurface_Map.at(field)[iMarker].value;
}
/*!
* \brief Get a vector with all output fields in a particular group
* \param groupname - Name of the history group
* \return Vector containing all output fields of a group
*/
vector<HistoryOutputField> GetHistoryGroup(string groupname){
vector<HistoryOutputField> HistoryGroup;
for (unsigned short iField = 0; iField < historyOutput_Map.size(); iField++){
if (historyOutput_Map.at(historyOutput_List[iField]).outputGroup == groupname){
HistoryGroup.push_back((historyOutput_Map[historyOutput_List[iField]]));
}
}
return HistoryGroup;
}
/*!
* \brief Get the list of all output fields
* \return Vector container all output fields
*/
vector<string> GetHistoryOutput_List(){
return historyOutput_List;
}
/*!
* \brief Get the map containing all output fields
* \return Map containing all output fields
*/
map<string, HistoryOutputField> GetHistoryFields(){
return historyOutput_Map;
}
/*!
* \brief Monitor the convergence of an output field
* \param[in] config - Definition of the particular problem.
* \param[in] Iteration - Index of the current iteration.
* \return Boolean indicating whether the problem is converged.
*/
bool Convergence_Monitoring(CConfig *config, unsigned long Iteration);
/*!
* \brief Print a summary of the convergence to screen.
*/
void PrintConvergenceSummary();
/*!
* \brief Get convergence of the problem.
* \return Boolean indicating whether the problem is converged.
*/
bool GetConvergence() const {return convergence;}
/*!
* \brief Monitor the time convergence of the specified windowed-time-averaged ouput
* \param[in] config - Definition of the particular problem.
* \param[in] Iteration - Index of the current iteration.
* \return Boolean indicating whether the problem is converged.
*/
bool MonitorTimeConvergence(CConfig *config, unsigned long Iteration);
/*!
* \brief Get convergence time convergence of the specified windowed-time-averaged ouput of the problem.
* \return Boolean indicating whether the problem is converged.
*/
bool GetTimeConvergence()const {return TimeConvergence;} /*! \brief Indicates, if the time loop is converged. COnvergence criterion: Windowed time average */
/*!
* \brief Set the value of the convergence flag.
* \param[in] conv - New value of the convergence flag.
*/
void SetConvergence(bool conv) {convergence = conv;}
/*!
* \brief Print a list of all history output fields to screen.
*/
void PrintHistoryFields();
/*!
* \brief Print a list of all volume output fields to screen.
*/
void PrintVolumeFields();
/*!
* \brief Loop through all requested output files and write the volume output data.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] config - Definition of the particular problem.
* \param[in] solver_container - Container vector with all the solutions.
* \param[in] iter - The current time, outer or inner iteration index.
* \param[in] force_writing - If <TRUE>, writing of output files is forced without checking the output frequency.
* \return <TRUE> if output files have been written to disk.
*/
bool SetResult_Files(CGeometry *geometry, CConfig *config, CSolver** solver_container,
unsigned long iter, bool force_writing = false);
/*!
* \brief Allocates the appropriate file writer based on the chosen format and writes sorted data to file.
* \param[in] config - Definition of the particular problem.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] format - The output format.
* \param[in] fileName - The file name. If empty, the filenames are automatically determined.
*/
void WriteToFile(CConfig *config, CGeometry *geomery, unsigned short format, string fileName = "");
protected:
/*----------------------------- Protected member functions ----------------------------*/
/*!
* \brief Set the history file header
* \param[in] config - Definition of the particular problem.
*/
void SetHistoryFile_Header(CConfig *config);
/*!
* \brief Write the history file output
* \param[in] config - Definition of the particular problem.
*/
void SetHistoryFile_Output(CConfig *config);
/*!
* \brief Write the screen header.
* \param[in] config - Definition of the particular problem.
*/
void SetScreen_Header(CConfig *config);
/*!
* \brief Write the screen output.
* \param[in] config - Definition of the particular problem.
*/
void SetScreen_Output(CConfig *config);
/*!
* \brief Add a new field to the history output.
* \param[in] name - Name for referencing it (in the config file and in the code).
* \param[in] field_name - Header that is printed on screen and in the history file.
* \param[in] format - The screen printing format (::ScreenOutputFormat).
* \param[in] groupname - The name of the group this field belongs to.
* \param[in] description - A description of the field.
* \param[in] field_type - The type of the field (::HistoryFieldType).
*/
inline void AddHistoryOutput(string name, string field_name, ScreenOutputFormat format,
string groupname, string description,
HistoryFieldType field_type = HistoryFieldType::DEFAULT ){
historyOutput_Map[name] = HistoryOutputField(field_name, format, groupname, field_type, description);
historyOutput_List.push_back(name);
}
/*!
* \brief Set the value of a history output field
* \param[in] name - Name of the field.
* \param[in] value - The new value of this field.
*/
inline void SetHistoryOutputValue(string name, su2double value){
if (historyOutput_Map.count(name) > 0){
historyOutput_Map[name].value = value;
} else {
SU2_MPI::Error(string("Cannot find output field with name ") + name, CURRENT_FUNCTION);
}
}
/*!
* \brief Add a new field per surface marker to the history output.
* \param[in] name - Name for referencing it (in the config file and in the code).
* \param[in] field_name - Header that is printed on screen and in the history file.
* \param[in] format - The screen printing format (::ScreenOutputFormat).
* \param[in] groupname - The name of the group this field belongs to.
* \param[in] marker_names - A list of markers. For every marker in this list a new field is created with "field_name + _marker_names[i]".
* \param[in] field_type - The type of the field (::HistoryFieldType).
*/
inline void AddHistoryOutputPerSurface(string name, string field_name, ScreenOutputFormat format,
string groupname, vector<string> marker_names,
HistoryFieldType field_type = HistoryFieldType::DEFAULT){
if (marker_names.size() != 0){
historyOutputPerSurface_List.push_back(name);
for (unsigned short i = 0; i < marker_names.size(); i++){
historyOutputPerSurface_Map[name].push_back(HistoryOutputField(field_name+"("+marker_names[i]+")", format, groupname, field_type, ""));
}
}
}
/*!
* \brief Set the value of a history output field for a specific surface marker
* \param[in] name - Name of the field.
* \param[in] value - The new value of this field.
* \param[in] iMarker - The index of the marker.
*/
inline void SetHistoryOutputPerSurfaceValue(string name, su2double value, unsigned short iMarker){
if (historyOutputPerSurface_Map.count(name) > 0){
historyOutputPerSurface_Map[name][iMarker].value = value;
} else {
SU2_MPI::Error(string("Cannot find output field with name ") + name, CURRENT_FUNCTION);
}
}
/*!
* \brief Add a new field to the volume output.
* \param[in] name - Name for referencing it (in the config file and in the code).
* \param[in] field_name - Header that is printed in the output files.
* \param[in] groupname - The name of the group this field belongs to.
* \param[in] description - Description of the volume field.
*/
inline void AddVolumeOutput(string name, string field_name, string groupname, string description){
volumeOutput_Map[name] = VolumeOutputField(field_name, -1, groupname, description);
volumeOutput_List.push_back(name);
}
/*!
* \brief Set the value of a volume output field
* \param[in] name - Name of the field.
* \param[in] value - The new value of this field.
*/
su2double GetVolumeOutputValue(string name, unsigned long iPoint);
/*!
* \brief Set the value of a volume output field
* \param[in] name - Name of the field.
* \param[in] value - The new value of this field.
*/
void SetVolumeOutputValue(string name, unsigned long iPoint, su2double value);
/*!
* \brief Set the value of a volume output field
* \param[in] name - Name of the field.
* \param[in] value - The new value of this field.
*/
void SetAvgVolumeOutputValue(string name, unsigned long iPoint, su2double value);
/*!
* \brief CheckHistoryOutput
*/
void CheckHistoryOutput();
/*!
* \brief Open the history file and write the header.
* \param[in] config - Definition of the particular problem.
*/
void PrepareHistoryFile(CConfig *config);
/*!
* \brief Load up the values of the requested volume fields into ::Local_Data array.
* \param[in] config - Definition of the particular problem.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver_container - The container holding all solution data.
*/
void LoadDataIntoSorter(CConfig* config, CGeometry* geometry, CSolver** solver);
/*!
* \brief Postprocess_HistoryData
* \param[in] config - Definition of the particular problem.
*/
void Postprocess_HistoryData(CConfig *config);
/*!
* \brief Postprocess_HistoryFields
* \param[in] config - Definition of the particular problem.
*/
void Postprocess_HistoryFields(CConfig *config);
/*!
* \brief Check whether we should print output.
* \param[in] iIter - Current iteration.
* \param[in] iFreq - Frequency of output printing.
*/
inline bool PrintOutput(unsigned long iIter, unsigned long iFreq) {
if (iFreq == 0){
return false;
}
return (iIter % iFreq == 0);
}
/*!
* \brief Set the history fields common for all solvers.
* \param[in] config - Definition of the particular problem.
*/
void SetCommonHistoryFields(CConfig *config);
/*!
* \brief Load values of the history fields common for all solvers.
* \param[in] config - Definition of the particular problem.
*/
void LoadCommonHistoryData(CConfig *config);
/*!
* \brief Allocates the data sorters if necessary.
* \param[in] config - Definition of the particular problem.
* \param[in] geometry - Geometrical definition of the problem.
*/
void AllocateDataSorters(CConfig *config, CGeometry *geometry);
/*--------------------------------- Virtual functions ---------------------------------------- */
public:
/*!
* \brief Destructor of the class.
*/
virtual ~COutput(void);
protected:
/*!
* \brief Determines if the history file output.
* \param[in] config - Definition of the particular problem.
*/
virtual bool WriteHistoryFile_Output(CConfig *config);
/*!
* \brief Determines if the screen header should be written.
* \param[in] config - Definition of the particular problem.
*/
virtual bool WriteScreen_Header(CConfig *config);
/*!
* \brief Determines if the screen header should be written.
* \param[in] config - Definition of the particular problem.
*/
virtual bool WriteScreen_Output(CConfig *config);
/*!
* \brief Determines if the the volume output should be written.
* \param[in] config - Definition of the particular problem.
* \param[in] Iter - Current iteration index.
* \param[in] force_writing - boolean that forces writing of volume output
*/
virtual bool WriteVolume_Output(CConfig *config, unsigned long Iter, bool force_writing);
/*!
* \brief Set the values of the volume output fields for a point.
* \param[in] config - Definition of the particular problem.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver - The container holding all solution data.
* \param[in] iPoint - Index of the point.
*/
inline virtual void LoadVolumeData(CConfig *config, CGeometry *geometry, CSolver **solver, unsigned long iPoint){}
/*!
* \brief Set the values of the volume output fields for a point.
* \param[in] config - Definition of the particular problem.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver - The container holding all solution data.
* \param[in] iElem - Index of the element.
* \param[in] index - Index of the value.
* \param[in] dof - Index of the local degree of freedom.
*/
inline virtual void LoadVolumeDataFEM(CConfig *config, CGeometry *geometry, CSolver **solver,
unsigned long iElem, unsigned long index, unsigned short dof){}
/*!
* \brief Check whether the base values for relative residuals should be initialized
* \param[in] config - Definition of the particular problem.
* \return <TRUE> if the residuals should be initialized.
*/
inline virtual bool SetInit_Residuals(CConfig *config) {return false;}
/*!
* \brief Check whether the averaged values should be updated
* \param[in] config - Definition of the particular problem.
* \return <TRUE> averages should be updated.
*/
inline virtual bool SetUpdate_Averages(CConfig *config){return false;}
/*!
* \brief Set the values of the volume output fields for a surface point.
* \param[in] config - Definition of the particular problem.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver - The container holding all solution data.
* \param[in] iPoint - Index of the point.
* \param[in] iMarker - Index of the surface marker.
* \param[in] iVertex - Index of the vertex on the marker.
*/
inline virtual void LoadSurfaceData(CConfig *config, CGeometry *geometry, CSolver **solver,
unsigned long iPoint, unsigned short iMarker, unsigned long iVertex){}
/*!
* \brief Set the available volume output fields
* \param[in] config - Definition of the particular problem.
*/
inline virtual void SetVolumeOutputFields(CConfig *config){}
/*!
* \brief Load the history output field values
* \param[in] config - Definition of the particular problem.
*/
inline virtual void LoadHistoryData(CConfig *config, CGeometry *geometry, CSolver **solver) {}
/*!
* \brief Load the multizone history output field values
* \param[in] output - Container holding the output instances per zone.
* \param[in] config - Definition of the particular problem.
*/
inline virtual void LoadMultizoneHistoryData(COutput **output, CConfig **config) {}
/*!
* \brief Set the available history output fields
* \param[in] config - Definition of the particular problem.
*/
inline virtual void SetHistoryOutputFields(CConfig *config) {}
/*!
* \brief Set the available multizone history output fields
* \param[in] output - Container holding the output instances per zone.
* \param[in] config - Definition of the particular problem per zone.
*/
inline virtual void SetMultizoneHistoryOutputFields(COutput **output, CConfig **config) {}
/*!
* \brief Write any additional files defined for the current solver.
* \param[in] config - Definition of the particular problem per zone.
* \param[in] geometry - Geometrical definition of the problem.
* \param[in] solver_container - The container holding all solution data.
*/
inline virtual void WriteAdditionalFiles(CConfig *config, CGeometry* geometry, CSolver** solver_container){}
/*!
* \brief Write any additional output defined for the current solver.
* \param[in] config - Definition of the particular problem per zone.
*/
inline virtual void SetAdditionalScreenOutput(CConfig *config){}
};
| 42.968789 | 159 | 0.678192 | [
"geometry",
"vector"
] |
72811fbc255282d723e3f0246466c83a814ee4dd | 11,214 | cpp | C++ | src/Sparrow/Sparrow/Implementations/RealTimeSpectroscopy/IR/IRCalculator.cpp | qcscine/sparrow | 387e56ed8da78e10d96861758c509f7c375dcf07 | [
"BSD-3-Clause"
] | 45 | 2019-06-12T20:04:00.000Z | 2022-02-28T21:43:54.000Z | src/Sparrow/Sparrow/Implementations/RealTimeSpectroscopy/IR/IRCalculator.cpp | qcscine/sparrow | 387e56ed8da78e10d96861758c509f7c375dcf07 | [
"BSD-3-Clause"
] | 12 | 2019-06-12T23:53:57.000Z | 2022-03-28T18:35:57.000Z | src/Sparrow/Sparrow/Implementations/RealTimeSpectroscopy/IR/IRCalculator.cpp | qcscine/sparrow | 387e56ed8da78e10d96861758c509f7c375dcf07 | [
"BSD-3-Clause"
] | 11 | 2019-06-22T22:52:51.000Z | 2022-03-11T16:59:59.000Z | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include "IRCalculator.h"
#include "../SpectroscopySettings.h"
#include "../Utils/Spectrum.h"
#include "IntensitiesCalculator.h"
#include <Core/Interfaces/Calculator.h>
#include <Core/Log.h>
#include <Core/ModuleManager.h>
#include <Sparrow/Implementations/RealTimeSpectroscopy/Utils/LineWidthGenerator.h>
#include <Utils/CalculatorBasics/PropertyList.h>
#include <Utils/CalculatorBasics/Results.h>
#include <Utils/GeometricDerivatives/NormalModeAnalysis.h>
#include <Utils/GeometricDerivatives/NumericalHessianCalculator.h>
#include <Utils/Geometry/AtomCollection.h>
#include <Utils/GeometryOptimization/GeometryOptimizer.h>
#include <Utils/IO/ChemicalFileFormats/XyzStreamHandler.h>
#include <Utils/Optimizer/GradientBased/Lbfgs.h>
#include <Utils/Optimizer/GradientBased/SteepestDescent.h>
#include <Utils/UniversalSettings/SettingsNames.h>
#include <chrono>
namespace Scine {
namespace Sparrow {
namespace RealTimeSpectroscopy {
IRCalculator::IRCalculator() {
settings_ = std::make_unique<IRSettings>();
}
void IRCalculator::updateState(std::shared_ptr<Core::State> state) {
if (calculator_) {
calculator_->loadState(std::move(state));
}
}
Spectrum IRCalculator::calculate(const Utils::PositionCollection& positions, int structureIndex, std::ostream& out) {
calculator_->modifyPositions(positions);
// Optimize or project after.
auto startOpt = std::chrono::system_clock::now();
if (settings_->getString(optimizationProfileOption) != "none") {
calculator_->modifyPositions(positions);
Utils::GeometryOptimizer<Utils::Bfgs> optimizer(*calculator_);
auto profile = profileFactory(optimizer.getSettings(), settings_->getString(optimizationProfileOption));
optimizer.setSettings(profile->toSettings());
// optimizer.transformCoordinates = false;
optimizer.optimize(*(calculator_->getStructure()), calculator_->getLog());
}
auto endOpt = std::chrono::system_clock::now();
out << std::chrono::duration_cast<std::chrono::milliseconds>(endOpt - startOpt).count() << " ";
auto startHes = std::chrono::system_clock::now();
Utils::Results results = calculateHessianAndDipoleGradient();
Utils::NormalModesContainer normalModesContainer;
if (settings_->getBool(projectionOption)) {
const Utils::GradientCollection& gradient = calculator_->calculate().get<Utils::Property::Gradients>().normalized();
normalModesContainer = calculateFrequencies(results.get<Utils::Property::Hessian>(), gradient);
}
else {
auto startAlign = std::chrono::system_clock::now();
normalModesContainer = calculateFrequencies(results.get<Utils::Property::Hessian>());
auto endAlign = std::chrono::system_clock::now();
calculator_->getLog().output << "Time to diagonalize Hessian: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(endAlign - startAlign).count()
<< Core::Log::nl;
}
auto w = normalModesContainer.getWaveNumbers();
Eigen::VectorXd wavenumbers = Eigen::Map<const Eigen::VectorXd>(w.data(), w.size());
Eigen::VectorXd intensities =
calculateIntensities(results.get<Utils::Property::DipoleGradient>(), normalModesContainer.getNormalModes());
std::pair<std::string, std::string> labels = {"Frequency / cm^-1", "Integral Absorption Coefficient / km mol^-1"};
Spectrum spectrum{wavenumbers, intensities, labels};
std::ofstream spectraIR("irLineSpectra" + std::to_string(structureIndex) + ".out");
std::ofstream states("irStates" + std::to_string(structureIndex) + ".out");
std::ofstream hessian("hessian" + std::to_string(structureIndex) + ".out");
states << normalModesContainer.getNormalModes() << std::endl;
hessian << *lastHessian_ << std::endl;
for (int i = 0; i < spectrum.size(); ++i)
spectraIR << spectrum.getXData(i) << " " << spectrum.getYData(i) << std::endl;
LineWidthGenerator processor(spectrum);
auto endHes = std::chrono::system_clock::now();
out << std::chrono::duration_cast<std::chrono::milliseconds>(endHes - startHes).count() << std::endl;
spectraIR.close();
states.close();
hessian.close();
return processor.generateLorentzianProfile(settings_->getDouble(resolutionOption), settings_->getDouble(fwhmOption));
}
Utils::Results IRCalculator::calculateHessianAndDipoleGradient() {
Utils::NumericalHessianCalculator hessianCalculator(*calculator_);
hessianCalculator.requiredDipoleGradient(true);
Utils::Results results;
if (settings_->getBool(partialHessianOption) && lastPositions_ && lastHessian_) {
auto startAlign = std::chrono::system_clock::now();
auto indices = Utils::Geometry::Distances::getListOfDivergingAtomsRobust(
*lastPositions_, calculator_->getPositions(), settings_->getDouble(partialHessianRMSDDeviationOption), 1e-2, 20,
calculator_->getStructure()->getElements());
auto endAlign = std::chrono::system_clock::now();
calculator_->getLog().output << "Number of diverging atoms for partial Hessian calculation: " << indices.size()
<< Core::Log::nl;
calculator_->getLog().output << "Time to align iteratively the structure: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(endAlign - startAlign).count()
<< Core::Log::nl;
startAlign = std::chrono::system_clock::now();
auto partialResults = hessianCalculator.calculate(indices);
endAlign = std::chrono::system_clock::now();
calculator_->getLog().output << "Time to calculate Hessian: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(endAlign - startAlign).count()
<< Core::Log::nl;
for (int index : indices) {
lastHessian_->middleCols(index * 3, 3) = partialResults.get<Utils::Property::Hessian>().middleCols(index * 3, 3);
// This doubles some of the work, but really any other way right now would be premature opt. Well readable
lastHessian_->middleRows(index * 3, 3) = partialResults.get<Utils::Property::Hessian>().middleRows(index * 3, 3);
lastDipoleGradient_->row(index) = partialResults.get<Utils::Property::DipoleGradient>().row(index);
}
results.set<Utils::Property::Hessian>(*lastHessian_);
results.set<Utils::Property::DipoleGradient>(*lastDipoleGradient_);
lastPositions_ = std::make_unique<Utils::PositionCollection>(calculator_->getPositions());
}
else {
results = hessianCalculator.calculate();
lastPositions_ = std::make_unique<Utils::PositionCollection>(calculator_->getPositions());
lastHessian_ = std::make_unique<Utils::HessianMatrix>(results.get<Utils::Property::Hessian>());
lastDipoleGradient_ = std::make_unique<Utils::DipoleGradient>(results.get<Utils::Property::DipoleGradient>());
}
return results;
}
Utils::NormalModesContainer IRCalculator::calculateFrequencies(const Utils::HessianMatrix& hessian,
const Utils::GradientCollection& gradients) const {
auto structure = calculator_->getStructure();
if (settings_->getBool(projectionOption)) {
// Project with gradient if not optimized
return Utils::NormalModeAnalysis::calculateOrthogonalNormalModes(hessian, structure->getElements(),
structure->getPositions(), gradients);
}
return Utils::NormalModeAnalysis::calculateNormalModes(hessian, structure->getElements(), structure->getPositions());
}
Eigen::VectorXd IRCalculator::calculateIntensities(const Utils::DipoleGradient& dipoleGradient,
const Eigen::MatrixXd& normalModes) const {
Eigen::VectorXd squaredNormalDipoleGradient = IntensitiesCalculator::transformCartesianToSquaredNormalDipoleGradient(
normalModes, dipoleGradient, Utils::Geometry::Properties::getMasses(calculator_->getStructure()->getElements()));
IntensitiesCalculator intensityCalculator;
intensityCalculator.setSquaredNormalDipoleGradient(squaredNormalDipoleGradient);
return intensityCalculator.getAdsorptionCoefficients();
}
// Utils::HessianMatrix IRCalculator::projectHessianMatrix(Utils::HessianMatrix hessian, Utils::GradientCollection
// gradient) const {
// Eigen::MatrixXd gradientMatrix = Eigen::Map<const Eigen::VectorXd>(gradient.data(), hessian.rows()) *
// Eigen::Map<const Eigen::VectorXd>(gradient.data(), hessian.rows()).transpose();
// Eigen::MatrixXd projector = Eigen::MatrixXd::Identity(hessian.rows(), hessian.cols()) - gradientMatrix;
// return projector * std::move(hessian).selfadjointView<Eigen::Lower>() * projector;
//}
const Utils::Settings& IRCalculator::settings() const {
return *settings_;
}
Utils::Settings& IRCalculator::settings() {
return *settings_;
}
void IRCalculator::initialize(const Utils::ElementTypeCollection& elements) {
auto& manager = Core::ModuleManager::getInstance();
try {
calculator_ = manager.get<Core::Calculator>(settings_->getString(Utils::SettingsNames::method));
}
catch (std::exception& e) {
throw std::runtime_error("Method " + settings_->getString(Utils::SettingsNames::method) + " not found.");
}
calculator_->setRequiredProperties(Utils::Property::Energy | Utils::Property::Gradients | Utils::Property::Hessian |
Utils::Property::DipoleGradient);
if (calculator_->settings().valueExists(Utils::SettingsNames::selfConsistenceCriterion)) {
calculator_->settings().modifyDouble(Utils::SettingsNames::selfConsistenceCriterion, 1e-9);
}
if (!settings_->getString(Utils::SettingsNames::methodParameters).empty()) {
calculator_->settings().modifyString(Utils::SettingsNames::methodParameters,
settings_->getString(Utils::SettingsNames::methodParameters));
}
Utils::PositionCollection positions = Utils::PositionCollection::Zero(elements.size(), 3);
auto structure = Utils::AtomCollection{elements, positions};
calculator_->setStructure(structure);
lastPositions_.reset(nullptr);
lastHessian_.reset(nullptr);
lastDipoleGradient_.reset(nullptr);
calculator_->getLog().output.add("cout", Core::Log::coutSink());
calculator_->getLog().warning.add("warning", Core::Log::coutSink());
calculator_->getLog().error.add("error", Core::Log::coutSink());
}
bool IRCalculator::gradientAllowsIRCalculation(const Utils::GradientCollection& gradient) const {
double gradientThreshold = settings_->getDouble("gradient_threshold");
return calculator_ && gradient.rowwise().norm().sum() < gradientThreshold;
}
void IRCalculator::modifyPositions(const Utils::PositionCollection& positions) {
if (calculator_)
calculator_->modifyPositions(positions);
}
std::unique_ptr<Utils::AtomCollection> IRCalculator::getOptimizedStructure() const {
return calculator_->getStructure();
}
} // namespace RealTimeSpectroscopy
} // namespace Sparrow
} // namespace Scine
| 49.400881 | 120 | 0.713751 | [
"geometry"
] |
7282b1e597b6219ffeb48d3605385920bdc36c1a | 1,218 | cpp | C++ | cpp/src/main/utils/Random.cpp | fbobee/Alpenglow | 5f956511017c1bee72390aaecd964c04d8ad4b45 | [
"Apache-2.0"
] | 28 | 2017-07-23T22:47:44.000Z | 2022-03-12T15:11:13.000Z | cpp/src/main/utils/Random.cpp | fbobee/Alpenglow | 5f956511017c1bee72390aaecd964c04d8ad4b45 | [
"Apache-2.0"
] | 4 | 2017-05-10T10:23:17.000Z | 2019-05-23T14:07:09.000Z | cpp/src/main/utils/Random.cpp | fbobee/Alpenglow | 5f956511017c1bee72390aaecd964c04d8ad4b45 | [
"Apache-2.0"
] | 9 | 2017-05-04T09:20:58.000Z | 2021-12-14T08:19:01.000Z | #include "Random.h"
bool Random::get_boolean(double p){
step(); return (state/(mod + 1.0) < p);
}
int Random::get_linear(int max){
step(); return sqrt(state/(mod + 1.0))*max;
}
double Random::get_linear(){
step(); return sqrt(state/(mod + 1.0));
}
int Random::get_geometric(double param, int max) {
step();
double x = state/(mod + 1.0);
return log((pow(param,max)-1)*x+1)/log(param);
}
int Random::get_arctg(double y, int max) {
return max*get_arctg(y);
}
double Random::get_arctg(double y) {
step();
double area = atan(y); //integrate from 0 to y: 1/(1+x^2)
//distribtuion fn (0:y): atan(x)/area
//distribution fn (0:1):atan(x*y)/area
//inverse: tan(x*area)/y
return tan(state/(mod + 1.0) *area)/y;
}
int Random::get_discrete(vector<double>& distribution){
//values should be non-negative sum of values of distribution should be ~=1
//probability of i is distribution[i] i<distribution.size()
//if sum!=1, the probablility of the last value is modified
double rand_val = get();
double sum = 0;
int random_index=0;
for(;random_index<(int)distribution.size()-1;random_index++){
sum+=distribution[random_index];
if (sum>rand_val) break;
}
return random_index;
}
| 27.066667 | 77 | 0.664204 | [
"vector"
] |
72845b8d70247f89e737b7011084255f68dccfcc | 3,662 | cpp | C++ | engine/src/Graphics/Text/FontManager.cpp | Husenap/Wraith | 79bdfdda77a97ee2859ea2455647b59700e22753 | [
"MIT"
] | 1 | 2021-06-27T14:46:46.000Z | 2021-06-27T14:46:46.000Z | engine/src/Graphics/Text/FontManager.cpp | Husenap/2DGE | 79bdfdda77a97ee2859ea2455647b59700e22753 | [
"MIT"
] | 19 | 2021-10-29T19:20:40.000Z | 2021-12-20T01:18:34.000Z | engine/src/Graphics/Text/FontManager.cpp | KyaZero/Wraith | 6e084f46c3c6ca1bcbedb7950d33d10b546e6454 | [
"MIT"
] | 1 | 2021-06-27T15:09:52.000Z | 2021-06-27T15:09:52.000Z | #include "FontManager.h"
#include "Graphics/ContentManager.h"
#include "Graphics/DXUtil.h"
namespace Wraith
{
FontManager::FontManager() { }
FontManager::~FontManager()
{
for (auto& [_, font] : m_Fonts)
{
font.Release();
}
if (m_FreetypeHandle)
msdfgen::deinitializeFreetype(m_FreetypeHandle);
}
bool FontManager::Init()
{
m_FreetypeHandle = msdfgen::initializeFreetype();
if (!m_FreetypeHandle)
return false;
m_DefaultFont = std::make_unique<Font>(m_FreetypeHandle);
if (!m_DefaultFont->Init("assets/engine/fonts/roboto-regular.ttf"))
return false;
m_Atlas.Create(TextureCreateInfo{
.size = { ATLAS_SIZE, ATLAS_SIZE },
.format = ImageFormat::R32G32B32A32_FLOAT,
.render_target = false,
.cpu_access = D3D11_CPU_ACCESS_WRITE,
});
SetDebugObjectName(m_Atlas.GetTexture(), "FontAtlas");
m_Packer = std::make_unique<dubu::rect_pack::Packer>(ATLAS_SIZE, ATLAS_SIZE);
return true;
}
std::optional<FontManager::GlyphData> FontManager::GetGlyph(StringID font_id, msdfgen::GlyphIndex glyph_index)
{
if (!glyph_index)
{
return std::nullopt;
}
if (auto it = m_Glyphs.find({ font_id, glyph_index.getIndex() }); it != m_Glyphs.end())
{
return it->second;
}
const auto [it, inserted] =
m_Glyphs.emplace(std::make_pair(font_id, glyph_index.getIndex()), LoadGlyph(GetFont(font_id), glyph_index));
return it->second;
}
Font::DisplayData FontManager::ShapeText(StringID font_id, std::string_view text, i32 direction)
{
return GetFont(font_id).ShapeText(text, direction);
}
f32 FontManager::GetLineHeight(StringID font_id) { return GetFont(font_id).GetLineHeight(); }
Font& FontManager::GetFont(StringID font_id)
{
if (auto it = m_Fonts.find(font_id); it == m_Fonts.end())
{
if (!LoadFont(font_id))
{
return *m_DefaultFont;
}
}
return m_Fonts[font_id];
}
bool FontManager::LoadFont(StringID font_id)
{
auto path = ContentManager::Get()->GetPath(font_id);
if (!path || !std::filesystem::exists(*path))
return false;
auto [it, inserted] = m_Fonts.emplace(font_id, m_FreetypeHandle);
if (!it->second.Init(*path))
{
m_Fonts.erase(it);
return false;
}
return true;
}
std::optional<FontManager::GlyphData> FontManager::LoadGlyph(Font& font, msdfgen::GlyphIndex glyph_index)
{
auto shape = font.LoadShape(glyph_index);
if (!shape)
return std::nullopt;
// 1px padding in atlas to avoid bleeding from other glyphs
const auto rect = m_Packer->Pack({ shape->width + 1, shape->height + 1 });
if (!rect)
return std::nullopt;
const auto glyph = font.GenerateGlyph(*shape);
if (!glyph)
return std::nullopt;
m_Atlas.Blit(glyph->bitmap.data(), rect->x, rect->y, shape->width, shape->height, glyph->stride);
const auto bounds = shape->shape.getBounds();
return GlyphData{
.uv_offset = { static_cast<f32>(rect->x) / ATLAS_SIZE, static_cast<f32>(rect->y) / ATLAS_SIZE },
.uv_scale = { static_cast<f32>(shape->width) / ATLAS_SIZE, static_cast<f32>(shape->height) / ATLAS_SIZE },
.offset = shape->offset / ATLAS_SIZE,
};
}
} // namespace Wraith | 30.773109 | 120 | 0.589842 | [
"shape"
] |
72889ed0abee1d43b1cbd67895350fc599274550 | 308 | cpp | C++ | source/pkgsrc/games/xu4/patches/patch-src_armor.cpp | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | 1 | 2021-11-20T22:46:39.000Z | 2021-11-20T22:46:39.000Z | source/pkgsrc/games/xu4/patches/patch-src_armor.cpp | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | source/pkgsrc/games/xu4/patches/patch-src_armor.cpp | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | $NetBSD: patch-src_armor.cpp,v 1.1.1.1 2012/01/08 15:52:12 wiz Exp $
Add missing header.
--- src/armor.cpp.orig 2004-05-26 03:32:52.000000000 +0000
+++ src/armor.cpp
@@ -12,6 +12,7 @@
#include "error.h"
#include "names.h"
#include "tile.h"
+#include <string.h>
using std::vector;
using std::string;
| 20.533333 | 68 | 0.659091 | [
"vector"
] |
7288f8864d898eef87baa9106806c39e1b51243c | 9,110 | cc | C++ | src/arch/runtime/message_hub.cc | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/arch/runtime/message_hub.cc | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/arch/runtime/message_hub.cc | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | // Copyright 2010-2013 RethinkDB, all rights reserved.
#include "arch/runtime/message_hub.hpp"
#include <math.h>
#include <unistd.h>
#include "config/args.hpp"
#include "arch/runtime/event_queue.hpp"
#include "arch/runtime/thread_pool.hpp"
#include "logger.hpp"
#include "random.hpp"
#include "utils.hpp"
// Set this to 1 if you would like some "unordered" messages to be unordered.
#ifndef NDEBUG
#define RDB_RELOOP_MESSAGES 0
#endif
linux_message_hub_t::linux_message_hub_t(linux_event_queue_t *queue,
linux_thread_pool_t *thread_pool,
threadnum_t current_thread)
: queue_(queue),
thread_pool_(thread_pool),
is_woken_up_(false),
current_thread_(current_thread) {
#ifndef NDEBUG
if(MESSAGE_SCHEDULER_GRANULARITY < (1 << (NUM_SCHEDULER_PRIORITIES))) {
logWRN("MESSAGE_SCHEDULER_GRANULARITY is too small to honor some of the "
"lower priorities");
}
#endif
queue_->watch_event(&event_, this);
}
linux_message_hub_t::~linux_message_hub_t() {
for (int i = 0; i < thread_pool_->n_threads; i++) {
guarantee(queues_[i].msg_local_list.empty());
}
for (int p = MESSAGE_SCHEDULER_MIN_PRIORITY;
p <= MESSAGE_SCHEDULER_MAX_PRIORITY;
++p) {
guarantee(get_priority_msg_list(p).empty());
}
guarantee(incoming_messages_.empty());
}
void linux_message_hub_t::do_store_message(threadnum_t nthread, linux_thread_message_t *msg) {
rassert(0 <= nthread.threadnum && nthread.threadnum < thread_pool_->n_threads);
queues_[nthread.threadnum].msg_local_list.push_back(msg);
}
// Collects a message for a given thread onto a local list.
void linux_message_hub_t::store_message_ordered(threadnum_t nthread,
linux_thread_message_t *msg) {
rassert(!msg->is_ordered); // Each message object can only be enqueued once,
// and once it is removed, is_ordered is reset to false.
#ifndef NDEBUG
#if RDB_RELOOP_MESSAGES
// We default to 1, not zero, to allow store_message_sometime messages to sometimes jump ahead of
// store_message messages.
msg->reloop_count_ = 1;
#else
msg->reloop_count_ = 0;
#endif
#endif // NDEBUG
msg->is_ordered = true;
do_store_message(nthread, msg);
}
int rand_reloop_count() {
int x;
frexp(randint(10000) / 10000.0, &x);
int ret = -x;
rassert(ret >= 0);
return ret;
}
void linux_message_hub_t::store_message_sometime(threadnum_t nthread, linux_thread_message_t *msg) {
#ifndef NDEBUG
#if RDB_RELOOP_MESSAGES
msg->reloop_count_ = rand_reloop_count();
#else
msg->reloop_count_ = 0;
#endif
#endif // NDEBUG
do_store_message(nthread, msg);
}
void linux_message_hub_t::insert_external_message(linux_thread_message_t *msg) {
bool do_wake_up;
{
spinlock_acq_t acq(&incoming_messages_lock_);
do_wake_up = !check_and_set_is_woken_up();
incoming_messages_.push_back(msg);
}
// Wakey wakey eggs and bakey
if (do_wake_up) {
event_.wakey_wakey();
}
}
linux_message_hub_t::msg_list_t &linux_message_hub_t::get_priority_msg_list(int priority) {
rassert(priority >= MESSAGE_SCHEDULER_MIN_PRIORITY);
rassert(priority <= MESSAGE_SCHEDULER_MAX_PRIORITY);
return priority_msg_lists_[priority - MESSAGE_SCHEDULER_MIN_PRIORITY];
}
void linux_message_hub_t::on_event(int events) {
if (events != poll_event_in) {
logERR("Unexpected event mask: %d", events);
}
// You must read wakey-wakeys so that the pipe-based implementation doesn't fill
// up and so that poll-based event triggering doesn't infinite-loop.
event_.consume_wakey_wakeys();
// Sort incoming messages into the respective priority_msg_lists_
sort_incoming_messages_by_priority();
// Compute how many messages of MESSAGE_SCHEDULER_MAX_PRIORITY we process
// before we check the incoming queues for new messages.
// We call this the granularity of the message scheduler, and it is
// MESSAGE_SCHEDULER_GRANULARITY or smaller.
size_t total_pending_msgs = 0;
for (int i = 0; i < NUM_SCHEDULER_PRIORITIES; ++i) {
total_pending_msgs += priority_msg_lists_[i].size();
}
const size_t effective_granularity = std::min(total_pending_msgs,
static_cast<size_t>(MESSAGE_SCHEDULER_GRANULARITY));
// Process a certain number of messages from each priority
for (int current_priority = MESSAGE_SCHEDULER_MAX_PRIORITY;
current_priority >= MESSAGE_SCHEDULER_MIN_PRIORITY; --current_priority) {
// Compute how many messages of `current_priority` we want to process
// in this pass.
// The priority has an exponential effect on how many messages
// get processed, i.e. if we process 8 messages of priority 1 per pass,
// we are going to process up to 16 messages of priority 2, 32 of
// priority 3 and so on.
// However, we process at least one message of each priority level per
// pass (in case the granularity is too small).
int priority_exponent = MESSAGE_SCHEDULER_MAX_PRIORITY - current_priority;
size_t to_process_from_priority =
std::max(static_cast<size_t>(1), effective_granularity >> priority_exponent);
for (linux_thread_message_t *m = get_priority_msg_list(current_priority).head();
m != nullptr && to_process_from_priority > 0;
m = get_priority_msg_list(current_priority).head()) {
get_priority_msg_list(current_priority).remove(m);
--to_process_from_priority;
#ifndef NDEBUG
if (m->reloop_count_ > 0) {
--m->reloop_count_;
do_store_message(current_thread_, m);
continue;
}
#endif
m->on_thread_switch();
}
}
// We might have left some messages unprocessed.
// Check if that is the case, and if yes, make sure we are called again.
for (int i = 0; i < NUM_SCHEDULER_PRIORITIES; ++i) {
if (!priority_msg_lists_[i].empty()) {
// Place wakey_wakey and then yield to the event processing.
// It will wake us up again immediately, but can handle a few
// OS events (such as timers, network messages etc.) in the meantime.
bool do_wake_up;
{
spinlock_acq_t acq(&incoming_messages_lock_);
do_wake_up = !check_and_set_is_woken_up();
}
if (do_wake_up) {
event_.wakey_wakey();
}
break;
}
}
}
void linux_message_hub_t::sort_incoming_messages_by_priority() {
// We do this in two steps to release the spinlock faster.
// append_and_clear is a very cheap operation, while
// assigning each message to a different priority queue
// is more expensive.
// 1. Pull the messages
msg_list_t new_messages;
{
spinlock_acq_t acq(&incoming_messages_lock_);
new_messages.append_and_clear(&incoming_messages_);
is_woken_up_ = false;
}
// 2. Sort the messages into their respective priority queues
while (linux_thread_message_t *m = new_messages.head()) {
new_messages.remove(m);
int effective_priority = m->priority;
if (m->is_ordered) {
// Ordered messages are treated as if they had
// priority MESSAGE_SCHEDULER_ORDERED_PRIORITY.
// This ensures that they can never bypass another
// ordered message.
effective_priority = MESSAGE_SCHEDULER_ORDERED_PRIORITY;
m->is_ordered = false;
}
get_priority_msg_list(effective_priority).push_back(m);
}
}
bool linux_message_hub_t::check_and_set_is_woken_up() {
const bool was_woken_up = is_woken_up_;
is_woken_up_ = true;
return was_woken_up;
}
// Pushes messages collected locally global lists available to all
// threads.
void linux_message_hub_t::push_messages() {
for (int i = 0; i < thread_pool_->n_threads; i++) {
// Append the local list for ith thread to that thread's global
// message list.
thread_queue_t *queue = &queues_[i];
if (!queue->msg_local_list.empty()) {
// Transfer messages to the other core
bool do_wake_up;
{
spinlock_acq_t acq(&thread_pool_->threads[i]->message_hub.incoming_messages_lock_);
// We only need to do a wake up if we're the first people to do a
// wake up.
do_wake_up =
!thread_pool_->threads[i]->message_hub.check_and_set_is_woken_up();
thread_pool_->threads[i]->message_hub.incoming_messages_.append_and_clear(&queue->msg_local_list);
}
// Wakey wakey, perhaps eggs and bakey
if (do_wake_up) {
thread_pool_->threads[i]->message_hub.event_.wakey_wakey();
}
}
}
}
| 35.447471 | 114 | 0.656092 | [
"object"
] |
72932cce6c73f4871466d942a8180f4dff939fb4 | 21,483 | cpp | C++ | src/DecisionEngine/Core/Components/Score.cpp | davidbrownell/DavidBrownell_DecisionEngine | f331b57f7b5ab4a5de84595f79df191fc0c13fba | [
"BSL-1.0"
] | null | null | null | src/DecisionEngine/Core/Components/Score.cpp | davidbrownell/DavidBrownell_DecisionEngine | f331b57f7b5ab4a5de84595f79df191fc0c13fba | [
"BSL-1.0"
] | null | null | null | src/DecisionEngine/Core/Components/Score.cpp | davidbrownell/DavidBrownell_DecisionEngine | f331b57f7b5ab4a5de84595f79df191fc0c13fba | [
"BSL-1.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////
///
/// \file Score.cpp
/// \brief See Score.h
///
/// \author David Brownell <db@DavidBrownell.com>
/// \date 2020-05-20 22:05:42
///
/// \note
///
/// \bug
///
/////////////////////////////////////////////////////////////////////////
///
/// \attention
/// Copyright David Brownell 2020-21
/// Distributed under the Boost Software License, Version 1.0. See
/// accompanying file LICENSE_1_0.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt.
///
/////////////////////////////////////////////////////////////////////////
#include "Score.h"
#include "Components.h"
namespace DecisionEngine {
namespace Core {
namespace Components {
namespace {
static float const constexpr GoodThreshold = MaxScore * 0.80f;
// GroupList{A|B}T will either be `Score::ResultGroup` or `Score::PendingData`
template <typename GroupLikeAT, typename GroupLikeBT>
int CompareGroups(GroupLikeAT const &a, GroupLikeBT const &b) {
if(static_cast<void const *>(&a) == static_cast<void const *>(&b))
return 0;
if(a.IsSuccessful != b.IsSuccessful)
return a.IsSuccessful == false ? -1 : 1;
if(a.NumFailures != b.NumFailures)
return a.NumFailures > b.NumFailures ? -1 : 1;
float const diff(a.AverageScore - b.AverageScore);
if(diff != 0.0f)
return diff < 0.0f ? -1 : 1;
if(a.NumResults != b.NumResults) {
// If here, we are looking at 2 groups with equal potential. If the score
// is a "good" one, the group with the higher number of matches has a high good
// potential. If the score is not a "good" score, give the group with the lower
// number of results the opportunity to get better over time.
if(a.AverageScore >= GoodThreshold)
return a.NumResults < b.NumResults ? -1 : 1;
return a.NumResults > b.NumResults ? -1 : 1;
}
return 0;
}
} // anonymous namespace
// ----------------------------------------------------------------------
// |
// | Score::Result
// |
// ----------------------------------------------------------------------
Score::Result::Result(
ConditionResults applicabilityResults,
ConditionResults requirementResults,
ConditionResults preferenceResults
) :
IsApplicable(false), // Placeholder
IsSuccessful(false), // Placeholder
Score(0.0f), // Placeholder
ApplicabilityResults(std::move(applicabilityResults)),
RequirementResults(std::move(requirementResults)),
PreferenceResults(std::move(preferenceResults))
{
// ----------------------------------------------------------------------
struct Internal {
static float CalculateScore(ConditionResults const &results) {
float score(0.0f);
unsigned long maxPossibleScore(0);
for(auto const &result : results) {
score += result.Ratio * result.Condition->MaxScore;
maxPossibleScore += result.Condition->MaxScore;
}
return maxPossibleScore != 0 ? score / static_cast<float>(maxPossibleScore) : 1.0f;
}
};
// ----------------------------------------------------------------------
make_mutable(IsApplicable) = std::all_of(ApplicabilityResults.cbegin(), ApplicabilityResults.cend(), [](Condition::Result const &cr) { return cr.IsSuccessful; });
if(IsApplicable == false) {
make_mutable(IsSuccessful) = true;
make_mutable(Score) = MaxScore;
return;
}
// The result is successful if all of the requirements are successful
make_mutable(IsSuccessful) = std::all_of(RequirementResults.cbegin(), RequirementResults.cend(), [](Condition::Result const &cr) { return cr.IsSuccessful; });
// Calculate the final score based on the requirement and preference results.
// Take special care to ensure that the preferences are never treated as more
// important than the requirements.
// The integer part of the final score is based on the requirements and the
// mantissa is based on the preferences. With this, we can enforce the rule that
// states "it is always more important to do better on the requirements than it
// it is on the preferences."
float const requirementsScore(Internal::CalculateScore(RequirementResults));
float const preferencesScore(Internal::CalculateScore(PreferenceResults));
assert(requirementsScore >= 0.0f && requirementsScore <= 1.0f);
assert(preferencesScore >= 0.0f && preferencesScore <= 1.0f);
make_mutable(Score) = requirementsScore * (MaxScore - 1) + preferencesScore;
assert(Score <= MaxScore);
}
std::string Score::Result::ToString(void) const {
return boost::str(
boost::format("Result(%d,%d,%.02f)")
% IsApplicable
% IsSuccessful
% Score
);
}
// ----------------------------------------------------------------------
// |
// | Score::ResultGroup
// |
// ----------------------------------------------------------------------
namespace {
auto ConstructResultGroupTuple(Score::ResultGroup::ResultPtrs results) {
float totalScore(0.0f);
unsigned long numResults(0);
unsigned long numFailures(0);
for(auto const &pResult : results) {
if(!pResult)
continue;
if(pResult->IsApplicable == false)
continue;
++numResults;
totalScore += pResult->Score;
if(pResult->IsSuccessful == false)
++numFailures;
}
return std::make_tuple(
std::move(results),
numFailures == 0,
numResults ? totalScore / static_cast<float>(numResults) : MaxScore,
numResults,
numFailures
);
}
} // anonymous namespace
Score::ResultGroup::ResultGroup(ResultPtrs results) :
ResultGroup(ConstructResultGroupTuple(std::move(results)))
{}
Score::ResultGroup::ResultGroup(
ResultPtrs results,
bool isSuccessful,
float averageScore,
unsigned long numResults,
unsigned long numFailures
) :
ResultGroup(std::make_tuple(std::move(results), isSuccessful, averageScore, numResults, numFailures))
{}
// static
int Score::ResultGroup::Compare(ResultGroup const &a, ResultGroup const &b) {
return CompareGroups(a, b);
}
bool Score::ResultGroup::operator==(ResultGroup const &other) const {
return Compare(*this, other) == 0;
}
bool Score::ResultGroup::operator!=(ResultGroup const &other) const {
return Compare(*this, other) != 0;
}
bool Score::ResultGroup::operator <(ResultGroup const &other) const {
return Compare(*this, other) < 0;
}
bool Score::ResultGroup::operator<=(ResultGroup const &other) const {
return Compare(*this, other) <= 0;
}
bool Score::ResultGroup::operator >(ResultGroup const &other) const {
return Compare(*this, other) > 0;
}
bool Score::ResultGroup::operator>=(ResultGroup const &other) const {
return Compare(*this, other) >= 0;
}
std::string Score::ResultGroup::ToString(void) const {
return boost::str(
boost::format("ResultGroup(%d,%.02f,%d,%d,%d)")
% IsSuccessful
% AverageScore
% NumResults
% NumFailures
% Results.size()
);
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
Score::ResultGroup::ResultGroup(std::tuple<ResultPtrs, bool, float, unsigned long, unsigned long> args) :
IsSuccessful(std::move(std::get<1>(args))),
AverageScore(
std::move(
[&args](void) -> float & {
float & score(std::get<2>(args));
ENSURE_ARGUMENT(score, score >= 0.0f && score <= MaxScore);
return score;
}()
)
),
NumResults(std::move(std::get<3>(args))),
NumFailures(std::move(std::get<4>(args))),
Results(
std::move(
[&args](void) -> ResultPtrs & {
ResultPtrs & results(std::get<0>(args));
ENSURE_ARGUMENT(results, results.empty() == false);
ENSURE_ARGUMENT(results, std::all_of(results.cbegin(), results.cend(), [](ResultPtr const &ptr) { return static_cast<bool>(ptr); }));
return results;
}()
)
)
{}
// ----------------------------------------------------------------------
// |
// | Score::PendingData
// |
// ----------------------------------------------------------------------
Score::PendingData::PendingData(ResultPtrs const *pOptionalResults, Result const *pOptionalResult) :
IsSuccessful(false), // Placeholder
AverageScore(0.0f), // Placeholder
NumResults(0), // Placeholder
NumFailures(0) // Placeholder
{
assert(pOptionalResults == nullptr || (pOptionalResults->empty() == false && std::all_of(pOptionalResults->cbegin(), pOptionalResults->cend(), [](ResultPtr const &ptr) { return static_cast<bool>(ptr); })));
float totalScore(0.0f);
unsigned long numResults(0);
unsigned long numFailures(0);
auto const processResultsFunc(
[&totalScore, &numResults, &numFailures](Result const &r) {
if(r.IsApplicable == false)
return;
++numResults;
if(r.IsSuccessful == false)
++numFailures;
totalScore += r.Score;
}
);
if(pOptionalResults) {
for(auto const &ptr : *pOptionalResults) {
processResultsFunc(*ptr);
}
}
if(pOptionalResult)
processResultsFunc(*pOptionalResult);
float averageScore(numResults ? totalScore / static_cast<float>(numResults) : MaxScore);
assert(averageScore >= 0.0f && averageScore <= MaxScore);
make_mutable(IsSuccessful) = numFailures == 0;
make_mutable(AverageScore) = std::move(averageScore);
make_mutable(NumResults) = std::move(numResults);
make_mutable(NumFailures) = std::move(numFailures);
}
std::string Score::PendingData::ToString(void) const {
return boost::str(
boost::format("Pending(%d,%.02f,%d,%d)")
% IsSuccessful
% AverageScore
% NumResults
% NumFailures
);
}
// ----------------------------------------------------------------------
// |
// | Score::SuffixInfo
// |
// ----------------------------------------------------------------------
Score::SuffixInfo::SuffixInfo(Result result, bool completesGroup) :
_result(std::move(result)),
_isMoved(false),
CompletesGroup(std::move(completesGroup))
{}
Score::Result Score::SuffixInfo::Move(void) {
if(_isMoved)
throw std::logic_error("invalid operation");
Result result(std::move(_result));
_isMoved = true;
return result;
}
Score::Result const & Score::SuffixInfo::GetResult(void) const {
if(_isMoved)
throw std::logic_error("invalid operation");
return _result;
}
std::string Score::SuffixInfo::ToString(void) const {
return boost::str(
boost::format("Suffix(%s,%d)")
% _result.ToString()
% CompletesGroup
);
}
// ----------------------------------------------------------------------
// |
// | Score
// |
// ----------------------------------------------------------------------
Score::Score(void) :
Score(
ResultGroupPtrsPtr(),
ResultPtrsPtr(),
std::unique_ptr<SuffixInfo>()
)
{}
Score::Score(Result suffix, bool completesGroup) :
Score(
ResultGroupPtrsPtr(),
ResultPtrsPtr(),
std::make_unique<SuffixInfo>(std::move(suffix), completesGroup)
)
{}
Score::Score(Condition::Result suffix, bool completesGroup) :
Score(
Result(
Score::Result::ConditionResults(),
CommonHelpers::Stl::CreateVector<Condition::Result>(std::move(suffix)),
Score::Result::ConditionResults()
),
completesGroup
)
{}
Score::Score(Score const &score, Result suffix, bool completesGroup) :
Score(
score._pResultGroups,
score._pResults,
std::make_unique<SuffixInfo>(std::move(suffix), completesGroup)
)
{
ENSURE_ARGUMENT(score, score.HasSuffix() == false);
}
Score::Score(Score const &score, Condition::Result suffix, bool completesGroup) :
Score(
score,
Result(
Score::Result::ConditionResults(),
CommonHelpers::Stl::CreateVector<Condition::Result>(std::move(suffix)),
Score::Result::ConditionResults()
),
completesGroup
)
{
ENSURE_ARGUMENT(score, score.HasSuffix() == false);
}
// static
int Score::Compare(Score const &a, Score const &b) {
if(static_cast<void const *>(&a) == static_cast<void const *>(&b))
return 0;
if(a.IsSuccessful != b.IsSuccessful)
return a.IsSuccessful == false ? -1 : 1;
ResultGroupPtrs::const_iterator pThisGroupPtr;
ResultGroupPtrs::const_iterator pThisGroupEnd;
ResultGroupPtrs::const_iterator pThatGroupPtr;
ResultGroupPtrs::const_iterator pThatGroupEnd;
if(a._pResultGroups) {
pThisGroupPtr = a._pResultGroups->cbegin();
pThisGroupEnd = a._pResultGroups->cend();
}
if(b._pResultGroups) {
pThatGroupPtr = b._pResultGroups->cbegin();
pThatGroupEnd = b._pResultGroups->cend();
}
while(pThisGroupPtr != pThisGroupEnd && pThatGroupPtr != pThatGroupEnd) {
int const result(CompareGroups(**pThisGroupPtr, **pThatGroupPtr));
if(result != 0)
return result;
++pThisGroupPtr;
++pThatGroupPtr;
}
if(pThisGroupPtr != pThisGroupEnd) {
int const result(CompareGroups(**pThisGroupPtr, b._pendingData));
if(result != 0)
return result;
++pThisGroupPtr;
bool const isThisSuccessful(pThisGroupPtr != pThisGroupEnd ? (*pThisGroupPtr)->IsSuccessful : a._pendingData.IsSuccessful);
return isThisSuccessful == false ? -1 : 1;
}
if(pThatGroupPtr != pThatGroupEnd) {
int const result(CompareGroups(a._pendingData, **pThatGroupPtr));
if(result != 0)
return result;
++pThatGroupPtr;
bool const isThatSuccessful(pThatGroupPtr != pThatGroupEnd ? (*pThatGroupPtr)->IsSuccessful : b._pendingData.IsSuccessful);
return isThatSuccessful ? -1 : 1;
}
assert(pThisGroupPtr == pThisGroupEnd);
assert(pThatGroupPtr == pThatGroupEnd);
return CompareGroups(a._pendingData, b._pendingData);
}
bool Score::operator==(Score const &other) const {
return Compare(*this, other) == 0;
}
bool Score::operator!=(Score const &other) const {
return Compare(*this, other) != 0;
}
bool Score::operator <(Score const &other) const {
return Compare(*this, other) < 0;
}
bool Score::operator<=(Score const &other) const {
return Compare(*this, other) <= 0;
}
bool Score::operator >(Score const &other) const {
return Compare(*this, other) > 0;
}
bool Score::operator>=(Score const &other) const {
return Compare(*this, other) >= 0;
}
std::string Score::ToString(void) const /*override*/ {
std::vector<std::string> strings;
if(_pResultGroups) {
std::vector<std::string> resultGroups;
for(ResultGroupPtr const &pResultGroup : *_pResultGroups)
resultGroups.emplace_back(pResultGroup->ToString());
strings.emplace_back(
boost::str(
boost::format("[%1%]") % boost::algorithm::join(resultGroups, ",")
)
);
}
if(_pResults) {
std::vector<std::string> results;
for(ResultPtr const &pResult : *_pResults)
results.emplace_back(pResult->ToString());
strings.emplace_back(
boost::str(
boost::format("[%1%]") % boost::algorithm::join(results, ",")
)
);
}
if(_suffix)
strings.emplace_back(_suffix->ToString());
strings.emplace_back(_pendingData.ToString());
return boost::str(
boost::format("Score(%1%)") % boost::algorithm::join(strings, ",")
);
}
bool Score::HasSuffix(void) const {
return static_cast<bool>(_suffix);
}
// This method should only be called when the object was created with a suffix
Score Score::Commit(void) {
if(HasSuffix() == false)
throw std::logic_error("Invalid operation");
ResultPtrs results;
if(_pResults) {
results.reserve(_pResults->size() + 1);
std::copy(_pResults->cbegin(), _pResults->cend(), std::back_inserter(results));
}
results.emplace_back(std::make_shared<Result>(_suffix->Move()));
if(_suffix->CompletesGroup == false)
return Score(_pResultGroups, std::make_shared<ResultPtrs>(std::move(results)));
ResultGroupPtrs groups;
if(_pResultGroups) {
groups.reserve(_pResultGroups->size() + 1);
std::copy(_pResultGroups->cbegin(), _pResultGroups->cend(), std::back_inserter(groups));
}
groups.emplace_back(
std::make_shared<ResultGroup>(
std::move(results),
_pendingData.IsSuccessful,
_pendingData.AverageScore,
_pendingData.NumResults,
_pendingData.NumFailures
)
);
return Score(std::make_shared<ResultGroupPtrs>(std::move(groups)));
}
// This method should only be called when the object was created without a suffix
Score Score::Copy(void) const {
if(HasSuffix())
throw std::logic_error("Invalid operation");
if(_pResults)
return Score(_pResultGroups, _pResults);
if(_pResultGroups)
return Score(_pResultGroups);
return Score();
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
Score::Score(ResultGroupPtrsPtr pResultGroups) :
Score(
std::move(
[&pResultGroups](void) -> ResultGroupPtrsPtr & {
assert(pResultGroups && pResultGroups->empty() == false && std::all_of(pResultGroups->cbegin(), pResultGroups->cend(), [](ResultGroupPtr const &ptr) { return static_cast<bool>(ptr); }));
return pResultGroups;
}()
),
ResultPtrsPtr(),
std::unique_ptr<SuffixInfo>()
)
{}
Score::Score(ResultGroupPtrsPtr pResultGroups, ResultPtrsPtr pResults) :
Score(
std::move(pResultGroups),
std::move(
[&pResults](void) -> ResultPtrsPtr & {
assert(pResults && pResults->empty() == false && std::all_of(pResults->cbegin(), pResults->cend(), [](ResultPtr const &ptr) { return static_cast<bool>(ptr); }));
return pResults;
}()
),
std::unique_ptr<SuffixInfo>()
)
{}
Score::Score(ResultGroupPtrsPtr pResultGroups, ResultPtrsPtr pResults, std::unique_ptr<SuffixInfo> suffix) :
IsSuccessful(false), // Placeholder
_pResultGroups(std::move(pResultGroups)),
_pResults(std::move(pResults)),
_suffix(std::move(suffix)),
_pendingData(
_pResults.get(),
_suffix ? &_suffix->GetResult() : nullptr
)
{
make_mutable(IsSuccessful) =
[this](void) {
if(_pResultGroups) {
if(std::all_of(_pResultGroups->cbegin(), _pResultGroups->cend(), [](ResultGroupPtr const &pGroup) { return pGroup->IsSuccessful; }) == false)
return false;
}
if(_pResults) {
if(std::all_of(_pResults->cbegin(), _pResults->cend(), [](ResultPtr const &ptr) { return ptr->IsApplicable == false || ptr->IsSuccessful; }) == false)
return false;
}
if(_suffix) {
Result const & result(_suffix->GetResult());
if(result.IsApplicable && result.IsSuccessful == false)
return false;
}
return true;
}();
}
} // namespace Components
} // namespace Core
} // namespace DecisionEngine
| 32.55 | 211 | 0.538752 | [
"object",
"vector"
] |
72967e8b4c0ad4b04ff7007a4d49e754aaeff729 | 7,444 | cpp | C++ | storage/src/tests/bucketdb/judyarraytest.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-06-02T13:28:29.000Z | 2020-06-02T13:28:29.000Z | storage/src/tests/bucketdb/judyarraytest.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2021-03-31T22:24:20.000Z | 2021-03-31T22:24:20.000Z | storage/src/tests/bucketdb/judyarraytest.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-09-03T11:39:52.000Z | 2020-09-03T11:39:52.000Z | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/storage/bucketdb/judyarray.h>
#include <boost/random.hpp>
#include <vespa/vespalib/gtest/gtest.h>
#include <gmock/gmock.h>
#include <map>
#include <vector>
using namespace ::testing;
namespace storage {
namespace {
std::vector<std::pair<JudyArray::key_type, JudyArray::data_type>>
getJudyArrayContents(const JudyArray& array) {
std::vector<std::pair<JudyArray::key_type, JudyArray::data_type>> vals;
for (JudyArray::const_iterator it = array.begin();
it != array.end(); ++it)
{
vals.push_back(std::make_pair(it.key(), it.value()));
}
return vals;
}
}
TEST(JudyArrayTest, iterating) {
JudyArray array;
// Test that things are sane for empty document
ASSERT_EQ(array.begin(), array.end());
// Add some values
std::vector<std::pair<JudyArray::key_type, JudyArray::data_type>> values({
{3, 2}, {5, 12}, {15, 8}, {13, 10}, {7, 6}, {9, 4}
});
for (uint32_t i=0; i<values.size(); ++i) {
array.insert(values[i].first, values[i].second);
}
// Create expected result
std::sort(values.begin(), values.end());
// Test that we can iterate through const iterator
auto foundVals = getJudyArrayContents(array);
ASSERT_EQ(values, foundVals);
{ // Test that we can alter through non-const iterator
JudyArray::iterator it = array.begin();
++it;
++it;
it.setValue(20);
ASSERT_EQ((JudyArray::key_type) 7, it.key());
ASSERT_EQ((JudyArray::data_type) 20, array[7]);
it.remove();
ASSERT_EQ((JudyArray::size_type) 5, getJudyArrayContents(array).size());
ASSERT_EQ(array.end(), array.find(7));
values.erase(values.begin() + 2);
ASSERT_EQ(values, getJudyArrayContents(array));
// And that we can continue iterating after removing.
++it;
ASSERT_EQ((JudyArray::key_type) 9, it.key());
ASSERT_EQ((JudyArray::data_type) 4, array[9]);
}
{ // Test printing of iterators
JudyArray::ConstIterator cit = array.begin();
EXPECT_THAT(cit.toString(), MatchesRegex("^ConstIterator\\(Key: 3, Valp: 0x[0-9a-f]{1,16}, Val: 2\\)$"));
JudyArray::Iterator it = array.end();
EXPECT_THAT(it.toString(), MatchesRegex("^Iterator\\(Key: 0, Valp: (0x)?0\\)$"));
}
}
TEST(JudyArrayTest, dual_array_functions) {
JudyArray array1;
JudyArray array2;
// Add values to array1
std::vector<std::pair<JudyArray::key_type, JudyArray::data_type>> values1({
{3, 2}, {5, 12}, {15, 8}, {13, 10}, {7, 6}, {9, 4}
});
for (uint32_t i=0; i<values1.size(); ++i) {
array1.insert(values1[i].first, values1[i].second);
}
// Add values to array2
std::vector<std::pair<JudyArray::key_type, JudyArray::data_type>> values2({
{4, 5}, {9, 40}
});
for (uint32_t i=0; i<values2.size(); ++i) {
array2.insert(values2[i].first, values2[i].second);
}
// Create expected result
std::sort(values1.begin(), values1.end());
std::sort(values2.begin(), values2.end());
EXPECT_EQ(values1, getJudyArrayContents(array1));
EXPECT_EQ(values2, getJudyArrayContents(array2));
EXPECT_LT(array2, array1);
EXPECT_NE(array1, array2);
array1.swap(array2);
EXPECT_EQ(values1, getJudyArrayContents(array2));
EXPECT_EQ(values2, getJudyArrayContents(array1));
EXPECT_LT(array1, array2);
EXPECT_NE(array1, array2);
// Test some operators
JudyArray array3;
for (uint32_t i=0; i<values1.size(); ++i) {
array3.insert(values1[i].first, values1[i].second);
}
EXPECT_NE(array1, array3);
EXPECT_EQ(array2, array3);
EXPECT_FALSE(array2 < array3);
}
TEST(JudyArrayTest, size) {
JudyArray array;
EXPECT_EQ(array.begin(), array.end());
EXPECT_TRUE(array.empty());
EXPECT_EQ((JudyArray::size_type) 0, array.size());
EXPECT_EQ((JudyArray::size_type) 0, array.getMemoryUsage());
// Test each method one can insert stuff into array
array.insert(4, 3);
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
array.insert(4, 7);
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
EXPECT_EQ((JudyArray::size_type) 24, array.getMemoryUsage());
array[6] = 8;
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
array[6] = 10;
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
EXPECT_EQ((JudyArray::size_type) 40, array.getMemoryUsage());
bool preExisted;
array.find(8, true, preExisted);
EXPECT_EQ(false, preExisted);
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
array.find(8, true, preExisted);
EXPECT_EQ(true, preExisted);
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
EXPECT_EQ((JudyArray::size_type) 3, array.size());
EXPECT_EQ((JudyArray::size_type) 56, array.getMemoryUsage());
// Test each method one can remove stuff in array with
array.erase(8);
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
array.erase(8);
EXPECT_EQ(getJudyArrayContents(array).size(), array.size());
EXPECT_EQ((JudyArray::size_type) 2, array.size());
EXPECT_EQ((JudyArray::size_type) 40, array.getMemoryUsage());
}
TEST(JudyArrayTest, stress) {
// Do a lot of random stuff to both judy array and std::map. Ensure equal
// behaviour
JudyArray judyArray;
typedef std::map<JudyArray::key_type, JudyArray::data_type> StdMap;
StdMap stdMap;
boost::rand48 rnd(55);
for (uint32_t checkpoint=0; checkpoint<50; ++checkpoint) {
for (uint32_t opnr=0; opnr<500; ++opnr) {
int optype = rnd() % 100;
if (optype < 30) { // Insert
JudyArray::key_type key(rnd() % 500);
JudyArray::key_type value(rnd());
judyArray.insert(key, value);
stdMap[key] = value;
} else if (optype < 50) { // operator[]
JudyArray::key_type key(rnd() % 500);
JudyArray::key_type value(rnd());
judyArray[key] = value;
stdMap[key] = value;
} else if (optype < 70) { // erase()
JudyArray::key_type key(rnd() % 500);
EXPECT_EQ(stdMap.erase(key), judyArray.erase(key));
} else if (optype < 75) { // size()
EXPECT_EQ(stdMap.size(), judyArray.size());
} else if (optype < 78) { // empty()
EXPECT_EQ(stdMap.empty(), judyArray.empty());
} else { // find()
JudyArray::key_type key(rnd() % 500);
auto it = judyArray.find(key);
auto it2 = stdMap.find(key);
EXPECT_EQ(it2 == stdMap.end(), it == judyArray.end());
if (it != judyArray.end()) {
EXPECT_EQ(it.key(), it2->first);
EXPECT_EQ(it.value(), it2->second);
}
}
}
// Ensure judy array contents is equal to std::map's at this point
StdMap tmpMap;
for (JudyArray::const_iterator it = judyArray.begin();
it != judyArray.end(); ++it)
{
tmpMap[it.key()] = it.value();
}
EXPECT_EQ(stdMap, tmpMap);
}
}
} // storage
| 36.851485 | 118 | 0.602096 | [
"vector"
] |
72969ff97cc4c61bec054bb2466a72ad15812b43 | 7,576 | cc | C++ | src/api/assets/pngw.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | src/api/assets/pngw.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | src/api/assets/pngw.cc | izzyaxel/Loft | 809b4e3df2c2b08092c6b3a94073f4509240b4f2 | [
"BSD-3-Clause"
] | null | null | null | #include "pngw.hh"
#include <png.h>
#include <cstring>
PNG::PNG(uint32_t width, uint32_t height, char colorFormat, char bitDepth, std::vector<uint8_t> &&imageData) : width(width), height(height), colorFormat(colorFormat), bitDepth(bitDepth), imageData(imageData){}
void pngErrorCallback(png_structp, png_const_charp error)
{
printf("%s\n", error);
}
PNG decodePNG(std::string const &filePath)
{
FILE *input = fopen(filePath.data(), "rb");
if(!input)
{
printf("PNG Decoder: Unable to open %s for reading\n", filePath.data());
return {0, 0, 0, 0, {}};
}
png_structp pngPtr;
png_infop infoPtr;
png_byte header[8];
size_t foo = fread(header, 8, 1, input);
if(png_sig_cmp(header, 0, 8) != 0)
{
printf("PNG Decoder: File %s is not PNG format\n", filePath.data());
return {0, 0, 0, 0, {}};
}
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, pngErrorCallback, nullptr);
if(pngPtr == nullptr)
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Failed to create PNG read struct\n");
return {0, 0, 0, 0, {}};
}
png_set_error_fn(pngPtr, png_get_error_ptr(pngPtr), [](png_structp, png_const_charp){}, [](png_structp, png_const_charp){});
infoPtr = png_create_info_struct(pngPtr);
if(!infoPtr)
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Failed to create PNG info struct\n");
return {0, 0, 0, 0, {}};
}
if(setjmp(png_jmpbuf(pngPtr)))
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Error during PNG read struct initialization\n");
return {0, 0, 0, 0, {}};
}
png_init_io(pngPtr, input);
png_set_sig_bytes(pngPtr, 8);
png_read_info(pngPtr, infoPtr);
uint32_t width, height;
char colorType, bitDepth;
width = png_get_image_width(pngPtr, infoPtr);
height = png_get_image_height(pngPtr, infoPtr);
colorType = png_get_color_type(pngPtr, infoPtr);
bitDepth = png_get_bit_depth(pngPtr, infoPtr);
if(colorType & PNG_COLOR_MASK_PALETTE)
{
printf("PNG Decoder: Paletted PNG files are not currently supported\n");
return {0, 0, 0, 0, {}};
}
png_set_interlace_handling(pngPtr);
png_read_update_info(pngPtr, infoPtr);
if(setjmp(png_jmpbuf(pngPtr)))
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Failed to read PNG\n");
return {0, 0, 0, 0, {}};
}
std::vector<uint8_t> imageData;
imageData.resize(height * png_get_rowbytes(pngPtr, infoPtr));
uint8_t **fauxData = new uint8_t*[height];
for(size_t i = 0; i < height; i++) fauxData[i] = imageData.data() + i * png_get_rowbytes(pngPtr, infoPtr);
png_read_image(pngPtr, fauxData);
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
delete [] fauxData;
fclose(input);
return PNG{width, height, colorType, bitDepth, std::move(imageData)};
}
struct PNGReadStruct
{
PNGReadStruct(uint8_t const *data, size_t bufferLocation) : data(data), bufferLocation(bufferLocation) {}
uint8_t const *data = nullptr;
size_t bufferLocation = 0;
};
void pngReadFn(png_structp read, png_bytep data, png_size_t length)
{
PNGReadStruct *buffer = reinterpret_cast<PNGReadStruct*>(png_get_io_ptr(read));
memcpy(data, buffer->data + buffer->bufferLocation, length);
buffer->bufferLocation += length;
}
PNG decodePNG(std::vector<uint8_t> const &file)
{
PNGReadStruct pngrs{file.data(), 0};
png_structp pngPtr;
png_infop infoPtr;
png_byte header[8];
memcpy(header, pngrs.data, 8);
if(png_sig_cmp(header, 0, 8) != 0)
{
printf("PNG Decoder: File is not PNG format\n");
return {0, 0, 0, 0, {}};
}
pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, pngErrorCallback, nullptr);
if(pngPtr == nullptr)
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Failed to create PNG read struct\n");
return {0, 0, 0, 0, {}};
}
png_set_error_fn(pngPtr, png_get_error_ptr(pngPtr), [](png_structp, png_const_charp){}, [](png_structp, png_const_charp){});
infoPtr = png_create_info_struct(pngPtr);
if(!infoPtr)
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Failed to create PNG info struct\n");
return {0, 0, 0, 0, {}};
}
if(setjmp(png_jmpbuf(pngPtr)))
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Error during PNG read struct initialization\n");
return {0, 0, 0, 0, {}};
}
png_set_read_fn(pngPtr, reinterpret_cast<png_voidp *>(&pngrs), pngReadFn);
png_set_sig_bytes(pngPtr, 0);
png_read_info(pngPtr, infoPtr);
uint32_t width, height;
char colorType, bitDepth;
width = png_get_image_width(pngPtr, infoPtr);
height = png_get_image_height(pngPtr, infoPtr);
colorType = png_get_color_type(pngPtr, infoPtr);
bitDepth = png_get_bit_depth(pngPtr, infoPtr);
if(colorType & PNG_COLOR_MASK_PALETTE)
{
printf("PNG Decoder: Paletted PNG files are not currently supported\n");
return {0, 0, 0, 0, {}};
}
png_set_interlace_handling(pngPtr);
png_read_update_info(pngPtr, infoPtr);
if(setjmp(png_jmpbuf(pngPtr)))
{
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
printf("PNG Decoder: Failed to read PNG\n");
return {0, 0, 0, 0, {}};
}
std::vector<uint8_t> imageData;
imageData.resize(height * png_get_rowbytes(pngPtr, infoPtr));
uint8_t **fauxData = new uint8_t*[height];
for(size_t i = 0; i < height; i++) fauxData[i] = imageData.data() + i * png_get_rowbytes(pngPtr, infoPtr);
png_read_image(pngPtr, fauxData);
png_destroy_read_struct(&pngPtr, &infoPtr, nullptr);
delete [] fauxData;
return PNG{width, height, colorType, bitDepth, std::move(imageData)};
}
void writePNG(std::string const &filePath, uint32_t width, uint32_t height, uint8_t *imageData, int32_t fmt, bool reverseRows)
{
uint8_t **data = new uint8_t*[height];
int32_t cpp = 0;
switch(fmt)
{
case PNG::COLOR_FMT_GREY:
cpp = 1;
break;
case PNG::COLOR_FMT_RGB:
cpp = 3;
break;
case PNG::COLOR_FMT_RGBA:
cpp = 4;
break;
}
if(reverseRows)
{
for(ssize_t i = 0; i < height; i++) data[i] = imageData + (height - i - 1) * width * cpp;
}
else
{
for(size_t i = 0; i < height; i++) data[i] = imageData + i * width * cpp;
}
FILE *output = fopen(filePath.data(), "wb");
if(!output)
{
printf("PNG Encoder: Failed to open %s for writing\n", filePath.data());
return;
}
png_structp pngPtr;
png_infop infoPtr;
pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if(!pngPtr)
{
printf("PNG Encoder: Failed to create PNG write struct\n");
fclose(output);
return;
}
infoPtr = png_create_info_struct(pngPtr);
if(!infoPtr)
{
printf("PNG Encoder: Failed to create PNG info struct\n");
fclose(output);
return;
}
if(setjmp((png_jmpbuf(pngPtr))))
{
printf("PNG Encoder: An error occured during I/O init\n");
fclose(output);
return;
}
png_init_io(pngPtr, output);
if(setjmp(png_jmpbuf(pngPtr)))
{
printf("PNG Encoder: An error occured while writing header\n");
fclose(output);
return;
}
png_set_IHDR(pngPtr,
infoPtr,
width,
height,
8,
fmt,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE,
PNG_FILTER_TYPE_BASE);
png_write_info(pngPtr, infoPtr);
if(setjmp(png_jmpbuf(pngPtr)))
{
printf("PNG Encoder: An error occured while writing\n");
fclose(output);
return;
}
png_write_image(pngPtr, data);
if(setjmp(png_jmpbuf(pngPtr)))
{
printf("PNG Encoder: An error occured during end of write\n");
fclose(output);
return;
}
png_write_end(pngPtr, nullptr);
fclose(output);
delete [] data;
}
| 28.163569 | 209 | 0.696278 | [
"vector"
] |
72a429e1647155a35d493856a98a3861241ad797 | 6,006 | cc | C++ | lib/process/process_builder.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | lib/process/process_builder.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | lib/process/process_builder.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 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 "garnet/lib/process/process_builder.h"
#include <fcntl.h>
#include <lib/fdio/io.h>
#include <lib/fdio/limits.h>
#include <lib/fdio/namespace.h>
#include <lib/fdio/util.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <zircon/assert.h>
#include <zircon/dlfcn.h>
#include <zircon/process.h>
#include <zircon/processargs.h>
#include <zircon/syscalls.h>
#include "lib/svc/cpp/services.h"
namespace process {
ProcessBuilder::ProcessBuilder(std::shared_ptr<component::Services> services)
: services_(services) {
services_->ConnectToService(launcher_.NewRequest());
}
ProcessBuilder::ProcessBuilder(zx::job job,
std::shared_ptr<component::Services> services)
: ProcessBuilder(services) {
launch_info_.job = std::move(job);
}
ProcessBuilder::~ProcessBuilder() = default;
void ProcessBuilder::LoadVMO(zx::vmo executable) {
launch_info_.executable = std::move(executable);
}
zx_status_t ProcessBuilder::LoadPath(const std::string& path) {
int fd = open(path.c_str(), O_RDONLY);
if (fd < 0)
return ZX_ERR_IO;
zx_status_t status =
fdio_get_vmo_clone(fd, launch_info_.executable.reset_and_get_address());
close(fd);
if (status == ZX_OK) {
const char* name = path.c_str();
if (path.length() >= ZX_MAX_NAME_LEN) {
size_t offset = path.rfind('/');
if (offset != std::string::npos) {
name += offset + 1;
}
}
launch_info_.executable.set_property(ZX_PROP_NAME, name, strlen(name));
}
return status;
}
void ProcessBuilder::AddArgs(const std::vector<std::string>& argv) {
if (argv.empty())
return;
if (launch_info_.name->empty())
launch_info_.name.reset(argv[0]);
fidl::VectorPtr<fidl::StringPtr> args;
for (const auto& arg : argv)
args.push_back(arg);
launcher_->AddArgs(std::move(args));
}
void ProcessBuilder::AddHandle(uint32_t id, zx::handle handle) {
handles_.push_back(fuchsia::process::HandleInfo{
.id = id,
.handle = std::move(handle),
});
}
void ProcessBuilder::AddHandles(
std::vector<fuchsia::process::HandleInfo> handles) {
handles_->insert(handles_->end(), std::make_move_iterator(handles.begin()),
std::make_move_iterator(handles.end()));
}
void ProcessBuilder::SetDefaultJob(zx::job job) {
handles_.push_back(fuchsia::process::HandleInfo{
.id = PA_JOB_DEFAULT,
.handle = std::move(job),
});
}
void ProcessBuilder::SetName(std::string name) {
launch_info_.name.reset(std::move(name));
}
void ProcessBuilder::CloneJob() {
zx::job duplicate_job;
if (launch_info_.job)
launch_info_.job.duplicate(ZX_RIGHT_SAME_RIGHTS, &duplicate_job);
else
zx::job::default_job()->duplicate(ZX_RIGHT_SAME_RIGHTS, &duplicate_job);
SetDefaultJob(std::move(duplicate_job));
}
void ProcessBuilder::CloneLdsvc() {
fuchsia::process::HandleInfo handle_info;
handle_info.id = PA_LDSVC_LOADER;
zx_status_t status =
dl_clone_loader_service(handle_info.handle.reset_and_get_address());
ZX_ASSERT(status == ZX_OK);
handles_.push_back(std::move(handle_info));
}
void ProcessBuilder::CloneNamespace() {
fdio_flat_namespace_t* flat = nullptr;
zx_status_t status = fdio_ns_export_root(&flat);
if (status == ZX_OK) {
fidl::VectorPtr<fuchsia::process::NameInfo> names;
for (size_t i = 0; i < flat->count; ++i) {
names.push_back(fuchsia::process::NameInfo{
flat->path[i],
fidl::InterfaceHandle<fuchsia::io::Directory>(zx::channel(flat->handle[i])),
});
}
launcher_->AddNames(std::move(names));
}
free(flat);
}
void ProcessBuilder::CloneStdio() {
// These file descriptors might be closed. Skip over erros cloning them.
CloneFileDescriptor(STDIN_FILENO, STDIN_FILENO);
CloneFileDescriptor(STDOUT_FILENO, STDOUT_FILENO);
CloneFileDescriptor(STDERR_FILENO, STDERR_FILENO);
}
void ProcessBuilder::CloneEnvironment() {
fidl::VectorPtr<fidl::StringPtr> env;
for (size_t i = 0; environ[i]; ++i)
env.push_back(environ[i]);
launcher_->AddEnvirons(std::move(env));
}
void ProcessBuilder::CloneAll() {
CloneJob();
CloneLdsvc();
CloneNamespace();
CloneStdio();
CloneEnvironment();
}
zx_status_t ProcessBuilder::CloneFileDescriptor(int local_fd, int target_fd) {
zx_handle_t fdio_handles[FDIO_MAX_HANDLES];
uint32_t fdio_types[FDIO_MAX_HANDLES];
zx_status_t status =
fdio_clone_fd(local_fd, target_fd, fdio_handles, fdio_types);
if (status < ZX_OK)
return status;
for (int i = 0; i < status; ++i) {
handles_.push_back(fuchsia::process::HandleInfo{
.id = fdio_types[i],
.handle = zx::handle(fdio_handles[i]),
});
}
return ZX_OK;
}
zx_status_t ProcessBuilder::Prepare(std::string* error_message) {
zx_status_t status = ZX_OK;
launcher_->AddHandles(std::move(handles_));
if (!launch_info_.job) {
status = zx::job::default_job()->duplicate(ZX_RIGHT_SAME_RIGHTS,
&launch_info_.job);
if (status != ZX_OK)
return status;
}
fuchsia::process::CreateWithoutStartingResult result;
status = launcher_->CreateWithoutStarting(std::move(launch_info_), &result);
if (status != ZX_OK)
return status;
if (result.status != ZX_OK) {
if (error_message)
*error_message = result.error_message;
return result.status;
}
if (!result.data)
return ZX_ERR_INVALID_ARGS;
data_ = std::move(*result.data);
return ZX_OK;
}
zx_status_t ProcessBuilder::Start(zx::process* process_out) {
zx_status_t status =
zx_process_start(data_.process.get(), data_.thread.get(), data_.entry,
data_.sp, data_.bootstrap.release(), data_.vdso_base);
if (status == ZX_OK && process_out)
*process_out = std::move(data_.process);
return status;
}
} // namespace process
| 28.875 | 86 | 0.689311 | [
"vector"
] |
72a677c09b4556c8754f3b1e7cc3402f5f0d75fa | 15,713 | cpp | C++ | dlls/buildcam.cpp | avwuff/Half-Life-TFC-AVC-Mod | 3b6a32b615e42cd541f078065458d47c3d4688ba | [
"MIT"
] | 5 | 2019-05-08T19:25:02.000Z | 2021-09-12T00:26:20.000Z | dlls/buildcam.cpp | avwuff/Half-Life-TFC-AVC-Mod | 3b6a32b615e42cd541f078065458d47c3d4688ba | [
"MIT"
] | 1 | 2018-08-28T13:46:12.000Z | 2018-08-28T13:48:40.000Z | dlls/buildcam.cpp | avwuff/Half-Life-TFC-AVC-Mod | 3b6a32b615e42cd541f078065458d47c3d4688ba | [
"MIT"
] | 1 | 2021-03-08T15:39:39.000Z | 2021-03-08T15:39:39.000Z |
#include "extdll.h"
#include "enginecallback.h"
#include "util.h"
#include "cbase.h"
#include "entity_state.h"
#include "soundent.h"
#include "studio.h"
#include "bot.h"
#include "avdll.h"
#include "sadll.h"
#include "buildcam.h"
extern GETENTITYAPI other_GetEntityAPI;
extern enginefuncs_t g_engfuncs;
extern globalvars_t *gpGlobals;
extern char *g_argv;
extern DLL_FUNCTIONS other_gFunctionTable;
extern const Vector g_vecZero;
int g_sModelIndexFireball;
float menushow[33];
static FILE *fp;
// This CPP deals with creating the engineers CAMERA (The THIRD thing they can build)
// Basics: We use the TRIPMINE model, and stick it onto the wall just as we would a tripmine!
enum tripmine_e {
TRIPMINE_IDLE1 = 0,
TRIPMINE_IDLE2,
TRIPMINE_ARM1,
TRIPMINE_ARM2,
TRIPMINE_FIDGET,
TRIPMINE_HOLSTER,
TRIPMINE_DRAW,
TRIPMINE_WORLD,
TRIPMINE_GROUND,
};
string_t clsname;
bool CamCreate( edict_t *pEntity )
{
// Create the camera and stick to the wall
entvars_t *pPev = VARS( pEntity );
UTIL_MakeVectors( pPev->v_angle + pPev->punchangle );
Vector vecSrc = GetGunPosition( pEntity );
Vector vecAiming = gpGlobals->v_forward;
TraceResult tr;
UTIL_TraceLine( vecSrc, vecSrc + vecAiming * 128, dont_ignore_monsters, pEntity , &tr );
if (tr.flFraction < 1.0)
{
if (tr.pHit && !(tr.pHit->v.flags & FL_CONVEYOR) && (FStrEq((char *)STRING(tr.pHit->v.classname), "worldspawn") || FStrEq((char *)STRING(tr.pHit->v.classname), "func_wall"))) // Make sure it isnt a conveyor!
{
Vector angles = UTIL_VecToAngles( tr.vecPlaneNormal );
if (angles.x > 30 || angles.x < -30)
{
ClientPrint( pPev, HUD_PRINTTALK, "* Can't place cameras on floors or cielings!\n");
return 0;
}
// Create the camera here!
KeyValueData kvd;
//edict_t *pent = CREATE_ENTITY();
edict_t *pent = CREATE_NAMED_ENTITY(clsname);
entvars_t *pev = VARS( pent );
pev->origin = tr.vecEndPos;
pev->angles = angles;
pev->controller[0] = 127;
pev->controller[1] = 127;
pev->euser4 = pEntity;
//pev->iuser1 = angles.y;
pev->vuser3 = angles;
// for now don't take damage
pev->takedamage = DAMAGE_YES;
pev->max_health = 40 + 10000;
pev->health = 40 + 10000;
// Call the SPAWN routine to set more stuff
kvd.fHandled = FALSE;
kvd.szClassName = NULL;
kvd.szKeyName = "classname";
kvd.szValue = "building_camera";
DispatchKeyValue( pent, &kvd );
kvd.fHandled = FALSE;
// Create the ent that we see out of.
edict_t *pentview = CREATE_NAMED_ENTITY(clsname);
kvd.fHandled = FALSE;
kvd.szClassName = NULL;
kvd.szKeyName = "classname";
kvd.szValue = "building_camera_view";
DispatchKeyValue( pentview, &kvd );
kvd.fHandled = FALSE;
pentview->v.angles = angles;
pentview->v.origin = pev->origin + tr.vecPlaneNormal * 24;
pentview->v.origin.z += 12;
pentview->v.movetype = MOVETYPE_FLY;
pentview->v.solid = SOLID_BBOX;
pentview->v.takedamage = DAMAGE_NO;
pentview->v.health = 20;
pentview->v.euser4 = pEntity;
SET_MODEL(pentview, "models/shell.mdl");
pentview->v.angles.x = -pentview->v.angles.x;
pentview->v.rendermode = 2;
pentview->v.renderamt = 0;
UTIL_SetOrigin( VARS(pentview), pentview->v.origin );
pev->euser1 = pentview;
(*other_gFunctionTable.pfnSpawn)(pentview);
CamSpawn( pent );
return 1;
}
else
{
ClientPrint( pPev, HUD_PRINTTALK, "* Couldn't place camera here!\n");
return 0;
}
}
else
{
ClientPrint( pPev, HUD_PRINTTALK, "* Couldn't place camera here!\n");
}
return 0;
}
void CamSpawn( edict_t *pent )
{
// Spawn routine
entvars_t *pev = VARS( pent );
pev->movetype = MOVETYPE_FLY;
pev->solid = SOLID_BBOX;
//SET_MODEL(pent, "models/v_tripmine.mdl");
SET_MODEL(pent, "avatar-x/avadd13.avfil");
pev->frame = 0;
//pev->body = 3;
//pev->sequence = TRIPMINE_WORLD;
pev->framerate = 0;
UTIL_SetSize(pev, Vector( -12, -12, -12), Vector(12, 12, 12));
UTIL_SetOrigin( pev, pev->origin );
// play deploy sound
EMIT_SOUND_DYN2( ENT(pev), CHAN_VOICE, "weapons/mine_deploy.wav", 1.0, ATTN_NORM , 0, 100);
pev->iuser2 = pev->euser4->v.team; // Set the team this camera belongs to
pev->nextthink = gpGlobals->time + 0.1;
// (*other_gFunctionTable.pfnSpawn)(pent);
//pent->v.classname = clsname;
UTIL_SetSize(pev, Vector( -12, -12, -12), Vector(12, 12, 12));
SET_ORIGIN( pent, pev->origin );
pev->solid = SOLID_BBOX;
}
void CamPrecache()
{
//PRECACHE_MODEL("models/v_tripmine.mdl");
PRECACHE_MODEL("avatar-x/avadd13.avfil");
PRECACHE_SOUND("weapons/mine_deploy.wav");
PRECACHE_SOUND("buttons/lever1.wav");
g_sModelIndexFireball = PRECACHE_MODEL ("sprites/zerogxplode.spr");// fireball
//clsname = MAKE_STRING("building_camera");
clsname = MAKE_STRING("info_target");
}
void CamSee( edict_t *pEntity )
{
// See out of the camera
int i = 1;
char *pClassname;
edict_t *frontEnt;
//frontEnt = pEntity->v.euser3;
for (i; i < 1025; i++) {
frontEnt = INDEXENT ( i );
if (frontEnt) {
pClassname = (char *)STRING(frontEnt->v.classname);
if (FStrEq("building_camera", pClassname)) {
if (frontEnt->v.euser4 == pEntity)
{
//frontEnt->v.angles.x = -frontEnt->v.angles.x;
UTIL_SetSize(VARS(frontEnt), Vector( -12, -12, -12), Vector(12, 12, 12));
SET_ORIGIN( frontEnt, frontEnt->v.origin );
frontEnt->v.iuser3 = 1;
frontEnt->v.vuser4 = pEntity->v.v_angle;
SET_VIEW( pEntity, frontEnt->v.euser1 );
return;
}
}
}
}
}
void CamOff( edict_t *pEntity )
{
// See out of the camera
// first find their camera
SET_VIEW( pEntity, pEntity );
int i = 1;
char *pClassname;
edict_t *frontEnt;
//frontEnt = pEntity->v.euser3;
for (i; i < 1025; i++) {
frontEnt = INDEXENT ( i );
if (frontEnt) {
pClassname = (char *)STRING(frontEnt->v.classname);
if (FStrEq("building_camera", pClassname)) {
if (frontEnt->v.euser4 == pEntity)
{
//frontEnt->v.angles.x = -frontEnt->v.angles.x;
frontEnt->v.iuser3 = 0;
frontEnt->v.euser1->v.avelocity.y = 0;
// reset to default state
frontEnt->v.controller[0] = 127;
frontEnt->v.controller[1] = 127;
frontEnt->v.euser1->v.angles = frontEnt->v.vuser3;
frontEnt->v.euser1->v.avelocity = g_vecZero;
return;
}
}
}
}
}
void CamKill( edict_t *pEntity )
{
// Delete the camera
int i = 1;
char *pClassname;
edict_t *frontEnt;
for (i; i < 1025; i++) {
frontEnt = INDEXENT ( i );
if (frontEnt) {
pClassname = (char *)STRING(frontEnt->v.classname);
if (FStrEq("building_camera", pClassname)) {
if (frontEnt->v.euser4 == pEntity)
{
// Delete this camera's VIEW and it.
frontEnt->v.euser1->v.flags |= FL_KILLME;
frontEnt->v.flags |= FL_KILLME;
}
}
}
}
}
void CamKillBoom( edict_t *pEntity )
{
// Delete the camera
int i = 1;
char *pClassname;
edict_t *frontEnt;
for (i; i < 1025; i++) {
frontEnt = INDEXENT ( i );
if (frontEnt) {
pClassname = (char *)STRING(frontEnt->v.classname);
if (FStrEq("building_camera", pClassname)) {
if (frontEnt->v.euser4 == pEntity)
{
// Delete this camera's VIEW and it.
frontEnt->v.euser1->v.flags |= FL_KILLME;
frontEnt->v.flags |= FL_KILLME;
// Boom
MESSAGE_BEGIN( MSG_PAS, SVC_TEMPENTITY, frontEnt->v.origin );
WRITE_BYTE( TE_EXPLOSION ); // This makes a dynamic light and the explosion sprites/sound
WRITE_COORD( frontEnt->v.origin.x ); // Send to PAS because of the sound
WRITE_COORD( frontEnt->v.origin.y );
WRITE_COORD( frontEnt->v.origin.z );
WRITE_SHORT( g_sModelIndexFireball );
WRITE_BYTE( 30 ); // scale * 10
WRITE_BYTE( 15 ); // framerate
WRITE_BYTE( 0 );
MESSAGE_END();
// Test: Make euser4 take damage.
/*
fp=fopen("takedamage.txt","a");
fprintf(fp, "Got to POINT 0A\n");
fclose(fp);
CBaseEntity *pEnt = NULL;
pEnt = CBaseEntity::Instance( pEntity );
fp=fopen("takedamage.txt","a");
fprintf(fp, "Got to POINT 0B\n");
fclose(fp);
pEnt->TakeDamage( VARS( frontEnt ), VARS( frontEnt ), 10, DMG_CRUSH );
*/
}
}
}
}
}
bool CamCheck ( edict_t *pent )
{
// Check if they have a camera
int i = 1;
char *pClassname;
edict_t *frontEnt;
for (i; i < 1025; i++) {
frontEnt = INDEXENT ( i );
if (frontEnt) {
pClassname = (char *)STRING(frontEnt->v.classname);
if (FStrEq("building_camera", pClassname)) {
if (frontEnt->v.euser4 == pent)
{
// Delete this camera's VIEW and it.
return 1;
}
}
}
}
return 0;
}
void CamThink ( edict_t *pent )
{
// turn the camera around a bit
if (pent->v.iuser3 != 0) {
/* //old code
int angadd = pent->v.iuser4;
int origang = pent->v.iuser1;
if (angadd == 0) angadd = 11;
int angval = origang - pent->v.euser1->v.angles.y;
if (angval > 25 && angadd < 0) angadd = -angadd;
if (angval < -25 && angadd > 0) angadd = -angadd;
pent->v.euser1->v.avelocity.y = angadd;
pent->v.iuser4 = angadd;
*/
// make the camera point the same way the user is looking
Vector theone;
Vector thetwo;
theone = pent->v.euser4->v.v_angle;
theone.y = pent->v.vuser3.y - (pent->v.vuser4.y - pent->v.euser4->v.v_angle.y) ;
// see the difference and if needed subtract.
thetwo = pent->v.vuser3 - theone;
if (thetwo.y > 360) thetwo.y -= 360;
if (thetwo.y < -360) thetwo.y += 360;
if (thetwo.y > 180) thetwo.y -= 360;
if (thetwo.y < -180) thetwo.y += 360;
if (thetwo.x > 30) thetwo.x = 30;
if (thetwo.x < -30) thetwo.x = -30;
if (thetwo.y > 70) thetwo.y = 70;
if (thetwo.y < -70) thetwo.y = -70;
thetwo = -thetwo;
// attempt at avelocity
theone = pent->v.vuser3 + thetwo;
pent->v.euser1->v.avelocity.y = ((theone.y - pent->v.euser1->v.angles.y) * 1.8);
pent->v.euser1->v.avelocity.x = ((theone.x - pent->v.euser1->v.angles.x) * 1.8);
// figure out the bone controller value
// set the camera controllers so it looks at where the player is seeing
pent->v.controller[0] = (int)(thetwo.y + 127);
pent->v.controller[1] = (int)(thetwo.x + 127);
// How about when the camera is TURNING it makes a little grating sound!!
// Only play the sound if the camera is turning relatively fast
if (abs(pent->v.euser1->v.avelocity.y) > 30 && pent->v.fuser2 < gpGlobals->time)
{
// ||| this is the volume
EMIT_SOUND_DYN2( pent, CHAN_VOICE, "buttons/lever1.wav", 0.8, ATTN_NORM , 0, 110); // lets play it faster than normal
pent->v.fuser2 = gpGlobals->time + 2;
}
}
if (!pent->v.euser4 || pent->v.health <= 10000 || pent->v.euser4->v.iuser1 != 0 || pent->v.iuser2 != pent->v.euser4->v.team)
{
// We've been destroyed! Make a boom and tell the euser4
if (pent->v.euser4) {
ClientPrint( VARS( pent->v.euser4 ), HUD_PRINTTALK, "* Your camera has been destroyed!\n");
CamOff( pent->v.euser4 );
}
pent->v.euser1->v.flags |= FL_KILLME;
pent->v.flags |= FL_KILLME;
// Boom
MESSAGE_BEGIN( MSG_PAS, SVC_TEMPENTITY, pent->v.origin );
WRITE_BYTE( TE_EXPLOSION ); // This makes a dynamic light and the explosion sprites/sound
WRITE_COORD( pent->v.origin.x ); // Send to PAS because of the sound
WRITE_COORD( pent->v.origin.y );
WRITE_COORD( pent->v.origin.z );
WRITE_SHORT( g_sModelIndexFireball );
WRITE_BYTE( 30 ); // scale * 10
WRITE_BYTE( 15 ); // framerate
WRITE_BYTE( 0 );
MESSAGE_END();
}
// check if the PLAYER is dead.
if (pent->v.euser4->v.deadflag != DEAD_NO && pent->v.iuser3 != 0)
{
// turn off the camera
CamOff( pent->v.euser4 );
}
pent->v.nextthink = gpGlobals->time + 0.2;
}
void CamShowMenu( edict_t *pEntity )
{
// Cant use camera in spec mode
if (pEntity->v.iuser1 > 0) return;
char menutext[1024];
int bitsel = 0;
sprintf(menutext, "Build Camera Menu:\n\n");
sprintf(menutext, "%s1. Place Camera Here\n", menutext);
sprintf(menutext, "%s2. Dismantle Camera\n", menutext);
sprintf(menutext, "%s3. Detonate Camera\n\n", menutext);
sprintf(menutext, "%s4. Turn On Camera\n", menutext);
sprintf(menutext, "%s5. Turn Off Camera\n\n", menutext);
sprintf(menutext, "%s6. Cancel\n\n", menutext);
sprintf(menutext, "%sNote: Bind +camlook to quickly\npeek into your camera!", menutext);
bitsel |= 1<<0; // activate this choice in the menu 1
bitsel |= 1<<1; // activate this choice in the menu 2
bitsel |= 1<<2; // activate this choice in the menu 3
bitsel |= 1<<3; // activate this choice in the menu 4
bitsel |= 1<<4; // activate this choice in the menu 5
bitsel |= 1<<5; // activate this choice in the menu 6
// Now, show the menu to everyone!
int gmsgShowMenu = 0;
gmsgShowMenu = REG_USER_MSG( "ShowMenu", -1 );
MESSAGE_BEGIN( MSG_ONE, gmsgShowMenu, NULL, pEntity);
WRITE_SHORT( bitsel);
WRITE_CHAR( 60 );
WRITE_BYTE( 0 );
WRITE_STRING (menutext);
MESSAGE_END();
// Set the values that determine how long we accept input...
menushow[ENTINDEX(pEntity)] = gpGlobals->time + 60;
}
void CamHandleMenuItem(edict_t *pEntity, const char *itm, bool ign)
{
int ind = ENTINDEX(pEntity);
if (!pEntity) return;
// Cant use camera in spec mode
if (pEntity->v.iuser1 > 0) return;
// Are we running a vote?
if ((menushow[ind] != 0 && (gpGlobals->time <= menushow[ind]) || ign)) {
if (ign == 0) menushow[ind] = 0;
// See what they pressed.
char msg[80];
sprintf(msg, "0");
if (FStrEq(itm, "1"))
{
if (CamCheck(pEntity))
{
sprintf(msg, "* You already have a camera! Remove it first!\n");
}
else
{
// Make sure we are allowed to build a camera
// we cant be dead
if (pEntity->v.deadflag == DEAD_NO)
{
if (CamCreate( pEntity )) sprintf(msg, "* You have built a camera!\n");
}
}
}
else if (FStrEq(itm, "2"))
{
if (!CamCheck(pEntity))
{
sprintf(msg, "* You don't have a camera to dismantle!\n");
}
else
{
CamOff( pEntity );
CamKill( pEntity );
sprintf(msg, "* You have dismantled your camera!\n");
}
}
else if (FStrEq(itm, "3"))
{
if (!CamCheck(pEntity))
{
sprintf(msg, "* You don't have a camera to detonate!\n");
}
else
{
CamOff( pEntity );
CamKillBoom( pEntity ); // same as kill but with a boom
sprintf(msg, "* You have detonated your camera!\n");
}
}
else if (FStrEq(itm, "4"))
{
if (!CamCheck(pEntity))
{
sprintf(msg, "* You don't have a camera to turn on!\n");
}
else
{
CamSee( pEntity );
if (!ign) sprintf(msg, "* Camera turned on!\n");
}
}
else if (FStrEq(itm, "5"))
{
if (!CamCheck(pEntity))
{
if (!ign) sprintf(msg, "* You don't have a camera to turn off!\n");
}
else
{
CamOff( pEntity );
if (!ign) sprintf(msg, "* Camera turned off!\n");
}
}
if (!FStrEq(msg, "0")) ClientPrint( VARS(pEntity), HUD_PRINTTALK, msg);
}
}
void CamTouch( edict_t *pEntity, edict_t *pTouch )
{
if (FStrEq("player", (char *)STRING(pTouch->v.classname)))
{
// player is touching us... make sure we arent stuck in him
bool stuck = 0;
entvars_t *pev = VARS(pTouch);
entvars_t *sign = VARS(pEntity);
stuck = 1;
if ( sign->absmin.x + 1 > pev->absmax.x - 1 ||
sign->absmin.y + 1 > pev->absmax.y - 1 ||
sign->absmin.z + 1 > pev->absmax.z - 1 ||
sign->absmax.x - 1 < pev->absmin.x + 1 ||
sign->absmax.y - 1 < pev->absmin.y + 1 ||
sign->absmax.z - 1 < pev->absmin.z + 1 ) stuck = 0;
if (stuck)
{
// player is blocked, remove sign
sign->health = 1;
//ClientPrint( pev, HUD_PRINTTALK, "* Camera removed because you were stuck in it!\n");
}
}
}
| 22.706647 | 209 | 0.628524 | [
"vector",
"model",
"solid"
] |
72a9598c4347a21029d6b18d7b03f8dd7eea2a3e | 4,584 | cpp | C++ | src/opengl/ProgramPool.cpp | Shachlan/lottie-example | b848580195ece4b8147cb5c8ab54caf5cbd6ac3c | [
"BSD-3-Clause"
] | null | null | null | src/opengl/ProgramPool.cpp | Shachlan/lottie-example | b848580195ece4b8147cb5c8ab54caf5cbd6ac3c | [
"BSD-3-Clause"
] | null | null | null | src/opengl/ProgramPool.cpp | Shachlan/lottie-example | b848580195ece4b8147cb5c8ab54caf5cbd6ac3c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2019 Lightricks. All rights reserved.
// Created by Shachar Langbeheim.
#include "ProgramPool.hpp"
#include <OpenGL/gl3.h>
#include <fstream>
#include <sstream>
#include <vector>
#include "GLException.hpp"
using namespace WREOpenGL;
void ProgramPool::delete_program(GLuint program_name) {
auto shaders = this->name_to_shader_names_mapping[program_name];
auto description = this->name_to_description_mapping[program_name];
glDeleteProgram(program_name);
glDeleteShader(shaders.first);
glDeleteShader(shaders.second);
}
void ProgramPool::flush() {
std::vector<GLuint> names_to_remove;
for (auto &pair : program_reference_count) {
if (pair.second > 0) {
continue;
}
delete_program(pair.first);
names_to_remove.insert(names_to_remove.end(), pair.first);
}
for (auto &name : names_to_remove) {
auto description = this->name_to_description_mapping[name];
this->description_to_name_mapping.erase(description);
this->name_to_shader_names_mapping.erase(name);
this->name_to_description_mapping.erase(name);
this->program_reference_count.erase(name);
}
}
void ProgramPool::clear() {
for (auto &pair : name_to_description_mapping) {
delete_program(pair.first);
}
this->description_to_name_mapping.clear();
this->name_to_shader_names_mapping.clear();
this->name_to_description_mapping.clear();
this->program_reference_count.clear();
}
static GLuint build_shader(const GLchar *shader_source, GLenum shader_type) {
GLuint shader = glCreateShader(shader_type);
if (!shader || !glIsShader(shader)) {
return 0;
}
glShaderSource(shader, 1, &shader_source, 0);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_TRUE) {
return shader;
}
GLint logSize = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize);
GLchar *errorLog = (GLchar *)calloc(logSize, sizeof(GLchar));
glGetShaderInfoLog(shader, logSize, 0, errorLog);
throw_gl_exception("Failed to build shader with error:\n%s", errorLog);
return 0;
}
static string get_shader_filename(string shader, GLenum shader_type) {
return shader + (shader_type == GL_VERTEX_SHADER ? ".vsh" : ".fsh");
}
static string get_shader_text(string shader_name, GLenum shader_type) {
auto shader_file_name = get_shader_filename(shader_name, shader_type);
std::ifstream stream(shader_file_name);
if (!stream.is_open()) {
throw_gl_exception("Can't open shader file %s", shader_file_name.c_str());
}
std::stringstream buffer;
buffer << stream.rdbuf();
return buffer.str();
}
int build_shader(string shader_name, GLenum shader_type) {
auto text = get_shader_text(shader_name, shader_type);
return build_shader(text.c_str(), shader_type);
}
GLuint create_program(GLuint vertex_shader, GLuint fragment_shader) {
GLuint program = glCreateProgram();
GLCheckDbg("create program");
glAttachShader(program, vertex_shader);
GLCheckDbg("attach vertex shader");
glAttachShader(program, fragment_shader);
GLCheckDbg("attach fragment shader");
glLinkProgram(program);
GLCheckDbg("linking program");
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status != GL_TRUE) {
GLint maxLength = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength);
GLchar infoLog[maxLength];
glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]);
throw_gl_exception("Failed to create program with error:\n%s", infoLog);
}
return program;
}
string get_key(string vertex_shader, string fragment_shader) {
return "vertx:" + vertex_shader + ".fragment:" + fragment_shader;
}
GLuint ProgramPool::get_program(string vertex_shader, string fragment_shader) {
auto key = get_key(vertex_shader, fragment_shader);
auto search = this->description_to_name_mapping.find(key);
if (search != this->description_to_name_mapping.end()) {
this->program_reference_count[search->second]++;
return search->second;
}
auto v_shader_name = build_shader(vertex_shader, GL_VERTEX_SHADER);
auto f_shader_name = build_shader(fragment_shader, GL_FRAGMENT_SHADER);
auto program = create_program(v_shader_name, f_shader_name);
this->description_to_name_mapping[key] = program;
this->name_to_shader_names_mapping[program] = std::pair<int, int>{v_shader_name, f_shader_name};
this->name_to_description_mapping[program] = key;
this->program_reference_count[program] = 1;
return program;
}
void ProgramPool::release_program(GLuint program_name) {
program_reference_count[program_name]--;
}
| 31.613793 | 98 | 0.749564 | [
"vector"
] |
72b17fc1fe8b4d87ef17d94c26c7875bfc7a1168 | 749 | hpp | C++ | installation/installation_scripts/mvs-stereo-code-samples/include/eopcc/gdal_io.hpp | sebasmurphy/iarpa | aca39cc5390a153a9779a636ab2523e65cb6d3b0 | [
"MIT"
] | 20 | 2017-02-01T14:54:57.000Z | 2022-01-25T06:34:35.000Z | installation/installation_scripts/mvs-stereo-code-samples/include/eopcc/gdal_io.hpp | sebasmurphy/iarpa | aca39cc5390a153a9779a636ab2523e65cb6d3b0 | [
"MIT"
] | 3 | 2020-04-21T12:11:26.000Z | 2021-01-10T07:00:51.000Z | installation/installation_scripts/mvs-stereo-code-samples/include/eopcc/gdal_io.hpp | sebasmurphy/iarpa | aca39cc5390a153a9779a636ab2523e65cb6d3b0 | [
"MIT"
] | 10 | 2017-12-18T18:45:25.000Z | 2021-11-22T02:43:03.000Z | #pragma once
#include <eopcc/utility.hpp>
namespace eopcc {
void GdalCheckRegistration();
struct CropInfo {
int pixel_begin;
int pixel_end;
int line_begin;
int line_end;
};
struct ImageType {
int width;
int height;
int bands;
std::vector<uint16_t> data;
bool x_backwards, y_backwards;
ImageType () {
x_backwards = false;
y_backwards = false;
}
};
bool read_cropped_image(const char *imageFileName, ImageType &img, const CropInfo& crop_info,
int& min_intensity, int& max_intensity, char *err);
bool write_jpeg_file(const char *FileName, ImageType &img, unsigned int min_intensity, unsigned int max_intensity, char *err);
bool write_tiff_file(const char *FileName, ImageType &img, char *err);
} // end namespace eopcc | 20.805556 | 126 | 0.740988 | [
"vector"
] |
72b304d8c5995fba44edee7719176efe32559e36 | 3,423 | cpp | C++ | src/Character/Character.cpp | makzyt4/dungeon-saga | a367d35fe2c4404a380e61f5b363e4a812cfa2c5 | [
"MIT"
] | null | null | null | src/Character/Character.cpp | makzyt4/dungeon-saga | a367d35fe2c4404a380e61f5b363e4a812cfa2c5 | [
"MIT"
] | null | null | null | src/Character/Character.cpp | makzyt4/dungeon-saga | a367d35fe2c4404a380e61f5b363e4a812cfa2c5 | [
"MIT"
] | null | null | null | #include "../../include/Character/Character.hpp"
void ds::Character::draw() {
sf::Sprite sprite = currentAnimation->currentSprite();
sprite.setPosition(position.x, position.y);
window->draw(sprite);
}
void ds::Character::jump() {
float velocityY = -(2 + agility / 100.0f);
if (climbing) {
velocity.y = velocityY;
onGround = false;
return;
}
if (onGround && stamina.getValue() >= 3) {
stamina.addValue(-3);
velocity.y = -(2 + agility / 100.0f);
onGround = false;
}
}
void ds::Character::update() {
stamina.update();
health.update();
magicka.update();
stepDelay = std::max(0, stepDelay - 1);
if (velocity.x < -getMaxSpeed()) {
velocity.x = -getMaxSpeed();
} else if (velocity.x > getMaxSpeed()) {
velocity.x = getMaxSpeed();
}
currentAnimation->play();
setPosition(sf::Vector2f(position.x + velocity.x,
position.y + velocity.y));
if (!onGround) {
velocity.y += 0.12;
}
if (fabs(velocity.x) > 0.1) {
currentAnimation = direction == Direction::Left ?
&movingLeft :
&movingRight;
if (stepDelay == 0 && onGround) {
sf::Sound* sound = new sf::Sound();
sound->setBuffer(*stepBuffer);
sound->play();
stepDelay = 40;
}
} else {
velocity.x = 0;
currentAnimation = direction == Direction::Left ?
&standingLeft :
&standingRight;
}
velocity.x *= 0.9;
}
void ds::Character::collide(std::vector<ds::Block*>* blocks) {
sf::Vector2f tmpPosition = position;
onGround = false;
climbing = false;
for (Block* block : *blocks) {
if (!block->isCollidable()) {
continue;
}
sf::IntRect tmpRect;
// If block on the ground
tmpRect = rect;
tmpRect.top += fabs(velocity.y + 1);
if (block->getRect().intersects(tmpRect) && velocity.y >= 0) {
velocity.y = 0;
position.y = tmpPosition.y;
onGround = true;
}
// If block above
tmpRect = rect;
tmpRect.top -= fabs(velocity.y + 1);
if (block->getRect().intersects(tmpRect) && velocity.y < 0) {
position.y = tmpPosition.y;
velocity.y = fabs(velocity.y);
}
// If block on the left
tmpRect = rect;
tmpRect.left -= fabs(velocity.x) + 1;
if (block->getRect().intersects(tmpRect) && velocity.x < 0) {
position.x = tmpPosition.x - velocity.x;
}
// If block on the right
tmpRect = rect;
tmpRect.left += fabs(velocity.x) + 1;
if (block->getRect().intersects(tmpRect) && velocity.x > 0) {
position.x = tmpPosition.x - velocity.x;
}
}
for (Block* block : *blocks) {
if (rect.intersects(block->getRect()) && block->isClimbable()) {
climbing = true;
break;
}
}
}
float ds::Character::getAcceleration() {
return agility / 10.0f;
}
float ds::Character::getMaxSpeed() {
return 3 + agility / 10.0f;
}
sf::Vector2f ds::Character::getCenter() {
return sf::Vector2f(rect.left + rect.width / 2.0f,
rect.top + rect.height / 2.0f);
}
| 25.544776 | 72 | 0.518551 | [
"vector"
] |
72bd4c03f847660709f1c2286b5ed4cdaa2a58c8 | 13,606 | hpp | C++ | C++17/include/GMSHparserTools.hpp | wme7/GMSHparser | d23d16b8dfb688a7a3a7bf1344baea72ad1e1550 | [
"MIT"
] | null | null | null | C++17/include/GMSHparserTools.hpp | wme7/GMSHparser | d23d16b8dfb688a7a3a7bf1344baea72ad1e1550 | [
"MIT"
] | null | null | null | C++17/include/GMSHparserTools.hpp | wme7/GMSHparser | d23d16b8dfb688a7a3a7bf1344baea72ad1e1550 | [
"MIT"
] | null | null | null | #ifndef GMSH_PARSER_TOOLS
#define GMSH_PARSER_TOOLS
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// Common tools required for reading GMSH-file in format v2.2 and v4.1
//
// Coded by Manuel A. Diaz @ Pprime | Univ-Poitiers, 2022.01.21
//
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#include "Globals.hpp"
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Get a sub-string from the main string-buffer using two unique delimiters:
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::string extractBetween(
const std::string &buffer,
const std::string &start_delimiter,
const std::string &stop_delimiter)
{
if (buffer.find(start_delimiter) != std::string::npos)
{
size_t first_delim_pos = buffer.find(start_delimiter);
size_t end_pos_of_first_delim = first_delim_pos + start_delimiter.length();
size_t last_delim_pos = buffer.find(stop_delimiter);
return buffer.substr(end_pos_of_first_delim,
last_delim_pos - end_pos_of_first_delim);
}
else
{
return ""; // an empty string
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Get a sub-vector from a std::vector using two delimiters:
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::vector<size_t> extractVectorBetween(
const std::vector<size_t> Vec,
const size_t first_index,
const size_t last_index)
{
std::vector<size_t>::const_iterator first = Vec.begin() + first_index;
std::vector<size_t>::const_iterator last = Vec.begin() + last_index;
std::vector<size_t> subVec(first, last);
return subVec;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Build convention map of Boundary Elements (BE) for ParadigmS:
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::map<std::string,int> get_BE_type()
{
std::map<std::string,int> BE_type;
// Initialize map of BCs
BE_type["BCfile"]=0;
BE_type["free"]=1;
BE_type["wall"]=2;
BE_type["outflow"]=3;
BE_type["imposedPressure"]=4;
BE_type["imposedVelocities"]=5;
BE_type["axisymmetric_y"]=6;
BE_type["axisymmetric_x"]=7;
BE_type["BC_rec"]=10;
BE_type["free_rec"]=11;
BE_type["wall_rec"]=12;
BE_type["outflow_rec"]=13;
BE_type["imposedPressure_rec"]=14;
BE_type["imposedVelocities_rec"]=15;
BE_type["axisymmetric_y_rec"]=16;
BE_type["axisymmetric_x_rec"]=17;
BE_type["piston_pressure"]=18;
BE_type["piston_velocity"]=19;
BE_type["recordingObject"]=20;
BE_type["recObj"]=20;
BE_type["piston_stress"]=21;
return BE_type;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Build convention map of Domain Elements (DE) for ParadigmS:
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::map<std::string,int> get_DE_type()
{
std::map<std::string,int> DE_type;
// Initialize map of DEs
DE_type["fluid" ]=0;
DE_type["fluid1"]=1;
DE_type["fluid2"]=2;
DE_type["fluid3"]=3;
DE_type["fluid4"]=4;
DE_type["solid" ]=5;
DE_type["solid1"]=6;
DE_type["solid2"]=7;
DE_type["solid3"]=8;
DE_type["solid4"]=9;
return DE_type;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Parse string between brackets
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
size_t extractBetweenBrackets(const std::string &name)
{
if(name.find("[")!=std::string::npos)
{
size_t first_delim_pos = name.find("[");
size_t last_delim_pos = name.find("]");
std::string strNumber = name.substr(first_delim_pos+1,last_delim_pos);
return std::stoul(strNumber,nullptr,0); // ID
}
else
{
return 0; // ID = 0;
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Set a unique id type for the piston BCs
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
size_t parse_BC(const std::string &strName)
{
bool DEBUG = false;
size_t BEtype{0};
auto id = extractBetweenBrackets(strName);
if(strName.find("BC_piston_pressure")!=std::string::npos){BEtype=1000+id;}
if(strName.find("BC_piston_velocity")!=std::string::npos){BEtype=2000+id;}
if(strName.find( "BC_piston_stress" )!=std::string::npos){BEtype=3000+id;}
if(DEBUG) std::cout << "active boundary condition, BEtype=" << BEtype << std::endl;
return BEtype;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Set a unique id for every recording object
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
size_t parse_rec(const std::string &strName)
{
bool DEBUG = false;
size_t BEtype{0};
auto id = extractBetweenBrackets(strName);
if(id<999) {BEtype=600+id;}
else {std::cout << "problem in parse_rec with the id of the recording object" << std::endl;}
if(DEBUG) std::cout << "active boundary condition, BEtype=" << BEtype << std::endl;
return BEtype;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Element structure to be acquired:
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
struct element
{
std::vector<size_t> EToV;
std::vector<int> phys_tag;
std::vector<int> geom_tag;
std::vector<int> part_tag;
std::vector<int> Etype;
};
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Split and input strings and return a vector with all double values
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::vector<double> str2double(const std::string &str)
{
std::stringstream ss(str);
std::istream_iterator<double> begin(ss);
std::istream_iterator<double> end;
std::vector<double> values(begin,end);
return values;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Split and input strings and return a vector with all size_t values
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::vector<size_t> str2size_t(const std::string &str)
{
std::stringstream ss(str);
std::istream_iterator<size_t> begin(ss);
std::istream_iterator<size_t> end;
std::vector<size_t> values(begin,end);
return values;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Get entity Tag and its associated physical Tag.
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::tuple<size_t, int> get_entity(const std::string &line, const size_t &Idx)
{
size_t entityTag;
size_t numPhysicalTags;
int physicalTag;
// get line data
auto vector = str2double(line);
switch (Idx) {
case 1: // case for nodes
// 1. get entityTag
entityTag = int(vector[0]);
// 2. get entity coordiantes // not needed
// ignore indexes 1, 2, 3
// 3. get physical tag associated
numPhysicalTags = int(vector[4]);
if (numPhysicalTags==0) {
physicalTag = -1; // set a negative tag!
} else {
physicalTag = int(vector[5]);
}
break;
default: // otherwise
// 1. get entityTag
entityTag = int(vector[0]);
// 2. get entity coordiantes // not needed
// ignore indexes 1, 2, 3, 4, 5, 6
// 3. get physical tag associated
numPhysicalTags = int(vector[7]);
if (numPhysicalTags==0) {
physicalTag = -1; // set a negative tag!
} else {
physicalTag = int(vector[8]);
}
// 4. get tags of subentities. // not needed
break;
}
return {entityTag, physicalTag};
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Get partitioned entity Tags and its associated physical Tag.
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
std::tuple<size_t, size_t, int, int> get_partitionedEntity(const std::string &line, const size_t &Idx)
{
size_t entityTag, parentTag;
size_t numPhysicalTags, numPartitionsTags;
int partitionTag, physicalTag;
// get line data
auto vector = str2double(line);
switch (Idx) {
case 1: // case for nodes
// 1. get entityTag
entityTag = int(vector[0]);
// 2. get parent dimension and tag
//parentDim = int(vector[1]); // not needed
parentTag = int(vector[2]);
// 3. get partitions tags
numPartitionsTags = int(vector[3]);
if (numPartitionsTags > 1) { // --> mark it as an interface element!
partitionTag = -1;
} else {
partitionTag = int(vector[4]);
}
// 4. get entity coordiantes // not needed
// ignore indexes 5, 6, 7
// 5. get physical tag associated
numPhysicalTags = int(vector[7+numPartitionsTags]);
if (numPhysicalTags==0) {
physicalTag = -1; // set a negative tag!
} else {
physicalTag = int(vector[8+numPartitionsTags]);
}
break;
default: //otherwise
// 1. get entityTag
entityTag = int(vector[0]);
// 2. get parent dimension and tag
//parentDim = int(vector[1]); // not needed
parentTag = int(vector[2]);
// 3. get partitions tags
numPartitionsTags = int(vector[3]);
if (numPartitionsTags > 1) { // --> mark it as an interface element!
partitionTag = -1; // set a negative tag!
} else {
partitionTag = int(vector[4]);
}
// 4. get entity coordiantes // not needed
// ignore indexes 5, 6, 7, 8, 9, 10
// 5. get physical tag associated
numPhysicalTags = int(vector[10+numPartitionsTags]);
if (numPhysicalTags==0) {
physicalTag = -1;
} else {
physicalTag = int(vector[11+numPartitionsTags]);
}
break;
}
return {entityTag, parentTag, partitionTag, physicalTag};
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Get nodes from block system (GMSG format 4.1)
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MArray<double,2> get_nodes(const std::string &Nodes, const size_t &numNodesBlocks, const size_t &numNodes, const size_t Dim, const size_t one)
{
// Allocate output
MArray<double,2> V({numNodes,Dim},0); // [x(:),y(:),z(:)]
// Node counter
size_t n=0;
size_t nID;
std::stringstream buffer(Nodes);
std::string line;
std::getline(buffer, line); // l = 1;
// Read nodes blocks: (this can be done in parallel!)
for (size_t i=0; i<numNodesBlocks; i++)
{
// update line counter, l = l+1;
std::getline(buffer, line);
std::stringstream hearder(line);
// Read Block parameters
size_t entityDim; // not needed
size_t entityTag; // not needed
size_t parametric; // not needed
size_t numNodesInBlock;
hearder >> entityDim >> entityTag >> parametric >> numNodesInBlock;
// Read Nodes IDs
size_t *nodeTag = new size_t[numNodesInBlock]; // nodeTag
for (size_t i=0; i<numNodesInBlock; i++)
{
std::getline(buffer, line);
std::stringstream stream(line);
stream >> nodeTag[i];
}
// Read Nodes Coordinates
for (size_t i=0; i<numNodesInBlock; i++)
{
std::getline(buffer, line);
std::stringstream stream(line);
nID = nodeTag[i]-one;
if (Dim==2) {stream >> V(nID,0) >> V(nID,1);}
if (Dim==3) {stream >> V(nID,0) >> V(nID,1) >> V(nID,2);}
n = n+1; // Update node counter
}
// Delete temporary new-arrays
delete [] nodeTag;
}
return V;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Get nodes from block system (GMSH format 2.2)
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MArray<double,2> get_nodes(const std::string &Nodes, const size_t &numNodes, const size_t Dim)
{
// Allocate output
MArray<double,2> V({numNodes,Dim},0); // [x(:),y(:),z(:)]
// Node counter
size_t nodeTag;
std::stringstream buffer(Nodes);
std::string line;
std::getline(buffer, line); // l = 1;
// Read nodes blocks:
for (size_t i=0; i<numNodes; i++)
{
std::getline(buffer, line);
std::stringstream stream(line);
if (Dim==2) {stream >> nodeTag >> V(i,0) >> V(i,1);}
if (Dim==3) {stream >> nodeTag >> V(i,0) >> V(i,1) >> V(i,2);}
}
return V;
}
#endif | 35.432292 | 144 | 0.474717 | [
"object",
"vector",
"solid"
] |
72c0102e222fa985cdc695878faab0715ad7f1d0 | 47,524 | hh | C++ | include/sicktoolbox/SickLD.hh | eurogroep/sicktoolbox | b5d2257c1a8b03d5c49489da486c2bbb6de47566 | [
"BSD-3-Clause"
] | 457 | 2020-03-21T05:27:37.000Z | 2022-03-30T12:05:52.000Z | include/sicktoolbox/SickLD.hh | eurogroep/sicktoolbox | b5d2257c1a8b03d5c49489da486c2bbb6de47566 | [
"BSD-3-Clause"
] | 29 | 2020-05-18T16:48:06.000Z | 2022-03-31T05:43:24.000Z | include/sicktoolbox/SickLD.hh | eurogroep/sicktoolbox | b5d2257c1a8b03d5c49489da486c2bbb6de47566 | [
"BSD-3-Clause"
] | 121 | 2020-03-21T06:43:04.000Z | 2022-03-31T12:27:29.000Z | /*!
* \file SickLD.hh
* \brief Defines the SickLD class for working with the
* Sick LD-OEM/LD-LRS long range LIDARs.
*
* Code by Jason C. Derenick and Thomas H. Miller.
* Contact derenick(at)lehigh(dot)edu
*
* The Sick LIDAR Matlab/C++ Toolbox
* Copyright (c) 2008, Jason C. Derenick and Thomas H. Miller
* All rights reserved.
*
* This software is released under a BSD Open-Source License.
* See http://sicktoolbox.sourceforge.net
*/
#ifndef SICK_LD_HH
#define SICK_LD_HH
/* Macros */
#define DEFAULT_SICK_IP_ADDRESS "192.168.1.10" ///< Default Sick LD INet 4 address
#define DEFAULT_SICK_TCP_PORT (49152) ///< Default TCP port
#define DEFAULT_SICK_MESSAGE_TIMEOUT (unsigned int)(5e6) ///< The max time to wait for a message reply (usecs)
#define DEFAULT_SICK_CONNECT_TIMEOUT (unsigned int)(1e6) ///< The max time to wait before considering a connection attempt as failed (usecs)
#define DEFAULT_SICK_NUM_SCAN_PROFILES (0) ///< Setting this value to 0 will tell the Sick LD to stream measurements when measurement data is requested (NOTE: A profile is a single scans worth of range measurements)
#define DEFAULT_SICK_SIGNAL_SET (0) ///< Default Sick signal configuration
/**
* \def SWAP_VALUES(x,y,t)
* \brief A simple macro for swapping two values.
*/
#define SWAP_VALUES(x,y,t) (t=x,x=y,y=t);
/* Definition dependencies */
#include <string>
#include <vector>
#include <pthread.h>
#include <arpa/inet.h>
#include "SickLIDAR.hh"
#include "SickLDBufferMonitor.hh"
#include "SickLDMessage.hh"
#include "SickException.hh"
/**
* \namespace SickToolbox
* \brief Encapsulates the Sick LIDAR Matlab/C++ toolbox
*/
namespace SickToolbox {
/**
* \class SickLD
* \brief Provides a simple driver interface for working with the
* Sick LD-OEM/Sick LD-LRS long-range models via Ethernet.
*/
class SickLD : public SickLIDAR< SickLDBufferMonitor, SickLDMessage > {
public:
/* Some constants for the developer/end-user */
static const uint16_t SICK_MAX_NUM_MEASUREMENTS = 2881; ///< Maximum number of measurements per sector
static const uint16_t SICK_MAX_NUM_SECTORS = 8; ///< Maximum number of scan sectors (NOTE: This value must be even)
static const uint16_t SICK_MAX_NUM_MEASURING_SECTORS = 4; ///< Maximum number of active/measuring scan sectors
static const uint16_t SICK_MAX_SCAN_AREA = 360; ///< Maximum area that can be covered in a single scan (deg)
static const uint16_t SICK_MIN_MOTOR_SPEED = 5; ///< Minimum motor speed in Hz
static const uint16_t SICK_MAX_MOTOR_SPEED = 20; ///< Maximum motor speed in Hz
static const uint16_t SICK_MIN_VALID_SENSOR_ID = 1; ///< The lowest value the Sick will accept as a Sensor ID
static const uint16_t SICK_MAX_VALID_SENSOR_ID = 254; ///< The largest value the Sick will accept as a Sensor ID
static const uint16_t SICK_MAX_MEAN_PULSE_FREQUENCY = 10800; ///< Max mean pulse frequence of the current device configuration (in Hz) (see page 22 of the operator's manual)
static const uint16_t SICK_MAX_PULSE_FREQUENCY = 14400; ///< Max pulse frequency of the device (in Hz) (see page 22 of the operator's manual)
static const uint16_t SICK_NUM_TICKS_PER_MOTOR_REV = 5760; ///< Odometer ticks per revolution of the Sick LD scan head
static constexpr double SICK_MAX_SCAN_ANGULAR_RESOLUTION = 0.125; ///< Minimum valid separation between laser pulses in active scan ares (deg)
static constexpr double SICK_DEGREES_PER_MOTOR_STEP = 0.0625; ///< Each odometer tick is equivalent to rotating the scan head this many degrees
/* Sick LD sensor modes of operation */
static const uint8_t SICK_SENSOR_MODE_IDLE = 0x01; ///< The Sick LD is powered but idle
static const uint8_t SICK_SENSOR_MODE_ROTATE = 0x02; ///< The Sick LD prism is rotating, but laser is off
static const uint8_t SICK_SENSOR_MODE_MEASURE = 0x03; ///< The Sick LD prism is rotating, and the laser is on
static const uint8_t SICK_SENSOR_MODE_ERROR = 0x04; ///< The Sick LD is in error mode
static const uint8_t SICK_SENSOR_MODE_UNKNOWN = 0xFF; ///< The Sick LD is in an unknown state
/* Sick LD motor modes */
static const uint8_t SICK_MOTOR_MODE_OK = 0x00; ///< Motor is functioning properly
static const uint8_t SICK_MOTOR_MODE_SPIN_TOO_HIGH = 0x09; ///< Motor spin too low (i.e. rotational velocity too low)
static const uint8_t SICK_MOTOR_MODE_SPIN_TOO_LOW = 0x04; ///< Motor spin too high (i.e. rotational velocity too fast)
static const uint8_t SICK_MOTOR_MODE_ERROR = 0x0B; ///< Motor stops or coder error
static const uint8_t SICK_MOTOR_MODE_UNKNOWN = 0xFF; ///< Motor is in an unknown state
/* Sick LD service codes */
static const uint8_t SICK_STAT_SERV_CODE = 0x01; ///< Status service code
static const uint8_t SICK_CONF_SERV_CODE = 0x02; ///< Configuration service code
static const uint8_t SICK_MEAS_SERV_CODE = 0x03; ///< Measurement service code
static const uint8_t SICK_WORK_SERV_CODE = 0x04; ///< Working service code
static const uint8_t SICK_ROUT_SERV_CODE = 0x06; ///< Routing service code
static const uint8_t SICK_FILE_SERV_CODE = 0x07; ///< File service code
static const uint8_t SICK_MONR_SERV_CODE = 0x08; ///< Monitor service code
/* Sick LD status services (service code 0x01) */
static const uint8_t SICK_STAT_SERV_GET_ID = 0x01; ///< Request the Sick LD ID
static const uint8_t SICK_STAT_SERV_GET_STATUS = 0x02; ///< Request status information
static const uint8_t SICK_STAT_SERV_GET_SIGNAL = 0x04; ///< Reads the value of the switch and LED port
static const uint8_t SICK_STAT_SERV_SET_SIGNAL = 0x05; ///< Sets the switches and LEDs
static const uint8_t SICK_STAT_SERV_LD_REGISTER_APPLICATION = 0x06; ///< Registers the ID data for the application firmware
/* Sick LD status service GET_IDENTIFICATION request codes */
static const uint8_t SICK_STAT_SERV_GET_ID_SENSOR_PART_NUM = 0x00; ///< Request the sensor's part number
static const uint8_t SICK_STAT_SERV_GET_ID_SENSOR_NAME = 0x01; ///< Request the sensor's name
static const uint8_t SICK_STAT_SERV_GET_ID_SENSOR_VERSION = 0x02; ///< Request the sensor's version
static const uint8_t SICK_STAT_SERV_GET_ID_SENSOR_SERIAL_NUM = 0x03; ///< Request the sensor's serial number
static const uint8_t SICK_STAT_SERV_GET_ID_SENSOR_EDM_SERIAL_NUM = 0x04; ///< Request the edm??? serial number
static const uint8_t SICK_STAT_SERV_GET_ID_FIRMWARE_PART_NUM = 0x10; ///< Requess the firmware's part number
static const uint8_t SICK_STAT_SERV_GET_ID_FIRMWARE_NAME = 0x11; ///< Request the firmware's name
static const uint8_t SICK_STAT_SERV_GET_ID_FIRMWARE_VERSION = 0x12; ///< Request the firmware's version
static const uint8_t SICK_STAT_SERV_GET_ID_APP_PART_NUM = 0x20; ///< Request the application part number
static const uint8_t SICK_STAT_SERV_GET_ID_APP_NAME = 0x21; ///< Request the application name
static const uint8_t SICK_STAT_SERV_GET_ID_APP_VERSION = 0x22; ///< Request the application version
/* Sick LD configuration services (service code 0x02) */
static const uint8_t SICK_CONF_SERV_SET_CONFIGURATION = 0x01; ///< Set the Sick LD configuration
static const uint8_t SICK_CONF_SERV_GET_CONFIGURATION = 0x02; ///< Read the Sick LD configuration information
static const uint8_t SICK_CONF_SERV_SET_TIME_ABSOLUTE = 0x03; ///< Set the internal clock to a timestamp value
static const uint8_t SICK_CONF_SERV_SET_TIME_RELATIVE = 0x04; ///< Correct the internal clock by some value
static const uint8_t SICK_CONF_SERV_GET_SYNC_CLOCK = 0x05; ///< Read the internal time of the LD-OEM/LD-LRS
static const uint8_t SICK_CONF_SERV_SET_FILTER = 0x09; ///< Set the filter configuration
static const uint8_t SICK_CONF_SERV_SET_FUNCTION = 0x0A; ///< Assigns a measurement function to an angle range
static const uint8_t SICK_CONF_SERV_GET_FUNCTION = 0x0B; ///< Returns the configuration of the given sector
/* Sick LD configuration filter codes */
static const uint8_t SICK_CONF_SERV_SET_FILTER_NEARFIELD = 0x01; ///< Code for identifying filter type: nearfield suppression
/* Sick LD nearfield suppression configuration codes */
static const uint8_t SICK_CONF_SERV_SET_FILTER_NEARFIELD_OFF = 0x00; ///< Used to set nearfield suppression off
static const uint8_t SICK_CONF_SERV_SET_FILTER_NEARFIELD_ON = 0x01; ///< Used to set nearfield suppression on
/* Sick LD measurement services (service code 0x03) */
static const uint8_t SICK_MEAS_SERV_GET_PROFILE = 0x01; ///< Requests n profiles of a defined format
static const uint8_t SICK_MEAS_SERV_CANCEL_PROFILE = 0x02; ///< Stops profile output
/* Sick LD working services (service code 0x04) */
static const uint8_t SICK_WORK_SERV_RESET = 0x01; ///< Sick LD enters a reset sequence
static const uint8_t SICK_WORK_SERV_TRANS_IDLE = 0x02; ///< Sick LD enters IDLE mode (motor stops and laser is turned off)
static const uint8_t SICK_WORK_SERV_TRANS_ROTATE = 0x03; ///< Sick LD enters ROTATE mode (motor starts and rotates with a specified speed in Hz, laser is off)
static const uint8_t SICK_WORK_SERV_TRANS_MEASURE = 0x04; ///< Sick LD enters MEASURE mode (laser starts with next revolution)
/* Sick LD working service DO_RESET request codes */
static const uint8_t SICK_WORK_SERV_RESET_INIT_CPU = 0x00; ///< Sick LD does a complete reset (Reinitializes the CPU)
static const uint8_t SICK_WORK_SERV_RESET_KEEP_CPU = 0x01; ///< Sick LD does a partial reset (CPU is not reinitialized)
static const uint8_t SICK_WORK_SERV_RESET_HALT_APP = 0x02; ///< Sick LD does a minimal reset (Application is halted and device enters IDLE state)
/* Sick LD working service TRANS_MEASURE return codes */
static const uint8_t SICK_WORK_SERV_TRANS_MEASURE_RET_OK = 0x00; ///< Sick LD is ready to stream/obtain scan profiles
static const uint8_t SICK_WORK_SERV_TRANS_MEASURE_RET_ERR_MAX_PULSE = 0x01; ///< Sick LD reports config yields a max laser pulse frequency that is too high
static const uint8_t SICK_WORK_SERV_TRANS_MEASURE_RET_ERR_MEAN_PULSE = 0x02; ///< Sick LD reports config yields a max mean pulse frequency that is too high
static const uint8_t SICK_WORK_SERV_TRANS_MEASURE_RET_ERR_SECT_BORDER = 0x03; ///< Sick LD reports sector borders are not configured correctly
static const uint8_t SICK_WORK_SERV_TRANS_MEASURE_RET_ERR_SECT_BORDER_MULT = 0x04; ///< Sick LD reports sector borders are not a multiple of the step angle
/* Sick LD interface routing services (service code 0x06) */
static const uint8_t SICK_ROUT_SERV_COM_ATTACH = 0x01; ///< Attach a master (host) communications interface
static const uint8_t SICK_ROUT_SERV_COM_DETACH = 0x02; ///< Detach a master (host) communications interface
static const uint8_t SICK_ROUT_SERV_COM_INITIALIZE = 0x03; ///< Initialize the interface (Note: using this may not be necessary for some interfaces, e.g. Ethernet)
static const uint8_t SICK_ROUT_SERV_COM_OUTPUT = 0x04; ///< Output data to the interface
static const uint8_t SICK_ROUT_SERV_COM_DATA = 0x05; ///< Forward data received on specified interface to master interface
/* Sick LD file services (service code 0x07) */
static const uint8_t SICK_FILE_SERV_DIR = 0x01; ///< List the stored files in flash memory
static const uint8_t SICK_FILE_SERV_SAVE = 0x02; ///< Saves the data into flash memory
static const uint8_t SICK_FILE_SERV_LOAD = 0x03; ///< Recalls a file from the flash
static const uint8_t SICK_FILE_SERV_DELETE = 0x04; ///< Deletes a file from the flash
/* Sick LD monitor services (service code 0x08) */
static const uint8_t SICK_MONR_SERV_MONITOR_RUN = 0x01; ///< Enable/disable monitor services
static const uint8_t SICK_MONR_SERV_MONITOR_PROFILE_LOG = 0x02; ///< Enable/disable profile logging
/* Sick LD configuration keys */
static const uint8_t SICK_CONF_KEY_RS232_RS422 = 0x01; ///< Key for configuring RS-232/RS-422
static const uint8_t SICK_CONF_KEY_CAN = 0x02; ///< Key for configuring CAN
static const uint8_t SICK_CONF_KEY_ETHERNET = 0x05; ///< Key for configuring Ethernet
static const uint8_t SICK_CONF_KEY_GLOBAL = 0x10; ///< Key for global configuration
/* Sick LD sector configuration codes */
static const uint8_t SICK_CONF_SECTOR_NOT_INITIALIZED = 0x00; ///< Sector is uninitialized
static const uint8_t SICK_CONF_SECTOR_NO_MEASUREMENT = 0x01; ///< Sector has no measurements
static const uint8_t SICK_CONF_SECTOR_RESERVED = 0x02; ///< Sector is reserved by Sick LD
static const uint8_t SICK_CONF_SECTOR_NORMAL_MEASUREMENT = 0x03; ///< Sector is returning measurements
static const uint8_t SICK_CONF_SECTOR_REFERENCE_MEASUREMENT = 0x04; ///< Sector can be used as reference measurement
/* Sick LD profile formats */
static const uint16_t SICK_SCAN_PROFILE_RANGE = 0x39FF; ///< Request sector scan data w/o any echo data
/*
* SICK_SCAN_PROFILE_RANGE format (0x39FF) interpretation:
* (See page 32 of telegram listing for fieldname definitions)
*
* Field Name | Send
* --------------------
* PROFILESENT | YES
* PROFILECOUNT | YES
* LAYERNUM | YES
* SECTORNUM | YES
* DIRSTEP | YES
* POINTNUM | YES
* TSTART | YES
* STARTDIR | YES
* DISTANCE-n | YES
* DIRECTION-n | NO
* ECHO-n | NO
* TEND | YES
* ENDDIR | YES
* SENSTAT | YES
*/
/* Sick LD profile formats */
static const uint16_t SICK_SCAN_PROFILE_RANGE_AND_ECHO = 0x3DFF; ///< Request sector scan data w/ echo data
/*
* SICK_SCAN_PROFILE_RANGE format (0x3DFF) interpretation:
* (See page 32 of telegram listing for fieldname definitions)
*
* Field Name | Send
* --------------------
* PROFILESENT | YES
* PROFILECOUNT | YES
* LAYERNUM | YES
* SECTORNUM | YES
* DIRSTEP | YES
* POINTNUM | YES
* TSTART | YES
* STARTDIR | YES
* DISTANCE-n | YES
* DIRECTION-n | NO
* ECHO-n | YES
* TEND | YES
* ENDDIR | YES
* SENSTAT | YES
*/
/* Masks for working with the Sick LD signals
*
* NOTE: Although the Sick LD manual defines the flag
* values for red and green LEDs the operation
* of these LEDs are reserved. So they can't
* be set by the device driver.
*/
static const uint8_t SICK_SIGNAL_LED_YELLOW_A = 0x01; ///< Mask for first yellow LED
static const uint8_t SICK_SIGNAL_LED_YELLOW_B = 0x02; ///< Mask for second yellow LED
static const uint8_t SICK_SIGNAL_LED_GREEN = 0x04; ///< Mask for green LED
static const uint8_t SICK_SIGNAL_LED_RED = 0x08; ///< Mask for red LED
static const uint8_t SICK_SIGNAL_SWITCH_0 = 0x10; ///< Mask for signal switch 0
static const uint8_t SICK_SIGNAL_SWITCH_1 = 0x20; ///< Mask for signal switch 1
static const uint8_t SICK_SIGNAL_SWITCH_2 = 0x40; ///< Mask for signal switch 2
static const uint8_t SICK_SIGNAL_SWITCH_3 = 0x80; ///< Mask for signal switch 3
/**
* \struct sick_ld_config_global_tag
* \brief A structure to aggregate the data used to configure the
* Sick LD global parameter values.
*/
/**
* \typedef sick_ld_config_global_t
* \brief Adopt c-style convention
*/
typedef struct sick_ld_config_global_tag {
uint16_t sick_sensor_id; ///< The single word sensor ID for the Sick unit
uint16_t sick_motor_speed; ///< Nominal motor speed value: 0x0005 to 0x0014 (5 to 20)
double sick_angle_step; ///< Difference between two laser pulse positions in 1/16th deg. (NOTE: this value must be a divisor of 5760 and be greater than 1)
} sick_ld_config_global_t;
/**
* \struct sick_ld_config_ethernet_tag
* \brief A structure to aggregate the data used to configure
* the Sick LD unit for Ethernet.
*
* \todo Eventually add similar config structures for the other protocols.
*/
/**
* \typedef sick_ld_config_ethernet_t
* \brief Adopt c-style convention
*/
typedef struct sick_ld_config_ethernet_tag {
uint16_t sick_ip_address[4]; ///< IP address in numerical form w/ leftmost part at sick_ip_address[0]
uint16_t sick_subnet_mask[4]; ///< Subnet mask for the network to which the Sick LD is assigned
uint16_t sick_gateway_ip_address[4]; ///< The address of the local gateway
uint16_t sick_node_id; ///< Single word address of the Sick LD
uint16_t sick_transparent_tcp_port; ///< The TCP/IP transparent port associated with the Sick LD
} sick_ld_config_ethernet_t;
/**
* \struct sick_ld_config_sector_tag
* \brief A structure to aggregate data used to define the
* Sick LD's sector configuration.
*/
/**
* \typedef sick_ld_config_sector_t
* \brief Adopt c-style convention
*/
typedef struct sick_ld_config_sector_tag {
uint8_t sick_num_active_sectors; ///< Number of active sectors (sectors that are actually being scanned)
uint8_t sick_num_initialized_sectors; ///< Number of sectors configured w/ a function other than "not initialized"
uint8_t sick_active_sector_ids[SICK_MAX_NUM_SECTORS]; ///< IDs of all active sectors
uint8_t sick_sector_functions[SICK_MAX_NUM_SECTORS]; ///< Function values associated w/ each of the Sick LD's sectors
double sick_sector_start_angles[SICK_MAX_NUM_SECTORS]; ///< Start angles for each initialized sector (deg)
double sick_sector_stop_angles[SICK_MAX_NUM_SECTORS]; ///< Stop angles for each sector (deg)
} sick_ld_config_sector_t;
/**
* \struct sick_ld_identity_tag
* \brief A structure to aggregate the fields that collectively
* define the identity of a Sick LD unit.
*/
/**
* \typedef sick_ld_identity_t
* \brief Adopt c-style convention
*/
typedef struct sick_ld_identity_tag {
std::string sick_part_number; ///< The Sick LD's part number
std::string sick_name; ///< The name assigned to the Sick
std::string sick_version; ///< The Sick LD's version number
std::string sick_serial_number; ///< The Sick LD's serial number
std::string sick_edm_serial_number; ///< The Sick LD's edm??? serial number
std::string sick_firmware_part_number; ///< The Sick LD's firmware part number
std::string sick_firmware_name; ///< The Sick LD's firmware name
std::string sick_firmware_version; ///< The Sick LD's firmware version
std::string sick_application_software_part_number; ///< The Sick LD's app. software part number
std::string sick_application_software_name; ///< The Sick LD's app. software name
std::string sick_application_software_version; ///< The Sick LD's app. software version
} sick_ld_identity_t;
/**
* \struct sick_ld_sector_data_tag
* \brief A structure to aggregate the fields that collectively
* define a sector in the scan area of the Sick LD unit.
*/
/**
* \typedef sick_ld_sector_data_t
* \brief Adopt c-style convention
*/
typedef struct sick_ld_sector_data_tag {
unsigned int sector_num; ///< The sector number in the scan area
unsigned int num_data_points; ///< The number of data points in the scan area
unsigned int timestamp_start; ///< The timestamp (in ms) corresponding to the time the first measurement in the sector was taken
unsigned int timestamp_stop; ///< The timestamp (in ms) corresponding to the time the last measurement in the sector was taken
unsigned int echo_values[SICK_MAX_NUM_MEASUREMENTS]; ///< The corresponding echo/reflectivity values
double angle_step; ///< The angle step used for the given sector (this should be the same for all sectors)
double angle_start; ///< The angle at which the first measurement in the sector was acquired
double angle_stop; ///< The angle at which the last measurement in the sector was acquired
double range_values[SICK_MAX_NUM_MEASUREMENTS]; ///< The corresponding range values (NOTE: The size of this array is intended to be large enough to accomodate various sector configs.)
double scan_angles[SICK_MAX_NUM_MEASUREMENTS]; ///< The scan angles corresponding to the respective measurements
} sick_ld_sector_data_t;
/**
* \struct sick_ld_scan_profile_tag
* \brief A structure to aggregate the fields that collectively
* define the profile of a single scan acquired from the
* Sick LD unit.
*/
/**
* \typedef sick_ld_scan_profile_t
* \brief Adopt c-style convention
*/
typedef struct sick_ld_scan_profile_tag {
unsigned int profile_number; ///< The number of profiles sent to the host (i.e. the current profile number)
unsigned int profile_counter; ///< The number of profiles gathered by the Sick LD
unsigned int layer_num; ///< The layer number associated with a scan (this will always be 0)
unsigned int sensor_status; ///< The status of the Sick LD sensor
unsigned int motor_status; ///< The status of the Sick LD motor
unsigned int num_sectors; ///< The number of sectors returned in the profile
sick_ld_sector_data_t sector_data[SICK_MAX_NUM_SECTORS]; ///< The sectors associated with the scan profile
} sick_ld_scan_profile_t;
/** Primary constructor */
SickLD( const std::string sick_ip_address = DEFAULT_SICK_IP_ADDRESS,
const uint16_t sick_tcp_port = DEFAULT_SICK_TCP_PORT );
/** Initializes the Sick LD unit (use scan areas defined in flash) */
void Initialize( ) throw( SickIOException, SickThreadException, SickTimeoutException, SickErrorException );
/** Gets the sensor and motor mode of the unit */
void GetSickStatus( unsigned int &sick_sensor_mode, unsigned int &sick_motor_mode )
throw( SickIOException, SickTimeoutException );
/** Sets the temporal scan configuration (until power is cycled) */
void SetSickTempScanAreas( const double * active_sector_start_angles, const double * const active_sector_stop_angles,
const unsigned int num_active_sectors )
throw( SickTimeoutException, SickIOException, SickConfigException );
/** Sets the internal clock of the Sick LD unit */
void SetSickTimeAbsolute( const uint16_t absolute_clock_time, uint16_t &new_sick_clock_time )
throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException );
/** Sets the internal clock of the Sick LD using the relative given time value */
void SetSickTimeRelative( const int16_t time_delta, uint16_t &new_sick_clock_time )
throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException );
/** Gets the internal clock time of the Sick LD unit */
void GetSickTime( uint16_t &sick_time )
throw( SickIOException, SickTimeoutException, SickErrorException );
/** Sets the signal LEDs and switches */
void SetSickSignals( const uint8_t sick_signal_flags = DEFAULT_SICK_SIGNAL_SET )
throw( SickIOException, SickTimeoutException, SickErrorException );
/** Query the Sick for its current signal settings */
void GetSickSignals( uint8_t &sick_signal_flags ) throw( SickIOException, SickTimeoutException );
/** Enables nearfield suppressive filtering (in flash) */
void EnableNearfieldSuppression( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Disables nearfield suppressive filtering (in flash) */
void DisableNearfieldSuppression( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Acquires measurements and related data for all active sectors */
void GetSickMeasurements( double * const range_measurements,
unsigned int * const echo_measurements = NULL,
unsigned int * const num_measurements = NULL,
unsigned int * const sector_ids = NULL,
unsigned int * const sector_data_offsets = NULL,
double * const sector_step_angles = NULL,
double * const sector_start_angles = NULL,
double * const sector_stop_angles = NULL,
unsigned int * const sector_start_timestamps = NULL,
unsigned int * const sector_stop_timestamps = NULL )
throw( SickErrorException, SickIOException, SickTimeoutException, SickConfigException );
/** Attempts to set a new senor ID for the device (in flash) */
void SetSickSensorID( const unsigned int sick_sensor_id )
throw( SickErrorException, SickTimeoutException, SickIOException );
/** Attempts to set a new motor speed for the device (in flash) */
void SetSickMotorSpeed( const unsigned int sick_motor_speed )
throw( SickErrorException, SickTimeoutException, SickIOException );
/** Attempts to set a new scan resolution for the device (in flash) */
void SetSickScanResolution( const double sick_step_angle )
throw( SickTimeoutException, SickIOException, SickConfigException );
/** Attempts to set the global params and the active scan sectors for the device (in flash) */
void SetSickGlobalParamsAndScanAreas( const unsigned int sick_motor_speed,
const double sick_step_angle,
const double * const active_sector_start_angles,
const double * const active_sector_stop_angles,
const unsigned int num_active_sectors )
throw( SickTimeoutException, SickIOException, SickConfigException, SickErrorException );
/** Attempts to set the active scan sectors for the device (in flash) */
void SetSickScanAreas( const double * const active_sector_start_angles,
const double * const active_sector_stop_angles,
const unsigned int num_active_sectors )
throw( SickTimeoutException, SickIOException, SickConfigException, SickErrorException );
/** Resets the Sick LD using the given reset level */
void ResetSick( const unsigned int reset_level = SICK_WORK_SERV_RESET_INIT_CPU )
throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException );
/** Returns the number of active/measuring sectors */
unsigned int GetSickNumActiveSectors( ) const;
/** Acquire the Sick LD's sensor ID */
unsigned int GetSickSensorID( ) const;
/** Acquire the Sick LD's current motor speed in Hz */
unsigned int GetSickMotorSpeed( ) const;
/** Acquire the Sick LD's current scan resolution */
double GetSickScanResolution( ) const;
/** Acquire the current IP address of the Sick */
std::string GetSickIPAddress( ) const;
/** Acquire the subnet mask for the Sick */
std::string GetSickSubnetMask( ) const;
/** Acquire the IP address of the Sick gateway */
std::string GetSickGatewayIPAddress( ) const;
/** Acquire the Sick LD's part number */
std::string GetSickPartNumber( ) const;
/** Acquire the Sick LD's name */
std::string GetSickName( ) const;
/** Acquire the Sick LD's version number */
std::string GetSickVersion( ) const;
/** Acquire the Sick LD's serial number */
std::string GetSickSerialNumber( ) const;
/** Acquire the Sick LD's EDM serial number */
std::string GetSickEDMSerialNumber( ) const;
/** Acquire the Sick LD's firmware part number */
std::string GetSickFirmwarePartNumber( ) const;
/** Acquire the Sick LD's firmware number */
std::string GetSickFirmwareName( ) const;
/** Acquire the Sick LD's firmware version */
std::string GetSickFirmwareVersion( ) const;
/** Acquire the Sick LD's application software part number */
std::string GetSickAppSoftwarePartNumber( ) const;
/** Acquire the Sick LD's application software name */
std::string GetSickAppSoftwareName( ) const;
/** Acquire the Sick LD's application software version number */
std::string GetSickAppSoftwareVersionNumber( ) const;
/** Acquire the Sick LD's status as a printable string */
std::string GetSickStatusAsString() const;
/** Acquire the Sick LD's identity as a printable string */
std::string GetSickIdentityAsString() const;
/** Acquire the Sick LD's global config as a printable string */
std::string GetSickGlobalConfigAsString() const;
/** Acquire the Sick LD's Ethernet config as a printable string */
std::string GetSickEthernetConfigAsString() const;
/** Acquire the Sick LD's sector config as a printable string */
std::string GetSickSectorConfigAsString() const;
/** Acquire the total scan area (in degrees) being scanned by the Sick LD */
double GetSickScanArea( ) const;
/** Prints the Sick LD's status information */
void PrintSickStatus( ) const;
/** Prints the Sick LD's identity information */
void PrintSickIdentity( ) const;
/** Prints the global configuration parameter values */
void PrintSickGlobalConfig( ) const;
/** Prints the Ethernet configuration parameter values */
void PrintSickEthernetConfig( ) const;
/** Prints the Sick Sector configuration */
void PrintSickSectorConfig( ) const;
/** Uninitializes the Sick LD unit */
void Uninitialize( ) throw( SickIOException, SickTimeoutException, SickErrorException, SickThreadException );
/** Destructor */
~SickLD();
private:
/** The Sick LD IP address */
std::string _sick_ip_address;
/** The Sick LD TCP port number */
uint16_t _sick_tcp_port;
/** Sick LD socket structure */
unsigned int _socket;
/** Sick LD socket address structure */
struct sockaddr_in _sick_inet_address_info;
/** The current sensor mode */
uint8_t _sick_sensor_mode;
/** The mode of the motor */
uint8_t _sick_motor_mode;
/** Indicates whether the Sick LD is currently streaming range data */
bool _sick_streaming_range_data;
/** Indicates whether the Sick LD is currently streaming range and echo data */
bool _sick_streaming_range_and_echo_data;
/** The identity structure for the Sick */
sick_ld_identity_t _sick_identity;
/** The current global configuration for the unit */
sick_ld_config_global_t _sick_global_config;
/** The current Ethernet configuration for the unit */
sick_ld_config_ethernet_t _sick_ethernet_config;
/** The current sector configuration for the unit */
sick_ld_config_sector_t _sick_sector_config;
/** Setup the connection parameters and establish TCP connection! */
void _setupConnection( ) throw( SickIOException, SickTimeoutException );
/** Synchronizes the driver state with the Sick LD (used for initialization) */
void _syncDriverWithSick( ) throw( SickIOException, SickTimeoutException, SickErrorException );
/** Set the function for a particular scan secto */
void _setSickSectorFunction( const uint8_t sector_number, const uint8_t sector_function,
const double sector_angle_stop, const bool write_to_flash = false )
throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException );
/** Acquires the given Sector's function (i.e. current config) */
void _getSickSectorFunction( const uint8_t sector_num, uint8_t §or_function, double §or_stop_angle )
throw( SickErrorException, SickTimeoutException, SickIOException );
/** Sets the Sick LD to IDLE mode */
void _setSickSensorModeToIdle( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Sets the Sick LD to ROTATE mode */
void _setSickSensorModeToRotate( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Sets the Sick LD to MEASURE mode */
void _setSickSensorModeToMeasure( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Sets the Sick LD's sensor mode to IDLE (laser off, motor off) */
void _setSickSensorMode( const uint8_t new_sick_sensor_mode )
throw( SickErrorException, SickTimeoutException, SickIOException );
/** Requests n range measurement profiles from the Sick LD */
void _getSickScanProfiles( const uint16_t profile_format, const uint16_t num_profiles = DEFAULT_SICK_NUM_SCAN_PROFILES )
throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException );
/** Parses a sequence of bytes and populates the profile_data struct w/ the results */
void _parseScanProfile( uint8_t * const src_buffer, sick_ld_scan_profile_t &profile_data ) const;
/** Cancels the active data stream */
void _cancelSickScanProfiles( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Turns nearfield suppression on/off */
void _setSickFilter( const uint8_t suppress_code )
throw( SickErrorException, SickTimeoutException, SickIOException );
/** Stores an image of the Sick LD's identity locally */
void _getSickIdentity( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for its sensor and motor status */
void _getSickStatus( ) throw( SickTimeoutException, SickIOException );
/** Sets the Sick LD's global configuration (in flash) */
void _setSickGlobalConfig( const uint8_t sick_sensor_id, const uint8_t sick_motor_speed, const double sick_angle_step )
throw( SickErrorException, SickTimeoutException, SickIOException );
/** Query the Sick for its global configuration parameters */
void _getSickGlobalConfig( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Query the Sick for its Ethernet configuration parameters */
void _getSickEthernetConfig( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Acquires the configuration (function and stop angle) for each sector */
void _getSickSectorConfig( ) throw( SickErrorException, SickTimeoutException, SickIOException );
/** Query the Sick for ID information */
void _getIdentificationString( const uint8_t id_request_code, std::string &id_return_string )
throw( SickTimeoutException, SickIOException );
/** Query the Sick for its sensor part number */
void _getSensorPartNumber( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for its assigned name */
void _getSensorName( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for its version number */
void _getSensorVersion( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for its serial number */
void _getSensorSerialNumber( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for its EDM unit's serial number */
void _getSensorEDMSerialNumber( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for the part number of its firmware */
void _getFirmwarePartNumber( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for the name of its firmware */
void _getFirmwareName( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for the version of the firmware */
void _getFirmwareVersion( ) throw( SickTimeoutException, SickIOException );
/** Query the part number of the application software */
void _getApplicationSoftwarePartNumber( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for the application name */
void _getApplicationSoftwareName( ) throw( SickTimeoutException, SickIOException );
/** Query the Sick for the application software version */
void _getApplicationSoftwareVersion( ) throw( SickTimeoutException, SickIOException );
/** Allows setting the global parameters and scan area definition (in flash) */
void _setSickGlobalParamsAndScanAreas( const unsigned int sick_motor_speed, const double sick_step_angle,
const double * const active_sector_start_angles,
const double * const active_sector_stop_angles,
const unsigned int num_active_sectors )
throw( SickTimeoutException, SickIOException, SickConfigException, SickErrorException );
/** Allows setting a temporary (until a device reset) sector configuration on the device */
void _setSickTemporaryScanAreas( const double * const active_sector_start_angles,
const double * const active_sector_stop_angles,
const unsigned int num_active_sectors )
throw( SickTimeoutException, SickIOException, SickConfigException );
/** Sets the sick sector configuration */
void _setSickSectorConfig( const unsigned int * const sector_functions, const double * const sector_stop_angles,
const unsigned int num_sectors, const bool write_to_flash = false )
throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException );
/** Sets the signals for the device */
void _setSickSignals( const uint8_t sick_signal_flags = DEFAULT_SICK_SIGNAL_SET )
throw( SickIOException, SickTimeoutException, SickErrorException );
/** Send a message, get the reply from the Sick LD and check it */
void _sendMessageAndGetReply( const SickLDMessage &send_message, SickLDMessage &recv_message,
const unsigned int timeout_value = DEFAULT_SICK_MESSAGE_TIMEOUT )
throw( SickIOException, SickTimeoutException );
/** Flushed the TCP receive buffer */
void _flushTCPRecvBuffer( ) throw ( SickIOException, SickThreadException );
/** Teardown the connection to the Sick LD */
void _teardownConnection( ) throw( SickIOException );
/** Generates a device-ready sector set given only an active sector spec. */
void _generateSickSectorConfig( const double * const active_sector_start_angles,
const double * const active_sector_stop_angles,
const unsigned int num_active_sectors,
const double sick_step_angle,
unsigned int * const sector_functions,
double * const sector_stop_angles,
unsigned int &num_sectors ) const;
/** Converts odometry ticks to an equivalent angle */
double _ticksToAngle( const uint16_t ticks ) const;
/** Converts angle to an equivalent representation in odometer ticks */
uint16_t _angleToTicks( const double angle ) const;
/** Computes the mean pulse frequency for the given config */
double _computeMeanPulseFrequency( const double active_scan_area, const double curr_motor_speed,
const double curr_angular_resolution ) const;
/** Computes the total pulse frequency for the given config */
double _computeMaxPulseFrequency( const double total_scan_area, const double curr_motor_speed,
const double curr_angular_resolution ) const;
/** Indicates whether a given sensor ID is valid for the device */
bool _validSickSensorID( const unsigned int sick_sensor_id ) const;
/** Indicates whether a given motor speed is valid for the device */
bool _validSickMotorSpeed( const unsigned int sick_motor_speed ) const;
/** Indicates whether a given motor speed is valid for the device */
bool _validSickScanResolution( const double sick_step_angle, const double * const active_sector_start_angles,
const double * const active_sector_stop_angles, const unsigned int num_active_sectors ) const;
/** Indicates whether the given configuration yields a valid max and mean pulse frequency */
bool _validPulseFrequency( const unsigned int sick_motor_speed, const double sick_step_angle ) const;
/** Indicates whether the given configuration yields a valid max and mean pulse frequency */
bool _validPulseFrequency( const unsigned int sick_motor_speed, const double sick_step_angle,
const double * const active_sector_start_angles,
const double * const active_sector_stop_angles,
const unsigned int num_active_sectors ) const;
/** Returns the scanning area for the device given the current sector configuration */
double _computeScanArea( const double sick_step_angle, const double * const sector_start_angles,
const double * const sector_stop_angles, const unsigned int num_sectors ) const;
/** Reorders given sector angle sets */
void _sortScanAreas( double * const sector_start_angles, double * const sector_stop_angles,
const unsigned int num_sectors ) const;
/** Checks the given sector arguments for overlapping regions yielding an invalid configuration */
bool _validActiveSectors( const double * const sector_start_angles, const double * const sector_stop_angles,
const unsigned int num_active_sectors ) const;
/** Indicates whether the supplied profile format is currently supported by the driver */
bool _supportedScanProfileFormat( const uint16_t profile_format ) const;
/** Prints data corresponding to a single scan sector (data obtained using GET_PROFILE) */
void _printSectorProfileData( const sick_ld_sector_data_t §or_data ) const;
/** Prints the data corresponding to the given scan profile (for debugging purposes) */
void _printSickScanProfile( const sick_ld_scan_profile_t profile_data, const bool print_sector_data = true ) const;
/** Returns the corresponding work service subcode required to transition the Sick LD to the given sensor mode. */
uint8_t _sickSensorModeToWorkServiceSubcode( const uint8_t sick_sensor_mode ) const;
/** Converts _sick_sensor_mode to a representative string */
std::string _sickSensorModeToString( const uint8_t sick_sensor_mode ) const;
/** Converts _sick_motor_mode to a representative string */
std::string _sickMotorModeToString( const uint8_t sick_motor_mode ) const;
/** Converts the specified trans measurement mode return value to a string */
std::string _sickTransMeasureReturnToString( const uint8_t return_value ) const;
/** Converts the specified reset level to a representative string */
std::string _sickResetLevelToString( const uint16_t reset_level ) const;
/** Converts Sick LD sector configuration word to a representative string */
std::string _sickSectorFunctionToString( const uint16_t sick_sector_function ) const;
/** Converts a given scan profile format to a string for friendlier output */
std::string _sickProfileFormatToString( const uint16_t profile_format ) const;
/** Prints the initialization footer */
void _printInitFooter( ) const;
};
} //namespace SickToolbox
#endif /* SICK_LD_HH */
| 58.962779 | 245 | 0.654048 | [
"vector"
] |
72c3f1117186b4aaab256d4bd698f286f1c2537e | 2,093 | cpp | C++ | src/Multivariate_Gaussian_emission.cpp | DiegoAE/BOSD | a7ce88462c64c540ba2922d16eb6f7eba8055b47 | [
"MIT"
] | 19 | 2019-05-03T05:31:43.000Z | 2022-01-08T18:14:31.000Z | src/Multivariate_Gaussian_emission.cpp | DiegoAE/BOSD | a7ce88462c64c540ba2922d16eb6f7eba8055b47 | [
"MIT"
] | 2 | 2019-02-14T15:29:34.000Z | 2020-06-04T10:14:54.000Z | src/Multivariate_Gaussian_emission.cpp | DiegoAE/BOSD | a7ce88462c64c540ba2922d16eb6f7eba8055b47 | [
"MIT"
] | 1 | 2019-07-01T07:44:09.000Z | 2019-07-01T07:44:09.000Z | #include <armadillo>
#include <cmath>
#include <json.hpp>
#include <iostream>
#include <Multivariate_Gaussian_emission.hpp>
using namespace arma;
using namespace robotics;
using namespace std;
using json = nlohmann::json;
namespace hsmm {
/**
* MultivariateGaussianEmission implementation.
*/
MultivariateGaussianEmission::MultivariateGaussianEmission(
vector<random::NormalDist> states) : states_(states),
AbstractEmissionObsCondIIDgivenState(states.size(),
states.at(0).mean().n_elem) {
for(auto& dist: states_)
assert(dist.mean().n_elem == getDimension());
}
MultivariateGaussianEmission* MultivariateGaussianEmission::clone() const {
return new MultivariateGaussianEmission(*this);
}
double MultivariateGaussianEmission::loglikelihood(int state,
const vec &single_obs) const {
return random::log_normal_density(states_.at(state), single_obs);
}
void MultivariateGaussianEmission::fitFromLabels(
const field<mat> &observations_seq, const field<ivec> &labels_seq) {
assert(observations_seq.n_elem == labels_seq.n_elem);
vector<vec> obs_for_each_state[states_.size()];
for(int j = 0; j < labels_seq.n_elem; j++) {
const mat& observations = observations_seq(j);
const ivec& labels = labels_seq(j);
assert(observations.n_cols == labels.n_elem);
for(int i = 0; i < labels.n_elem; i++)
obs_for_each_state[labels(i)].push_back(observations.col(i));
}
for(int i = 0; i < states_.size(); i++)
states_.at(i) = random::mle_multivariate_normal(
obs_for_each_state[i]);
}
field<mat> MultivariateGaussianEmission::sampleFromState(int state,
int size, mt19937 &rng) const {
vector<vec> s = sample_multivariate_normal(rng, states_.at(state),
size);
field<mat> ret(size);
for(int i = 0; i < size; i++)
ret(i) = s.at(i);
return ret;
}
};
| 34.311475 | 80 | 0.631151 | [
"vector"
] |
72c7dae777aea45960435e57198c12eadd063121 | 6,886 | cpp | C++ | presence/error_reporter.cpp | HCLOpenBMC/phosphor-fan-presence | 3efec61c8f0ba530a24ad46e6c10d8827fbf9219 | [
"Apache-2.0"
] | 8 | 2017-03-20T22:56:15.000Z | 2020-10-28T06:45:05.000Z | presence/error_reporter.cpp | HCLOpenBMC/phosphor-fan-presence | 3efec61c8f0ba530a24ad46e6c10d8827fbf9219 | [
"Apache-2.0"
] | 25 | 2017-03-03T15:26:43.000Z | 2022-02-11T15:00:39.000Z | presence/error_reporter.cpp | HCLOpenBMC/phosphor-fan-presence | 3efec61c8f0ba530a24ad46e6c10d8827fbf9219 | [
"Apache-2.0"
] | 9 | 2017-02-13T18:11:49.000Z | 2022-01-19T12:12:46.000Z | /**
* Copyright © 2020 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "error_reporter.hpp"
#include "get_power_state.hpp"
#include "logging.hpp"
#include "psensor.hpp"
#include "utility.hpp"
#include <fmt/format.h>
#include <unistd.h>
#include <phosphor-logging/log.hpp>
#include <xyz/openbmc_project/Logging/Create/server.hpp>
#include <xyz/openbmc_project/Logging/Entry/server.hpp>
namespace phosphor::fan::presence
{
using json = nlohmann::json;
using namespace phosphor::logging;
using namespace sdbusplus::bus::match;
using namespace std::literals::string_literals;
using namespace std::chrono;
namespace fs = std::filesystem;
const auto itemIface = "xyz.openbmc_project.Inventory.Item"s;
const auto invPrefix = "/xyz/openbmc_project/inventory"s;
const auto loggingPath = "/xyz/openbmc_project/logging";
const auto loggingCreateIface = "xyz.openbmc_project.Logging.Create";
ErrorReporter::ErrorReporter(
sdbusplus::bus::bus& bus,
const std::vector<
std::tuple<Fan, std::vector<std::unique_ptr<PresenceSensor>>>>& fans) :
_bus(bus),
_event(sdeventplus::Event::get_default()),
_powerState(getPowerStateObject())
{
_powerState->addCallback("errorReporter",
std::bind(&ErrorReporter::powerStateChanged, this,
std::placeholders::_1));
for (const auto& fan : fans)
{
const auto& fanData = std::get<0>(fan);
// Only deal with fans that have an error time defined.
if (std::get<std::optional<size_t>>(fanData))
{
auto path = invPrefix + std::get<1>(fanData);
// Register for fan presence changes, get their initial states,
// and create the fan missing timers.
_matches.emplace_back(
_bus, rules::propertiesChanged(path, itemIface),
std::bind(std::mem_fn(&ErrorReporter::presenceChanged), this,
std::placeholders::_1));
_fanStates.emplace(path, getPresence(fanData));
auto timer = std::make_unique<
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>>(
_event,
std::bind(std::mem_fn(&ErrorReporter::fanMissingTimerExpired),
this, path));
seconds errorTime{std::get<std::optional<size_t>>(fanData).value()};
_fanMissingTimers.emplace(
path, std::make_tuple(std::move(timer), std::move(errorTime)));
}
}
// If power is already on, check for currently missing fans.
if (_powerState->isPowerOn())
{
powerStateChanged(true);
}
}
void ErrorReporter::presenceChanged(sdbusplus::message::message& msg)
{
bool present;
auto fanPath = msg.get_path();
std::string interface;
std::map<std::string, std::variant<bool>> properties;
msg.read(interface, properties);
auto presentProp = properties.find("Present");
if (presentProp != properties.end())
{
present = std::get<bool>(presentProp->second);
if (_fanStates[fanPath] != present)
{
getLogger().log(fmt::format("Fan {} presence state change to {}",
fanPath, present));
_fanStates[fanPath] = present;
checkFan(fanPath);
}
}
}
void ErrorReporter::checkFan(const std::string& fanPath)
{
auto& timer = std::get<0>(_fanMissingTimers[fanPath]);
if (!_fanStates[fanPath])
{
// Fan is missing. If power is on, start the timer.
// If power is off, stop a running timer.
if (_powerState->isPowerOn())
{
timer->restartOnce(std::get<seconds>(_fanMissingTimers[fanPath]));
}
else if (timer->isEnabled())
{
timer->setEnabled(false);
}
}
else
{
// Fan is present. Stop a running timer.
if (timer->isEnabled())
{
timer->setEnabled(false);
}
}
}
void ErrorReporter::fanMissingTimerExpired(const std::string& fanPath)
{
getLogger().log(
fmt::format("Creating event log for missing fan {}", fanPath),
Logger::error);
std::map<std::string, std::string> additionalData;
additionalData.emplace("_PID", std::to_string(getpid()));
additionalData.emplace("CALLOUT_INVENTORY_PATH", fanPath);
auto severity =
sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage(
sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level::
Error);
// Save our logs to a temp file and get the file descriptor
// so it can be passed in as FFDC data.
auto logFile = getLogger().saveToTempFile();
util::FileDescriptor fd{-1};
fd.open(logFile, O_RDONLY);
std::vector<std::tuple<
sdbusplus::xyz::openbmc_project::Logging::server::Create::FFDCFormat,
uint8_t, uint8_t, sdbusplus::message::unix_fd>>
ffdc;
ffdc.emplace_back(sdbusplus::xyz::openbmc_project::Logging::server::Create::
FFDCFormat::Text,
0x01, 0x01, fd());
try
{
util::SDBusPlus::lookupAndCallMethod(
loggingPath, loggingCreateIface, "CreateWithFFDCFiles",
"xyz.openbmc_project.Fan.Error.Missing", severity, additionalData,
ffdc);
}
catch (const util::DBusError& e)
{
getLogger().log(
fmt::format(
"Call to create an error log for missing fan {} failed: {}",
fanPath, e.what()),
Logger::error);
fs::remove(logFile);
throw;
}
fs::remove(logFile);
}
void ErrorReporter::powerStateChanged(bool powerState)
{
if (powerState)
{
// If there are fans already missing, log it.
auto missing = std::count_if(
_fanStates.begin(), _fanStates.end(),
[](const auto& fanState) { return fanState.second == false; });
if (missing)
{
getLogger().log(
fmt::format("At power on, there are {} missing fans", missing));
}
}
std::for_each(
_fanStates.begin(), _fanStates.end(),
[this](const auto& fanState) { this->checkFan(fanState.first); });
}
} // namespace phosphor::fan::presence
| 31.3 | 80 | 0.613999 | [
"vector"
] |
72cac39bcb859d0f2295738ae37c31b273615e44 | 2,148 | cc | C++ | player.cc | elliott1177/Blackjack | 072297b30e5bc42be0f048b775eb28e3c869c55b | [
"MIT"
] | null | null | null | player.cc | elliott1177/Blackjack | 072297b30e5bc42be0f048b775eb28e3c869c55b | [
"MIT"
] | 3 | 2020-04-27T06:28:25.000Z | 2020-05-07T08:51:13.000Z | player.cc | elliott1177/Blackjack | 072297b30e5bc42be0f048b775eb28e3c869c55b | [
"MIT"
] | null | null | null | /**
* @file player.cc
*
* @Copyright 2020 Elliott Krohnke, All rights reserved.
*/
#include "player.h"
// returns 1 if bust
int Player::Hit(Card dealt) {
hand.push_back(dealt);
int result = Update(dealt);
return result;
}
// Call clear because this is a new round. Take two cards then print out stats.
void Player::Deal(Card c_one, Card c_two) {
Clear();
Hit(c_one);
Hit(c_two);
Print();
}
int Player::Update(Card dealt) {
// If ace in hand we keep track of both scores.
if (dealt.value == 1 && score2bust == 0) {
score2 += score1 + 11;
score1 += 1;
haveace = 1;
} else if (haveace && score2bust == 0) {
score1 += dealt.value;
score2 += dealt.value;
} else {
score1 += dealt.value;
}
// This big bust is a guaranteed loss.
if (score1 > 21) {
score1 = -1;
return 1;
}
// The hand is busted now with the ace being 11 so we have to cut it out.
if (score2 > 21) {
score2 = 0;
score2bust = 1;
}
return 0;
}
void Player::Clear() {
score1 = 0;
score2 = 0;
score2bust = 0;
haveace = 0;
hand.clear();
}
int Player::Score() {
if (score2 > score1 && score2bust == 0 && score1 != -1) {
return score2;
}
return score1;
}
// This method prints out the names of the cards.
void Player::PrintCards() {
for (std::vector<Card>::iterator it = hand.begin(); it != hand.end(); ++it) {
std::cout<< (*it).name << ", ";
}
std::cout<< std::endl;
}
// Prints score out according to wether the person has an ace and a non-busted
// second score. Or just one score they need to keep track of.
void Player::PrintScore() {
if (haveace && score2bust == 0) {
std::cout << " score is either: " << score1 << " or " << score2 << std::
endl;
} else if (score1 < 0) {
std::cout << " hand is busted" << std::endl;
} else {
std::cout << " score is: " << score1 << std::endl;
}
}
// This method prints out the cards that someone has and their score. It is
// virtual because it may be overriden for different types of players.
void Player::Print() {
std::cout<< "Your cards are: ";
PrintCards();
std::cout<< "Your";
PrintScore();
}
| 23.347826 | 79 | 0.602421 | [
"vector"
] |
72cfd59da66406b8d4f1ff57bede74282cb1fe40 | 829 | cpp | C++ | src/metric_term.cpp | Conrekatsu/repulsive-surfaces | 74d6a16e6ca55c8296fa5a49757c2318bea62a84 | [
"MIT"
] | 35 | 2021-12-13T09:58:08.000Z | 2022-03-30T11:03:01.000Z | src/metric_term.cpp | Conrekatsu/repulsive-surfaces | 74d6a16e6ca55c8296fa5a49757c2318bea62a84 | [
"MIT"
] | null | null | null | src/metric_term.cpp | Conrekatsu/repulsive-surfaces | 74d6a16e6ca55c8296fa5a49757c2318bea62a84 | [
"MIT"
] | 3 | 2022-02-25T06:46:34.000Z | 2022-03-16T05:46:53.000Z | #include "metric_term.h"
#include "matrix_utils.h"
#include "sobolev/h2.h"
namespace rsurfaces
{
BiLaplacianMetricTerm::BiLaplacianMetricTerm(MeshPtr &mesh, GeomPtr &geom)
{
nMultiplyRows = 3 * mesh->nVertices();
std::vector<Triplet> biTriplets, biTriplets3x;
// Build the bi-Laplacian
H2::getTriplets(biTriplets, mesh, geom, 1e-10);
// Triple it to operate on vectors of length 3V
MatrixUtils::TripleTriplets(biTriplets, biTriplets3x);
biLaplacian.resize(nMultiplyRows, nMultiplyRows);
biLaplacian.setFromTriplets(biTriplets3x.begin(), biTriplets3x.end());
}
void BiLaplacianMetricTerm::MultiplyAdd(Eigen::VectorXd &vec, Eigen::VectorXd &result) const
{
result.head(nMultiplyRows) += biLaplacian * vec.head(nMultiplyRows);
}
}
| 30.703704 | 96 | 0.688782 | [
"mesh",
"vector"
] |
72d3c3793b109f5fd3a8f67b84bf174b0f692e69 | 700 | cpp | C++ | Section 6/Video 5/stringstream.cpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | 17 | 2019-10-10T21:09:51.000Z | 2022-01-13T15:54:24.000Z | Section 6/Video 5/stringstream.cpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | null | null | null | Section 6/Video 5/stringstream.cpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | 16 | 2019-10-10T21:09:55.000Z | 2022-02-13T11:42:52.000Z | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
stringstream ss;
ss << 25 << " " << 50 << " " << 75 << " ";
cout << ss.str() << "\n";
int i = 0;
ss >> i;
cout << i << "\n";
ss << 100;
cout << ss.str() << "\n";
while(!ss.eof()) {
ss >> i;
cout << i << "\n";
}
ss.clear(); //Remove the EOF state
vector<int> v(10);
iota(begin(v), end(v), 1);
copy(begin(v), end(v), ostream_iterator<int>(ss, " "));
cout << ss.str() << "\n";
cout << "Reading again\n";
while(!ss.eof()) {
ss >> i;
cout << i << "\n";
}
return 0;
}
| 14.285714 | 57 | 0.49 | [
"vector"
] |
72dbd51e65305be0629f9a89fa1b913c9a500101 | 574 | cpp | C++ | Graphs/DFS/C++/DFS.cpp | ARulzz/codezilla | 6bceb9ce2835942c6f7dfcaa420ea18d5c9935a6 | [
"MIT"
] | 147 | 2018-02-27T03:26:43.000Z | 2022-01-21T18:25:33.000Z | Graphs/DFS/C++/DFS.cpp | ARulzz/codezilla | 6bceb9ce2835942c6f7dfcaa420ea18d5c9935a6 | [
"MIT"
] | 273 | 2018-02-26T18:40:18.000Z | 2021-07-31T10:37:44.000Z | Graphs/DFS/C++/DFS.cpp | ARulzz/codezilla | 6bceb9ce2835942c6f7dfcaa420ea18d5c9935a6 | [
"MIT"
] | 234 | 2018-02-27T03:27:51.000Z | 2021-05-11T08:44:22.000Z | /*
* adikul30
* Aditya Kulkarni <aditya.kulkarni15@siesgst.ac.in>
*/
#include <bits/stdc++.h>
using namespace std;
#define REP(i, a, b) for(int i = a; i < b; ++i)
#define pb push_back
#define MAX 100
typedef vector<int> vi;
bool visited[MAX];
vi adj[MAX];
void dfs(int s){
if (visited[s]) return;
visited[s] = true;
cout << s << endl;
for (auto u : adj[s]){
dfs(u);
}
}
int main()
{
ios_base::sync_with_stdio(0);
int n = 5;
REP(i,1,n+1) visited[i] = false;
adj[1].pb(2);
adj[1].pb(3);
adj[1].pb(5);
adj[2].pb(3);
adj[3].pb(4);
dfs(1);
return 0;
} | 14.35 | 52 | 0.592334 | [
"vector"
] |
72ddea9bab028d607c93c8827e46192a70a21766 | 5,185 | cpp | C++ | ext/openMVG/openMVG/sfm/pipelines/sequential/SfmSceneInitializerStellar.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 90 | 2019-05-19T03:48:23.000Z | 2022-02-02T15:20:49.000Z | ext/openMVG/openMVG/sfm/pipelines/sequential/SfmSceneInitializerStellar.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 11 | 2019-05-22T07:45:46.000Z | 2021-05-20T01:48:26.000Z | ext/openMVG/openMVG/sfm/pipelines/sequential/SfmSceneInitializerStellar.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 18 | 2019-05-19T03:48:32.000Z | 2021-05-29T18:19:16.000Z |
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2018 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/sfm/pipelines/sequential/SfmSceneInitializerStellar.hpp"
#include "openMVG/sfm/pipelines/relative_pose_engine.hpp"
#include "openMVG/sfm/pipelines/sfm_matches_provider.hpp"
#include "openMVG/sfm/pipelines/stellar/stellar_solver.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/stl/stlMap.hpp"
namespace openMVG {
using namespace matching;
namespace sfm {
SfMSceneInitializerStellar::SfMSceneInitializerStellar(
SfM_Data & sfm_data,
const Features_Provider * features_provider,
const Matches_Provider * matches_provider)
:SfMSceneInitializer(sfm_data, features_provider, matches_provider)
{
sfm_data_.poses.clear();
}
bool find_largest_stellar_configuration
(
const Pair_Set & pairs,
const Matches_Provider * matches_provider,
Pair_Set & stellar_pod
)
{
// List all possible stellar configurations
using StellarPods = Hash_Map<IndexT, Pair_Set>;
StellarPods stellar_pods;
for (const auto & it : pairs)
{
stellar_pods[it.first].insert(it);
stellar_pods[it.second].insert(it);
}
// Find the stellar configuration with the most correspondences support
std::vector<float> matches_count_per_stellar_pod(stellar_pods.size(), 0);
IndexT id = 0;
for (const auto & stellar_pod : stellar_pods)
{
const Pair_Set & pairs = stellar_pod.second;
for (const auto & pair : pairs)
{
const matching::IndMatches & matches = matches_provider->pairWise_matches_.at(pair);
matches_count_per_stellar_pod[id] += matches.size();
}
matches_count_per_stellar_pod[id] /= pairs.size();
++id;
}
const auto stellar_pod_max_matches_iterator =
std::max_element(matches_count_per_stellar_pod.cbegin(),
matches_count_per_stellar_pod.cend());
if (stellar_pod_max_matches_iterator == matches_count_per_stellar_pod.cend())
return false;
auto stellar_pod_it =
std::next(stellar_pods.cbegin(),
std::distance(matches_count_per_stellar_pod.cbegin(),
stellar_pod_max_matches_iterator));
stellar_pod = stellar_pod_it->second;
return true;
}
bool SfMSceneInitializerStellar::Process()
{
if (sfm_data_.GetIntrinsics().empty())
return false;
// List the pairs that are valid for relative pose estimation:
// - Each pair must have different pose ids and defined intrinsic data.
const Pair_Set pairs = matches_provider_->getPairs();
Pair_Set relative_pose_pairs;
for (const auto & pair_it : pairs)
{
const View * v1 = sfm_data_.GetViews().at(pair_it.first).get();
const View * v2 = sfm_data_.GetViews().at(pair_it.second).get();
if (v1->id_pose != v2->id_pose
&& sfm_data_.GetIntrinsics().count(v1->id_intrinsic)
&& sfm_data_.GetIntrinsics().count(v2->id_intrinsic))
relative_pose_pairs.insert({v1->id_pose, v2->id_pose});
}
// Find the stellar configuration with the most pair candidate.
Pair_Set selected_putative_stellar_pod;
if (!find_largest_stellar_configuration(
relative_pose_pairs,
matches_provider_,
selected_putative_stellar_pod))
{
std::cerr << "Unable to find a valid stellar configuration." << std::endl;
return false;
}
// Compute a relative pose for each selected edge of the pose pair graph
const Relative_Pose_Engine::Relative_Pair_Poses relative_poses = [&]
{
Relative_Pose_Engine relative_pose_engine;
if (!relative_pose_engine.Process(
selected_putative_stellar_pod,
sfm_data_,
matches_provider_,
features_provider_))
return Relative_Pose_Engine::Relative_Pair_Poses();
else
return relative_pose_engine.Get_Relative_Poses();
}();
Pair_Set relative_poses_pairs;
// Retrieve all keys
std::transform(relative_poses.begin(), relative_poses.end(),
std::inserter(relative_poses_pairs, relative_poses_pairs.begin()),
stl::RetrieveKey());
Pair_Set selected_stellar_pod;
if (!find_largest_stellar_configuration(
relative_pose_pairs,
matches_provider_,
selected_stellar_pod))
{
std::cerr << "Unable to select a valid stellar configuration from the computed relative poses." << std::endl;
return false;
}
std::cout << "The chosen stellar pod has " << selected_stellar_pod.size() << " pairs." << std::endl;
// Configure the stellar pod optimization to use all the matches relating to the considered view id.
// The found camera poses will be better thanks to the larger point support.
const bool use_all_matches = true;
const bool use_threading = true;
Stellar_Solver stellar_pod_solver(
selected_stellar_pod,
relative_poses,
sfm_data_,
matches_provider_,
features_provider_,
use_all_matches,
use_threading);
if (stellar_pod_solver.Solve(sfm_data_.poses))
{
return true;
}
return false;
}
} // namespace sfm
} // namespace openMVG
| 31.615854 | 113 | 0.725169 | [
"geometry",
"vector",
"transform"
] |
72e5595f47b167ce372bbd311a7b5d40acf135b2 | 4,787 | hxx | C++ | main/sw/inc/hhcwrp.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sw/inc/hhcwrp.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sw/inc/hhcwrp.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _HHCWRP_HXX
#define _HHCWRP_HXX
#include <editeng/hangulhanja.hxx>
#include <pam.hxx>
class SwView;
class Window;
class SwWrtShell;
struct SwConversionArgs;
//////////////////////////////////////////////////////////////////////
class SwHHCWrapper : public editeng::HangulHanjaConversion
{
SwView * pView;
Window* pWin;
SwWrtShell &rWrtShell;
SwConversionArgs *pConvArgs; // object for arguments (and results) needed
// to find of next convertible text portion
xub_StrLen nLastPos; // starting position of the last found text part
// (needs to be sth that gets not moved like
// SwPaM or SwPosition by replace operations!)
sal_Int32 nUnitOffset;
sal_uInt16 nPageCount; // page count for progress bar
sal_uInt16 nPageStart; // first checked page
sal_Bool bIsDrawObj;
sal_Bool bIsStart;
sal_Bool bIsOtherCntnt;
sal_Bool bStartChk;
sal_Bool bIsSelection; // true if only the selected text should be converted
sal_Bool bInfoBox; // true if message should be displayed at the end
sal_Bool bIsConvSpecial; // true if special regions: header, footer, ... should be converted
sal_Bool bStartDone;
sal_Bool bEndDone;
// sal_Bool bLastRet;
// from SvxSpellWrapper copied and modified
sal_Bool ConvNext_impl(); // former SpellNext
sal_Bool FindConvText_impl(); // former FindSpellError
// from SwSpellWrapper copied and modified
sal_Bool HasOtherCnt_impl();
void ConvStart_impl( SwConversionArgs *pConvArgs, SvxSpellArea eSpell ); // former SpellStart
void ConvEnd_impl( SwConversionArgs *pConvArgs ); // former SpellEnd
sal_Bool ConvContinue_impl( SwConversionArgs *pConvArgs ); // former SpellContinue
void SelectNewUnit_impl( const sal_Int32 nUnitStart,
const sal_Int32 nUnitEnd );
void ChangeText( const String &rNewText,
const ::rtl::OUString& rOrigText,
const ::com::sun::star::uno::Sequence< sal_Int32 > *pOffsets,
SwPaM *pCrsr );
void ChangeText_impl( const String &rNewText, sal_Bool bKeepAttributes );
inline sal_Bool IsDrawObj() { return bIsDrawObj; }
inline void SetDrawObj( sal_Bool bNew ) { bIsDrawObj = bNew; }
protected:
virtual void GetNextPortion( ::rtl::OUString& rNextPortion,
LanguageType& rLangOfPortion,
sal_Bool bAllowImplicitChangesForNotConvertibleText );
virtual void HandleNewUnit( const sal_Int32 nUnitStart,
const sal_Int32 nUnitEnd );
virtual void ReplaceUnit(
const sal_Int32 nUnitStart, const sal_Int32 nUnitEnd,
const ::rtl::OUString& rOrigText,
const ::rtl::OUString& rReplaceWith,
const ::com::sun::star::uno::Sequence< sal_Int32 > &rOffsets,
ReplacementAction eAction,
LanguageType *pNewUnitLanguage );
virtual sal_Bool HasRubySupport() const;
public:
SwHHCWrapper(
SwView* pView,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rxMSF,
LanguageType nSourceLanguage, LanguageType nTargetLanguage,
const Font *pTargetFont,
sal_Int32 nConvOptions, sal_Bool bIsInteractive,
sal_Bool bStart, sal_Bool bOther, sal_Bool bSelection );
virtual ~SwHHCWrapper();
void Convert();
};
#endif
| 40.567797 | 109 | 0.606852 | [
"object"
] |
72e6654127c39cd4951b54788a417db5263e0e1a | 4,232 | cpp | C++ | third_party/WebKit/Source/core/animation/AnimationSimTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/animation/AnimationSimTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/animation/AnimationSimTest.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 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 "core/animation/ElementAnimation.h"
#include "core/css/PropertyDescriptor.h"
#include "core/css/PropertyRegistration.h"
#include "core/frame/WebLocalFrameBase.h"
#include "core/page/Page.h"
#include "core/testing/sim/SimCompositor.h"
#include "core/testing/sim/SimDisplayItemList.h"
#include "core/testing/sim/SimRequest.h"
#include "core/testing/sim/SimTest.h"
#include "platform/wtf/CurrentTime.h"
#include "public/web/WebScriptSource.h"
namespace blink {
class AnimationSimTest : public SimTest {};
TEST_F(AnimationSimTest, CustomPropertyBaseComputedStyle) {
// This is a regression test for bug where custom property animations failed
// to disable the baseComputedStyle optimisation. When custom property
// animations are in effect we lose the guarantee that the baseComputedStyle
// optimisation relies on where the non-animated style rules always produce
// the same ComputedStyle. This is not the case if they use var() references
// to custom properties that are being animated.
// The bug was that we never cleared the existing baseComputedStyle during a
// custom property animation so the stale ComputedStyle object would hang
// around and not be valid in the exit frame of the next custom property
// animation.
RuntimeEnabledFeatures::SetCSSVariables2Enabled(true);
RuntimeEnabledFeatures::SetCSSAdditiveAnimationsEnabled(true);
RuntimeEnabledFeatures::SetStackedCSSPropertyAnimationsEnabled(true);
WebView().GetPage()->Animator().Clock().DisableSyntheticTimeForTesting();
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete("<div id=\"target\"></div>");
Element* target = GetDocument().getElementById("target");
// CSS.registerProperty({
// name: '--x',
// syntax: '<percentage>',
// initialValue: '0%',
// })
DummyExceptionStateForTesting exception_state;
PropertyDescriptor property_descriptor;
property_descriptor.setName("--x");
property_descriptor.setSyntax("<percentage>");
property_descriptor.setInitialValue("0%");
PropertyRegistration::registerProperty(&GetDocument(), property_descriptor,
exception_state);
EXPECT_FALSE(exception_state.HadException());
// target.style.setProperty('--x', '100%');
target->style()->setProperty("--x", "100%", g_empty_string, exception_state);
EXPECT_FALSE(exception_state.HadException());
// target.animate({'--x': '100%'}, 1000);
RefPtr<StringKeyframe> keyframe = StringKeyframe::Create();
keyframe->SetCSSPropertyValue("--x", GetDocument().GetPropertyRegistry(),
"100%",
GetDocument().ElementSheet().Contents());
StringKeyframeVector keyframes;
keyframes.push_back(std::move(keyframe));
Timing timing;
timing.iteration_duration = 1; // Seconds.
ElementAnimation::animateInternal(
*target, StringKeyframeEffectModel::Create(keyframes), timing);
// This sets the baseComputedStyle on the animation exit frame.
Compositor().BeginFrame(1);
Compositor().BeginFrame(1);
// target.style.setProperty('--x', '0%');
target->style()->setProperty("--x", "0%", g_empty_string, exception_state);
EXPECT_FALSE(exception_state.HadException());
// target.animate({'--x': '100%'}, 1000);
keyframe = StringKeyframe::Create();
keyframe->SetCSSPropertyValue("--x", GetDocument().GetPropertyRegistry(),
"100%",
GetDocument().ElementSheet().Contents());
keyframes.clear();
keyframes.push_back(std::move(keyframe));
timing = Timing::Defaults();
timing.iteration_duration = 1; // Seconds.
ElementAnimation::animateInternal(
*target, StringKeyframeEffectModel::Create(keyframes), timing);
// This (previously) would not clear the existing baseComputedStyle and would
// crash on the equality assertion in the exit frame when it tried to update
// it.
Compositor().BeginFrame(1);
Compositor().BeginFrame(1);
}
} // namespace blink
| 41.087379 | 79 | 0.714556 | [
"object"
] |
72e793cb760730072f4fa1a9ab7ede142154730e | 3,154 | cpp | C++ | UEngine/UEngine/Game Architecture/Scene/GameScene.cpp | yus1108/UnsungEngine2 | c824c049069a0d8283f84b09af7ae0182d9a48c9 | [
"MIT"
] | null | null | null | UEngine/UEngine/Game Architecture/Scene/GameScene.cpp | yus1108/UnsungEngine2 | c824c049069a0d8283f84b09af7ae0182d9a48c9 | [
"MIT"
] | 4 | 2021-03-12T06:11:36.000Z | 2021-03-19T11:09:06.000Z | UEngine/UEngine/Game Architecture/Scene/GameScene.cpp | yus1108/UnsungEngine2 | c824c049069a0d8283f84b09af7ae0182d9a48c9 | [
"MIT"
] | null | null | null | #include "UEngine.h"
#include "../../XMLParser/XMLSceneParser.h"
#include "GameScene.h"
void UEngine::GameScene::Init(bool isDebugMode)
{
InitDebugMode(isDebugMode);
ResourceManager.Init();
partition2D = new Physics2D::SpatialPartition2D();
}
void UEngine::GameScene::InitDebugMode(bool isDebugMode)
{
this->isDebugMode = isDebugMode;
if (isDebugMode)
{
debugRenderer = new UEngine::DebugRenderer();
debugRenderer->Init(DXRenderer::Get()->GetDevice(), DXRenderer::Get()->GetImmediateDeviceContext());
}
}
void UEngine::GameScene::Release()
{
for (auto obj : gameObjects)
GameObject::Release(&obj);
for (auto obj : creationList)
GameObject::Release(&obj);
delete partition2D;
if (isDebugMode)
{
delete debugRenderer;
debugRenderer = nullptr;
}
}
void UEngine::GameScene::Update()
{
while (true)
{
partition2D->Release();
for (auto obj : gameObjects)
obj->FixedUpdate();
for (auto obj : gameObjects)
obj->PhysicsUpdate();
if (GameState::IsFixedUpdate()) break;
}
for (auto obj : gameObjects)
obj->Update();
for (auto obj : gameObjects)
obj->LateUpdate();
for (auto obj : gameObjects)
obj->AnimationUpdate();
}
void UEngine::GameScene::Render(ID3D11DeviceContext* deviceContext)
{
for (auto view : gpu_view)
{
auto fRender = sceneSync.CreateSyncTask([view, this]()
{
static_cast<GameView>(view).Render(isDebugMode, view.IsMain);
});
WinApplication::Get()->threadPool.AddTask(fRender);
}
sceneSync.Join();
for (auto view : gpu_view)
view.PostRender();
}
void UEngine::GameScene::PostRender()
{
for (auto obj : gameObjects)
obj->OnPostRender();
}
void UEngine::GameScene::Sync()
{
if (isDebugMode && this == GameState::GetCurrentScene() && MainView) debugRenderer->Flush(MainView->cameraBuffer);
for (auto obj : creationList)
gameObjects.emplace_back(obj);
for (auto diter = deletionList.begin(); diter != deletionList.end(); diter++)
{
for (auto iter = gameObjects.begin(); iter != gameObjects.end(); iter++)
{
if (*iter == *diter)
{
GameObject::Release(&(*iter));
gameObjects.erase(iter);
break;
}
}
}
deletionList.clear();
creationList.clear();
ResourceManager.ApplyChange();
for (auto obj : gameObjects)
obj->Initialize();
for (auto obj : gameObjects)
obj->Sync();
gpu_view.clear();
for (auto obj : gameObjects)
obj->OnPreRender();
}
UEngine::GameObject* const UEngine::GameScene::GetGameObject(std::string name)
{
for (auto obj : gameObjects)
if (obj->name == name) return obj;
return nullptr;
}
void UEngine::GameScene::RemoveGameObject(GameObject** obj)
{
deletionList.emplace_back(*obj);
*obj = nullptr;
}
void UEngine::GameScene::RemoveGameObject(std::string name)
{
for (auto iter = gameObjects.begin(); iter != gameObjects.end(); iter++)
{
if ((*iter)->name == name)
{
deletionList.emplace_back(*iter);
return;
}
}
}
void UEngine::GameScene::SaveScene()
{
XMLSceneParser parser;
parser.SaveScene(name, isDebugMode, gameObjects);
}
UEngine::GameScene* UEngine::GameScene::LoadScene(std::string name, bool editorMode)
{
XMLSceneParser parser;
return parser.LoadScene(name, editorMode);
} | 21.455782 | 115 | 0.696893 | [
"render"
] |
638fe460ec04faaa42dac3347263961b8b54c58e | 2,407 | inl | C++ | include/visionaray/cuda/detail/pixel_pack_buffer.inl | ukoeln-vis/ctpperf | 2d896c4e8f4a46a6aee198ed6492e7571361e00b | [
"MIT"
] | 5 | 2017-08-11T00:11:45.000Z | 2022-01-24T14:47:47.000Z | include/visionaray/cuda/detail/pixel_pack_buffer.inl | ukoeln-vis/ctpperf | 2d896c4e8f4a46a6aee198ed6492e7571361e00b | [
"MIT"
] | null | null | null | include/visionaray/cuda/detail/pixel_pack_buffer.inl | ukoeln-vis/ctpperf | 2d896c4e8f4a46a6aee198ed6492e7571361e00b | [
"MIT"
] | null | null | null | // This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/config.h>
#include <stdexcept>
#if VSNRAY_HAVE_GLEW
#include <GL/glew.h>
#endif
#include <cuda_gl_interop.h>
#include <visionaray/gl/handle.h>
#include "../graphics_resource.h"
namespace visionaray
{
namespace cuda
{
struct pixel_pack_buffer::impl
{
graphics_resource resource;
gl::buffer buffer;
recti viewport;
pixel_format format = PF_UNSPECIFIED;
};
pixel_pack_buffer::pixel_pack_buffer()
: impl_(new impl())
{
cudaError_t err = cudaSuccess;
int dev = 0;
cudaDeviceProp prop;
err = cudaChooseDevice(&dev, &prop);
if (err != cudaSuccess)
{
throw std::runtime_error("choose device");
}
err = cudaGLSetGLDevice(dev);
/* if (err == cudaErrorSetOnActiveProcess)
{
err = cudaDeviceReset();
err = cudaGLSetGLDevice(dev);
}
if (err != cudaSuccess)
{
throw std::runtime_error("set GL device");
}*/
}
void pixel_pack_buffer::map(recti viewport, pixel_format format)
{
auto info = map_pixel_format(format);
if (impl_->viewport != viewport || impl_->format != format)
{
// GL buffer
impl_->buffer.reset( gl::create_buffer() );
glBindBuffer(GL_PIXEL_PACK_BUFFER, impl_->buffer.get());
glBufferData(GL_PIXEL_PACK_BUFFER, viewport.w * viewport.h * info.size, 0, GL_STREAM_COPY);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
// Register buffer object with CUDA
impl_->resource.register_buffer(impl_->buffer.get(), cudaGraphicsRegisterFlagsReadOnly);
// Update state
impl_->viewport = viewport;
impl_->format = format;
}
// Transfer pixels
glBindBuffer(GL_PIXEL_PACK_BUFFER, impl_->buffer.get());
glReadPixels(
viewport.x,
viewport.y,
viewport.w,
viewport.h,
info.format,
info.type,
0
);
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
// Map graphics resource
if (impl_->resource.map() == 0)
{
throw std::runtime_error("bad resource mapped");
}
}
void pixel_pack_buffer::unmap()
{
impl_->resource.unmap();
}
void const* pixel_pack_buffer::data() const
{
return impl_->resource.dev_ptr();
}
} // cuda
} // visionaray
| 21.684685 | 99 | 0.622351 | [
"object"
] |
639be714f7a34d179fcb25176d53e25cc5c128bc | 49,297 | cpp | C++ | neo/idlib/MapFile.cpp | vic3t3chn0/OpenKrown | 201c8fb6895cb0439e39c984d2fbc2c2eaf185b4 | [
"MIT"
] | 1 | 2018-11-07T22:44:23.000Z | 2018-11-07T22:44:23.000Z | neo/idlib/MapFile.cpp | vic3t3chn0/OpenKrown | 201c8fb6895cb0439e39c984d2fbc2c2eaf185b4 | [
"MIT"
] | null | null | null | neo/idlib/MapFile.cpp | vic3t3chn0/OpenKrown | 201c8fb6895cb0439e39c984d2fbc2c2eaf185b4 | [
"MIT"
] | null | null | null | /*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
Copyright (C) 2015 Robert Beckebans
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Doom 3 BFG Edition Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
/*
===============
FloatCRC
===============
*/
ID_INLINE unsigned int FloatCRC( float f )
{
return *( unsigned int* )&f;
}
/*
===============
StringCRC
===============
*/
ID_INLINE unsigned int StringCRC( const char* str )
{
unsigned int i, crc;
const unsigned char* ptr;
crc = 0;
ptr = reinterpret_cast<const unsigned char*>( str );
for( i = 0; str[i]; i++ )
{
crc ^= str[i] << ( i & 3 );
}
return crc;
}
/*
=================
ComputeAxisBase
WARNING : special case behaviour of atan2(y,x) <-> atan(y/x) might not be the same everywhere when x == 0
rotation by (0,RotY,RotZ) assigns X to normal
=================
*/
static void ComputeAxisBase( const idVec3& normal, idVec3& texS, idVec3& texT )
{
float RotY, RotZ;
idVec3 n;
// do some cleaning
n[0] = ( idMath::Fabs( normal[0] ) < 1e-6f ) ? 0.0f : normal[0];
n[1] = ( idMath::Fabs( normal[1] ) < 1e-6f ) ? 0.0f : normal[1];
n[2] = ( idMath::Fabs( normal[2] ) < 1e-6f ) ? 0.0f : normal[2];
RotY = -atan2( n[2], idMath::Sqrt( n[1] * n[1] + n[0] * n[0] ) );
RotZ = atan2( n[1], n[0] );
// rotate (0,1,0) and (0,0,1) to compute texS and texT
texS[0] = -sin( RotZ );
texS[1] = cos( RotZ );
texS[2] = 0;
// the texT vector is along -Z ( T texture coorinates axis )
texT[0] = -sin( RotY ) * cos( RotZ );
texT[1] = -sin( RotY ) * sin( RotZ );
texT[2] = -cos( RotY );
}
/*
=================
idMapBrushSide::GetTextureVectors
=================
*/
void idMapBrushSide::GetTextureVectors( idVec4 v[2] ) const
{
int i;
idVec3 texX, texY;
ComputeAxisBase( plane.Normal(), texX, texY );
for( i = 0; i < 2; i++ )
{
v[i][0] = texX[0] * texMat[i][0] + texY[0] * texMat[i][1];
v[i][1] = texX[1] * texMat[i][0] + texY[1] * texMat[i][1];
v[i][2] = texX[2] * texMat[i][0] + texY[2] * texMat[i][1];
v[i][3] = texMat[i][2] + ( origin * v[i].ToVec3() );
}
}
/*
=================
idMapPatch::Parse
=================
*/
idMapPatch* idMapPatch::Parse( idLexer& src, const idVec3& origin, bool patchDef3, float version )
{
float info[7];
idDrawVert* vert;
idToken token;
int i, j;
if( !src.ExpectTokenString( "{" ) )
{
return NULL;
}
// read the material (we had an implicit 'textures/' in the old format...)
if( !src.ReadToken( &token ) )
{
src.Error( "idMapPatch::Parse: unexpected EOF" );
return NULL;
}
// Parse it
if( patchDef3 )
{
if( !src.Parse1DMatrix( 7, info ) )
{
src.Error( "idMapPatch::Parse: unable to Parse patchDef3 info" );
return NULL;
}
}
else
{
if( !src.Parse1DMatrix( 5, info ) )
{
src.Error( "idMapPatch::Parse: unable to parse patchDef2 info" );
return NULL;
}
}
idMapPatch* patch = new( TAG_IDLIB ) idMapPatch( info[0], info[1] );
patch->SetSize( info[0], info[1] );
if( version < 2.0f )
{
patch->SetMaterial( "textures/" + token );
}
else
{
patch->SetMaterial( token );
}
if( patchDef3 )
{
patch->SetHorzSubdivisions( info[2] );
patch->SetVertSubdivisions( info[3] );
patch->SetExplicitlySubdivided( true );
}
if( patch->GetWidth() < 0 || patch->GetHeight() < 0 )
{
src.Error( "idMapPatch::Parse: bad size" );
delete patch;
return NULL;
}
// these were written out in the wrong order, IMHO
if( !src.ExpectTokenString( "(" ) )
{
src.Error( "idMapPatch::Parse: bad patch vertex data" );
delete patch;
return NULL;
}
for( j = 0; j < patch->GetWidth(); j++ )
{
if( !src.ExpectTokenString( "(" ) )
{
src.Error( "idMapPatch::Parse: bad vertex row data" );
delete patch;
return NULL;
}
for( i = 0; i < patch->GetHeight(); i++ )
{
float v[5];
if( !src.Parse1DMatrix( 5, v ) )
{
src.Error( "idMapPatch::Parse: bad vertex column data" );
delete patch;
return NULL;
}
vert = &( ( *patch )[i * patch->GetWidth() + j] );
vert->xyz[0] = v[0] - origin[0];
vert->xyz[1] = v[1] - origin[1];
vert->xyz[2] = v[2] - origin[2];
vert->SetTexCoord( v[3], v[4] );
}
if( !src.ExpectTokenString( ")" ) )
{
delete patch;
src.Error( "idMapPatch::Parse: unable to parse patch control points" );
return NULL;
}
}
if( !src.ExpectTokenString( ")" ) )
{
src.Error( "idMapPatch::Parse: unable to parse patch control points, no closure" );
delete patch;
return NULL;
}
// read any key/value pairs
while( src.ReadToken( &token ) )
{
if( token == "}" )
{
src.ExpectTokenString( "}" );
break;
}
if( token.type == TT_STRING )
{
idStr key = token;
src.ExpectTokenType( TT_STRING, 0, &token );
patch->epairs.Set( key, token );
}
}
return patch;
}
/*
============
idMapPatch::Write
============
*/
bool idMapPatch::Write( idFile* fp, int primitiveNum, const idVec3& origin ) const
{
int i, j;
const idDrawVert* v;
if( GetExplicitlySubdivided() )
{
fp->WriteFloatString( "// primitive %d\n{\n patchDef3\n {\n", primitiveNum );
fp->WriteFloatString( " \"%s\"\n ( %d %d %d %d 0 0 0 )\n", GetMaterial(), GetWidth(), GetHeight(), GetHorzSubdivisions(), GetVertSubdivisions() );
}
else
{
fp->WriteFloatString( "// primitive %d\n{\n patchDef2\n {\n", primitiveNum );
fp->WriteFloatString( " \"%s\"\n ( %d %d 0 0 0 )\n", GetMaterial(), GetWidth(), GetHeight() );
}
fp->WriteFloatString( " (\n" );
idVec2 st;
for( i = 0; i < GetWidth(); i++ )
{
fp->WriteFloatString( " ( " );
for( j = 0; j < GetHeight(); j++ )
{
v = &verts[ j * GetWidth() + i ];
st = v->GetTexCoord();
fp->WriteFloatString( " ( %f %f %f %f %f )", v->xyz[0] + origin[0],
v->xyz[1] + origin[1], v->xyz[2] + origin[2], st[0], st[1] );
}
fp->WriteFloatString( " )\n" );
}
fp->WriteFloatString( " )\n }\n}\n" );
return true;
}
/*
===============
idMapPatch::GetGeometryCRC
===============
*/
unsigned int idMapPatch::GetGeometryCRC() const
{
int i, j;
unsigned int crc;
crc = GetHorzSubdivisions() ^ GetVertSubdivisions();
for( i = 0; i < GetWidth(); i++ )
{
for( j = 0; j < GetHeight(); j++ )
{
crc ^= FloatCRC( verts[j * GetWidth() + i].xyz.x );
crc ^= FloatCRC( verts[j * GetWidth() + i].xyz.y );
crc ^= FloatCRC( verts[j * GetWidth() + i].xyz.z );
}
}
crc ^= StringCRC( GetMaterial() );
return crc;
}
/*
=================
idMapBrush::Parse
=================
*/
idMapBrush* idMapBrush::Parse( idLexer& src, const idVec3& origin, bool newFormat, float version )
{
int i;
idVec3 planepts[3];
idToken token;
idList<idMapBrushSide*> sides;
idMapBrushSide* side;
idDict epairs;
if( !src.ExpectTokenString( "{" ) )
{
return NULL;
}
do
{
if( !src.ReadToken( &token ) )
{
src.Error( "idMapBrush::Parse: unexpected EOF" );
sides.DeleteContents( true );
return NULL;
}
if( token == "}" )
{
break;
}
// here we may have to jump over brush epairs ( only used in editor )
do
{
// if token is a brace
if( token == "(" )
{
break;
}
// the token should be a key string for a key/value pair
if( token.type != TT_STRING )
{
src.Error( "idMapBrush::Parse: unexpected %s, expected ( or epair key string", token.c_str() );
sides.DeleteContents( true );
return NULL;
}
idStr key = token;
if( !src.ReadTokenOnLine( &token ) || token.type != TT_STRING )
{
src.Error( "idMapBrush::Parse: expected epair value string not found" );
sides.DeleteContents( true );
return NULL;
}
epairs.Set( key, token );
// try to read the next key
if( !src.ReadToken( &token ) )
{
src.Error( "idMapBrush::Parse: unexpected EOF" );
sides.DeleteContents( true );
return NULL;
}
}
while( 1 );
src.UnreadToken( &token );
side = new( TAG_IDLIB ) idMapBrushSide();
sides.Append( side );
if( newFormat )
{
if( !src.Parse1DMatrix( 4, side->plane.ToFloatPtr() ) )
{
src.Error( "idMapBrush::Parse: unable to read brush side plane definition" );
sides.DeleteContents( true );
return NULL;
}
}
else
{
// read the three point plane definition
if( !src.Parse1DMatrix( 3, planepts[0].ToFloatPtr() ) ||
!src.Parse1DMatrix( 3, planepts[1].ToFloatPtr() ) ||
!src.Parse1DMatrix( 3, planepts[2].ToFloatPtr() ) )
{
src.Error( "idMapBrush::Parse: unable to read brush side plane definition" );
sides.DeleteContents( true );
return NULL;
}
planepts[0] -= origin;
planepts[1] -= origin;
planepts[2] -= origin;
side->plane.FromPoints( planepts[0], planepts[1], planepts[2] );
}
// read the texture matrix
// this is odd, because the texmat is 2D relative to default planar texture axis
if( !src.Parse2DMatrix( 2, 3, side->texMat[0].ToFloatPtr() ) )
{
src.Error( "idMapBrush::Parse: unable to read brush side texture matrix" );
sides.DeleteContents( true );
return NULL;
}
side->origin = origin;
// read the material
if( !src.ReadTokenOnLine( &token ) )
{
src.Error( "idMapBrush::Parse: unable to read brush side material" );
sides.DeleteContents( true );
return NULL;
}
// we had an implicit 'textures/' in the old format...
if( version < 2.0f )
{
side->material = "textures/" + token;
}
else
{
side->material = token;
}
// Q2 allowed override of default flags and values, but we don't any more
if( src.ReadTokenOnLine( &token ) )
{
if( src.ReadTokenOnLine( &token ) )
{
if( src.ReadTokenOnLine( &token ) )
{
}
}
}
}
while( 1 );
if( !src.ExpectTokenString( "}" ) )
{
sides.DeleteContents( true );
return NULL;
}
idMapBrush* brush = new( TAG_IDLIB ) idMapBrush();
for( i = 0; i < sides.Num(); i++ )
{
brush->AddSide( sides[i] );
}
brush->epairs = epairs;
return brush;
}
/*
=================
idMapBrush::ParseQ3
=================
*/
idMapBrush* idMapBrush::ParseQ3( idLexer& src, const idVec3& origin )
{
int i, shift[2], rotate;
float scale[2];
idVec3 planepts[3];
idToken token;
idList<idMapBrushSide*> sides;
idMapBrushSide* side;
idDict epairs;
do
{
if( src.CheckTokenString( "}" ) )
{
break;
}
side = new( TAG_IDLIB ) idMapBrushSide();
sides.Append( side );
// read the three point plane definition
if( !src.Parse1DMatrix( 3, planepts[0].ToFloatPtr() ) ||
!src.Parse1DMatrix( 3, planepts[1].ToFloatPtr() ) ||
!src.Parse1DMatrix( 3, planepts[2].ToFloatPtr() ) )
{
src.Error( "idMapBrush::ParseQ3: unable to read brush side plane definition" );
sides.DeleteContents( true );
return NULL;
}
planepts[0] -= origin;
planepts[1] -= origin;
planepts[2] -= origin;
side->plane.FromPoints( planepts[0], planepts[1], planepts[2] );
// read the material
if( !src.ReadTokenOnLine( &token ) )
{
src.Error( "idMapBrush::ParseQ3: unable to read brush side material" );
sides.DeleteContents( true );
return NULL;
}
// we have an implicit 'textures/' in the old format
side->material = "textures/" + token;
// read the texture shift, rotate and scale
shift[0] = src.ParseInt();
shift[1] = src.ParseInt();
rotate = src.ParseInt();
scale[0] = src.ParseFloat();
scale[1] = src.ParseFloat();
side->texMat[0] = idVec3( 0.03125f, 0.0f, 0.0f );
side->texMat[1] = idVec3( 0.0f, 0.03125f, 0.0f );
side->origin = origin;
// Q2 allowed override of default flags and values, but we don't any more
if( src.ReadTokenOnLine( &token ) )
{
if( src.ReadTokenOnLine( &token ) )
{
if( src.ReadTokenOnLine( &token ) )
{
}
}
}
}
while( 1 );
idMapBrush* brush = new( TAG_IDLIB ) idMapBrush();
for( i = 0; i < sides.Num(); i++ )
{
brush->AddSide( sides[i] );
}
brush->epairs = epairs;
return brush;
}
/*
============
idMapBrush::Write
============
*/
bool idMapBrush::Write( idFile* fp, int primitiveNum, const idVec3& origin ) const
{
int i;
idMapBrushSide* side;
fp->WriteFloatString( "// primitive %d\n{\n brushDef3\n {\n", primitiveNum );
// write brush epairs
for( i = 0; i < epairs.GetNumKeyVals(); i++ )
{
fp->WriteFloatString( " \"%s\" \"%s\"\n", epairs.GetKeyVal( i )->GetKey().c_str(), epairs.GetKeyVal( i )->GetValue().c_str() );
}
// write brush sides
for( i = 0; i < GetNumSides(); i++ )
{
side = GetSide( i );
fp->WriteFloatString( " ( %f %f %f %f ) ", side->plane[0], side->plane[1], side->plane[2], side->plane[3] );
fp->WriteFloatString( "( ( %f %f %f ) ( %f %f %f ) ) \"%s\" 0 0 0\n",
side->texMat[0][0], side->texMat[0][1], side->texMat[0][2],
side->texMat[1][0], side->texMat[1][1], side->texMat[1][2],
side->material.c_str() );
}
fp->WriteFloatString( " }\n}\n" );
return true;
}
/*
===============
idMapBrush::GetGeometryCRC
===============
*/
unsigned int idMapBrush::GetGeometryCRC() const
{
int i, j;
idMapBrushSide* mapSide;
unsigned int crc;
crc = 0;
for( i = 0; i < GetNumSides(); i++ )
{
mapSide = GetSide( i );
for( j = 0; j < 4; j++ )
{
crc ^= FloatCRC( mapSide->GetPlane()[j] );
}
crc ^= StringCRC( mapSide->GetMaterial() );
}
return crc;
}
/*
================
idMapEntity::Parse
================
*/
idMapEntity* idMapEntity::Parse( idLexer& src, bool worldSpawn, float version )
{
idToken token;
idMapEntity* mapEnt;
idMapPatch* mapPatch;
idMapBrush* mapBrush;
// RB begin
MapPolygonMesh* mapMesh;
// RB end
bool worldent;
idVec3 origin;
double v1, v2, v3;
if( !src.ReadToken( &token ) )
{
return NULL;
}
if( token != "{" )
{
src.Error( "idMapEntity::Parse: { not found, found %s", token.c_str() );
return NULL;
}
mapEnt = new( TAG_IDLIB ) idMapEntity();
if( worldSpawn )
{
mapEnt->primitives.Resize( 1024, 256 );
}
origin.Zero();
worldent = false;
do
{
if( !src.ReadToken( &token ) )
{
src.Error( "idMapEntity::Parse: EOF without closing brace" );
return NULL;
}
if( token == "}" )
{
break;
}
if( token == "{" )
{
// parse a brush or patch
if( !src.ReadToken( &token ) )
{
src.Error( "idMapEntity::Parse: unexpected EOF" );
return NULL;
}
if( worldent )
{
origin.Zero();
}
// if is it a brush: brush, brushDef, brushDef2, brushDef3
if( token.Icmpn( "brush", 5 ) == 0 )
{
mapBrush = idMapBrush::Parse( src, origin, ( !token.Icmp( "brushDef2" ) || !token.Icmp( "brushDef3" ) ), version );
if( !mapBrush )
{
return NULL;
}
mapEnt->AddPrimitive( mapBrush );
}
// if is it a patch: patchDef2, patchDef3
else if( token.Icmpn( "patch", 5 ) == 0 )
{
mapPatch = idMapPatch::Parse( src, origin, !token.Icmp( "patchDef3" ), version );
if( !mapPatch )
{
return NULL;
}
mapEnt->AddPrimitive( mapPatch );
}
// RB: new mesh primitive with ngons
else if( token.Icmpn( "mesh", 4 ) == 0 )
{
mapMesh = MapPolygonMesh::Parse( src, origin, version );
if( !mapMesh )
{
return NULL;
}
mapEnt->AddPrimitive( mapMesh );
}
// RB end
// assume it's a brush in Q3 or older style
else
{
src.UnreadToken( &token );
mapBrush = idMapBrush::ParseQ3( src, origin );
if( !mapBrush )
{
return NULL;
}
mapEnt->AddPrimitive( mapBrush );
}
}
else
{
idStr key, value;
// parse a key / value pair
key = token;
src.ReadTokenOnLine( &token );
value = token;
// strip trailing spaces that sometimes get accidentally
// added in the editor
value.StripTrailingWhitespace();
key.StripTrailingWhitespace();
mapEnt->epairs.Set( key, value );
if( !idStr::Icmp( key, "origin" ) )
{
// scanf into doubles, then assign, so it is idVec size independent
v1 = v2 = v3 = 0;
sscanf( value, "%lf %lf %lf", &v1, &v2, &v3 );
origin.x = v1;
origin.y = v2;
origin.z = v3;
}
else if( !idStr::Icmp( key, "classname" ) && !idStr::Icmp( value, "worldspawn" ) )
{
worldent = true;
}
}
}
while( 1 );
return mapEnt;
}
/*
============
idMapEntity::Write
============
*/
bool idMapEntity::Write( idFile* fp, int entityNum ) const
{
int i;
idMapPrimitive* mapPrim;
idVec3 origin;
fp->WriteFloatString( "// entity %d\n{\n", entityNum );
// write entity epairs
for( i = 0; i < epairs.GetNumKeyVals(); i++ )
{
fp->WriteFloatString( "\"%s\" \"%s\"\n", epairs.GetKeyVal( i )->GetKey().c_str(), epairs.GetKeyVal( i )->GetValue().c_str() );
}
epairs.GetVector( "origin", "0 0 0", origin );
// write pritimives
for( i = 0; i < GetNumPrimitives(); i++ )
{
mapPrim = GetPrimitive( i );
switch( mapPrim->GetType() )
{
case idMapPrimitive::TYPE_BRUSH:
static_cast<idMapBrush*>( mapPrim )->Write( fp, i, origin );
break;
case idMapPrimitive::TYPE_PATCH:
static_cast<idMapPatch*>( mapPrim )->Write( fp, i, origin );
break;
// RB begin
case idMapPrimitive::TYPE_MESH:
static_cast<MapPolygonMesh*>( mapPrim )->Write( fp, i, origin );
break;
// RB end
}
}
fp->WriteFloatString( "}\n" );
return true;
}
// RB begin
bool idMapEntity::WriteJSON( idFile* fp, int entityNum, int numEntities ) const
{
idVec3 origin;
fp->WriteFloatString( "\t\t{\n\t\t\t\"entity\": \"%d\",\n", entityNum );
idStr key;
idStr value;
for( int i = 0; i < epairs.GetNumKeyVals(); i++ )
{
key = epairs.GetKeyVal( i )->GetKey();
key.ReplaceChar( '\t', ' ' );
value = epairs.GetKeyVal( i )->GetValue();
value.BackSlashesToSlashes();
fp->WriteFloatString( "\t\t\t\"%s\": \"%s\"%s\n", key.c_str(), value.c_str(), ( ( i == ( epairs.GetNumKeyVals() - 1 ) ) && !GetNumPrimitives() ) ? "" : "," );
}
epairs.GetVector( "origin", "0 0 0", origin );
// write pritimives
if( GetNumPrimitives() )
{
fp->WriteFloatString( "\t\t\t\"primitives\":\n\t\t\t[\n" );
}
int numPrimitives = GetNumPrimitives();
for( int i = 0; i < numPrimitives; i++ )
{
idMapPrimitive* mapPrim = GetPrimitive( i );
switch( mapPrim->GetType() )
{
#if 0
case idMapPrimitive::TYPE_BRUSH:
static_cast<idMapBrush*>( mapPrim )->Write( fp, i, origin );
break;
case idMapPrimitive::TYPE_PATCH:
static_cast<idMapPatch*>( mapPrim )->Write( fp, i, origin );
break;
#endif
case idMapPrimitive::TYPE_MESH:
static_cast<MapPolygonMesh*>( mapPrim )->WriteJSON( fp, i, origin );
break;
default:
continue;
}
// find next mesh primitive
idMapPrimitive* nextPrim = NULL;
for( int j = i + 1; j < numPrimitives; j++ )
{
nextPrim = GetPrimitive( j );
if( nextPrim->GetType() == idMapPrimitive::TYPE_MESH )
{
break;
}
}
if( nextPrim && ( nextPrim->GetType() == idMapPrimitive::TYPE_MESH ) )
{
fp->WriteFloatString( ",\n" );
}
else
{
fp->WriteFloatString( "\n" );
}
}
if( GetNumPrimitives() )
{
fp->WriteFloatString( "\t\t\t]\n" );
}
fp->WriteFloatString( "\t\t}%s\n", ( entityNum == ( numEntities - 1 ) ) ? "" : "," );
return true;
}
idMapEntity* idMapEntity::ParseJSON( idLexer& src )
{
idToken token;
idMapEntity* mapEnt;
//idMapPatch* mapPatch;
//idMapBrush* mapBrush;
// RB begin
MapPolygonMesh* mapMesh;
// RB end
bool worldent;
idVec3 origin;
double v1, v2, v3;
if( !src.ReadToken( &token ) )
{
return NULL;
}
if( token == "]" )
{
return NULL;
}
if( token == "," )
{
if( !src.ReadToken( &token ) )
{
return NULL;
}
}
if( token != "{" )
{
src.Error( "idMapEntity::ParseJSON: { not found, found %s", token.c_str() );
return NULL;
}
mapEnt = new idMapEntity();
/*
if( worldSpawn )
{
mapEnt->primitives.Resize( 1024, 256 );
}
*/
origin.Zero();
worldent = false;
do
{
if( !src.ReadToken( &token ) )
{
src.Error( "idMapEntity::ParseJSON: EOF without closing brace" );
return NULL;
}
if( token == "}" )
{
break;
}
if( token == "," )
{
continue;
}
// RB: new mesh primitive with ngons
if( token == "primitives" )
{
if( !src.ExpectTokenString( ":" ) )
{
delete mapEnt;
src.Error( "idMapEntity::ParseJSON: expected : for primitives" );
return NULL;
}
if( !src.ExpectTokenString( "[" ) )
{
delete mapEnt;
src.Error( "idMapEntity::ParseJSON: expected [ for primitives" );
return NULL;
}
while( true )
{
if( !src.ReadToken( &token ) )
{
src.Error( "idMapEntity::ParseJSON: EOF without closing brace" );
return NULL;
}
if( token == "]" )
{
break;
}
if( token == "," )
{
continue;
}
if( token == "{" )
{
mapMesh = MapPolygonMesh::ParseJSON( src );
if( !mapMesh )
{
break;
}
mapEnt->AddPrimitive( mapMesh );
}
}
}
else
{
idStr key, value;
// parse a key / value pair
key = token;
if( !src.ReadToken( &token ) )
{
src.Error( "idMapEntity::ParseJSON: EOF without closing brace" );
delete mapEnt;
return NULL;
}
if( token != ":" )
{
delete mapEnt;
return NULL;
}
src.ReadTokenOnLine( &token );
value = token;
// strip trailing spaces that sometimes get accidentally
// added in the editor
value.StripTrailingWhitespace();
key.StripTrailingWhitespace();
mapEnt->epairs.Set( key, value );
if( !idStr::Icmp( key, "origin" ) )
{
// scanf into doubles, then assign, so it is idVec size independent
v1 = v2 = v3 = 0;
sscanf( value, "%lf %lf %lf", &v1, &v2, &v3 );
origin.x = v1;
origin.y = v2;
origin.z = v3;
}
else if( !idStr::Icmp( key, "classname" ) && !idStr::Icmp( value, "worldspawn" ) )
{
worldent = true;
}
}
}
while( 1 );
return mapEnt;
}
// RB end
/*
===============
idMapEntity::RemovePrimitiveData
===============
*/
void idMapEntity::RemovePrimitiveData()
{
primitives.DeleteContents( true );
}
/*
===============
idMapEntity::GetGeometryCRC
===============
*/
unsigned int idMapEntity::GetGeometryCRC() const
{
int i;
unsigned int crc;
idMapPrimitive* mapPrim;
crc = 0;
for( i = 0; i < GetNumPrimitives(); i++ )
{
mapPrim = GetPrimitive( i );
switch( mapPrim->GetType() )
{
case idMapPrimitive::TYPE_BRUSH:
crc ^= static_cast<idMapBrush*>( mapPrim )->GetGeometryCRC();
break;
case idMapPrimitive::TYPE_PATCH:
crc ^= static_cast<idMapPatch*>( mapPrim )->GetGeometryCRC();
break;
// RB begin
case idMapPrimitive::TYPE_MESH:
crc ^= static_cast<MapPolygonMesh*>( mapPrim )->GetGeometryCRC();
break;
// RB end
}
}
return crc;
}
class idSort_CompareMapEntity : public idSort_Quick< idMapEntity*, idSort_CompareMapEntity >
{
public:
int Compare( idMapEntity* const& a, idMapEntity* const& b ) const
{
if( idStr::Icmp( a->epairs.GetString( "name" ), "worldspawn" ) == 0 )
{
return 1;
}
if( idStr::Icmp( b->epairs.GetString( "name" ), "worldspawn" ) == 0 )
{
return -1;
}
return idStr::Icmp( a->epairs.GetString( "name" ), b->epairs.GetString( "name" ) );
}
};
/*
===============
idMapFile::Parse
===============
*/
bool idMapFile::Parse( const char* filename, bool ignoreRegion, bool osPath )
{
// no string concatenation for epairs and allow path names for materials
idLexer src( LEXFL_NOSTRINGCONCAT | LEXFL_NOSTRINGESCAPECHARS | LEXFL_ALLOWPATHNAMES );
idToken token;
idStr fullName;
idMapEntity* mapEnt;
int i, j, k;
name = filename;
name.StripFileExtension();
fullName = name;
hasPrimitiveData = false;
bool isJSON = false;
if( !ignoreRegion )
{
// RB: try loading a .json file first
fullName.SetFileExtension( "json" );
src.LoadFile( fullName, osPath );
if( src.IsLoaded() )
{
isJSON = true;
}
}
if( !src.IsLoaded() )
{
// now try a .map file
fullName.SetFileExtension( "map" );
src.LoadFile( fullName, osPath );
if( !src.IsLoaded() )
{
// didn't get anything at all
return false;
}
}
version = OLD_MAP_VERSION;
fileTime = src.GetFileTime();
entities.DeleteContents( true );
if( !src.ReadToken( &token ) )
{
return false;
}
if( token == "{" )
{
isJSON = true;
}
if( isJSON )
{
while( true )
{
if( !src.ReadToken( &token ) )
{
break;
}
if( token == "entities" )
{
if( !src.ReadToken( &token ) )
{
return false;
}
if( token != ":" )
{
src.Error( "idMapFile::Parse: : not found, found %s", token.c_str() );
return false;
}
if( !src.ReadToken( &token ) )
{
return false;
}
if( token != "[" )
{
src.Error( "idMapFile::Parse: [ not found, found %s", token.c_str() );
return false;
}
while( true )
{
mapEnt = idMapEntity::ParseJSON( src );
if( !mapEnt )
{
break;
}
entities.Append( mapEnt );
}
}
}
//entities.SortWithTemplate( idSort_CompareMapEntity() );
if( entities.Num() > 0 && ( idStr::Icmp( entities[0]->epairs.GetString( "name" ), "worldspawn" ) != 0 ) )
{
// move world spawn to first place
for( int i = 1; i < entities.Num(); i++ )
{
if( idStr::Icmp( entities[i]->epairs.GetString( "name" ), "worldspawn" ) == 0 )
{
idMapEntity* tmp = entities[0];
entities[0] = entities[i];
entities[i] = tmp;
break;
}
}
}
}
else
{
if( token == "Version" )
{
src.ReadTokenOnLine( &token );
version = token.GetFloatValue();
}
while( 1 )
{
mapEnt = idMapEntity::Parse( src, ( entities.Num() == 0 ), version );
if( !mapEnt )
{
break;
}
entities.Append( mapEnt );
}
}
SetGeometryCRC();
// if the map has a worldspawn
if( entities.Num() )
{
// "removeEntities" "classname" can be set in the worldspawn to remove all entities with the given classname
const idKeyValue* removeEntities = entities[0]->epairs.MatchPrefix( "removeEntities", NULL );
while( removeEntities )
{
RemoveEntities( removeEntities->GetValue() );
removeEntities = entities[0]->epairs.MatchPrefix( "removeEntities", removeEntities );
}
// "overrideMaterial" "material" can be set in the worldspawn to reset all materials
idStr material;
if( entities[0]->epairs.GetString( "overrideMaterial", "", material ) )
{
for( i = 0; i < entities.Num(); i++ )
{
mapEnt = entities[i];
for( j = 0; j < mapEnt->GetNumPrimitives(); j++ )
{
idMapPrimitive* mapPrimitive = mapEnt->GetPrimitive( j );
switch( mapPrimitive->GetType() )
{
case idMapPrimitive::TYPE_BRUSH:
{
idMapBrush* mapBrush = static_cast<idMapBrush*>( mapPrimitive );
for( k = 0; k < mapBrush->GetNumSides(); k++ )
{
mapBrush->GetSide( k )->SetMaterial( material );
}
break;
}
case idMapPrimitive::TYPE_PATCH:
{
static_cast<idMapPatch*>( mapPrimitive )->SetMaterial( material );
break;
}
}
}
}
}
// force all entities to have a name key/value pair
if( entities[0]->epairs.GetBool( "forceEntityNames" ) )
{
for( i = 1; i < entities.Num(); i++ )
{
mapEnt = entities[i];
if( !mapEnt->epairs.FindKey( "name" ) )
{
mapEnt->epairs.Set( "name", va( "%s%d", mapEnt->epairs.GetString( "classname", "forcedName" ), i ) );
}
}
}
// move the primitives of any func_group entities to the worldspawn
if( entities[0]->epairs.GetBool( "moveFuncGroups" ) )
{
for( i = 1; i < entities.Num(); i++ )
{
mapEnt = entities[i];
if( idStr::Icmp( mapEnt->epairs.GetString( "classname" ), "func_group" ) == 0 )
{
entities[0]->primitives.Append( mapEnt->primitives );
mapEnt->primitives.Clear();
}
}
}
}
hasPrimitiveData = true;
return true;
}
/*
============
idMapFile::Write
============
*/
bool idMapFile::Write( const char* fileName, const char* ext, bool fromBasePath )
{
int i;
idStr qpath;
idFile* fp;
qpath = fileName;
qpath.SetFileExtension( ext );
idLib::common->Printf( "writing %s...\n", qpath.c_str() );
if( fromBasePath )
{
fp = idLib::fileSystem->OpenFileWrite( qpath, "fs_basepath" );
}
else
{
fp = idLib::fileSystem->OpenExplicitFileWrite( qpath );
}
if( !fp )
{
idLib::common->Warning( "Couldn't open %s\n", qpath.c_str() );
return false;
}
fp->WriteFloatString( "Version %f\n", ( float ) CURRENT_MAP_VERSION );
for( i = 0; i < entities.Num(); i++ )
{
entities[i]->Write( fp, i );
}
idLib::fileSystem->CloseFile( fp );
return true;
}
// RB begin
bool idMapFile::WriteJSON( const char* fileName, const char* ext, bool fromBasePath )
{
int i;
idStr qpath;
idFile* fp;
qpath = fileName;
qpath.SetFileExtension( ext );
idLib::common->Printf( "writing %s...\n", qpath.c_str() );
if( fromBasePath )
{
fp = idLib::fileSystem->OpenFileWrite( qpath, "fs_basepath" );
}
else
{
fp = idLib::fileSystem->OpenExplicitFileWrite( qpath );
}
if( !fp )
{
idLib::common->Warning( "Couldn't open %s\n", qpath.c_str() );
return false;
}
fp->Printf( "{\n" );
fp->WriteFloatString( "\t\"version\": \"%f\",\n", ( float ) CURRENT_MAP_VERSION );
fp->Printf( "\t\"entities\": \n\t[\n" );
for( i = 0; i < entities.Num(); i++ )
{
entities[i]->WriteJSON( fp, i, entities.Num() );
}
fp->Printf( "\t]\n" );
fp->Printf( "}\n" );
idLib::fileSystem->CloseFile( fp );
return true;
}
// RB end
/*
===============
idMapFile::SetGeometryCRC
===============
*/
void idMapFile::SetGeometryCRC()
{
int i;
geometryCRC = 0;
for( i = 0; i < entities.Num(); i++ )
{
geometryCRC ^= entities[i]->GetGeometryCRC();
}
}
/*
===============
idMapFile::AddEntity
===============
*/
int idMapFile::AddEntity( idMapEntity* mapEnt )
{
int ret = entities.Append( mapEnt );
return ret;
}
/*
===============
idMapFile::FindEntity
===============
*/
idMapEntity* idMapFile::FindEntity( const char* name )
{
for( int i = 0; i < entities.Num(); i++ )
{
idMapEntity* ent = entities[i];
if( idStr::Icmp( ent->epairs.GetString( "name" ), name ) == 0 )
{
return ent;
}
}
return NULL;
}
/*
===============
idMapFile::RemoveEntity
===============
*/
void idMapFile::RemoveEntity( idMapEntity* mapEnt )
{
entities.Remove( mapEnt );
delete mapEnt;
}
/*
===============
idMapFile::RemoveEntity
===============
*/
void idMapFile::RemoveEntities( const char* classname )
{
for( int i = 0; i < entities.Num(); i++ )
{
idMapEntity* ent = entities[i];
if( idStr::Icmp( ent->epairs.GetString( "classname" ), classname ) == 0 )
{
delete entities[i];
entities.RemoveIndex( i );
i--;
}
}
}
/*
===============
idMapFile::RemoveAllEntities
===============
*/
void idMapFile::RemoveAllEntities()
{
entities.DeleteContents( true );
hasPrimitiveData = false;
}
/*
===============
idMapFile::RemovePrimitiveData
===============
*/
void idMapFile::RemovePrimitiveData()
{
for( int i = 0; i < entities.Num(); i++ )
{
idMapEntity* ent = entities[i];
ent->RemovePrimitiveData();
}
hasPrimitiveData = false;
}
/*
===============
idMapFile::NeedsReload
===============
*/
bool idMapFile::NeedsReload()
{
if( name.Length() )
{
ID_TIME_T time = FILE_NOT_FOUND_TIMESTAMP;
if( idLib::fileSystem->ReadFile( name, NULL, &time ) > 0 )
{
return ( time > fileTime );
}
}
return true;
}
// RB begin
MapPolygonMesh::MapPolygonMesh()
{
type = TYPE_MESH;
originalType = TYPE_MESH;
polygons.Resize( 8, 4 );
contents = CONTENTS_SOLID;
opaque = true;
}
void MapPolygonMesh::ConvertFromBrush( const idMapBrush* mapBrush, int entityNum, int primitiveNum )
{
originalType = TYPE_BRUSH;
// fix degenerate planes
idPlane* planes = ( idPlane* ) _alloca16( mapBrush->GetNumSides() * sizeof( planes[0] ) );
for( int i = 0; i < mapBrush->GetNumSides(); i++ )
{
planes[i] = mapBrush->GetSide( i )->GetPlane();
planes[i].FixDegeneracies( DEGENERATE_DIST_EPSILON );
}
idList<idFixedWinding> planeWindings;
idBounds bounds;
bounds.Clear();
int numVerts = 0;
int numIndexes = 0;
bool badBrush = false;
for( int i = 0; i < mapBrush->GetNumSides(); i++ )
{
idMapBrushSide* mapSide = mapBrush->GetSide( i );
const idMaterial* material = declManager->FindMaterial( mapSide->GetMaterial() );
//contents |= ( material->GetContentFlags() & CONTENTS_REMOVE_UTIL );
//materials.AddUnique( material );
// chop base plane by other brush sides
idFixedWinding& w = planeWindings.Alloc();
w.BaseForPlane( -planes[i] );
if( !w.GetNumPoints() )
{
common->Printf( "Entity %i, Brush %i: base winding has no points\n", entityNum, primitiveNum );
badBrush = true;
break;
}
for( int j = 0; j < mapBrush->GetNumSides() && w.GetNumPoints(); j++ )
{
if( i == j )
{
continue;
}
if( !w.ClipInPlace( -planes[j], 0 ) )
{
// no intersection
//badBrush = true;
common->Printf( "Entity %i, Brush %i: no intersection with other brush plane\n", entityNum, primitiveNum );
//break;
}
}
if( w.GetNumPoints() <= 2 )
{
continue;
}
// only used for debugging
for( int j = 0; j < w.GetNumPoints(); j++ )
{
const idVec3& v = w[j].ToVec3();
bounds.AddPoint( v );
}
}
if( badBrush )
{
//common->Error( "" )
return;
}
// copy the data from the windings and build polygons
for( int i = 0; i < mapBrush->GetNumSides(); i++ )
{
idMapBrushSide* mapSide = mapBrush->GetSide( i );
idFixedWinding& w = planeWindings[i];
if( !w.GetNumPoints() )
{
continue;
}
MapPolygon& polygon = polygons.Alloc();
polygon.SetMaterial( mapSide->GetMaterial() );
//for( int j = 0; j < w.GetNumPoints(); j++ )
// reverse order, so normal does not point inwards
for( int j = w.GetNumPoints() - 1; j >= 0; j-- )
{
polygon.AddIndex( verts.Num() + j );
}
for( int j = 0; j < w.GetNumPoints(); j++ )
{
idDrawVert& dv = verts.Alloc();
const idVec3& xyz = w[j].ToVec3();
dv.xyz = xyz;
// calculate texture s/t from brush primitive texture matrix
idVec4 texVec[2];
mapSide->GetTextureVectors( texVec );
idVec2 st;
st.x = ( xyz * texVec[0].ToVec3() ) + texVec[0][3];
st.y = ( xyz * texVec[1].ToVec3() ) + texVec[1][3];
// flip y
//st.y = 1.0f - st.y;
dv.SetTexCoord( st );
// copy normal
dv.SetNormal( mapSide->GetPlane().Normal() );
//if( dv->GetNormal().Length() < 0.9 || dv->GetNormal().Length() > 1.1 )
//{
// common->Error( "Bad normal in TriListForSide" );
//}
}
}
SetContents();
}
void MapPolygonMesh::ConvertFromPatch( const idMapPatch* patch, int entityNum, int primitiveNum )
{
originalType = TYPE_PATCH;
idSurface_Patch* cp = new idSurface_Patch( *patch );
if( patch->GetExplicitlySubdivided() )
{
cp->SubdivideExplicit( patch->GetHorzSubdivisions(), patch->GetVertSubdivisions(), true );
}
else
{
cp->Subdivide( DEFAULT_CURVE_MAX_ERROR, DEFAULT_CURVE_MAX_ERROR, DEFAULT_CURVE_MAX_LENGTH, true );
}
for( int i = 0; i < cp->GetNumIndexes(); i += 3 )
{
verts.Append( ( *cp )[cp->GetIndexes()[i + 1]] );
verts.Append( ( *cp )[cp->GetIndexes()[i + 2]] );
verts.Append( ( *cp )[cp->GetIndexes()[i + 0]] );
}
for( int i = 0; i < cp->GetNumIndexes(); i += 3 )
{
MapPolygon& polygon = polygons.Alloc();
polygon.SetMaterial( patch->GetMaterial() );
polygon.AddIndex( i + 0 );
polygon.AddIndex( i + 1 );
polygon.AddIndex( i + 2 );
}
delete cp;
SetContents();
}
bool MapPolygonMesh::Write( idFile* fp, int primitiveNum, const idVec3& origin ) const
{
fp->WriteFloatString( "// primitive %d\n{\n meshDef\n {\n", primitiveNum );
//fp->WriteFloatString( " \"%s\"\n ( %d %d 0 0 0 )\n", GetMaterial(), GetWidth(), GetHeight() );
fp->WriteFloatString( " ( %d %d 0 0 0 )\n", verts.Num(), polygons.Num() );
fp->WriteFloatString( " (\n" );
idVec2 st;
idVec3 n;
for( int i = 0; i < verts.Num(); i++ )
{
const idDrawVert* v = &verts[ i ];
st = v->GetTexCoord();
n = v->GetNormalRaw();
//fp->WriteFloatString( " ( %f %f %f %f %f %f %f %f )\n", v->xyz[0] + origin[0], v->xyz[1] + origin[1], v->xyz[2] + origin[2], st[0], st[1], n[0], n[1], n[2] );
fp->WriteFloatString( " ( %f %f %f %f %f %f %f %f )\n", v->xyz[0], v->xyz[1], v->xyz[2], st[0], st[1], n[0], n[1], n[2] );
}
fp->WriteFloatString( " )\n" );
fp->WriteFloatString( " (\n" );
for( int i = 0; i < polygons.Num(); i++ )
{
const MapPolygon& poly = polygons[ i ];
fp->WriteFloatString( " \"%s\" %d = ", poly.GetMaterial(), poly.indexes.Num() );
for( int j = 0; j < poly.indexes.Num(); j++ )
{
fp->WriteFloatString( "%d ", poly.indexes[j] );
}
fp->WriteFloatString( "\n" );
}
fp->WriteFloatString( " )\n" );
fp->WriteFloatString( " }\n}\n" );
return true;
}
bool MapPolygonMesh::WriteJSON( idFile* fp, int primitiveNum, const idVec3& origin ) const
{
fp->WriteFloatString( "\t\t\t\t{\n\t\t\t\t\t\"primitive\": \"%d\",\n", primitiveNum );
if( originalType == TYPE_BRUSH )
{
fp->WriteFloatString( "\t\t\t\t\t\"original\": \"brush\",\n" );
}
else if( originalType == TYPE_PATCH )
{
fp->WriteFloatString( "\t\t\t\t\t\"original\": \"curve\",\n" );
}
fp->WriteFloatString( "\t\t\t\t\t\"verts\":\n\t\t\t\t\t[\n" );
idVec2 st;
idVec3 n;
for( int i = 0; i < verts.Num(); i++ )
{
const idDrawVert& v = verts[ i ];
st = v.GetTexCoord();
n = v.GetNormalRaw();
//if( IsNAN( v.xyz ) )
//{
// continue;
//}
//idVec3 xyz = v.xyz - origin;
fp->WriteFloatString( "\t\t\t\t\t\t{ \"xyz\": [%f, %f, %f], \"st\": [%f, %f], \"normal\": [%f, %f, %f] }%s\n", v.xyz[0], v.xyz[1], v.xyz[2], st[0], st[1], n[0], n[1], n[2], ( i == ( verts.Num() - 1 ) ) ? "" : "," );
}
fp->WriteFloatString( "\t\t\t\t\t],\n" );
fp->WriteFloatString( "\t\t\t\t\t\"polygons\":\n\t\t\t\t\t[\n" );
for( int i = 0; i < polygons.Num(); i++ )
{
const MapPolygon& poly = polygons[ i ];
fp->WriteFloatString( "\t\t\t\t\t\t{ \"material\": \"%s\", \"indices\": [", poly.GetMaterial() );
#if 0
for( int j = 0; j < poly.indexes.Num(); j++ )
{
fp->WriteFloatString( "%d%s", poly.indexes[j], ( j == poly.indexes.Num() - 1 ) ? "" : ", " );
}
#else
for( int j = poly.indexes.Num() - 1 ; j >= 0; j-- )
{
fp->WriteFloatString( "%d%s", poly.indexes[j], ( j == 0 ) ? "" : ", " );
}
#endif
fp->WriteFloatString( "] }%s\n", ( i == ( polygons.Num() - 1 ) ) ? "" : "," );
}
fp->WriteFloatString( "\t\t\t\t\t]\n" );
fp->WriteFloatString( "\t\t\t\t}" );
return true;
}
MapPolygonMesh* MapPolygonMesh::Parse( idLexer& src, const idVec3& origin, float version )
{
float info[7];
idToken token;
int i;
if( !src.ExpectTokenString( "{" ) )
{
return NULL;
}
// Parse it
if( !src.Parse1DMatrix( 5, info ) )
{
src.Error( "MapPolygonMesh::Parse: unable to parse meshDef info" );
return NULL;
}
const int numVertices = ( int ) info[0];
const int numPolygons = ( int ) info[1];
MapPolygonMesh* mesh = new MapPolygonMesh();
// parse vertices
if( !src.ExpectTokenString( "(" ) )
{
src.Error( "MapPolygonMesh::Parse: bad mesh vertex data" );
delete mesh;
return NULL;
}
for( i = 0; i < numVertices; i++ )
{
float v[8];
if( !src.Parse1DMatrix( 8, v ) )
{
src.Error( "MapPolygonMesh::Parse: bad vertex column data" );
delete mesh;
return NULL;
}
// TODO optimize: preallocate vertices
//vert = &( ( *patch )[i * patch->GetWidth() + j] );
idDrawVert vert;
vert.xyz[0] = v[0];// - origin[0];
vert.xyz[1] = v[1];// - origin[1];
vert.xyz[2] = v[2];// - origin[2];
vert.SetTexCoord( v[3], v[4] );
idVec3 n( v[5], v[6], v[7] );
vert.SetNormal( n );
mesh->AddVertex( vert );
}
if( !src.ExpectTokenString( ")" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::Parse: unable to parse vertices" );
return NULL;
}
// parse polygons
if( !src.ExpectTokenString( "(" ) )
{
src.Error( "MapPolygonMesh::Parse: bad mesh polygon data" );
delete mesh;
return NULL;
}
for( i = 0; i < numPolygons; i++ )
{
// get material name
MapPolygon& polygon = mesh->polygons.Alloc();
src.ReadToken( &token );
if( token.type == TT_STRING )
{
polygon.SetMaterial( token );;
}
else
{
src.Error( "MapPolygonMesh::Parse: bad mesh polygon data" );
delete mesh;
return NULL;
}
int numIndexes = src.ParseInt();
if( !src.ExpectTokenString( "=" ) )
{
src.Error( "MapPolygonMesh::Parse: bad mesh polygon data" );
delete mesh;
return NULL;
}
//idTempArray<int> indexes( numIndexes );
for( int j = 0; j < numIndexes; j++ )
{
//indexes[j] = src.ParseInt();
int index = src.ParseInt();
polygon.AddIndex( index );
}
//polygon->SetIndexes( indexes );
}
if( !src.ExpectTokenString( ")" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::Parse: unable to parse polygons" );
return NULL;
}
if( !src.ExpectTokenString( "}" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::Parse: unable to parse mesh primitive end" );
return NULL;
}
if( !src.ExpectTokenString( "}" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::Parse: unable to parse mesh primitive end" );
return NULL;
}
mesh->SetContents();
return mesh;
}
MapPolygonMesh* MapPolygonMesh::ParseJSON( idLexer& src )
{
idToken token;
MapPolygonMesh* mesh = new MapPolygonMesh();
while( true )
{
if( !src.ReadToken( &token ) )
{
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
if( token == "}" )
{
break;
}
if( token == "," )
{
continue;
}
if( token == "verts" )
{
idDrawVert vert;
float v[8];
while( true )
{
if( !src.ReadToken( &token ) )
{
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
if( token == "}" )
{
mesh->AddVertex( vert );
continue;
}
if( token == "]" )
{
break;
}
if( token == "," )
{
continue;
}
if( token == "xyz" )
{
if( !src.ExpectTokenString( ":" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
if( !src.Parse1DMatrixJSON( 3, v ) )
{
delete mesh;
src.Error( "MapPolygonMesh::ParseJSON: bad vertex column data" );
return NULL;
}
vert.xyz[0] = v[0];
vert.xyz[1] = v[1];
vert.xyz[2] = v[2];
}
else if( token == "st" )
{
if( !src.ExpectTokenString( ":" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
if( !src.Parse1DMatrixJSON( 2, v ) )
{
delete mesh;
src.Error( "MapPolygonMesh::ParseJSON: bad vertex column data" );
return NULL;
}
vert.SetTexCoord( v[0], v[1] );
}
else if( token == "normal" )
{
if( !src.ExpectTokenString( ":" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
if( !src.Parse1DMatrixJSON( 3, v ) )
{
delete mesh;
src.Error( "MapPolygonMesh::ParseJSON: bad vertex column data" );
return NULL;
}
idVec3 n( v[0], v[1], v[2] );
vert.SetNormal( n );
}
}
}
if( token == "polygons" )
{
MapPolygon* polygon = NULL;
while( true )
{
if( !src.ReadToken( &token ) )
{
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
if( token == "{" )
{
polygon = &mesh->polygons.Alloc();
continue;
}
if( token == "]" )
{
break;
}
if( token == "," )
{
continue;
}
if( token == "material" )
{
if( !src.ExpectTokenString( ":" ) )
{
delete mesh;
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
src.ReadToken( &token );
if( token.type == TT_STRING )
{
polygon->SetMaterial( token );
}
}
else if( token == "indices" )
{
idList<int> indices;
while( true )
{
if( !src.ReadToken( &token ) )
{
src.Error( "MapPolygonMesh::ParseJSON: EOF without closing brace" );
return NULL;
}
if( token == "]" )
{
// reverse order from Blender
for( int i = indices.Num() - 1; i >= 0; i-- )
{
polygon->AddIndex( indices[i] );
}
break;
}
else if( token.type == TT_NUMBER )
{
int index = token.GetIntValue();
indices.Append( index );
}
else if( token == "," )
{
continue;
}
}
}
}
}
}
mesh->SetContents();
return mesh;
}
void MapPolygonMesh::SetContents()
{
if( polygons.Num() < 1 )
{
contents = CONTENTS_SOLID;
opaque = true;
return;
}
int c2;
MapPolygon* poly = &polygons[0];
const idMaterial* mat = declManager->FindMaterial( poly->GetMaterial() );
contents = mat->GetContentFlags();
//b->contentShader = s->material;
bool mixed = false;
// a brush is only opaque if all sides are opaque
opaque = true;
for( int i = 1 ; i < polygons.Num() ; i++ )
{
poly = &polygons[i];
const idMaterial* mat2 = declManager->FindMaterial( poly->GetMaterial() );
c2 = mat2->GetContentFlags();
if( c2 != contents )
{
mixed = true;
contents |= c2;
}
if( mat2->Coverage() != MC_OPAQUE )
{
opaque = false;
}
}
}
unsigned int MapPolygonMesh::GetGeometryCRC() const
{
int i;
unsigned int crc;
crc = 0;
for( i = 0; i < verts.Num(); i++ )
{
crc ^= FloatCRC( verts[i].xyz.x );
crc ^= FloatCRC( verts[i].xyz.y );
crc ^= FloatCRC( verts[i].xyz.z );
}
for( i = 0; i < polygons.Num(); i++ )
{
const MapPolygon& poly = polygons[i];
crc ^= StringCRC( poly.GetMaterial() );
}
return crc;
}
bool MapPolygonMesh::IsAreaportal() const
{
return ( ( contents & CONTENTS_AREAPORTAL ) != 0 );
}
void MapPolygonMesh::GetBounds( idBounds& bounds ) const
{
if( !verts.Num() )
{
bounds.Clear();
return;
}
bounds[0] = bounds[1] = verts[0].xyz;
for( int i = 1; i < verts.Num(); i++ )
{
const idVec3& p = verts[i].xyz;
if( p.x < bounds[0].x )
{
bounds[0].x = p.x;
}
else if( p.x > bounds[1].x )
{
bounds[1].x = p.x;
}
if( p.y < bounds[0].y )
{
bounds[0].y = p.y;
}
else if( p.y > bounds[1].y )
{
bounds[1].y = p.y;
}
if( p.z < bounds[0].z )
{
bounds[0].z = p.z;
}
else if( p.z > bounds[1].z )
{
bounds[1].z = p.z;
}
}
}
bool idMapFile::ConvertToPolygonMeshFormat()
{
int count = GetNumEntities();
for( int j = 0; j < count; j++ )
{
idMapEntity* ent = GetEntity( j );
if( ent )
{
idStr classname = ent->epairs.GetString( "classname" );
//if( classname == "worldspawn" )
{
for( int i = 0; i < ent->GetNumPrimitives(); i++ )
{
idMapPrimitive* mapPrim;
mapPrim = ent->GetPrimitive( i );
if( mapPrim->GetType() == idMapPrimitive::TYPE_BRUSH )
{
MapPolygonMesh* meshPrim = new MapPolygonMesh();
meshPrim->epairs.Copy( mapPrim->epairs );
meshPrim->ConvertFromBrush( static_cast<idMapBrush*>( mapPrim ), j, i );
ent->primitives[ i ] = meshPrim;
delete mapPrim;
continue;
}
else if( mapPrim->GetType() == idMapPrimitive::TYPE_PATCH )
{
MapPolygonMesh* meshPrim = new MapPolygonMesh();
meshPrim->epairs.Copy( mapPrim->epairs );
meshPrim->ConvertFromPatch( static_cast<idMapPatch*>( mapPrim ), j, i );
ent->primitives[ i ] = meshPrim;
delete mapPrim;
continue;
}
}
}
}
}
return true;
}
// RB end
| 21.203011 | 366 | 0.575999 | [
"mesh",
"vector"
] |
639d5c58aac21fb5161edde15b78492afc17abcf | 7,836 | cpp | C++ | pxr/usd/usdSkel/animMapper.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 3,680 | 2016-07-26T18:28:11.000Z | 2022-03-31T09:55:05.000Z | pxr/usd/usdSkel/animMapper.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 1,759 | 2016-07-26T19:19:59.000Z | 2022-03-31T21:24:00.000Z | pxr/usd/usdSkel/animMapper.cpp | DougRogers-DigitalFish/USD | d8a405a1344480f859f025c4f97085143efacb53 | [
"BSD-2-Clause"
] | 904 | 2016-07-26T18:33:40.000Z | 2022-03-31T09:55:16.000Z | //
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/usd/usdSkel/animMapper.h"
#include "pxr/base/gf/matrix4d.h"
#include "pxr/base/gf/matrix4f.h"
#include "pxr/base/tf/type.h"
#include <algorithm>
#include <unordered_map>
PXR_NAMESPACE_OPEN_SCOPE
namespace {
enum _MapFlags {
_NullMap = 0,
_SomeSourceValuesMapToTarget = 0x1,
_AllSourceValuesMapToTarget = 0x2,
_SourceOverridesAllTargetValues = 0x4,
_OrderedMap = 0x8,
_IdentityMap = (_AllSourceValuesMapToTarget|
_SourceOverridesAllTargetValues|_OrderedMap),
_NonNullMap = (_SomeSourceValuesMapToTarget|_AllSourceValuesMapToTarget)
};
} // namespace
UsdSkelAnimMapper::UsdSkelAnimMapper()
: _targetSize(0), _offset(0), _flags(_NullMap)
{}
UsdSkelAnimMapper::UsdSkelAnimMapper(size_t size)
: _targetSize(size), _offset(0), _flags(_IdentityMap)
{}
UsdSkelAnimMapper::UsdSkelAnimMapper(const VtTokenArray& sourceOrder,
const VtTokenArray& targetOrder)
: UsdSkelAnimMapper(sourceOrder.cdata(), sourceOrder.size(),
targetOrder.cdata(), targetOrder.size())
{}
UsdSkelAnimMapper::UsdSkelAnimMapper(const TfToken* sourceOrder,
size_t sourceOrderSize,
const TfToken* targetOrder,
size_t targetOrderSize)
: _targetSize(targetOrderSize), _offset(0)
{
if(sourceOrderSize == 0 || targetOrderSize == 0) {
_flags = _NullMap;
return;
}
{
// Determine if this an ordered mapping of the source
// onto the target, with a simple offset.
// This includes identity maps.
// Find where the first source element begins on the target.
const auto it = std::find(targetOrder, targetOrder + targetOrderSize,
sourceOrder[0]);
const size_t pos = it - targetOrder;
if((pos + sourceOrderSize) <= targetOrderSize) {
if(std::equal(sourceOrder, sourceOrder+sourceOrderSize, it)) {
_offset = pos;
_flags = _OrderedMap | _AllSourceValuesMapToTarget;
if(pos == 0 && sourceOrderSize == targetOrderSize) {
_flags |= _SourceOverridesAllTargetValues;
}
return;
}
}
}
// No ordered mapping can be produced.
// Settle for an unordered, indexed mapping.
// Need a map of path->targetIndex.
std::unordered_map<TfToken,int,TfToken::HashFunctor> targetMap;
for(size_t i = 0; i < targetOrderSize; ++i) {
targetMap[targetOrder[i]] = static_cast<int>(i);
}
_indexMap.resize(sourceOrderSize);
int* indexMap = _indexMap.data();
size_t mappedCount = 0;
std::vector<bool> targetMapped(targetOrderSize);
for(size_t i = 0; i < sourceOrderSize; ++i) {
auto it = targetMap.find(sourceOrder[i]);
if(it != targetMap.end()) {
indexMap[i] = it->second;
targetMapped[it->second] = true;
++mappedCount;
} else {
indexMap[i] = -1;
}
}
_flags = mappedCount == sourceOrderSize ?
_AllSourceValuesMapToTarget : _SomeSourceValuesMapToTarget;
if(std::all_of(targetMapped.begin(), targetMapped.end(),
[](bool val) { return val; })) {
_flags |= _SourceOverridesAllTargetValues;
}
}
bool
UsdSkelAnimMapper::IsIdentity() const
{
return (_flags&_IdentityMap) == _IdentityMap;
}
bool
UsdSkelAnimMapper::IsSparse() const
{
return !(_flags&_SourceOverridesAllTargetValues);
}
bool
UsdSkelAnimMapper::IsNull() const
{
return !(_flags&_NonNullMap);
}
bool
UsdSkelAnimMapper::_IsOrdered() const
{
return _flags&_OrderedMap;
}
template <typename T>
bool
UsdSkelAnimMapper::_UntypedRemap(const VtValue& source,
VtValue* target,
int elementSize,
const VtValue& defaultValue) const
{
TF_DEV_AXIOM(source.IsHolding<VtArray<T> >());
if (!target) {
TF_CODING_ERROR("'target' pointer is null.");
return false;
}
if (target->IsEmpty()) {
*target = VtArray<T>();
} else if (!target->IsHolding<VtArray<T> >()) {
TF_CODING_ERROR("Type of 'target' [%s] did not match the type of "
"'source' [%s].", target->GetTypeName().c_str(),
source.GetTypeName().c_str());
return false;
}
const T* defaultValueT = nullptr;
if (!defaultValue.IsEmpty()) {
if (defaultValue.IsHolding<T>()) {
defaultValueT = &defaultValue.UncheckedGet<T>();
} else {
TF_CODING_ERROR("Unexpected type [%s] for defaultValue: expecting "
"'%s'.", defaultValue.GetTypeName().c_str(),
TfType::Find<T>().GetTypeName().c_str());
return false;
}
}
const auto& sourceArray = source.UncheckedGet<VtArray<T> >();
auto targetArray = target->UncheckedGet<VtArray<T> >();
if (Remap(sourceArray, &targetArray, elementSize, defaultValueT)) {
*target = targetArray;
return true;
}
return false;
}
bool
UsdSkelAnimMapper::Remap(const VtValue& source,
VtValue* target,
int elementSize,
const VtValue& defaultValue) const
{
#define _UNTYPED_REMAP(r, unused, elem) \
if(source.IsHolding<SDF_VALUE_CPP_ARRAY_TYPE(elem)>()) { \
return _UntypedRemap<SDF_VALUE_CPP_TYPE(elem)>( \
source, target, elementSize, defaultValue); \
}
BOOST_PP_SEQ_FOR_EACH(_UNTYPED_REMAP, ~, SDF_VALUE_TYPES);
#undef _UNTYPED_REMAP
return false;
}
template <typename Matrix4>
bool
UsdSkelAnimMapper::RemapTransforms(const VtArray<Matrix4>& source,
VtArray<Matrix4>* target,
int elementSize) const
{
static const Matrix4 identity(1);
return Remap(source, target, elementSize, &identity);
}
template USDSKEL_API bool
UsdSkelAnimMapper::RemapTransforms(const VtMatrix4dArray&,
VtMatrix4dArray*, int) const;
template USDSKEL_API bool
UsdSkelAnimMapper::RemapTransforms(const VtMatrix4fArray&,
VtMatrix4fArray*, int) const;
bool
UsdSkelAnimMapper::operator==(const UsdSkelAnimMapper& o) const
{
return _targetSize == o._targetSize &&
_offset == o._offset &&
_flags == o._flags &&
_indexMap == o._indexMap;
}
PXR_NAMESPACE_CLOSE_SCOPE
| 29.794677 | 79 | 0.616258 | [
"vector"
] |
639d66943af910261a0e2cfbc35e7b1073590113 | 24,223 | hh | C++ | extern/OpenVolumeMesh/src/OpenVolumeMesh/Core/Iterators.hh | msraig/CE-PolyCube | e46aff6e0594b711735118bfa902a91bc3d392ca | [
"MIT"
] | 19 | 2020-08-13T05:15:09.000Z | 2022-03-31T14:51:29.000Z | extern/OpenVolumeMesh/src/OpenVolumeMesh/Core/Iterators.hh | xh-liu-tech/CE-PolyCube | 86d4ed0023215307116b6b3245e2dbd82907cbb8 | [
"MIT"
] | 2 | 2020-09-08T07:03:04.000Z | 2021-08-04T05:43:27.000Z | extern/OpenVolumeMesh/src/OpenVolumeMesh/Core/Iterators.hh | xh-liu-tech/CE-PolyCube | 86d4ed0023215307116b6b3245e2dbd82907cbb8 | [
"MIT"
] | 10 | 2020-08-06T02:37:46.000Z | 2021-07-01T09:12:06.000Z | /*===========================================================================*\
* *
* OpenVolumeMesh *
* Copyright (C) 2011 by Computer Graphics Group, RWTH Aachen *
* www.openvolumemesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenVolumeMesh. *
* *
* OpenVolumeMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenVolumeMesh is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU LesserGeneral Public *
* License along with OpenVolumeMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* $LastChangedBy$ *
* *
\*===========================================================================*/
#ifndef ITERATORS_HH_
#define ITERATORS_HH_
#include <set>
#include <vector>
#include <iterator>
#include "OpenVolumeMeshHandle.hh"
namespace OpenVolumeMesh {
class TopologyKernel;
template <
class IH /* Input handle type */,
class OH /* Output handle type */>
class BaseIterator {
public:
// STL compliance
typedef std::bidirectional_iterator_tag iterator_category;
typedef int difference_type;
typedef OH value_type;
typedef OH* pointer;
typedef OH& reference;
BaseIterator(const TopologyKernel* _mesh, const IH& _ih, const OH& _ch) :
valid_(true), cur_handle_(_ch), ref_handle_(_ih), mesh_(_mesh) {}
BaseIterator(const TopologyKernel* _mesh, const IH& _ih) :
valid_(true), ref_handle_(_ih), mesh_(_mesh) {}
BaseIterator(const TopologyKernel* _mesh) :
valid_(true), mesh_(_mesh) {}
// STL compliance (needs to have default constructor)
BaseIterator() : valid_(false), mesh_(0) {}
virtual ~BaseIterator() {}
bool operator== (const BaseIterator& _c) const {
return (this->cur_handle_ == _c.cur_handle() &&
this->ref_handle_ == _c.ref_handle() &&
this->mesh_ == _c.mesh());
}
bool operator!= (const BaseIterator& _c) const {
return !this->operator==(_c);
}
const OH* operator->() const {
return &cur_handle_;
}
const OH& operator*() const {
return cur_handle_;
}
bool operator< (const BaseIterator& _c) const {
return cur_handle_.idx() < _c.cur_handle_.idx();
}
BaseIterator& operator=(const BaseIterator& _c) {
this->valid_ = _c.valid();
this->cur_handle_ = _c.cur_handle();
this->ref_handle_ = _c.ref_handle();
this->mesh_ = _c.mesh();
return *this;
}
operator bool() const {
return valid_;
}
void valid(bool _valid) {
valid_ = _valid;
}
bool valid() const {
return valid_;
}
void cur_handle(const OH& _h) {
cur_handle_ = _h;
}
const OH& cur_handle() const {
return cur_handle_;
}
const IH& ref_handle() const {
return ref_handle_;
}
const TopologyKernel* mesh() const {
return mesh_;
}
private:
bool valid_;
OH cur_handle_;
IH ref_handle_;
const TopologyKernel* mesh_;
};
//===========================================================================
class VertexOHalfEdgeIter :
public BaseIterator<
VertexHandle,
HalfEdgeHandle> {
public:
typedef BaseIterator<
VertexHandle,
HalfEdgeHandle> BaseIter;
VertexOHalfEdgeIter(const VertexHandle& _vIdx,
const TopologyKernel* _mesh);
// Post increment/decrement operator
VertexOHalfEdgeIter operator++(int) {
VertexOHalfEdgeIter cpy = *this;
++(*this);
return cpy;
}
VertexOHalfEdgeIter operator--(int) {
VertexOHalfEdgeIter cpy = *this;
--(*this);
return cpy;
}
VertexOHalfEdgeIter operator+(int _n) {
VertexOHalfEdgeIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
VertexOHalfEdgeIter operator-(int _n) {
VertexOHalfEdgeIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
VertexOHalfEdgeIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
VertexOHalfEdgeIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
VertexOHalfEdgeIter& operator++();
VertexOHalfEdgeIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class HalfEdgeHalfFaceIter : public BaseIterator<
HalfEdgeHandle,
HalfFaceHandle> {
public:
typedef BaseIterator<
HalfEdgeHandle,
HalfFaceHandle> BaseIter;
HalfEdgeHalfFaceIter(const HalfEdgeHandle& _heIdx, const TopologyKernel* _mesh);
// Post increment/decrement operator
HalfEdgeHalfFaceIter operator++(int) {
HalfEdgeHalfFaceIter cpy = *this;
++(*this);
return cpy;
}
HalfEdgeHalfFaceIter operator--(int) {
HalfEdgeHalfFaceIter cpy = *this;
--(*this);
return cpy;
}
HalfEdgeHalfFaceIter operator+(int _n) {
HalfEdgeHalfFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
HalfEdgeHalfFaceIter operator-(int _n) {
HalfEdgeHalfFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
HalfEdgeHalfFaceIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
HalfEdgeHalfFaceIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
HalfEdgeHalfFaceIter& operator++();
HalfEdgeHalfFaceIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class VertexCellIter : public BaseIterator<
VertexHandle,
CellHandle> {
public:
typedef BaseIterator<
VertexHandle,
CellHandle> BaseIter;
VertexCellIter(const VertexHandle& _vIdx, const TopologyKernel* _mesh);
VertexCellIter& operator=(const VertexCellIter& _c) {
BaseIter::operator=(_c);
cells_ = cells_;
cell_iter_ = cells_.begin();
return *this;
}
// Post increment/decrement operator
VertexCellIter operator++(int) {
VertexCellIter cpy = *this;
++(*this);
return cpy;
}
VertexCellIter operator--(int) {
VertexCellIter cpy = *this;
--(*this);
return cpy;
}
VertexCellIter operator+(int _n) {
VertexCellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
VertexCellIter operator-(int _n) {
VertexCellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
VertexCellIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
VertexCellIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
VertexCellIter& operator++();
VertexCellIter& operator--();
private:
std::set<CellHandle> cells_;
std::set<CellHandle>::const_iterator cell_iter_;
};
class HalfEdgeCellIter : public BaseIterator<
HalfEdgeHandle,
CellHandle> {
public:
typedef BaseIterator<
HalfEdgeHandle,
CellHandle> BaseIter;
HalfEdgeCellIter(const HalfEdgeHandle& _heIdx, const TopologyKernel* _mesh);
// Post increment/decrement operator
HalfEdgeCellIter operator++(int) {
HalfEdgeCellIter cpy = *this;
++(*this);
return cpy;
}
HalfEdgeCellIter operator--(int) {
HalfEdgeCellIter cpy = *this;
--(*this);
return cpy;
}
HalfEdgeCellIter operator+(int _n) {
HalfEdgeCellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
HalfEdgeCellIter operator-(int _n) {
HalfEdgeCellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
HalfEdgeCellIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
HalfEdgeCellIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
HalfEdgeCellIter& operator++();
HalfEdgeCellIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class CellVertexIter : public BaseIterator<
CellHandle,
VertexHandle> {
public:
typedef BaseIterator<
CellHandle,
VertexHandle> BaseIter;
CellVertexIter(const CellHandle& _cIdx, const TopologyKernel* _mesh);
CellVertexIter& operator=(const CellVertexIter& _c) {
BaseIter::operator=(_c);
incident_vertices_ = _c.incident_vertices_;
v_iter_ = incident_vertices_.begin();
return *this;
}
// Post increment/decrement operator
CellVertexIter operator++(int) {
CellVertexIter cpy = *this;
++(*this);
return cpy;
}
CellVertexIter operator--(int) {
CellVertexIter cpy = *this;
--(*this);
return cpy;
}
CellVertexIter operator+(int _n) {
CellVertexIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
CellVertexIter operator-(int _n) {
CellVertexIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
CellVertexIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
CellVertexIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
CellVertexIter& operator++();
CellVertexIter& operator--();
private:
std::vector<VertexHandle> incident_vertices_;
std::vector<VertexHandle>::const_iterator v_iter_;
};
//===========================================================================
class CellCellIter : public BaseIterator<
CellHandle,
CellHandle> {
public:
typedef BaseIterator<
CellHandle,
CellHandle> BaseIter;
CellCellIter(const CellHandle& _cIdx, const TopologyKernel* _mesh);
CellCellIter& operator=(const CellCellIter& _c) {
BaseIter::operator=(_c);
adjacent_cells_ = _c.adjacent_cells_;
c_iter_ = adjacent_cells_.begin();
return *this;
}
// Post increment/decrement operator
CellCellIter operator++(int) {
CellCellIter cpy = *this;
++(*this);
return cpy;
}
CellCellIter operator--(int) {
CellCellIter cpy = *this;
--(*this);
return cpy;
}
CellCellIter operator+(int _n) {
CellCellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
CellCellIter operator-(int _n) {
CellCellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
CellCellIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
CellCellIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
CellCellIter& operator++();
CellCellIter& operator--();
private:
std::set<CellHandle> adjacent_cells_;
std::set<CellHandle>::const_iterator c_iter_;
};
//===========================================================================
class HalfFaceVertexIter : public BaseIterator<
HalfFaceHandle,
VertexHandle> {
public:
typedef BaseIterator<
HalfFaceHandle,
VertexHandle> BaseIter;
HalfFaceVertexIter(const HalfFaceHandle& _hIdx, const TopologyKernel* _mesh);
HalfFaceVertexIter();
HalfFaceVertexIter& operator=(const HalfFaceVertexIter& _c) {
BaseIter::operator=(_c);
vertices_ = _c.vertices_;
iter_ = vertices_.begin();
return *this;
}
void construct_iter(const HalfFaceHandle& _hIdx, const TopologyKernel* _mesh);
// Post increment/decrement operator
HalfFaceVertexIter operator++(int) {
HalfFaceVertexIter cpy = *this;
++(*this);
return cpy;
}
HalfFaceVertexIter operator--(int) {
HalfFaceVertexIter cpy = *this;
--(*this);
return cpy;
}
HalfFaceVertexIter operator+(int _n) {
HalfFaceVertexIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
HalfFaceVertexIter operator-(int _n) {
HalfFaceVertexIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
HalfFaceVertexIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
HalfFaceVertexIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
HalfFaceVertexIter& operator++();
HalfFaceVertexIter& operator--();
private:
std::vector<VertexHandle> vertices_;
std::vector<VertexHandle>::const_iterator iter_;
};
//===========================================================================
class BoundaryHalfFaceHalfFaceIter : public BaseIterator<HalfFaceHandle,
HalfFaceHandle> {
private:
typedef BaseIterator<HalfFaceHandle,
HalfFaceHandle> BaseIter;
public:
BoundaryHalfFaceHalfFaceIter(const HalfFaceHandle& _ref_h,
const TopologyKernel* _mesh);
BoundaryHalfFaceHalfFaceIter& operator=(const BoundaryHalfFaceHalfFaceIter& _c) {
BaseIter::operator=(_c);
neighbor_halffaces_ = _c.neighbor_halffaces_;
cur_it_ = neighbor_halffaces_.begin();
return *this;
}
// Post increment/decrement operator
BoundaryHalfFaceHalfFaceIter operator++(int) {
BoundaryHalfFaceHalfFaceIter cpy = *this;
++(*this);
return cpy;
}
BoundaryHalfFaceHalfFaceIter operator--(int) {
BoundaryHalfFaceHalfFaceIter cpy = *this;
--(*this);
return cpy;
}
BoundaryHalfFaceHalfFaceIter operator+(int _n) {
BoundaryHalfFaceHalfFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
BoundaryHalfFaceHalfFaceIter operator-(int _n) {
BoundaryHalfFaceHalfFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
BoundaryHalfFaceHalfFaceIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
BoundaryHalfFaceHalfFaceIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
const EdgeHandle& common_edge() const { return *edge_it_; }
BoundaryHalfFaceHalfFaceIter& operator++();
BoundaryHalfFaceHalfFaceIter& operator--();
private:
std::vector<HalfFaceHandle> neighbor_halffaces_;
std::vector<EdgeHandle> common_edges_;
std::vector<HalfFaceHandle>::const_iterator cur_it_;
std::vector<EdgeHandle>::const_iterator edge_it_;
};
//===========================================================================
class VertexIter : public BaseIterator<
VertexHandle,
VertexHandle> {
public:
typedef BaseIterator<
VertexHandle,
VertexHandle> BaseIter;
VertexIter(const TopologyKernel* _mesh, const VertexHandle& _vh = VertexHandle(0));
// Post increment/decrement operator
VertexIter operator++(int) {
VertexIter cpy = *this;
++(*this);
return cpy;
}
VertexIter operator--(int) {
VertexIter cpy = *this;
--(*this);
return cpy;
}
VertexIter operator+(int _n) {
VertexIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
VertexIter operator-(int _n) {
VertexIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
VertexIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
VertexIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
VertexIter& operator++();
VertexIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class EdgeIter : public BaseIterator<
EdgeHandle,
EdgeHandle> {
public:
typedef BaseIterator<
EdgeHandle,
EdgeHandle> BaseIter;
EdgeIter(const TopologyKernel* _mesh, const EdgeHandle& _eh = EdgeHandle(0));
// Post increment/decrement operator
EdgeIter operator++(int) {
EdgeIter cpy = *this;
++(*this);
return cpy;
}
EdgeIter operator--(int) {
EdgeIter cpy = *this;
--(*this);
return cpy;
}
EdgeIter operator+(int _n) {
EdgeIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
EdgeIter operator-(int _n) {
EdgeIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
EdgeIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
EdgeIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
EdgeIter& operator++();
EdgeIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class HalfEdgeIter : public BaseIterator<
HalfEdgeHandle,
HalfEdgeHandle> {
public:
typedef BaseIterator<
HalfEdgeHandle,
HalfEdgeHandle> BaseIter;
HalfEdgeIter(const TopologyKernel* _mesh, const HalfEdgeHandle& _heh = HalfEdgeHandle(0));
// Post increment/decrement operator
HalfEdgeIter operator++(int) {
HalfEdgeIter cpy = *this;
++(*this);
return cpy;
}
HalfEdgeIter operator--(int) {
HalfEdgeIter cpy = *this;
--(*this);
return cpy;
}
HalfEdgeIter operator+(int _n) {
HalfEdgeIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
HalfEdgeIter operator-(int _n) {
HalfEdgeIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
HalfEdgeIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
HalfEdgeIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
HalfEdgeIter& operator++();
HalfEdgeIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class FaceIter : public BaseIterator<
FaceHandle,
FaceHandle> {
public:
typedef BaseIterator<
FaceHandle,
FaceHandle> BaseIter;
FaceIter(const TopologyKernel* _mesh, const FaceHandle& _fh = FaceHandle(0));
// Post increment/decrement operator
FaceIter operator++(int) {
FaceIter cpy = *this;
++(*this);
return cpy;
}
FaceIter operator--(int) {
FaceIter cpy = *this;
--(*this);
return cpy;
}
FaceIter operator+(int _n) {
FaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
FaceIter operator-(int _n) {
FaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
FaceIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
FaceIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
FaceIter& operator++();
FaceIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class HalfFaceIter : public BaseIterator<
HalfFaceHandle,
HalfFaceHandle> {
public:
typedef BaseIterator<
HalfFaceHandle,
HalfFaceHandle> BaseIter;
HalfFaceIter(const TopologyKernel* _mesh, const HalfFaceHandle& _hfh = HalfFaceHandle(0));
// Post increment/decrement operator
HalfFaceIter operator++(int) {
HalfFaceIter cpy = *this;
++(*this);
return cpy;
}
HalfFaceIter operator--(int) {
HalfFaceIter cpy = *this;
--(*this);
return cpy;
}
HalfFaceIter operator+(int _n) {
HalfFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
HalfFaceIter operator-(int _n) {
HalfFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
HalfFaceIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
HalfFaceIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
HalfFaceIter& operator++();
HalfFaceIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class CellIter : public BaseIterator<
CellHandle,
CellHandle> {
public:
typedef BaseIterator<
CellHandle,
CellHandle> BaseIter;
CellIter(const TopologyKernel* _mesh, const CellHandle& _ch = CellHandle(0));
// Post increment/decrement operator
CellIter operator++(int) {
CellIter cpy = *this;
++(*this);
return cpy;
}
CellIter operator--(int) {
CellIter cpy = *this;
--(*this);
return cpy;
}
CellIter operator+(int _n) {
CellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
CellIter operator-(int _n) {
CellIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
CellIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
CellIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
CellIter& operator++();
CellIter& operator--();
private:
int cur_index_;
};
//===========================================================================
class BoundaryFaceIter : public BaseIterator<FaceHandle,FaceHandle> {
public:
typedef BaseIterator<
FaceHandle,
FaceHandle> BaseIter;
BoundaryFaceIter(const TopologyKernel* _mesh);
// Post increment/decrement operator
BoundaryFaceIter operator++(int) {
BoundaryFaceIter cpy = *this;
++(*this);
return cpy;
}
BoundaryFaceIter operator--(int) {
BoundaryFaceIter cpy = *this;
--(*this);
return cpy;
}
BoundaryFaceIter operator+(int _n) {
BoundaryFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
++cpy;
}
return cpy;
}
BoundaryFaceIter operator-(int _n) {
BoundaryFaceIter cpy = *this;
for(int i = 0; i < _n; ++i) {
--cpy;
}
return cpy;
}
BoundaryFaceIter& operator+=(int _n) {
for(int i = 0; i < _n; ++i) {
++(*this);
}
return *this;
}
BoundaryFaceIter& operator-=(int _n) {
for(int i = 0; i < _n; ++i) {
--(*this);
}
return *this;
}
BoundaryFaceIter& operator++();
BoundaryFaceIter& operator--();
private:
FaceIter bf_it_;
};
//===========================================================================
} // Namespace OpenVolumeMesh
#endif /* ITERATORS_HH_ */
| 23.047574 | 91 | 0.553111 | [
"mesh",
"vector"
] |
63a8ed90285477b0fd039bb7462de95cc9335c3a | 2,865 | cpp | C++ | Atcoder/ARC_104/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Atcoder/ARC_104/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Atcoder/ARC_104/c.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | // Optimise
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/home/shahraaz/bin/debug.h"
#else
#define db(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()
const int NAX = 2e5 + 5, MOD = 1000000007;
void no()
{
cout << "No\n";
exit(0);
}
void yes()
{
cout << "Yes\n";
exit(0);
}
int dp[201][201];
void solveCase()
{
int n;
cin >> n;
vector<int> a(n), b(n);
int diff = -1;
vector<int> who(2 * n, -1);
for (size_t i = 0; i < n; i++)
{
cin >> a[i] >> b[i];
if (a[i] >= 0)
a[i]--;
if (b[i] >= 0)
b[i]--;
if (a[i] >= 0 && b[i] >= 0)
if (a[i] >= b[i])
no();
if (a[i] >= 0)
if (who[a[i]] == -1)
who[a[i]] = i;
else
no();
if (b[i] >= 0)
if (who[b[i]] == -1)
who[b[i]] = i;
else
no();
}
memset(dp, -1, sizeof dp);
function<int(int, int)> solve = [&](int pos, int len) -> int {
if (pos > 2 * n)
return false;
if (pos == 2 * n)
return true;
int &ret = dp[pos][len];
if (ret >= 0)
return ret;
ret = false;
int rptr = pos + 2 * len;
db(pos, len, rptr);
if (rptr > 2 * n)
return false;
vector<int> occupied(2 * n);
for (size_t i = pos; i < pos + len; i++)
{
if (who[i] >= 0) // left
{
if (a[who[i]] != -1 && a[who[i]] != i)
return ret = false;
if (b[who[i]] != -1 && b[who[i]] != (i + len))
return ret = false;
if (who[i + len] >= 0)
if (who[i] != who[i + len])
return ret = false;
}
if (who[i + len] >= 0)
{
if (a[who[i + len]] != -1 && a[who[i + len]] != i)
return ret = false;
if (b[who[i + len]] != -1 && b[who[i + len]] != (i + len))
return ret = false;
}
}
for (size_t i = 1; i <= n; i++)
if (solve(rptr, i))
return ret = true;
return ret;
};
for (size_t i = 1; i <= n; i++)
if (solve(0, i))
yes();
no();
}
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
for (int i = 1; i <= t; ++i)
{
solveCase();
#ifdef LOCAL
cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
TimeStart = chrono::steady_clock::now();
#endif
}
return 0;
}
| 23.104839 | 131 | 0.381152 | [
"vector"
] |
63b789afa3fa40361c8becf89a00795f0c259ce6 | 4,050 | cpp | C++ | Examples/StereoKitCTest/demo_lines.cpp | AdrianaMusic/StereoKit | 99aaa4fb71c0420519a903e15deb3da9875e0f99 | [
"MIT"
] | 1 | 2021-11-17T10:30:21.000Z | 2021-11-17T10:30:21.000Z | Examples/StereoKitCTest/demo_lines.cpp | AdrianaMusic/StereoKit | 99aaa4fb71c0420519a903e15deb3da9875e0f99 | [
"MIT"
] | null | null | null | Examples/StereoKitCTest/demo_lines.cpp | AdrianaMusic/StereoKit | 99aaa4fb71c0420519a903e15deb3da9875e0f99 | [
"MIT"
] | null | null | null | #include "demo_lines.h"
#include "../../StereoKitC/stereokit.h"
#include "../../StereoKitC/stereokit_ui.h"
using namespace sk;
#include <vector>
using namespace std;
///////////////////////////////////////////
pose_t line_window_pose;
pose_t line_palette_pose;
model_t line_palette_model;
color32 line_color = {255,255,255,255};
float line_size = 0.02f;
material_t line_hand_mat;
vec3 line_prev_tip;
bool line_painting = false;
vector<line_point_t> line_draw;
vector<vector<line_point_t>> line_list;
///////////////////////////////////////////
void demo_lines_init() {
line_palette_model = model_create_file("Palette.glb", shader_find(default_id_shader_ui));
line_window_pose = { { 0.3f, 0, -0.3f}, quat_lookat(vec3_zero, {-1,0,1}) };
line_palette_pose = { {-0.3f, 0, -0.3f}, quat_lookat(vec3_zero, { 1,0,1}) };
line_hand_mat = material_find(default_id_material_hand);
}
///////////////////////////////////////////
void demo_lines_set_color(color128 color)
{
line_color = color_to_32( color );
material_set_color(line_hand_mat, "color", color);
}
///////////////////////////////////////////
void demo_lines_palette()
{
ui_handle_begin("PaletteMenu", line_palette_pose, model_get_bounds( line_palette_model ), false);
render_add_model(line_palette_model, matrix_identity);
pose_t p = { vec3_zero, quat_from_angles(90, 0, 0) };
ui_handle_begin("LineSlider", p, {}, true);
ui_hslider_at("Size", line_size, 0.001f, 0.02f, 0, vec3{ 6,-1,0 } *cm2m, vec2{ 8, 2 } *cm2m);
line_add(vec3{ 6, 1, -1 } *cm2m, vec3{ -2,1,-1 } *cm2m, line_color, line_color, line_size);
ui_handle_end();
if (ui_volume_at("White", bounds_t{vec3{4, 0, 7} * cm2m, vec3{4,2,4} * cm2m}))
demo_lines_set_color({1,1,1,1});
if (ui_volume_at("Red", bounds_t{vec3{9, 0, 3} * cm2m, vec3{4,2,4} * cm2m}))
demo_lines_set_color({1,0,0,1});
if (ui_volume_at("Green", bounds_t{vec3{9, 0,-3} * cm2m, vec3{4,2,4} * cm2m}))
demo_lines_set_color({0,1,0,1});
if (ui_volume_at("Blue", bounds_t{vec3{3, 0,-6} * cm2m, vec3{4,2,4} * cm2m}))
demo_lines_set_color({0,0,1,1});
ui_handle_end();
}
///////////////////////////////////////////
void demo_lines_draw() {
const hand_t *hand = input_hand(handed_right);
vec3 tip = hand->fingers[1][4].position;
tip = line_prev_tip + (tip-line_prev_tip) * 0.3f;
if ((hand->pinch_state & button_state_just_active) && !ui_is_interacting(handed_right)) {
if (line_draw.size() > 0)
line_list.push_back(line_draw);
line_draw.clear();
line_draw.push_back(line_point_t{tip, line_size, line_color});
line_draw.push_back(line_point_t{tip, line_size, line_color});
line_prev_tip = tip;
line_painting = true;
}
if (hand->pinch_state & button_state_just_inactive)
line_painting = false;
if (line_painting && line_draw.size() > 1)
{
vec3 prev = line_draw[line_draw.size() - 2].pt;
vec3 dir = vec3_normalize(prev - (line_draw.size() > 2 ? line_draw[line_draw.size() - 3].pt : line_draw[line_draw.size() - 1].pt));
float dist = vec3_magnitude(prev - tip);
float speed = vec3_magnitude(tip - line_prev_tip) * time_elapsedf();
line_point_t here = line_point_t{tip, max(1-speed/0.0003f,0.1f) * line_size, line_color};
line_draw[line_draw.size() - 1] = here;
if ((vec3_dot( dir, vec3_normalize(tip-prev)) < 0.99f && dist > 0.01f) || dist > 0.05f) {
line_draw.push_back(here);
}
}
line_add_listv(line_draw.data(), (int32_t)line_draw.size());
for (size_t i = 0; i < line_list.size(); i++)
line_add_listv(&line_list[i][0], (int32_t)line_list[i].size());
line_prev_tip = tip;
}
///////////////////////////////////////////
void demo_lines_update() {
ui_window_begin("Settings", line_window_pose, vec2{ 20 }*cm2m);
if (ui_button("Clear")) {
line_draw.clear();
line_list.clear();
}
ui_window_end();
demo_lines_palette();
demo_lines_draw();
}
///////////////////////////////////////////
void demo_lines_shutdown() {
model_release(line_palette_model);
} | 32.66129 | 143 | 0.62963 | [
"vector"
] |
63bd96c2311bf5e9a5fc02d8ebeccece6f0cde63 | 2,332 | hpp | C++ | source/Animation/SkeletalMeshComponent.hpp | dantros/MonaEngine | e3d0048c2fe2dd282b84686f0e31e5741714222b | [
"MIT"
] | null | null | null | source/Animation/SkeletalMeshComponent.hpp | dantros/MonaEngine | e3d0048c2fe2dd282b84686f0e31e5741714222b | [
"MIT"
] | null | null | null | source/Animation/SkeletalMeshComponent.hpp | dantros/MonaEngine | e3d0048c2fe2dd282b84686f0e31e5741714222b | [
"MIT"
] | 1 | 2021-09-07T03:06:01.000Z | 2021-09-07T03:06:01.000Z | #pragma once
#ifndef SKELETALMESHCOMPONENT_H
#define SKELETALMESHCOMPONENT_H
#include <string_view>
#include <memory>
#include <vector>
#include "../Core/Log.hpp"
#include "../World/ComponentTypes.hpp"
#include "AnimationController.hpp"
#include "../Rendering/Material.hpp"
namespace Mona {
class TransformComponent;
class Skeleton;
class Material;
class AnimationClip;
class SkinnedMesh;
class SkeletalMeshComponent
{
public:
friend class Renderer;
friend class World;
friend class AnimationSystem;
//using managerType = ComponentManager<SkeletalMeshComponent>;
using LifetimePolicyType = DefaultLifetimePolicy<SkeletalMeshComponent>;
using dependencies = DependencyList<TransformComponent>;
static constexpr std::string_view componentName = "SkeletalMeshComponent";
static constexpr uint8_t componentIndex = GetComponentIndex(EComponentType::SkeletalMeshComponent);
SkeletalMeshComponent(std::shared_ptr<SkinnedMesh> skinnedMesh, std::shared_ptr<AnimationClip> animation, std::shared_ptr<Material> material)
: m_skinnedMeshPtr(skinnedMesh), m_materialPtr(material), m_animationController(animation), m_skeleton(animation->GetSkeleton())
{
MONA_ASSERT(skinnedMesh != nullptr, "SkeletalMeshComponent Error: Mesh pointer cannot be null.");
MONA_ASSERT(material != nullptr, "SkeletalMeshComponent Error: Material cannot be null.");
MONA_ASSERT(material->IsForSkinning(), "SkeletalMeshComponent Error: Material cannot be used for this type of Mesh");
}
std::shared_ptr<Material> GetMaterial() const noexcept {
return m_materialPtr;
}
void SetMaterial(std::shared_ptr<Material> material) noexcept {
if (material != nullptr)
{
MONA_ASSERT(material->IsForSkinning(), "SkeletalMeshComponent Error: Material cannot be used for this type of Mesh");
m_materialPtr = material;
}
}
std::shared_ptr<Skeleton> GetSkeleton() const noexcept {
return m_skeleton;
}
const AnimationController& GetAnimationController() const
{
return m_animationController;
}
AnimationController& GetAnimationController() {
return m_animationController;
}
private:
std::shared_ptr<Skeleton> m_skeleton;
std::shared_ptr<SkinnedMesh> m_skinnedMeshPtr;
std::shared_ptr<Material> m_materialPtr;
AnimationController m_animationController;
};
}
#endif | 33.314286 | 143 | 0.774871 | [
"mesh",
"vector"
] |
63c8340729f948778e586174ff6ab5363cf77583 | 5,601 | cpp | C++ | src/demos/vehicle/wheeled_models/demo_VEH_Sedan_Lockable_Diff.cpp | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | 1,383 | 2015-02-04T14:17:40.000Z | 2022-03-30T04:58:16.000Z | src/demos/vehicle/wheeled_models/demo_VEH_Sedan_Lockable_Diff.cpp | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | 245 | 2015-01-11T15:30:51.000Z | 2022-03-30T21:28:54.000Z | src/demos/vehicle/wheeled_models/demo_VEH_Sedan_Lockable_Diff.cpp | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | 351 | 2015-02-04T14:17:47.000Z | 2022-03-30T04:42:52.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Rainer Gericke
// =============================================================================
//
// Demo the Sedan model with lockable differential gear box.
//
// The vehicle reference frame has Z up, X towards the front of the vehicle, and
// Y pointing to the left.
//
// =============================================================================
#include "chrono/utils/ChUtilsInputOutput.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/RigidTerrain.h"
#include "chrono_vehicle/wheeled_vehicle/utils/ChWheeledVehicleIrrApp.h"
#include "chrono_models/vehicle/sedan/Sedan.h"
#include "chrono_thirdparty/filesystem/path.h"
using namespace chrono;
using namespace chrono::irrlicht;
using namespace chrono::vehicle;
using namespace chrono::vehicle::sedan;
// =============================================================================
const double step_size = 1e-3;
const std::string out_dir = GetChronoOutputPath() + "SEDAN";
// =============================================================================
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
bool lock_diff = (argc > 1) ? true : false;
if (lock_diff) {
GetLog() << "The differential box is locked\n";
} else {
GetLog() << "The differential box is unlocked\n";
}
// Create the vehicle
Sedan my_sedan;
my_sedan.SetContactMethod(ChContactMethod::SMC);
my_sedan.SetChassisCollisionType(CollisionType::NONE);
my_sedan.SetChassisFixed(false);
my_sedan.SetInitPosition(ChCoordsys<>(ChVector<>(-40, 0, 1.0)));
my_sedan.SetTireType(TireModelType::TMEASY);
my_sedan.SetTireStepSize(1e-3);
my_sedan.Initialize();
my_sedan.SetChassisVisualizationType(VisualizationType::NONE);
my_sedan.SetSuspensionVisualizationType(VisualizationType::PRIMITIVES);
my_sedan.SetSteeringVisualizationType(VisualizationType::PRIMITIVES);
my_sedan.SetWheelVisualizationType(VisualizationType::MESH);
my_sedan.SetTireVisualizationType(VisualizationType::MESH);
my_sedan.LockAxleDifferential(0, lock_diff);
// Create the terrain
RigidTerrain terrain(my_sedan.GetSystem());
auto patch1_mat = chrono_types::make_shared<ChMaterialSurfaceSMC>();
patch1_mat->SetFriction(0.1f);
patch1_mat->SetRestitution(0.01f);
patch1_mat->SetYoungModulus(2e7f);
patch1_mat->SetPoissonRatio(0.3f);
auto patch2_mat = chrono_types::make_shared<ChMaterialSurfaceSMC>();
patch2_mat->SetFriction(0.9f);
patch2_mat->SetRestitution(0.01f);
patch2_mat->SetYoungModulus(2e7f);
patch2_mat->SetPoissonRatio(0.3f);
auto patch1 = terrain.AddPatch(patch1_mat, ChVector<>(0, -25, 0), ChVector<>(0, 0, 1), 100, 50);
auto patch2 = terrain.AddPatch(patch2_mat, ChVector<>(0, +25, 0), ChVector<>(0, 0, 1), 100, 50);
patch1->SetColor(ChColor(0.8f, 0.8f, 0.5f));
patch1->SetTexture(vehicle::GetDataFile("terrain/textures/dirt.jpg"), 200, 50);
patch2->SetColor(ChColor(0.5f, 0.5f, 0.8f));
patch2->SetTexture(vehicle::GetDataFile("terrain/textures/tile4.jpg"), 200, 50);
terrain.Initialize();
// Create the vehicle Irrlicht interface
ChWheeledVehicleIrrApp app(&my_sedan.GetVehicle(), L"Sedan Demo Locked Diff");
app.SetSkyBox();
app.AddTypicalLights(irr::core::vector3df(30.f, -30.f, 100.f), irr::core::vector3df(30.f, 50.f, 100.f), 250, 130);
app.SetChaseCamera(ChVector<>(0.0, 0.0, 1.5), 4.0, 0.5);
app.AssetBindAll();
app.AssetUpdateAll();
// Initialize output
if (!filesystem::create_directory(filesystem::path(out_dir))) {
std::cout << "Error creating directory " << out_dir << std::endl;
return 1;
}
utils::CSV_writer wheelomega_csv("\t");
// Simulation loop
while (app.GetDevice()->run()) {
double time = my_sedan.GetSystem()->GetChTime();
if (time > 15 || my_sedan.GetVehicle().GetVehiclePos().x() > 49)
break;
// Render scene
app.BeginScene();
app.DrawAll();
app.EndScene();
// Driver inputs
ChDriver::Inputs driver_inputs = {0, 0, 0};
if (time > 2)
driver_inputs.m_throttle = 0.6;
else if (time > 1)
driver_inputs.m_throttle = 0.6 * (time - 1);
// Output
double omega_front_left = my_sedan.GetVehicle().GetSuspension(0)->GetAxleSpeed(LEFT);
double omega_front_right = my_sedan.GetVehicle().GetSuspension(0)->GetAxleSpeed(RIGHT);
wheelomega_csv << time << omega_front_left << omega_front_right << std::endl;
// Synchronize subsystems
terrain.Synchronize(time);
my_sedan.Synchronize(time, driver_inputs, terrain);
app.Synchronize("", driver_inputs);
// Advance simulation for all subsystems
terrain.Advance(step_size);
my_sedan.Advance(step_size);
app.Advance(step_size);
}
wheelomega_csv.write_to_file(out_dir + "/FrontWheelOmega_" + std::to_string(lock_diff) + ".csv");
return 0;
}
| 36.607843 | 118 | 0.625603 | [
"mesh",
"render",
"model"
] |
63cac792a6da2c7c6b20f9ea5a9dd3c0f3f9dca6 | 29,804 | cc | C++ | tensorflow/compiler/mlir/hlo/lib/Dialect/lhlo/transforms/lhlo_legalize_to_parallel_loops.cc | piquark6046/tensorflow | 57771c5d008f6d16fd147110213855d145a7e0bc | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/mlir/hlo/lib/Dialect/lhlo/transforms/lhlo_legalize_to_parallel_loops.cc | piquark6046/tensorflow | 57771c5d008f6d16fd147110213855d145a7e0bc | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/mlir/hlo/lib/Dialect/lhlo/transforms/lhlo_legalize_to_parallel_loops.cc | piquark6046/tensorflow | 57771c5d008f6d16fd147110213855d145a7e0bc | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir-hlo/Dialect/lhlo/IR/lhlo_ops.h"
#include "mlir-hlo/Dialect/lhlo/transforms/PassDetail.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/SCF.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace lmhlo {
namespace {
// Clones and adapts the code in `lhlo_block` that works on buffers and has a
// single output buffer to make it compatible with `operands` that have element
// types of the respective buffers. Returns the computed value.
//
// Example. For `operands` with (f32, i32) types and a block with LHLO ops and
// with signature:
// ^bb(%lhs: memref<f32>, %rhs: memref<i32>, %res: memref<i1>):
// <LHLO_ops>
//
// inserts necessary alloc and store ops to compute and return result that has
// `i1` type.
Value applySingleResultLhloCode(Location loc, ValueRange operands,
Block* lhloBlock, OpBuilder* b) {
SmallVector<Value, 2> argBufs;
for (auto argType : lhloBlock->getArgumentTypes()) {
argBufs.push_back(
b->create<memref::AllocOp>(loc, argType.cast<MemRefType>()));
}
for (const auto& operand : llvm::enumerate(operands)) {
b->create<memref::StoreOp>(loc, operand.value(), argBufs[operand.index()]);
}
// Clone the ops from `lhlo_block`.
BlockAndValueMapping mapping;
mapping.map(lhloBlock->getArguments(), argBufs);
for (auto& nested : lhloBlock->without_terminator()) {
auto* clone = b->clone(nested, mapping);
mapping.map(nested.getResults(), clone->getResults());
}
return b->create<memref::LoadOp>(loc, argBufs.back());
}
// Converts a block with LHLO ops and with signature:
// ^bb(%lhs: memref<f32>, %rhs: memref<f32>, %res: memref<f32>):
// into a reduction operator of scf.reduce by doing buffer allocation for
// scalar arguments and the result of `scf.reduce` to make it compatible with
// LHLO ops.
void convertToReductionOperator(Location loc, scf::ReduceOp reduceOp,
Block* lhloBlock, OpBuilder* b) {
Block& loopReduceOpBody = reduceOp.getReductionOperator().front();
OpBuilder::InsertionGuard guard(*b);
b->setInsertionPointToStart(&loopReduceOpBody);
b->create<scf::ReduceReturnOp>(
loc, applySingleResultLhloCode(loc, loopReduceOpBody.getArguments(),
lhloBlock, b));
}
// Returns result of arith::ConstantOp if `dim` is static, otherwise uses DimOp
// to extract dimension at runtime.
Value getStaticOrDynamicDim(mlir::Location loc, Value shapedValue,
size_t dimIndex, int64_t dim, OpBuilder* b) {
return dim == ShapedType::kDynamicSize
? b->create<memref::DimOp>(loc, shapedValue, dimIndex).getResult()
: b->create<arith::ConstantIndexOp>(loc, dim);
}
struct MappedIvs {
// False if the mapped indices are in the padding area, true otherwise.
Value inBounds;
// Mapped indices.
SmallVector<Value, 2> ivs;
};
template <typename OpTy>
MappedIvs mapWindowIvsToInput(OpTy op, Value operand, ValueRange ivs,
ValueRange windowIvs, OpBuilder* b) {
MappedIvs mappedIvs;
if (!op.window_strides().hasValue()) {
op.emitOpError("No window strides specified.");
}
auto windowStrides = op.window_strides().getValue();
if (!op.padding().hasValue()) {
op.emitOpError("No padding specified.");
}
auto padding = op.padding().getValue();
auto loc = op.getLoc();
auto operandShape = operand.getType().template cast<MemRefType>().getShape();
// `in_bounds` is false when the mapped indices are in the padding area.
mappedIvs.inBounds = b->create<mlir::arith::ConstantOp>(
loc, b->getI1Type(), b->getIntegerAttr(b->getI1Type(), 1));
for (unsigned i = 0, e = ivs.size(); i < e; ++i) {
auto stride = windowStrides.template getValues<llvm::APInt>()[i];
auto padLow = padding.template getValues<llvm::APInt>()[{i, 0}];
Value strideVal =
b->create<arith::ConstantIndexOp>(loc, stride.getSExtValue());
Value padLowVal =
b->create<arith::ConstantIndexOp>(loc, padLow.getSExtValue());
Value center = b->create<arith::MulIOp>(loc, ivs[i], strideVal);
Value offset = b->create<arith::SubIOp>(loc, windowIvs[i], padLowVal);
Value index = b->create<arith::AddIOp>(loc, center, offset);
Value upperBound =
getStaticOrDynamicDim(loc, operand, i, operandShape[i], b);
// We must check whether 0 <= index_i < shape_i, as otherwise we are in
// the pad and then we have to use the neutral element for reduction.
// Equivalently, it can be computed as the unsigned comparison index_i <
// shape_i, since a negative value wraps to a large positive value.
mappedIvs.inBounds = b->create<mlir::arith::AndIOp>(
loc, mappedIvs.inBounds,
b->create<arith::CmpIOp>(loc, arith::CmpIPredicate::ult, index,
upperBound));
mappedIvs.ivs.push_back(index);
}
return mappedIvs;
}
// Returns scf::Parallel over a shaped value with static or dynamic shape.
scf::ParallelOp makeLoopOverShape(Location loc, Value shapedValue,
OpBuilder* b) {
Value zero = b->create<arith::ConstantIndexOp>(loc, 0);
Value one = b->create<arith::ConstantIndexOp>(loc, 1);
ArrayRef<int64_t> shape = shapedValue.getType().cast<ShapedType>().getShape();
SmallVector<Value, 2> lower, upper, step;
for (const auto& dim : llvm::enumerate(shape)) {
upper.push_back(
getStaticOrDynamicDim(loc, shapedValue, dim.index(), dim.value(), b));
lower.push_back(zero);
step.push_back(one);
}
return b->create<scf::ParallelOp>(loc, lower, upper, step);
}
// Converts `lmhlo.ReduceOp` into two scf::ParallelOp and a scf::ReduceOp.
// The outper `ParallelOp` refers to the parallel loops if there are
// any. The inner `ParalleOp` refers to the reduction loops and `ReduceOp`
// contains the reduction operator.
//
// Example:
//
// "lmhlo.reduce"(%buffer, %init_buf, %result) ({
// ^bb0(%lhs: memref<f32>, %rhs: memref<f32>, %res: memref<f32>):
// <LHLO ops>
// } ) {dimensions = dense<[1]> : tensor<1xi64>}
// : (memref<100x10x5xf32>, memref<f32>, memref<100x5xf32>) -> ()
//
// is roughly converted into:
//
// %init = load %init_buf[] : memref<f32>
// scf.parallel (%i, %k) = (%c0, %c0) to (%c100, %c5) step (%c1, %c1) {
// %result = scf.parallel (%j) = (%c0) to (%c10) step (%c1) init (%init) {
// %elem_to_reduce = load %buffer[%i, %j, %k] : memref<100x10x5xf32>
// scf.reduce(%elem_to_reduce) {
// ^bb0(%elem: f32, %acc: f32):
// elem_buf = alloc() : memref<f32>
// store %elem, elem_buf[] : memref<f32>
// acc_buf = alloc() : memref<f32>
// store %acc, acc_buf[] : memref<f32>
// <LHLO_ops>
// %acc_result = load acc_buf[] : memref<f32>
// scf.reduce.return %acc_result : f32
// } : f32
// scf.yield
// } : f32
// scf.yield
// }
class ReduceOpConverter : public OpConversionPattern<lmhlo::ReduceOp> {
public:
using OpConversionPattern<lmhlo::ReduceOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
lmhlo::ReduceOp reduceOp, OpAdaptor /*adaptor*/,
ConversionPatternRewriter& rewriter) const final {
// TODO(b/183977252) : Handle variadic ReduceOp/ReduceWindowOp
if (reduceOp.out().size() != 1) return failure();
scf::ReduceOp scfReduceOp =
createReduceOpInNestedParallelLoops(reduceOp, &rewriter);
convertToReductionOperator(reduceOp.getLoc(), scfReduceOp,
&reduceOp.body().front(), &rewriter);
rewriter.replaceOp(reduceOp, llvm::None);
return success();
}
private:
// Creates nested `scf.parallel` ops with `scf.reduce`. The outer ParallelOp
// refers to the parallel dimensions of `reduce_op` if any and the inner
// ParallelOp refers to the reduction dimensions. The scf.reduce op is
// returned.
//
// If the reduction argument is a memref<100x10x5xf32> and the
// reduction is performed along dimension 1 then this method will generate
//
// %init = load %init_buf[] : memref<f32>
// scf.parallel (%i, %k) = (%c0, %c0) to (%c100, %c5) step (%c1, %c1) {
// %result = scf.parallel (%j) = (%c0) to (%c10) step (%c1) init (%init) {
// %elem_to_reduce = load %buffer[%i, %j, %k] : memref<100x10x5xf32>
// scf.reduce(%elem_to_reduce) {
// <THE BLOCK PTR TO BE RETURNED>
// } : f32
// scf.yield
// } : f32
// scf.yield
// }
scf::ReduceOp createReduceOpInNestedParallelLoops(
lmhlo::ReduceOp reduceOp, ConversionPatternRewriter* rewriter) const {
auto loc = reduceOp.getLoc();
DenseSet<int> reducingDims;
for (const auto& rdim : reduceOp.dimensions().getValues<APInt>()) {
reducingDims.insert(rdim.getSExtValue());
}
Value operand = reduceOp.inputs().front();
Value out = reduceOp.out().front();
SmallVector<Value, 2> parallelLower, parallelUpper, parallelStep;
SmallVector<Value, 2> reduceLower, reduceUpper, reduceStep;
auto operandShape = operand.getType().cast<MemRefType>().getShape();
for (const auto& dim : llvm::enumerate(operandShape)) {
const bool isReducingDim = reducingDims.count(dim.index());
Value ub = getStaticOrDynamicDim(loc, operand, dim.index(), dim.value(),
rewriter);
Value lb = rewriter->create<arith::ConstantIndexOp>(loc, 0);
Value step = rewriter->create<arith::ConstantIndexOp>(loc, 1);
(isReducingDim ? reduceLower : parallelLower).push_back(lb);
(isReducingDim ? reduceUpper : parallelUpper).push_back(ub);
(isReducingDim ? reduceStep : parallelStep).push_back(step);
}
// Load initial value from memref<element_type>.
SmallVector<Value, 1> initValue = {
rewriter->create<memref::LoadOp>(loc, *reduceOp.init_values().begin())};
// Outer ParallelOp is not needed if it is a reduction across all dims.
scf::ParallelOp outer;
if (!parallelLower.empty()) {
outer = rewriter->create<scf::ParallelOp>(loc, parallelLower,
parallelUpper, parallelStep);
rewriter->setInsertionPointToStart(outer.getBody());
}
scf::ParallelOp inner = rewriter->create<scf::ParallelOp>(
loc, reduceLower, reduceUpper, reduceStep, ValueRange(initValue));
Value reductionResult = *inner.getResults().begin();
SmallVector<Value, 1> outIndices;
if (outer != nullptr) {
outIndices.reserve(outer.getNumLoops());
for (Value iv : outer.getInductionVars()) {
outIndices.push_back(iv);
}
} else {
outIndices.push_back(rewriter->create<arith::ConstantIndexOp>(loc, 0));
}
rewriter->create<memref::StoreOp>(loc, reductionResult, out, outIndices);
// Load the element to reduce.
SmallVector<Value, 2> indices;
indices.reserve(operandShape.size());
if (outer) {
auto innerIvsIt = inner.getInductionVars().begin();
auto outerIvsIt = outer.getInductionVars().begin();
for (unsigned i = 0, e = operandShape.size(); i < e; ++i) {
indices.push_back(reducingDims.count(i) ? *innerIvsIt++
: *outerIvsIt++);
}
} else {
indices = inner.getInductionVars();
}
rewriter->setInsertionPointToStart(inner.getBody());
Value elem = rewriter->create<mlir::memref::LoadOp>(
loc, reduceOp.inputs().front(), indices);
return rewriter->create<scf::ReduceOp>(loc, elem);
}
};
// Pseudocode:
// for each index O in output
// accumulator = neutral_value
// in_bounds = true
// for each index W in window
// for each dimension i from 0 to rank - 1
// index = O[i] * stride[i] + W[i] - pad_low[i]
// in_bounds = inbounds && (index `ult` shape[i])
// I[i] = index
// if (in_bounds)
// value = input[I]
// else
// value = neutral_value
// accumulator = reduction_operator(accumulator, value)
// output[O] = accumulator
//
// Converts `lmhlo.ReduceWindowOp` into two scf::ParallelOp and a
// scf::ReduceOp.
// The outper `ParallelOp` refers to the parallel loops that traverese output
// buffer. The inner `ParalleOp` refers to the reduction loops that traverse
// reduction windows and `ReduceOp` contains the reduction operator.
//
// Example:
//
// func @reduce_window(%arg: memref<112x112xf32>,
// %init: memref<f32>,
// %result: memref<56x56xf32>) {
// "lmhlo.reduce_window"(%arg, %init, %result) ({
// ^bb0(%lhs: memref<f32>, %rhs: memref<f32>, %res: memref<f32>):
// "lmhlo.maximum"(%lhs, %rhs, %res)
// : (memref<f32>, memref<f32>, memref<f32>) -> ()
// "lmhlo.terminator"() : () -> ()
// }) {
// padding = dense<[[0, 1], [0, 1]]> : tensor<2x2xi64>,
// window_dimensions = dense<[3, 3]> : tensor<2xi64>,
// window_strides = dense<[2, 2]> : tensor<2xi64>
// } : (memref<112x112xf32>, memref<f32>, memref<56x56xf32>) -> ()
// return
// }
//
// is roughly converted into:
//
// %neutral_elem = load %init_buf[] : memref<f32>
// scf.parallel (%i, %j) = (%c0, %c0) to (%c56, %c56) step (%c1, %c1) {
// %result = scf.parallel (%iw, %jw) = (%c0, %c0)
// to (%c3, %c3) step (%c1, %c1) neutral_elem (%0) -> f32 {
// %in_bounds = <COMPUTE IF INDEX IS IN OPERAND'S pad>
// %elem = load %operand[%computed_i, %computed_j]
// %elem_or_neutral = select %in_bounds, %elem, %neutral_elem : f32
// scf.reduce(%elem_to_reduce) : f32 {
// ^bb0(%arg7: f32, %arg8: f32):
// <LHLO ops>
// }
// scf.yield
// }
// store %result, %output_buffer[%i, %j] : memref<56x56xf32>
// scf.yield
// }
// return
// }
class ReduceWindowOpConverter
: public OpConversionPattern<lmhlo::ReduceWindowOp> {
public:
using OpConversionPattern<lmhlo::ReduceWindowOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
lmhlo::ReduceWindowOp reduceWindowOp, OpAdaptor /*adaptor*/,
ConversionPatternRewriter& rewriter) const final {
// TODO(b/183977252) : Handle variadic ReduceOp/ReduceWindowOp
if (reduceWindowOp.out().size() != 1) return failure();
scf::ParallelOp outputLoop, windowLoop;
std::tie(outputLoop, windowLoop) =
createParallelLoopsToTraverseOutputAndWindow(reduceWindowOp, &rewriter);
scf::ReduceOp reduceOp = createReduceOpInNestedParallelLoops(
reduceWindowOp, outputLoop, windowLoop, &rewriter);
convertToReductionOperator(reduceWindowOp.getLoc(), reduceOp,
&reduceWindowOp.body().front(), &rewriter);
rewriter.replaceOp(reduceWindowOp, llvm::None);
return success();
}
private:
std::pair<scf::ParallelOp, scf::ParallelOp>
createParallelLoopsToTraverseOutputAndWindow(
lmhlo::ReduceWindowOp reduceWindowOp,
ConversionPatternRewriter* rewriter) const {
auto loc = reduceWindowOp.getLoc();
Value initValue =
rewriter->create<memref::LoadOp>(loc, reduceWindowOp.init_values()[0]);
Value zero = rewriter->create<arith::ConstantIndexOp>(loc, 0);
Value one = rewriter->create<arith::ConstantIndexOp>(loc, 1);
// Create an outer parallel loop that spans the output of ReduceWindowOp.
Value output = reduceWindowOp.out()[0];
auto outputLoop = makeLoopOverShape(loc, output, rewriter);
// Create a nested loop that traverses the window.
SmallVector<Value, 2> windowLower, windowUpper, windowStep;
rewriter->setInsertionPointToStart(outputLoop.getBody());
for (const auto& windowDim : reduceWindowOp.window_dimensions()) {
windowStep.push_back(one);
windowLower.push_back(zero);
windowUpper.push_back(rewriter->create<arith::ConstantIndexOp>(
loc, windowDim.getSExtValue()));
}
auto windowLoop = rewriter->create<scf::ParallelOp>(
loc, windowLower, windowUpper, windowStep, ValueRange(initValue));
Value reductionResult = *windowLoop.getResults().begin();
auto outputIvs = outputLoop.getInductionVars();
rewriter->create<memref::StoreOp>(loc, reductionResult, output, outputIvs);
return std::make_pair(outputLoop, windowLoop);
}
scf::ReduceOp createReduceOpInNestedParallelLoops(
lmhlo::ReduceWindowOp reduceWindowOp, scf::ParallelOp outputLoop,
scf::ParallelOp windowLoop, ConversionPatternRewriter* rewriter) const {
rewriter->setInsertionPointToStart(windowLoop.getBody());
auto loc = reduceWindowOp.getLoc();
if (reduceWindowOp.base_dilations().hasValue() ||
reduceWindowOp.window_dilations().hasValue()) {
reduceWindowOp.emitRemark(
"Lowering to parallel loops does not support `base_dilations` or "
"`window_dilations` attributes yet. The attributes will be ignored.");
}
Value input = reduceWindowOp.inputs()[0];
auto inputType = input.getType().cast<MemRefType>();
// Compute ivs in 'arg' buffer and whether these ivs are in pad area or not.
MappedIvs mappedIvs = mapWindowIvsToInput(
reduceWindowOp, input, outputLoop.getInductionVars(),
windowLoop.getInductionVars(), rewriter);
auto elemOrInit = rewriter->create<scf::IfOp>(
loc, inputType.getElementType(), mappedIvs.inBounds,
/*withElseRegion=*/true);
OpBuilder thenBuilder =
elemOrInit.getThenBodyBuilder(rewriter->getListener());
Value elem =
thenBuilder.create<mlir::memref::LoadOp>(loc, input, mappedIvs.ivs);
thenBuilder.create<scf::YieldOp>(loc, elem);
OpBuilder elseBuilder =
elemOrInit.getElseBodyBuilder(rewriter->getListener());
elseBuilder.create<scf::YieldOp>(loc, *windowLoop.getInitVals().begin());
return rewriter->create<scf::ReduceOp>(loc,
*elemOrInit.getResults().begin());
}
};
// See the operation semantics in
// https://www.tensorflow.org/xla/operation_semantics#selectandscatter
//
// Pseudocode:
// scf.parallel(coordinates O in the output):
// output[O] = init
// scf.parallel(coordinates S in the source):
// selected_ivs = 0
// selected_val = 0
// initialized_flag = false
// scf.for (first dim W_1 in the window)
// iter_args (selected_ivs, selected_val, initialized_flag):
// ...
// scf.for (last dim W_N in the window):
// iter_args (selected_ivs, selected_val, initialized_flag):
// I = S * stride + W - pad_low
// if I within bounds of operand:
// if (initialized_flag):
// pred = select(selected_value, operand(I))):
// if (pred)
// selected_value = operand(I)
// selected_index = I
// else
// selected_value = operand(I)
// selected_index = I
// initialized_flag = true
// output(selected_index) = scatter(output(selected_index), source(S))
class SelectAndScatterOpConverter
: public OpConversionPattern<lmhlo::SelectAndScatterOp> {
public:
using OpConversionPattern<lmhlo::SelectAndScatterOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
lmhlo::SelectAndScatterOp sAndSOp, OpAdaptor /*adaptor*/,
ConversionPatternRewriter& rewriter) const final {
auto loc = sAndSOp.getLoc();
initializeOutput(sAndSOp, &rewriter);
scf::ParallelOp loopOverSrc =
makeLoopOverShape(loc, sAndSOp.source(), &rewriter);
rewriter.setInsertionPointToStart(loopOverSrc.getBody());
// Compute indices of the selected element in the window.
auto selectedIvs = selectIvs(sAndSOp, loopOverSrc, &rewriter);
// Load `source[selected_ivs]`.
auto srcElem = rewriter.create<memref::LoadOp>(
loc, sAndSOp.source(), loopOverSrc.getInductionVars());
// Compute `out[selected_ivs]` = scatter(out[selected_ivs], src_element)`.
auto rmw = rewriter.create<memref::GenericAtomicRMWOp>(loc, sAndSOp.out(),
selectedIvs);
OpBuilder rmwBuilder = OpBuilder::atBlockEnd(rmw.getBody());
auto accResult =
applySingleResultLhloCode(loc, {srcElem, rmw.getCurrentValue()},
&sAndSOp.scatter().front(), &rmwBuilder);
rmwBuilder.create<memref::AtomicYieldOp>(loc, accResult);
rewriter.replaceOp(sAndSOp, llvm::None);
return success();
}
private:
void initializeOutput(lmhlo::SelectAndScatterOp sAndSOp, OpBuilder* b) const {
auto loc = sAndSOp.getLoc();
Value initValue = b->create<memref::LoadOp>(loc, sAndSOp.init_value());
scf::ParallelOp loopOverOutput = makeLoopOverShape(loc, sAndSOp.out(), b);
OpBuilder::InsertionGuard guard(*b);
b->setInsertionPointToStart(loopOverOutput.getBody());
b->create<memref::StoreOp>(loc, initValue, sAndSOp.out(),
loopOverOutput.getInductionVars());
}
struct WindowLoops {
SmallVector<Value, 2> selectedIvs;
SmallVector<Value, 2> windowIvs;
scf::ForOp innerLoop;
};
WindowLoops insertWindowLoops(lmhlo::SelectAndScatterOp sAndSOp,
scf::ParallelOp loopOverSrc,
OpBuilder* b) const {
auto loc = sAndSOp.getLoc();
Value zero = b->create<arith::ConstantIndexOp>(loc, 0);
Value one = b->create<arith::ConstantIndexOp>(loc, 1);
auto elementType =
sAndSOp.out().getType().cast<MemRefType>().getElementType();
auto rank = loopOverSrc.getNumLoops();
// `iter_args` = [iv_1, ..., iv_N, selected_value, is_initialized]
SmallVector<Value, 4> iterArgs(rank, zero);
iterArgs.push_back(b->create<mlir::arith::ConstantOp>(
loc, elementType, b->getFloatAttr(elementType, 0)));
iterArgs.push_back(b->create<mlir::arith::ConstantOp>(
loc, b->getI1Type(), b->getIntegerAttr(b->getI1Type(), 0)));
// Create a nested loop that traverses the window.
OpBuilder::InsertPoint ip;
WindowLoops result;
for (const auto& windowDim :
sAndSOp.window_dimensions()->getValues<APInt>()) {
Value upper =
b->create<arith::ConstantIndexOp>(loc, windowDim.getSExtValue());
result.innerLoop = b->create<scf::ForOp>(loc, zero, upper, one, iterArgs);
if (b->getInsertionBlock() == loopOverSrc.getBody()) {
ip = b->saveInsertionPoint();
result.selectedIvs = result.innerLoop.getResults().take_front(rank);
} else {
b->create<scf::YieldOp>(loc, result.innerLoop.getResults());
}
b->setInsertionPointToStart(result.innerLoop.getBody());
iterArgs = ValueRange{result.innerLoop.getRegionIterArgs()};
result.windowIvs.push_back(result.innerLoop.getInductionVar());
}
b->restoreInsertionPoint(ip);
return result;
}
// Adapter to store iteration arguments of sequential loops that perform
// select in a window.
class IterArgs {
public:
explicit IterArgs(ValueRange ivsValFlag) : ivsValFlag(ivsValFlag) {}
IterArgs(ValueRange ivs, Value value, Value flag) {
ivsValFlag = ivs;
ivsValFlag.push_back(value);
ivsValFlag.push_back(flag);
}
ArrayRef<Value> toVector() const { return ivsValFlag; }
// Indices of the currently selected value.
ArrayRef<Value> ivs() const { return toVector().drop_back(2); }
// Currently selected value w.r.t. select() function.
Value value() const { return ivsValFlag.end()[-2]; }
// i1 flag if value() and ivs() were initialized.
Value isInit() const { return ivsValFlag.back(); }
private:
// Vector that stores iv_1, ..., iv_N, value, init.
SmallVector<Value, 4> ivsValFlag;
};
SmallVector<Value, 2> selectIvs(lmhlo::SelectAndScatterOp sAndSOp,
scf::ParallelOp loopOverSrc,
OpBuilder* b) const {
auto loc = sAndSOp.getLoc();
WindowLoops windowLoops = insertWindowLoops(sAndSOp, loopOverSrc, b);
auto innerLoopB = OpBuilder::atBlockEnd(windowLoops.innerLoop.getBody());
// Compute ivs in 'arg' buffer and whether these ivs are in the pad area.
MappedIvs mappedIvs = mapWindowIvsToInput(
sAndSOp, sAndSOp.operand(), loopOverSrc.getInductionVars(),
windowLoops.windowIvs, &innerLoopB);
IterArgs ivsValFlag(windowLoops.innerLoop.getRegionIterArgs());
auto ifInBounds = innerLoopB.create<scf::IfOp>(
loc, windowLoops.innerLoop.getResultTypes(), mappedIvs.inBounds,
/*withElseRegion=*/true);
// Case when we are inside boundaries of 'arg' and not in the pad area.
{
OpBuilder inBoundsThenB = ifInBounds.getThenBodyBuilder(b->getListener());
auto selectOrInitResults = selectOrInitialize(
sAndSOp, mappedIvs.ivs, &ivsValFlag, &inBoundsThenB);
inBoundsThenB.create<scf::YieldOp>(loc, selectOrInitResults);
}
// Case when we are in the pad.
{
OpBuilder inBoundsElseB = ifInBounds.getElseBodyBuilder(b->getListener());
inBoundsElseB.create<scf::YieldOp>(loc, ivsValFlag.toVector());
}
innerLoopB.create<scf::YieldOp>(loc, ifInBounds.getResults());
return windowLoops.selectedIvs;
}
SmallVector<Value, 4> selectOrInitialize(lmhlo::SelectAndScatterOp sAndSOp,
ArrayRef<Value> operandIvs,
IterArgs* ivsValFlag,
OpBuilder* b) const {
auto loc = sAndSOp.getLoc();
Value trueI1 = b->create<mlir::arith::ConstantOp>(
loc, b->getI1Type(), b->getIntegerAttr(b->getI1Type(), 1));
TypeRange iterArgTypes{ivsValFlag->toVector()};
Value operandElem =
b->create<memref::LoadOp>(loc, sAndSOp.operand(), operandIvs);
auto ifInit = b->create<scf::IfOp>(loc, iterArgTypes, ivsValFlag->isInit(),
/*withElseRegion=*/true);
// Init == true, i.e. iter args are already initialized with a selected
// element in boundaries of the operand. Select function has to be computed
// here.
{
OpBuilder ifInitThenB = ifInit.getThenBodyBuilder(b->getListener());
auto& lhloSelect = sAndSOp.select().front();
Value pred = applySingleResultLhloCode(
loc, {operandElem, ivsValFlag->value()}, &lhloSelect, &ifInitThenB);
auto ifPred = ifInitThenB.create<scf::IfOp>(loc, iterArgTypes, pred,
/*withElseRegion=*/true);
// Pred == true, therefore pack newly selected ivs, val and init flag back
// to iter_args and return.
{
OpBuilder ifPredThenB = ifPred.getThenBodyBuilder(b->getListener());
ifPredThenB.create<scf::YieldOp>(
loc, IterArgs{operandIvs, operandElem, trueI1}.toVector());
}
// Pred == false, therefore return old iter_args.
{
OpBuilder ifPredElseB = ifPred.getElseBodyBuilder(b->getListener());
ifPredElseB.create<scf::YieldOp>(loc, ivsValFlag->toVector());
}
ifInitThenB.create<scf::YieldOp>(loc, ifPred.getResults());
}
// Init == false, i.e. only pad was visited before and this is the first
// element in the boundaries of the operand.
{
OpBuilder ifInitElseB = ifInit.getElseBodyBuilder(b->getListener());
ifInitElseB.create<scf::YieldOp>(
loc, IterArgs{operandIvs, operandElem, trueI1}.toVector());
}
return ifInit.getResults();
}
};
struct LhloLegalizeToParallelLoopsPass
: public LhloLegalizeToParallelLoopsPassBase<
LhloLegalizeToParallelLoopsPass> {
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<arith::ArithmeticDialect, func::FuncDialect,
memref::MemRefDialect, scf::SCFDialect>();
}
void runOnOperation() override {
auto func = getOperation();
RewritePatternSet patterns(&getContext());
// clang-format off
patterns.add<
ReduceOpConverter,
ReduceWindowOpConverter,
SelectAndScatterOpConverter
>(func.getContext());
// clang-format on
ConversionTarget target(getContext());
target.addLegalDialect<arith::ArithmeticDialect, linalg::LinalgDialect,
memref::MemRefDialect, func::FuncDialect,
scf::SCFDialect, LmhloDialect>();
target.addIllegalOp<lmhlo::ReduceOp, lmhlo::ReduceWindowOp,
lmhlo::SelectAndScatterOp>();
if (failed(applyPartialConversion(func, target, std::move(patterns)))) {
signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<func::FuncOp>>
createLegalizeLhloToParallelLoopsPass() {
return std::make_unique<LhloLegalizeToParallelLoopsPass>();
}
} // namespace lmhlo
} // namespace mlir
| 40.43962 | 80 | 0.653067 | [
"shape",
"vector"
] |
63d3f04f049f412f8df4baaba91c1ce927261f28 | 2,229 | cpp | C++ | src/main.cpp | Butataki/cpp-simple-config-parser | 26877faff122d8269a304f23897e97fe3e633557 | [
"MIT"
] | null | null | null | src/main.cpp | Butataki/cpp-simple-config-parser | 26877faff122d8269a304f23897e97fe3e633557 | [
"MIT"
] | null | null | null | src/main.cpp | Butataki/cpp-simple-config-parser | 26877faff122d8269a304f23897e97fe3e633557 | [
"MIT"
] | 1 | 2022-02-22T15:53:44.000Z | 2022-02-22T15:53:44.000Z | #include <iostream>
#include <vector>
#include <iterator>
#include <unistd.h>
#include <typeinfo>
#include "simple_config_parser/parser.h"
//Example usage
int main() {
simple_config_parser::parser::Configuration conf = simple_config_parser::parser::Configuration("test.cfg");
simple_config_parser::parser::Configuration * conf_ptr = new simple_config_parser::parser::Configuration("test.cfg");
char * name_ptr = getlogin();
if (name_ptr) {
std::cout << "user is " << name_ptr << std::endl;
}
int one_from_ptr = conf_ptr->get_int_value("One");
std::cout << "ptr accressed Parameter \"One\" have value of " << one_from_ptr << std::endl;
int one = conf.get_int_value("One");
std::cout << "Parameter \"One\" have value of " << one << std::endl;
int section_one = conf.get_int_value("One", "section1");
std::cout << "Parameter \"One\" from \"section1\" have value of " << section_one << std::endl;
int def_one = conf.get_int_value("AnotherOne");
std::cout << "Not present \"AnotherOne\" have default value of " << def_one << std::endl;
int nonex_section_one = conf.get_int_value("One", "section_nonex");
std::cout << "Parameter \"One\" from not existsing section \"section_nonex\" have value of " << nonex_section_one << std::endl;
float test_part = conf.get_float_value("TestPArt", "section1");
std::cout << "Parameter \"TestPArt\" from \"section1\" have value of " << test_part << std::endl;
std::string st = conf.get_string_value("Some", "section1");
std::cout << "Parameter \"Some\" from \"section1\" have value of " << st << std::endl;
std::vector<std::string> v_st = conf.get_string_vector_value("List", "section1");
for(std::vector<std::string>::size_type i = 0; i != v_st.size(); i++) {
std::cout << i << " position of parameter \"List\" from \"section1\" have value of " << v_st[i] << std::endl;
}
std::vector<int> v_in = conf.get_int_vector_value("Point", "section1");
for(std::vector<int>::size_type i = 0; i != v_in.size(); i++) {
std::cout << i << " position of parameter \"Point\" from \"section1\" have value of " << v_in[i] << std::endl;
}
if (conf_ptr) delete conf_ptr;
return(1);
}
| 53.071429 | 131 | 0.645132 | [
"vector"
] |
63d48b57390dc1e7ff80dfe64dc3f6b1a19c3e4e | 23,434 | cpp | C++ | Tests/PromiscuousPacketHandling_Test.cpp | MasonT8198/xlinkhandheldassistant | 16233b21f16686b63466dd8d9cf427e6e255d711 | [
"MIT"
] | null | null | null | Tests/PromiscuousPacketHandling_Test.cpp | MasonT8198/xlinkhandheldassistant | 16233b21f16686b63466dd8d9cf427e6e255d711 | [
"MIT"
] | null | null | null | Tests/PromiscuousPacketHandling_Test.cpp | MasonT8198/xlinkhandheldassistant | 16233b21f16686b63466dd8d9cf427e6e255d711 | [
"MIT"
] | null | null | null | /* Copyright (c) 2021 [Rick de Bondt] - PromiscuousPacketHandling_Test.cpp
* This file contains tests for the WirelessPromiscuousDevice class.
**/
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "IConnectorMock.h"
#include "IPCapWrapperMock.h"
#include "IWifiInterfaceMock.h"
#include "NetConversionFunctions.h"
#include "PCapReader.h"
#include "WirelessPromiscuousDevice.h"
using ::testing::_;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::WithArg;
class PromiscuousPacketHandlingTest : public ::testing::Test
{};
TEST_F(PromiscuousPacketHandlingTest, NormalPacketHandlingXLinkSide)
{
std::shared_ptr<IWifiInterface> lWifiInterface{std::make_shared<IWifiInterfaceMock>()};
std::vector<std::string> lSSIDFilter{""};
auto lPCapWrapperMock{std::make_shared<::testing::NiceMock<IPCapWrapperMock>>()};
auto lPromiscuousDevice{
std::make_shared<WirelessPromiscuousDevice>(false,
WirelessPromiscuousBase_Constants::cReconnectionTimeOut,
nullptr,
std::make_shared<Handler8023>(),
std::static_pointer_cast<IPCapWrapper>(lPCapWrapperMock))};
// Expectation classes (PCapReader and the like)
const std::string lOutputFileName{"../Tests/Output/PromiscuousTestXLink.pcap"};
std::vector<std::string> lReceiveBuffer{};
std::vector<timeval> lReceiveTimeStamp{};
std::vector<std::string> lExpectedPackets{};
std::vector<std::string> lOutputPackets{};
std::vector<timeval> lTimeStamp{};
PCapWrapper lWrapper;
lWrapper.OpenDead(DLT_EN10MB, 65535);
pcap_dumper_t* lDumper{lWrapper.DumpOpen(lOutputFileName.c_str())};
std::shared_ptr<IConnector> lExpectedConnector{std::make_shared<IConnectorMock>()};
PCapReader lPCapInputReader{false, false, false};
PCapReader lPCapExpectedReader{false, false, false};
// Expectations
// The WiFi Mac address obviously needs to stay the same during testing so return a fake one
EXPECT_CALL(*std::static_pointer_cast<IWifiInterfaceMock>(lWifiInterface), GetAdapterMacAddress)
.WillOnce(Return(0xb03f29f81800));
// PCAP set-up
lPCapInputReader.Open("../Tests/Input/PromiscuousTestXLink.pcap");
lPCapInputReader.SetIncomingConnection(lPromiscuousDevice);
// Should be the same as the input
lPCapExpectedReader.Open("../Tests/Input/PromiscuousTestXLink.pcap");
lPCapExpectedReader.SetConnector(lExpectedConnector);
// Put everything sent to the "WiFi-card" into a messagebuffer with timestamps
ON_CALL(*lPCapWrapperMock, IsActivated()).WillByDefault(Return(true));
EXPECT_CALL(*lPCapWrapperMock, SendPacket(_))
.WillRepeatedly(DoAll(WithArg<0>([&](std::string_view aMessage) {
lOutputPackets.emplace_back(std::string(aMessage));
lTimeStamp.push_back(lPCapInputReader.GetHeader()->ts);
}),
Return(0)));
// Put all expected packets into a buffer as well for easy comparison
EXPECT_CALL(*std::static_pointer_cast<IConnectorMock>(lExpectedConnector), Send(_))
.WillRepeatedly(
DoAll(WithArg<0>([&](std::string_view aMessage) { lExpectedPackets.emplace_back(std::string(aMessage)); }),
Return(true)));
// Test class set-up
lPromiscuousDevice->Open("wlan0", lSSIDFilter, lWifiInterface);
// Normally the XLink Kai connection side blacklists this, but we'll do it here
lPromiscuousDevice->BlackList(0x0018f8293fb0);
lPCapInputReader.StartReceiverThread();
lPCapExpectedReader.StartReceiverThread();
while (!lPCapInputReader.IsDoneReceiving() || !lPCapExpectedReader.IsDoneReceiving()) {}
// Should have the same amount of packets
ASSERT_EQ(lExpectedPackets.size(), lOutputPackets.size());
// Output a file with the results as well so the results can be further inspected
int lCount = 0;
for (auto& lMessage : lOutputPackets) {
// Packet should be the same
ASSERT_EQ(lMessage, lExpectedPackets.at(lCount));
pcap_pkthdr lHeader{};
lHeader.caplen = lMessage.size();
lHeader.len = lMessage.size();
lHeader.ts = lTimeStamp.at(lCount);
lWrapper.Dump(
reinterpret_cast<unsigned char*>(lDumper), &lHeader, reinterpret_cast<unsigned char*>(lMessage.data()));
lCount++;
}
lWrapper.DumpClose(lDumper);
lWrapper.Close();
lPCapInputReader.Close();
lPCapExpectedReader.Close();
lPromiscuousDevice->Close();
}
// This test should prove that the VRRP Mac sent by XLink Kai would be replaced by the adapter Mac on DDS
TEST_F(PromiscuousPacketHandlingTest, ReplaceMacXLinkSide)
{
std::shared_ptr<IWifiInterface> lWifiInterface{std::make_shared<IWifiInterfaceMock>()};
std::vector<std::string> lSSIDFilter{""};
auto lPCapWrapperMock{std::make_shared<::testing::NiceMock<IPCapWrapperMock>>()};
auto lPromiscuousDevice{
std::make_shared<WirelessPromiscuousDevice>(false,
WirelessPromiscuousBase_Constants::cReconnectionTimeOut,
nullptr,
std::make_shared<Handler8023>(),
std::static_pointer_cast<IPCapWrapper>(lPCapWrapperMock))};
// Expectation classes (PCapReader and the like)
const std::string lOutputFileName{"../Tests/Output/DDSMacReplaceTest.pcap"};
std::vector<std::string> lReceiveBuffer{};
std::vector<timeval> lReceiveTimeStamp{};
std::vector<std::string> lExpectedPackets{};
std::vector<std::string> lOutputPackets{};
std::vector<timeval> lTimeStamp{};
PCapWrapper lWrapper;
lWrapper.OpenDead(DLT_EN10MB, 65535);
pcap_dumper_t* lDumper{lWrapper.DumpOpen(lOutputFileName.c_str())};
std::shared_ptr<IConnector> lExpectedConnector{std::make_shared<IConnectorMock>()};
PCapReader lPCapInputReader{false, false, false};
PCapReader lPCapExpectedReader{false, false, false};
// Expectations
// The WiFi Mac address obviously needs to stay the same during testing so return a fake one
EXPECT_CALL(*std::static_pointer_cast<IWifiInterfaceMock>(lWifiInterface), GetAdapterMacAddress)
.WillOnce(Return(0xb03f29f81800));
// PCAP set-up
lPCapInputReader.Open("../Tests/Input/DDSMacReplaceTest.pcap");
lPCapInputReader.SetIncomingConnection(lPromiscuousDevice);
lPCapExpectedReader.Open("../Tests/Input/DDSMacReplaceTest_Expected.pcap");
lPCapExpectedReader.SetConnector(lExpectedConnector);
// Put everything sent to the "WiFi-card" into a messagebuffer with timestamps
ON_CALL(*lPCapWrapperMock, IsActivated()).WillByDefault(Return(true));
EXPECT_CALL(*lPCapWrapperMock, SendPacket(_))
.WillRepeatedly(DoAll(WithArg<0>([&](std::string_view aMessage) {
lOutputPackets.emplace_back(std::string(aMessage));
lTimeStamp.push_back(lPCapInputReader.GetHeader()->ts);
}),
Return(0)));
// Put all expected packets into a buffer as well for easy comparison
EXPECT_CALL(*std::static_pointer_cast<IConnectorMock>(lExpectedConnector), Send(_))
.WillRepeatedly(
DoAll(WithArg<0>([&](std::string_view aMessage) { lExpectedPackets.emplace_back(std::string(aMessage)); }),
Return(true)));
// Test class set-up
lPromiscuousDevice->Open("wlan0", lSSIDFilter, lWifiInterface);
// Normally the XLink Kai connection side blacklists this, but we'll do it here
lPromiscuousDevice->BlackList(0xd44b5e02ed20);
lPromiscuousDevice->BlackList(0x00005e0001fe);
lPCapInputReader.StartReceiverThread();
lPCapExpectedReader.StartReceiverThread();
while (!lPCapInputReader.IsDoneReceiving() || !lPCapExpectedReader.IsDoneReceiving()) {}
// Should have the same amount of packets
ASSERT_EQ(lExpectedPackets.size(), lOutputPackets.size());
// Output a file with the results as well so the results can be further inspected
int lCount = 0;
for (auto& lMessage : lOutputPackets) {
// Packet should be the same
ASSERT_EQ(lMessage, lExpectedPackets.at(lCount));
pcap_pkthdr lHeader{};
lHeader.caplen = lMessage.size();
lHeader.len = lMessage.size();
lHeader.ts = lTimeStamp.at(lCount);
lWrapper.Dump(
reinterpret_cast<unsigned char*>(lDumper), &lHeader, reinterpret_cast<unsigned char*>(lMessage.data()));
lCount++;
}
lWrapper.DumpClose(lDumper);
lWrapper.Close();
lPCapInputReader.Close();
lPCapExpectedReader.Close();
lPromiscuousDevice->Close();
}
// This test should prove that the VRRP Mac sent by XLink Kai would be replaced by the adapter Mac on DDS on arp replies
TEST_F(PromiscuousPacketHandlingTest, ReplaceMacArpReplyXLinkSide)
{
std::shared_ptr<IWifiInterface> lWifiInterface{std::make_shared<IWifiInterfaceMock>()};
std::vector<std::string> lSSIDFilter{""};
auto lPCapWrapperMock{std::make_shared<::testing::NiceMock<IPCapWrapperMock>>()};
auto lPromiscuousDevice{
std::make_shared<WirelessPromiscuousDevice>(false,
WirelessPromiscuousBase_Constants::cReconnectionTimeOut,
nullptr,
std::make_shared<Handler8023>(),
std::static_pointer_cast<IPCapWrapper>(lPCapWrapperMock))};
// Expectation classes (PCapReader and the like)
const std::string lOutputFileName{"../Tests/Output/DDSArpMacReplaceTestReply.pcap"};
std::vector<std::string> lReceiveBuffer{};
std::vector<timeval> lReceiveTimeStamp{};
std::vector<std::string> lExpectedPackets{};
std::vector<std::string> lOutputPackets{};
std::vector<timeval> lTimeStamp{};
PCapWrapper lWrapper;
lWrapper.OpenDead(DLT_EN10MB, 65535);
pcap_dumper_t* lDumper{lWrapper.DumpOpen(lOutputFileName.c_str())};
std::shared_ptr<IConnector> lExpectedConnector{std::make_shared<IConnectorMock>()};
PCapReader lPCapInputReader{false, false, false};
PCapReader lPCapExpectedReader{false, false, false};
// Expectations
// The WiFi Mac address obviously needs to stay the same during testing so return a fake one
EXPECT_CALL(*std::static_pointer_cast<IWifiInterfaceMock>(lWifiInterface), GetAdapterMacAddress)
.WillOnce(Return(0xb03f29f81800));
// PCAP set-up
lPCapInputReader.Open("../Tests/Input/DDSArpMacReplaceTestReply.pcap");
lPCapInputReader.SetIncomingConnection(lPromiscuousDevice);
lPCapExpectedReader.Open("../Tests/Input/DDSArpMacReplaceTestReply_Expected.pcap");
lPCapExpectedReader.SetConnector(lExpectedConnector);
// Put everything sent to the "WiFi-card" into a messagebuffer with timestamps
ON_CALL(*lPCapWrapperMock, IsActivated()).WillByDefault(Return(true));
EXPECT_CALL(*lPCapWrapperMock, SendPacket(_))
.WillRepeatedly(DoAll(WithArg<0>([&](std::string_view aMessage) {
lOutputPackets.emplace_back(std::string(aMessage));
lTimeStamp.push_back(lPCapInputReader.GetHeader()->ts);
}),
Return(0)));
// Put all expected packets into a buffer as well for easy comparison
EXPECT_CALL(*std::static_pointer_cast<IConnectorMock>(lExpectedConnector), Send(_))
.WillRepeatedly(
DoAll(WithArg<0>([&](std::string_view aMessage) { lExpectedPackets.emplace_back(std::string(aMessage)); }),
Return(true)));
// Test class set-up
lPromiscuousDevice->Open("wlan0", lSSIDFilter, lWifiInterface);
// Normally the XLink Kai connection side blacklists this, but we'll do it here
lPromiscuousDevice->BlackList(0xd44b5e02ed20);
lPromiscuousDevice->BlackList(0x00005e0001fe);
lPCapInputReader.StartReceiverThread();
lPCapExpectedReader.StartReceiverThread();
while (!lPCapInputReader.IsDoneReceiving() || !lPCapExpectedReader.IsDoneReceiving()) {}
// Should have the same amount of packets
ASSERT_EQ(lExpectedPackets.size(), lOutputPackets.size());
// Output a file with the results as well so the results can be further inspected
int lCount = 0;
for (auto& lMessage : lOutputPackets) {
// Packet should be the same
ASSERT_EQ(lMessage, lExpectedPackets.at(lCount));
pcap_pkthdr lHeader{};
lHeader.caplen = lMessage.size();
lHeader.len = lMessage.size();
lHeader.ts = lTimeStamp.at(lCount);
lWrapper.Dump(
reinterpret_cast<unsigned char*>(lDumper), &lHeader, reinterpret_cast<unsigned char*>(lMessage.data()));
lCount++;
}
lWrapper.DumpClose(lDumper);
lWrapper.Close();
lPCapInputReader.Close();
lPCapExpectedReader.Close();
lPromiscuousDevice->Close();
}
// This test should prove that the VRRP Mac sent by XLink Kai would be replaced by the adapter Mac on DDS on arp
// requests
TEST_F(PromiscuousPacketHandlingTest, ReplaceMacArpRequestXLinkSide)
{
std::shared_ptr<IWifiInterface> lWifiInterface{std::make_shared<IWifiInterfaceMock>()};
std::vector<std::string> lSSIDFilter{""};
auto lPCapWrapperMock{std::make_shared<::testing::NiceMock<IPCapWrapperMock>>()};
auto lPromiscuousDevice{
std::make_shared<WirelessPromiscuousDevice>(false,
WirelessPromiscuousBase_Constants::cReconnectionTimeOut,
nullptr,
std::make_shared<Handler8023>(),
std::static_pointer_cast<IPCapWrapper>(lPCapWrapperMock))};
// Expectation classes (PCapReader and the like)
const std::string lOutputFileName{"../Tests/Output/DDSArpMacReplaceTestRequest.pcap"};
std::vector<std::string> lReceiveBuffer{};
std::vector<timeval> lReceiveTimeStamp{};
std::vector<std::string> lExpectedPackets{};
std::vector<std::string> lOutputPackets{};
std::vector<timeval> lTimeStamp{};
PCapWrapper lWrapper;
lWrapper.OpenDead(DLT_EN10MB, 65535);
pcap_dumper_t* lDumper{lWrapper.DumpOpen(lOutputFileName.c_str())};
std::shared_ptr<IConnector> lExpectedConnector{std::make_shared<IConnectorMock>()};
PCapReader lPCapInputReader{false, false, false};
PCapReader lPCapExpectedReader{false, false, false};
// Expectations
// The WiFi Mac address obviously needs to stay the same during testing so return a fake one
EXPECT_CALL(*std::static_pointer_cast<IWifiInterfaceMock>(lWifiInterface), GetAdapterMacAddress)
.WillOnce(Return(0xb03f29f81800));
// PCAP set-up
lPCapInputReader.Open("../Tests/Input/DDSArpMacReplaceTestRequest.pcap");
lPCapInputReader.SetIncomingConnection(lPromiscuousDevice);
lPCapExpectedReader.Open("../Tests/Input/DDSArpMacReplaceTestRequest_Expected.pcap");
lPCapExpectedReader.SetConnector(lExpectedConnector);
// Put everything sent to the "WiFi-card" into a messagebuffer with timestamps
ON_CALL(*lPCapWrapperMock, IsActivated()).WillByDefault(Return(true));
EXPECT_CALL(*lPCapWrapperMock, SendPacket(_))
.WillRepeatedly(DoAll(WithArg<0>([&](std::string_view aMessage) {
lOutputPackets.emplace_back(std::string(aMessage));
lTimeStamp.push_back(lPCapInputReader.GetHeader()->ts);
}),
Return(0)));
// Put all expected packets into a buffer as well for easy comparison
EXPECT_CALL(*std::static_pointer_cast<IConnectorMock>(lExpectedConnector), Send(_))
.WillRepeatedly(
DoAll(WithArg<0>([&](std::string_view aMessage) { lExpectedPackets.emplace_back(std::string(aMessage)); }),
Return(true)));
// Test class set-up
lPromiscuousDevice->Open("wlan0", lSSIDFilter, lWifiInterface);
// Normally the XLink Kai connection side blacklists this, but we'll do it here
lPromiscuousDevice->BlackList(0xd44b5e02ed20);
lPromiscuousDevice->BlackList(0x00005e0001fe);
lPCapInputReader.StartReceiverThread();
lPCapExpectedReader.StartReceiverThread();
while (!lPCapInputReader.IsDoneReceiving() || !lPCapExpectedReader.IsDoneReceiving()) {}
// Should have the same amount of packets
ASSERT_EQ(lExpectedPackets.size(), lOutputPackets.size());
// Output a file with the results as well so the results can be further inspected
int lCount = 0;
for (auto& lMessage : lOutputPackets) {
// Packet should be the same
ASSERT_EQ(lMessage, lExpectedPackets.at(lCount));
pcap_pkthdr lHeader{};
lHeader.caplen = lMessage.size();
lHeader.len = lMessage.size();
lHeader.ts = lTimeStamp.at(lCount);
lWrapper.Dump(
reinterpret_cast<unsigned char*>(lDumper), &lHeader, reinterpret_cast<unsigned char*>(lMessage.data()));
lCount++;
}
lWrapper.DumpClose(lDumper);
lWrapper.Close();
lPCapInputReader.Close();
lPCapExpectedReader.Close();
lPromiscuousDevice->Close();
}
// When a packet is received from the PSP the Mac address at the end should be moved back to its proper place before
// being sent to XLink Kai.
TEST_F(PromiscuousPacketHandlingTest, NormalPacketHandlingDeviceSide)
{
// Class to be tested, with components needed for it to function
std::shared_ptr<IWifiInterface> lWifiInterface{std::make_shared<IWifiInterfaceMock>()};
std::shared_ptr<IConnector> lOutputConnector{std::make_shared<IConnectorMock>()};
std::vector<std::string> lSSIDFilter{""};
auto lPCapWrapperMock{std::make_shared<::testing::NiceMock<IPCapWrapperMock>>()};
WirelessPromiscuousDevice lPromiscuousDevice{false,
WirelessPromiscuousBase_Constants::cReconnectionTimeOut,
nullptr,
std::make_shared<Handler8023>(),
std::static_pointer_cast<IPCapWrapper>(lPCapWrapperMock)};
// Expectation classes (PCapReader and the like)
const std::string lOutputFileName{"../Tests/Output/PromiscuousTestDevice.pcap"};
std::vector<std::string> lReceiveBuffer{};
std::vector<timeval> lReceiveTimeStamp{};
std::vector<std::string> lInputPackets{};
std::vector<std::string> lExpectedPackets{};
std::vector<std::string> lOutputPackets{};
std::vector<timeval> lTimeStamp{};
PCapWrapper lWrapper;
lWrapper.OpenDead(DLT_EN10MB, 65535);
pcap_dumper_t* lDumper{lWrapper.DumpOpen(lOutputFileName.c_str())};
std::shared_ptr<IConnector> lInputConnector{std::make_shared<IConnectorMock>()};
std::shared_ptr<IConnector> lExpectedConnector{std::make_shared<IConnectorMock>()};
PCapReader lPCapInputReader{false, false, false};
PCapReader lPCapExpectedReader{false, false, false};
// Expectations
// The WiFi Mac address obviously needs to stay the same during testing so return a fake one
EXPECT_CALL(*std::static_pointer_cast<IWifiInterfaceMock>(lWifiInterface), GetAdapterMacAddress)
.WillOnce(Return(0xb03f29f81800));
// PCAP set-up
lPCapInputReader.Open("../Tests/Input/PromiscuousTestDevice.pcap");
lPCapInputReader.SetConnector(lInputConnector);
// Should be the same as the input
lPCapExpectedReader.Open("../Tests/Input/PromiscuousTestDevice.pcap");
lPCapExpectedReader.SetConnector(lExpectedConnector);
EXPECT_CALL(*std::static_pointer_cast<IConnectorMock>(lInputConnector), Send(_))
.WillRepeatedly(DoAll(WithArg<0>([&](std::string_view aMessage) {
lInputPackets.emplace_back(aMessage);
lTimeStamp.push_back(lPCapInputReader.GetHeader()->ts);
}),
Return(true)));
EXPECT_CALL(*std::static_pointer_cast<IConnectorMock>(lOutputConnector), Send(_))
.WillRepeatedly(
DoAll(WithArg<0>([&](std::string_view aMessage) { lOutputPackets.emplace_back(std::string(aMessage)); }),
Return(true)));
EXPECT_CALL(*std::static_pointer_cast<IConnectorMock>(lExpectedConnector), Send(_))
.WillRepeatedly(
DoAll(WithArg<0>([&](std::string_view aMessage) { lExpectedPackets.emplace_back(std::string(aMessage)); }),
Return(true)));
lPCapInputReader.StartReceiverThread();
lPCapExpectedReader.StartReceiverThread();
while (!lPCapInputReader.IsDoneReceiving() || !lPCapExpectedReader.IsDoneReceiving()) {}
// Test class set-up
lPromiscuousDevice.SetConnector(lOutputConnector);
lPromiscuousDevice.Open("wlan0", lSSIDFilter, lWifiInterface);
// Normally the XLink Kai connection side blacklists this, but we'll do it here
lPromiscuousDevice.BlackList(0xd44b5e69dfa6);
// Receiving data
for (int lCount = 0; lCount < lInputPackets.size(); lCount++) {
pcap_pkthdr lHeader{};
lHeader.caplen = lInputPackets.at(lCount).size();
lHeader.len = lInputPackets.at(lCount).size();
lHeader.ts = lTimeStamp.at(lCount);
lPromiscuousDevice.ReadCallback(reinterpret_cast<const unsigned char*>(lInputPackets.at(lCount).data()),
&lHeader);
}
// Should have the same amount of packets
ASSERT_EQ(lExpectedPackets.size(), lOutputPackets.size());
// Output a file with the results as well so the results can be further inspected
int lCount = 0;
for (auto& lMessage : lOutputPackets) {
// Packet should be the same
ASSERT_EQ(lMessage, lExpectedPackets.at(lCount));
pcap_pkthdr lHeader{};
lHeader.caplen = lMessage.size();
lHeader.len = lMessage.size();
lHeader.ts = lTimeStamp.at(lCount);
lWrapper.Dump(
reinterpret_cast<unsigned char*>(lDumper), &lHeader, reinterpret_cast<unsigned char*>(lMessage.data()));
lCount++;
}
lWrapper.DumpClose(lDumper);
lWrapper.Close();
lPCapInputReader.Close();
lPCapExpectedReader.Close();
lPromiscuousDevice.Close();
}
| 44.978887 | 120 | 0.653879 | [
"vector"
] |
63d80eb18db0e3547b5c7f8e04b68f84cf191bc3 | 4,835 | hpp | C++ | phosphor-regulators/src/rail.hpp | smccarney/phosphor-power | 39ea02bc9458f3d5a7fdd317cb546ed046eaff78 | [
"Apache-2.0"
] | 7 | 2019-10-04T01:19:49.000Z | 2021-06-02T23:11:19.000Z | phosphor-regulators/src/rail.hpp | smccarney/phosphor-power | 39ea02bc9458f3d5a7fdd317cb546ed046eaff78 | [
"Apache-2.0"
] | 9 | 2019-10-23T14:22:03.000Z | 2022-03-22T20:39:05.000Z | phosphor-regulators/src/rail.hpp | smccarney/phosphor-power | 39ea02bc9458f3d5a7fdd317cb546ed046eaff78 | [
"Apache-2.0"
] | 11 | 2019-10-04T01:20:01.000Z | 2022-03-03T06:08:16.000Z | /**
* Copyright © 2019 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "configuration.hpp"
#include "sensor_monitoring.hpp"
#include "services.hpp"
#include <memory>
#include <string>
#include <utility>
namespace phosphor::power::regulators
{
// Forward declarations to avoid circular dependencies
class Chassis;
class Device;
class System;
/**
* @class Rail
*
* A voltage rail produced by a voltage regulator.
*
* Voltage regulators produce one or more rails. Each rail typically provides a
* different output voltage level, such as 1.1V.
*/
class Rail
{
public:
// Specify which compiler-generated methods we want
Rail() = delete;
Rail(const Rail&) = delete;
Rail(Rail&&) = delete;
Rail& operator=(const Rail&) = delete;
Rail& operator=(Rail&&) = delete;
~Rail() = default;
/**
* Constructor.
*
* @param id unique rail ID
* @param configuration configuration changes to apply to this rail, if any
* @param sensorMonitoring sensor monitoring for this rail, if any
*/
explicit Rail(
const std::string& id,
std::unique_ptr<Configuration> configuration = nullptr,
std::unique_ptr<SensorMonitoring> sensorMonitoring = nullptr) :
id{id},
configuration{std::move(configuration)}, sensorMonitoring{std::move(
sensorMonitoring)}
{}
/**
* Clears all error history.
*
* All data on previously logged errors will be deleted. If errors occur
* again in the future they will be logged again.
*
* This method is normally called when the system is being powered on.
*/
void clearErrorHistory();
/**
* Configure this rail.
*
* Applies the configuration changes that are defined for this rail, if any.
*
* This method should be called during the boot before regulators are
* enabled.
*
* @param services system services like error logging and the journal
* @param system system that contains the chassis
* @param chassis chassis that contains the device
* @param device device that contains this rail
*/
void configure(Services& services, System& system, Chassis& chassis,
Device& device);
/**
* Returns the configuration changes to apply to this rail, if any.
*
* @return Pointer to Configuration object. Will equal nullptr if no
* configuration changes are defined for this rail.
*/
const std::unique_ptr<Configuration>& getConfiguration() const
{
return configuration;
}
/**
* Returns the unique ID of this rail.
*
* @return rail ID
*/
const std::string& getID() const
{
return id;
}
/**
* Monitor the sensors for this rail.
*
* Sensor monitoring is optional. If sensor monitoring is defined for this
* rail, the sensor values are read.
*
* This method should be called repeatedly based on a timer.
*
* @param services system services like error logging and the journal
* @param system system that contains the chassis
* @param chassis chassis that contains the device
* @param device device that contains this rail
*/
void monitorSensors(Services& services, System& system, Chassis& chassis,
Device& device);
/**
* Returns the sensor monitoring for this rail, if any.
*
* @return Pointer to SensorMonitoring object. Will equal nullptr if no
* sensor monitoring is defined for this rail.
*/
const std::unique_ptr<SensorMonitoring>& getSensorMonitoring() const
{
return sensorMonitoring;
}
private:
/**
* Unique ID of this rail.
*/
const std::string id{};
/**
* Configuration changes to apply to this rail, if any. Set to nullptr if
* no configuration changes are defined for this rail.
*/
std::unique_ptr<Configuration> configuration{};
/**
* Sensor monitoring for this rail, if any. Set to nullptr if no sensor
* monitoring is defined for this rail.
*/
std::unique_ptr<SensorMonitoring> sensorMonitoring{};
};
} // namespace phosphor::power::regulators
| 29.662577 | 80 | 0.650672 | [
"object"
] |
63dbc05a6b4037d4fdcf4e1483de1b51b7720bf1 | 45,672 | cc | C++ | third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2014 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/callback_interface.cpp.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/tests/results/core/v8_test_callback_interface.h"
#include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_test_interface_empty.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
namespace blink {
v8::Maybe<void> V8TestCallbackInterface::voidMethod(ScriptWrappable* callback_this_value) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethod",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethod",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "voidMethod"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethod",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Value> *argv = nullptr;
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
0,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
v8::Maybe<bool> V8TestCallbackInterface::booleanMethod(ScriptWrappable* callback_this_value) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"booleanMethod",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<bool>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"booleanMethod",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<bool>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "booleanMethod"))
.ToLocal(&value)) {
return v8::Nothing<bool>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"booleanMethod",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<bool>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Value> *argv = nullptr;
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
0,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<bool>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
{
ExceptionState exception_state(GetIsolate(),
ExceptionState::kExecutionContext,
"TestCallbackInterface",
"booleanMethod");
auto native_result =
NativeValueTraits<IDLBoolean>::NativeValue(
GetIsolate(), call_result, exception_state);
if (exception_state.HadException())
return v8::Nothing<bool>();
else
return v8::Just<bool>(native_result);
}
}
v8::Maybe<void> V8TestCallbackInterface::voidMethodBooleanArg(ScriptWrappable* callback_this_value, bool boolArg) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodBooleanArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodBooleanArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "voidMethodBooleanArg"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodBooleanArg",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> boolArgHandle = v8::Boolean::New(GetIsolate(), boolArg);
v8::Local<v8::Value> argv[] = { boolArgHandle };
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
1,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
v8::Maybe<void> V8TestCallbackInterface::voidMethodSequenceArg(ScriptWrappable* callback_this_value, const HeapVector<Member<TestInterfaceEmpty>>& sequenceArg) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodSequenceArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodSequenceArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "voidMethodSequenceArg"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodSequenceArg",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> sequenceArgHandle = ToV8(sequenceArg, argument_creation_context, GetIsolate());
v8::Local<v8::Value> argv[] = { sequenceArgHandle };
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
1,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
v8::Maybe<void> V8TestCallbackInterface::voidMethodFloatArg(ScriptWrappable* callback_this_value, float floatArg) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodFloatArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodFloatArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "voidMethodFloatArg"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodFloatArg",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> floatArgHandle = v8::Number::New(GetIsolate(), floatArg);
v8::Local<v8::Value> argv[] = { floatArgHandle };
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
1,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
v8::Maybe<void> V8TestCallbackInterface::voidMethodTestInterfaceEmptyArg(ScriptWrappable* callback_this_value, TestInterfaceEmpty* testInterfaceEmptyArg) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodTestInterfaceEmptyArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodTestInterfaceEmptyArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "voidMethodTestInterfaceEmptyArg"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodTestInterfaceEmptyArg",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> testInterfaceEmptyArgHandle = ToV8(testInterfaceEmptyArg, argument_creation_context, GetIsolate());
v8::Local<v8::Value> argv[] = { testInterfaceEmptyArgHandle };
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
1,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
v8::Maybe<void> V8TestCallbackInterface::voidMethodTestInterfaceEmptyStringArg(ScriptWrappable* callback_this_value, TestInterfaceEmpty* testInterfaceEmptyArg, const String& stringArg) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodTestInterfaceEmptyStringArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodTestInterfaceEmptyStringArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "voidMethodTestInterfaceEmptyStringArg"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"voidMethodTestInterfaceEmptyStringArg",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> testInterfaceEmptyArgHandle = ToV8(testInterfaceEmptyArg, argument_creation_context, GetIsolate());
v8::Local<v8::Value> stringArgHandle = V8String(GetIsolate(), stringArg);
v8::Local<v8::Value> argv[] = { testInterfaceEmptyArgHandle, stringArgHandle };
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
2,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
v8::Maybe<void> V8TestCallbackInterface::callbackWithThisValueVoidMethodStringArg(ScriptWrappable* callback_this_value, const String& stringArg) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"callbackWithThisValueVoidMethodStringArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"callbackWithThisValueVoidMethodStringArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "callbackWithThisValueVoidMethodStringArg"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"callbackWithThisValueVoidMethodStringArg",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> stringArgHandle = V8String(GetIsolate(), stringArg);
v8::Local<v8::Value> argv[] = { stringArgHandle };
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
1,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
v8::Maybe<void> V8TestCallbackInterface::customVoidMethodTestInterfaceEmptyArg(ScriptWrappable* callback_this_value, TestInterfaceEmpty* testInterfaceEmptyArg) {
// This function implements "call a user object's operation".
// https://heycam.github.io/webidl/#call-a-user-objects-operation
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackObject().IsEmpty());
v8::Context::Scope context_scope(CallbackObject()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"customVoidMethodTestInterfaceEmptyArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 7. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 8. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"customVoidMethodTestInterfaceEmptyArg",
"TestCallbackInterface",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Function> function;
if (IsCallbackObjectCallable()) {
// step 9.1. If value's interface is a single operation callback interface
// and !IsCallable(O) is true, then set X to O.
function = CallbackObject().As<v8::Function>();
} else {
// step 9.2.1. Let getResult be Get(O, opName).
// step 9.2.2. If getResult is an abrupt completion, set completion to
// getResult and jump to the step labeled return.
v8::Local<v8::Value> value;
if (!CallbackObject()->Get(CallbackRelevantScriptState()->GetContext(),
V8String(GetIsolate(), "customVoidMethodTestInterfaceEmptyArg"))
.ToLocal(&value)) {
return v8::Nothing<void>();
}
// step 10. If !IsCallable(X) is false, then set completion to a new
// Completion{[[Type]]: throw, [[Value]]: a newly created TypeError
// object, [[Target]]: empty}, and jump to the step labeled return.
if (!value->IsFunction()) {
V8ThrowException::ThrowTypeError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"customVoidMethodTestInterfaceEmptyArg",
"TestCallbackInterface",
"The provided callback is not callable."));
return v8::Nothing<void>();
}
function = value.As<v8::Function>();
}
v8::Local<v8::Value> this_arg;
if (!IsCallbackObjectCallable()) {
// step 11. If value's interface is not a single operation callback
// interface, or if !IsCallable(O) is false, set thisArg to O (overriding
// the provided value).
this_arg = CallbackObject();
} else if (!callback_this_value) {
// step 2. If thisArg was not given, let thisArg be undefined.
this_arg = v8::Undefined(GetIsolate());
} else {
this_arg = ToV8(callback_this_value, CallbackRelevantScriptState());
}
// step 12. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> testInterfaceEmptyArgHandle = ToV8(testInterfaceEmptyArg, argument_creation_context, GetIsolate());
v8::Local<v8::Value> argv[] = { testInterfaceEmptyArgHandle };
// step 13. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
function,
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
1,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 14. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 15. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::voidMethod(ScriptWrappable* callback_this_value) {
return Proxy()->voidMethod(
callback_this_value);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<bool> V8PersistentCallbackInterface<V8TestCallbackInterface>::booleanMethod(ScriptWrappable* callback_this_value) {
return Proxy()->booleanMethod(
callback_this_value);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::voidMethodBooleanArg(ScriptWrappable* callback_this_value, bool boolArg) {
return Proxy()->voidMethodBooleanArg(
callback_this_value, boolArg);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::voidMethodSequenceArg(ScriptWrappable* callback_this_value, const HeapVector<Member<TestInterfaceEmpty>>& sequenceArg) {
return Proxy()->voidMethodSequenceArg(
callback_this_value, sequenceArg);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::voidMethodFloatArg(ScriptWrappable* callback_this_value, float floatArg) {
return Proxy()->voidMethodFloatArg(
callback_this_value, floatArg);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::voidMethodTestInterfaceEmptyArg(ScriptWrappable* callback_this_value, TestInterfaceEmpty* testInterfaceEmptyArg) {
return Proxy()->voidMethodTestInterfaceEmptyArg(
callback_this_value, testInterfaceEmptyArg);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::voidMethodTestInterfaceEmptyStringArg(ScriptWrappable* callback_this_value, TestInterfaceEmpty* testInterfaceEmptyArg, const String& stringArg) {
return Proxy()->voidMethodTestInterfaceEmptyStringArg(
callback_this_value, testInterfaceEmptyArg, stringArg);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::callbackWithThisValueVoidMethodStringArg(ScriptWrappable* callback_this_value, const String& stringArg) {
return Proxy()->callbackWithThisValueVoidMethodStringArg(
callback_this_value, stringArg);
}
CORE_EXTERN_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackInterface<V8TestCallbackInterface>::customVoidMethodTestInterfaceEmptyArg(ScriptWrappable* callback_this_value, TestInterfaceEmpty* testInterfaceEmptyArg) {
return Proxy()->customVoidMethodTestInterfaceEmptyArg(
callback_this_value, testInterfaceEmptyArg);
}
} // namespace blink
| 43.290995 | 217 | 0.684993 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.