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
f507f679e8f2a808d119076c248d881ef5972cda
2,546
cpp
C++
src/MSMTRX.cpp
aptrn/aP-Modules
5c9524936dfdfe9ae5af261519b89b906a3bd148
[ "BSD-3-Clause" ]
13
2018-09-22T06:30:00.000Z
2022-03-03T20:52:24.000Z
src/MSMTRX.cpp
aptrn/aP-Modules
5c9524936dfdfe9ae5af261519b89b906a3bd148
[ "BSD-3-Clause" ]
4
2018-09-06T09:49:27.000Z
2018-11-11T09:59:48.000Z
src/MSMTRX.cpp
aptrn/aP-Modules
5c9524936dfdfe9ae5af261519b89b906a3bd148
[ "BSD-3-Clause" ]
2
2018-10-22T19:16:40.000Z
2019-09-02T22:40:19.000Z
#include "aP.hpp" //Mid/Side Matrix, simple LR to MS encoder and MS to LR decoder struct MSMTRX : Module { enum ParamIds { NUM_PARAMS }; enum InputIds { LEFT_INPUT, RIGHT_INPUT, MID_INPUT, SIDE_INPUT, NUM_INPUTS }; enum OutputIds { LEFT_OUTPUT, RIGHT_OUTPUT, MID_OUTPUT, SIDE_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; MSMTRX() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);} void process(const ProcessArgs &args) override; }; void MSMTRX::process(const ProcessArgs &args) { //ENCODER float left_in = inputs[LEFT_INPUT].getVoltage(); float right_in = inputs[RIGHT_INPUT].getVoltage(); float mid_out = (left_in + right_in)/sqrt(2); float side_out = (left_in - right_in)/sqrt(2); outputs[MID_OUTPUT].value = mid_out; outputs[SIDE_OUTPUT].value = side_out; //DECODER float mid_in = inputs[MID_INPUT].getVoltage(); float side_in = inputs[SIDE_INPUT].getVoltage(); float left_out = (mid_in + side_in)/sqrt(2); float right_out = (mid_in - side_in)/sqrt(2); outputs[LEFT_OUTPUT].value = left_out; outputs[RIGHT_OUTPUT].setVoltage(right_out); } struct MSMTRXWidget : ModuleWidget { MSMTRXWidget(MSMTRX *module) : ModuleWidget(module) { setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/MSMTRX.svg"))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); //ENCODER addInput(createInput<aPJackGiallo>(Vec(16.7, 113.2), module, MSMTRX::LEFT_INPUT)); addInput(createInput<aPJackArancione>(Vec(79.7, 113.2), module, MSMTRX::RIGHT_INPUT)); addOutput(createOutput<aPJackTurchese>(Vec(16.7, 167.2), module, MSMTRX::MID_OUTPUT)); addOutput(createOutput<aPJackBlu>(Vec(79.7, 167.2), module, MSMTRX::SIDE_OUTPUT)); //DECODER addInput(createInput<aPJackTurchese>(Vec(16.7, 247.9), module, MSMTRX::MID_INPUT)); addInput(createInput<aPJackBlu>(Vec(79.7, 247.9), module, MSMTRX::SIDE_INPUT)); addOutput(createOutput<aPJackVerde>(Vec(16.7, 305), module, MSMTRX::LEFT_OUTPUT)); addOutput(createOutput<aPJackRosso>(Vec(79.7, 305), module, MSMTRX::RIGHT_OUTPUT)); } }; Model *modelMSMTRX = createModel<MSMTRX, MSMTRXWidget>("MS-Matrix");
29.264368
114
0.705027
[ "model" ]
f50d65bf0f29d0614cd0b1db2aa99d48f1bb645f
36,236
cpp
C++
src/core/core/dsn.layer2_types.cpp
0xflotus/rdsn
f2beaded488cd40ace25b32c320e143d60b2c04e
[ "MIT" ]
null
null
null
src/core/core/dsn.layer2_types.cpp
0xflotus/rdsn
f2beaded488cd40ace25b32c320e143d60b2c04e
[ "MIT" ]
null
null
null
src/core/core/dsn.layer2_types.cpp
0xflotus/rdsn
f2beaded488cd40ace25b32c320e143d60b2c04e
[ "MIT" ]
null
null
null
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include <dsn/cpp/serialization_helper/dsn.layer2_types.h> #include <algorithm> #include <ostream> #include <thrift/TToString.h> namespace dsn { int _kapp_statusValues[] = {app_status::AS_INVALID, app_status::AS_AVAILABLE, app_status::AS_CREATING, app_status::AS_CREATE_FAILED, app_status::AS_DROPPING, app_status::AS_DROP_FAILED, app_status::AS_DROPPED, app_status::AS_RECALLING}; const char *_kapp_statusNames[] = {"AS_INVALID", "AS_AVAILABLE", "AS_CREATING", "AS_CREATE_FAILED", "AS_DROPPING", "AS_DROP_FAILED", "AS_DROPPED", "AS_RECALLING"}; const std::map<int, const char *> _app_status_VALUES_TO_NAMES( ::apache::thrift::TEnumIterator(8, _kapp_statusValues, _kapp_statusNames), ::apache::thrift::TEnumIterator(-1, NULL, NULL)); partition_configuration::~partition_configuration() throw() {} void partition_configuration::__set_pid(const ::dsn::gpid &val) { this->pid = val; } void partition_configuration::__set_ballot(const int64_t val) { this->ballot = val; } void partition_configuration::__set_max_replica_count(const int32_t val) { this->max_replica_count = val; } void partition_configuration::__set_primary(const ::dsn::rpc_address &val) { this->primary = val; } void partition_configuration::__set_secondaries(const std::vector<::dsn::rpc_address> &val) { this->secondaries = val; } void partition_configuration::__set_last_drops(const std::vector<::dsn::rpc_address> &val) { this->last_drops = val; } void partition_configuration::__set_last_committed_decree(const int64_t val) { this->last_committed_decree = val; } void partition_configuration::__set_partition_flags(const int32_t val) { this->partition_flags = val; } uint32_t partition_configuration::read(::apache::thrift::protocol::TProtocol *iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->pid.read(iprot); this->__isset.pid = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->ballot); this->__isset.ballot = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->max_replica_count); this->__isset.max_replica_count = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->primary.read(iprot); this->__isset.primary = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->secondaries.clear(); uint32_t _size0; ::apache::thrift::protocol::TType _etype3; xfer += iprot->readListBegin(_etype3, _size0); this->secondaries.resize(_size0); uint32_t _i4; for (_i4 = 0; _i4 < _size0; ++_i4) { xfer += this->secondaries[_i4].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.secondaries = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->last_drops.clear(); uint32_t _size5; ::apache::thrift::protocol::TType _etype8; xfer += iprot->readListBegin(_etype8, _size5); this->last_drops.resize(_size5); uint32_t _i9; for (_i9 = 0; _i9 < _size5; ++_i9) { xfer += this->last_drops[_i9].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.last_drops = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->last_committed_decree); this->__isset.last_committed_decree = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->partition_flags); this->__isset.partition_flags = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t partition_configuration::write(::apache::thrift::protocol::TProtocol *oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("partition_configuration"); xfer += oprot->writeFieldBegin("pid", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->pid.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("ballot", ::apache::thrift::protocol::T_I64, 2); xfer += oprot->writeI64(this->ballot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("max_replica_count", ::apache::thrift::protocol::T_I32, 3); xfer += oprot->writeI32(this->max_replica_count); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("primary", ::apache::thrift::protocol::T_STRUCT, 4); xfer += this->primary.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("secondaries", ::apache::thrift::protocol::T_LIST, 5); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->secondaries.size())); std::vector<::dsn::rpc_address>::const_iterator _iter10; for (_iter10 = this->secondaries.begin(); _iter10 != this->secondaries.end(); ++_iter10) { xfer += (*_iter10).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("last_drops", ::apache::thrift::protocol::T_LIST, 6); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->last_drops.size())); std::vector<::dsn::rpc_address>::const_iterator _iter11; for (_iter11 = this->last_drops.begin(); _iter11 != this->last_drops.end(); ++_iter11) { xfer += (*_iter11).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("last_committed_decree", ::apache::thrift::protocol::T_I64, 7); xfer += oprot->writeI64(this->last_committed_decree); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("partition_flags", ::apache::thrift::protocol::T_I32, 8); xfer += oprot->writeI32(this->partition_flags); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(partition_configuration &a, partition_configuration &b) { using ::std::swap; swap(a.pid, b.pid); swap(a.ballot, b.ballot); swap(a.max_replica_count, b.max_replica_count); swap(a.primary, b.primary); swap(a.secondaries, b.secondaries); swap(a.last_drops, b.last_drops); swap(a.last_committed_decree, b.last_committed_decree); swap(a.partition_flags, b.partition_flags); swap(a.__isset, b.__isset); } partition_configuration::partition_configuration(const partition_configuration &other12) { pid = other12.pid; ballot = other12.ballot; max_replica_count = other12.max_replica_count; primary = other12.primary; secondaries = other12.secondaries; last_drops = other12.last_drops; last_committed_decree = other12.last_committed_decree; partition_flags = other12.partition_flags; __isset = other12.__isset; } partition_configuration::partition_configuration(partition_configuration &&other13) { pid = std::move(other13.pid); ballot = std::move(other13.ballot); max_replica_count = std::move(other13.max_replica_count); primary = std::move(other13.primary); secondaries = std::move(other13.secondaries); last_drops = std::move(other13.last_drops); last_committed_decree = std::move(other13.last_committed_decree); partition_flags = std::move(other13.partition_flags); __isset = std::move(other13.__isset); } partition_configuration &partition_configuration::operator=(const partition_configuration &other14) { pid = other14.pid; ballot = other14.ballot; max_replica_count = other14.max_replica_count; primary = other14.primary; secondaries = other14.secondaries; last_drops = other14.last_drops; last_committed_decree = other14.last_committed_decree; partition_flags = other14.partition_flags; __isset = other14.__isset; return *this; } partition_configuration &partition_configuration::operator=(partition_configuration &&other15) { pid = std::move(other15.pid); ballot = std::move(other15.ballot); max_replica_count = std::move(other15.max_replica_count); primary = std::move(other15.primary); secondaries = std::move(other15.secondaries); last_drops = std::move(other15.last_drops); last_committed_decree = std::move(other15.last_committed_decree); partition_flags = std::move(other15.partition_flags); __isset = std::move(other15.__isset); return *this; } void partition_configuration::printTo(std::ostream &out) const { using ::apache::thrift::to_string; out << "partition_configuration("; out << "pid=" << to_string(pid); out << ", " << "ballot=" << to_string(ballot); out << ", " << "max_replica_count=" << to_string(max_replica_count); out << ", " << "primary=" << to_string(primary); out << ", " << "secondaries=" << to_string(secondaries); out << ", " << "last_drops=" << to_string(last_drops); out << ", " << "last_committed_decree=" << to_string(last_committed_decree); out << ", " << "partition_flags=" << to_string(partition_flags); out << ")"; } configuration_query_by_index_request::~configuration_query_by_index_request() throw() {} void configuration_query_by_index_request::__set_app_name(const std::string &val) { this->app_name = val; } void configuration_query_by_index_request::__set_partition_indices(const std::vector<int32_t> &val) { this->partition_indices = val; } uint32_t configuration_query_by_index_request::read(::apache::thrift::protocol::TProtocol *iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->app_name); this->__isset.app_name = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->partition_indices.clear(); uint32_t _size16; ::apache::thrift::protocol::TType _etype19; xfer += iprot->readListBegin(_etype19, _size16); this->partition_indices.resize(_size16); uint32_t _i20; for (_i20 = 0; _i20 < _size16; ++_i20) { xfer += iprot->readI32(this->partition_indices[_i20]); } xfer += iprot->readListEnd(); } this->__isset.partition_indices = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t configuration_query_by_index_request::write(::apache::thrift::protocol::TProtocol *oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("configuration_query_by_index_request"); xfer += oprot->writeFieldBegin("app_name", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->app_name); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("partition_indices", ::apache::thrift::protocol::T_LIST, 2); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_I32, static_cast<uint32_t>(this->partition_indices.size())); std::vector<int32_t>::const_iterator _iter21; for (_iter21 = this->partition_indices.begin(); _iter21 != this->partition_indices.end(); ++_iter21) { xfer += oprot->writeI32((*_iter21)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(configuration_query_by_index_request &a, configuration_query_by_index_request &b) { using ::std::swap; swap(a.app_name, b.app_name); swap(a.partition_indices, b.partition_indices); swap(a.__isset, b.__isset); } configuration_query_by_index_request::configuration_query_by_index_request( const configuration_query_by_index_request &other22) { app_name = other22.app_name; partition_indices = other22.partition_indices; __isset = other22.__isset; } configuration_query_by_index_request::configuration_query_by_index_request( configuration_query_by_index_request &&other23) { app_name = std::move(other23.app_name); partition_indices = std::move(other23.partition_indices); __isset = std::move(other23.__isset); } configuration_query_by_index_request &configuration_query_by_index_request:: operator=(const configuration_query_by_index_request &other24) { app_name = other24.app_name; partition_indices = other24.partition_indices; __isset = other24.__isset; return *this; } configuration_query_by_index_request &configuration_query_by_index_request:: operator=(configuration_query_by_index_request &&other25) { app_name = std::move(other25.app_name); partition_indices = std::move(other25.partition_indices); __isset = std::move(other25.__isset); return *this; } void configuration_query_by_index_request::printTo(std::ostream &out) const { using ::apache::thrift::to_string; out << "configuration_query_by_index_request("; out << "app_name=" << to_string(app_name); out << ", " << "partition_indices=" << to_string(partition_indices); out << ")"; } configuration_query_by_index_response::~configuration_query_by_index_response() throw() {} void configuration_query_by_index_response::__set_err(const ::dsn::error_code &val) { this->err = val; } void configuration_query_by_index_response::__set_app_id(const int32_t val) { this->app_id = val; } void configuration_query_by_index_response::__set_partition_count(const int32_t val) { this->partition_count = val; } void configuration_query_by_index_response::__set_is_stateful(const bool val) { this->is_stateful = val; } void configuration_query_by_index_response::__set_partitions( const std::vector<partition_configuration> &val) { this->partitions = val; } uint32_t configuration_query_by_index_response::read(::apache::thrift::protocol::TProtocol *iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->err.read(iprot); this->__isset.err = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->app_id); this->__isset.app_id = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->partition_count); this->__isset.partition_count = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->is_stateful); this->__isset.is_stateful = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->partitions.clear(); uint32_t _size26; ::apache::thrift::protocol::TType _etype29; xfer += iprot->readListBegin(_etype29, _size26); this->partitions.resize(_size26); uint32_t _i30; for (_i30 = 0; _i30 < _size26; ++_i30) { xfer += this->partitions[_i30].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.partitions = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t configuration_query_by_index_response::write(::apache::thrift::protocol::TProtocol *oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("configuration_query_by_index_response"); xfer += oprot->writeFieldBegin("err", ::apache::thrift::protocol::T_STRUCT, 1); xfer += this->err.write(oprot); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("app_id", ::apache::thrift::protocol::T_I32, 2); xfer += oprot->writeI32(this->app_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("partition_count", ::apache::thrift::protocol::T_I32, 3); xfer += oprot->writeI32(this->partition_count); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("is_stateful", ::apache::thrift::protocol::T_BOOL, 4); xfer += oprot->writeBool(this->is_stateful); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("partitions", ::apache::thrift::protocol::T_LIST, 5); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->partitions.size())); std::vector<partition_configuration>::const_iterator _iter31; for (_iter31 = this->partitions.begin(); _iter31 != this->partitions.end(); ++_iter31) { xfer += (*_iter31).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(configuration_query_by_index_response &a, configuration_query_by_index_response &b) { using ::std::swap; swap(a.err, b.err); swap(a.app_id, b.app_id); swap(a.partition_count, b.partition_count); swap(a.is_stateful, b.is_stateful); swap(a.partitions, b.partitions); swap(a.__isset, b.__isset); } configuration_query_by_index_response::configuration_query_by_index_response( const configuration_query_by_index_response &other32) { err = other32.err; app_id = other32.app_id; partition_count = other32.partition_count; is_stateful = other32.is_stateful; partitions = other32.partitions; __isset = other32.__isset; } configuration_query_by_index_response::configuration_query_by_index_response( configuration_query_by_index_response &&other33) { err = std::move(other33.err); app_id = std::move(other33.app_id); partition_count = std::move(other33.partition_count); is_stateful = std::move(other33.is_stateful); partitions = std::move(other33.partitions); __isset = std::move(other33.__isset); } configuration_query_by_index_response &configuration_query_by_index_response:: operator=(const configuration_query_by_index_response &other34) { err = other34.err; app_id = other34.app_id; partition_count = other34.partition_count; is_stateful = other34.is_stateful; partitions = other34.partitions; __isset = other34.__isset; return *this; } configuration_query_by_index_response &configuration_query_by_index_response:: operator=(configuration_query_by_index_response &&other35) { err = std::move(other35.err); app_id = std::move(other35.app_id); partition_count = std::move(other35.partition_count); is_stateful = std::move(other35.is_stateful); partitions = std::move(other35.partitions); __isset = std::move(other35.__isset); return *this; } void configuration_query_by_index_response::printTo(std::ostream &out) const { using ::apache::thrift::to_string; out << "configuration_query_by_index_response("; out << "err=" << to_string(err); out << ", " << "app_id=" << to_string(app_id); out << ", " << "partition_count=" << to_string(partition_count); out << ", " << "is_stateful=" << to_string(is_stateful); out << ", " << "partitions=" << to_string(partitions); out << ")"; } app_info::~app_info() throw() {} void app_info::__set_status(const app_status::type val) { this->status = val; } void app_info::__set_app_type(const std::string &val) { this->app_type = val; } void app_info::__set_app_name(const std::string &val) { this->app_name = val; } void app_info::__set_app_id(const int32_t val) { this->app_id = val; } void app_info::__set_partition_count(const int32_t val) { this->partition_count = val; } void app_info::__set_envs(const std::map<std::string, std::string> &val) { this->envs = val; } void app_info::__set_is_stateful(const bool val) { this->is_stateful = val; } void app_info::__set_max_replica_count(const int32_t val) { this->max_replica_count = val; } void app_info::__set_expire_second(const int64_t val) { this->expire_second = val; } void app_info::__set_create_second(const int64_t val) { this->create_second = val; } void app_info::__set_drop_second(const int64_t val) { this->drop_second = val; } uint32_t app_info::read(::apache::thrift::protocol::TProtocol *iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast36; xfer += iprot->readI32(ecast36); this->status = (app_status::type)ecast36; this->__isset.status = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->app_type); this->__isset.app_type = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->app_name); this->__isset.app_name = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->app_id); this->__isset.app_id = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->partition_count); this->__isset.partition_count = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_MAP) { { this->envs.clear(); uint32_t _size37; ::apache::thrift::protocol::TType _ktype38; ::apache::thrift::protocol::TType _vtype39; xfer += iprot->readMapBegin(_ktype38, _vtype39, _size37); uint32_t _i41; for (_i41 = 0; _i41 < _size37; ++_i41) { std::string _key42; xfer += iprot->readString(_key42); std::string &_val43 = this->envs[_key42]; xfer += iprot->readString(_val43); } xfer += iprot->readMapEnd(); } this->__isset.envs = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->is_stateful); this->__isset.is_stateful = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->max_replica_count); this->__isset.max_replica_count = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->expire_second); this->__isset.expire_second = true; } else { xfer += iprot->skip(ftype); } break; case 10: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->create_second); this->__isset.create_second = true; } else { xfer += iprot->skip(ftype); } break; case 11: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->drop_second); this->__isset.drop_second = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); return xfer; } uint32_t app_info::write(::apache::thrift::protocol::TProtocol *oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("app_info"); xfer += oprot->writeFieldBegin("status", ::apache::thrift::protocol::T_I32, 1); xfer += oprot->writeI32((int32_t)this->status); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("app_type", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->app_type); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("app_name", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->app_name); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("app_id", ::apache::thrift::protocol::T_I32, 4); xfer += oprot->writeI32(this->app_id); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("partition_count", ::apache::thrift::protocol::T_I32, 5); xfer += oprot->writeI32(this->partition_count); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("envs", ::apache::thrift::protocol::T_MAP, 6); { xfer += oprot->writeMapBegin(::apache::thrift::protocol::T_STRING, ::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->envs.size())); std::map<std::string, std::string>::const_iterator _iter44; for (_iter44 = this->envs.begin(); _iter44 != this->envs.end(); ++_iter44) { xfer += oprot->writeString(_iter44->first); xfer += oprot->writeString(_iter44->second); } xfer += oprot->writeMapEnd(); } xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("is_stateful", ::apache::thrift::protocol::T_BOOL, 7); xfer += oprot->writeBool(this->is_stateful); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("max_replica_count", ::apache::thrift::protocol::T_I32, 8); xfer += oprot->writeI32(this->max_replica_count); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("expire_second", ::apache::thrift::protocol::T_I64, 9); xfer += oprot->writeI64(this->expire_second); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("create_second", ::apache::thrift::protocol::T_I64, 10); xfer += oprot->writeI64(this->create_second); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("drop_second", ::apache::thrift::protocol::T_I64, 11); xfer += oprot->writeI64(this->drop_second); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(app_info &a, app_info &b) { using ::std::swap; swap(a.status, b.status); swap(a.app_type, b.app_type); swap(a.app_name, b.app_name); swap(a.app_id, b.app_id); swap(a.partition_count, b.partition_count); swap(a.envs, b.envs); swap(a.is_stateful, b.is_stateful); swap(a.max_replica_count, b.max_replica_count); swap(a.expire_second, b.expire_second); swap(a.create_second, b.create_second); swap(a.drop_second, b.drop_second); swap(a.__isset, b.__isset); } app_info::app_info(const app_info &other45) { status = other45.status; app_type = other45.app_type; app_name = other45.app_name; app_id = other45.app_id; partition_count = other45.partition_count; envs = other45.envs; is_stateful = other45.is_stateful; max_replica_count = other45.max_replica_count; expire_second = other45.expire_second; create_second = other45.create_second; drop_second = other45.drop_second; __isset = other45.__isset; } app_info::app_info(app_info &&other46) { status = std::move(other46.status); app_type = std::move(other46.app_type); app_name = std::move(other46.app_name); app_id = std::move(other46.app_id); partition_count = std::move(other46.partition_count); envs = std::move(other46.envs); is_stateful = std::move(other46.is_stateful); max_replica_count = std::move(other46.max_replica_count); expire_second = std::move(other46.expire_second); create_second = std::move(other46.create_second); drop_second = std::move(other46.drop_second); __isset = std::move(other46.__isset); } app_info &app_info::operator=(const app_info &other47) { status = other47.status; app_type = other47.app_type; app_name = other47.app_name; app_id = other47.app_id; partition_count = other47.partition_count; envs = other47.envs; is_stateful = other47.is_stateful; max_replica_count = other47.max_replica_count; expire_second = other47.expire_second; create_second = other47.create_second; drop_second = other47.drop_second; __isset = other47.__isset; return *this; } app_info &app_info::operator=(app_info &&other48) { status = std::move(other48.status); app_type = std::move(other48.app_type); app_name = std::move(other48.app_name); app_id = std::move(other48.app_id); partition_count = std::move(other48.partition_count); envs = std::move(other48.envs); is_stateful = std::move(other48.is_stateful); max_replica_count = std::move(other48.max_replica_count); expire_second = std::move(other48.expire_second); create_second = std::move(other48.create_second); drop_second = std::move(other48.drop_second); __isset = std::move(other48.__isset); return *this; } void app_info::printTo(std::ostream &out) const { using ::apache::thrift::to_string; out << "app_info("; out << "status=" << to_string(status); out << ", " << "app_type=" << to_string(app_type); out << ", " << "app_name=" << to_string(app_name); out << ", " << "app_id=" << to_string(app_id); out << ", " << "partition_count=" << to_string(partition_count); out << ", " << "envs=" << to_string(envs); out << ", " << "is_stateful=" << to_string(is_stateful); out << ", " << "max_replica_count=" << to_string(max_replica_count); out << ", " << "expire_second=" << to_string(expire_second); out << ", " << "create_second=" << to_string(create_second); out << ", " << "drop_second=" << to_string(drop_second); out << ")"; } } // namespace
35.317739
99
0.594961
[ "vector" ]
f50d7b52e3d634937f17d0a5fbe25a44d698fe7c
12,650
cpp
C++
Extensions/TextObject/Dialogs/TextObjectDialogs.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
1
2019-08-24T03:18:42.000Z
2019-08-24T03:18:42.000Z
Extensions/TextObject/Dialogs/TextObjectDialogs.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
9
2020-04-04T19:26:47.000Z
2022-03-25T18:41:20.000Z
Extensions/TextObject/Dialogs/TextObjectDialogs.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
2
2020-03-02T05:20:41.000Z
2021-05-10T03:59:05.000Z
////////////////////////////////////////////////////////////////////// // This file was auto-generated by codelite's wxCrafter Plugin // wxCrafter project file: TextObjectEditor.wxcp // Do not modify this file by hand! ////////////////////////////////////////////////////////////////////// #include "TextObjectDialogs.h" // Declare the bitmap loading function extern void wxC9DFDInitBitmapResources(); static bool bBitmapLoaded = false; TextObjectEditorBase::TextObjectEditorBase(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) { if (!bBitmapLoaded) { // We need to initialise the default bitmap handler wxXmlResource::Get()->AddHandler(new wxBitmapXmlHandler); wxC9DFDInitBitmapResources(); bBitmapLoaded = true; } m_auimgr = new wxAuiManager; m_auimgr->SetManagedWindow(this); m_auimgr->SetFlags(wxAUI_MGR_LIVE_RESIZE | wxAUI_MGR_TRANSPARENT_HINT | wxAUI_MGR_TRANSPARENT_DRAG); m_auimgr->GetArtProvider()->SetMetric(wxAUI_DOCKART_GRADIENT_TYPE, wxAUI_GRADIENT_NONE); m_toolbar = new wxAuiToolBar(this, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_HORZ_TEXT | wxAUI_TB_HORZ_LAYOUT | wxAUI_TB_NO_AUTORESIZE); m_toolbar->SetToolBitmapSize(wxSize(16, 16)); m_auimgr->AddPane(m_toolbar, wxAuiPaneInfo() .Direction(wxAUI_DOCK_TOP) .Layer(0) .Row(0) .Position(0) .BestSize(100, 30) .MinSize(100, 20) .MaxSize(-1, 50) .Fixed() .CaptionVisible(false) .MaximizeButton(false) .CloseButton(false) .MinimizeButton(false) .PinButton(false)); m_fontTextCtrl = new wxTextCtrl( m_toolbar, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(150, -1), 0); m_fontTextCtrl->SetToolTip( _("The font used by the text object.\nIf empty, uses the default font " "provided with GDevelop (Liberation)")); #if wxVERSION_NUMBER >= 3000 m_fontTextCtrl->SetHint(_("Default font")); #endif m_toolbar->AddControl(m_fontTextCtrl); m_toolbar->AddTool(CHANGE_FONT_BUTTON, wxT(""), wxXmlResource::Get()->LoadBitmap(wxT("open16")), wxNullBitmap, wxITEM_NORMAL, _("Change the font file"), wxT(""), NULL); m_toolbar->AddSeparator(); wxArrayString m_sizeComboboxArr; m_sizeComboboxArr.Add(wxT("8")); m_sizeComboboxArr.Add(wxT("10")); m_sizeComboboxArr.Add(wxT("12")); m_sizeComboboxArr.Add(wxT("14")); m_sizeComboboxArr.Add(wxT("16")); m_sizeComboboxArr.Add(wxT("18")); m_sizeComboboxArr.Add(wxT("20")); m_sizeComboboxArr.Add(wxT("24")); m_sizeComboboxArr.Add(wxT("28")); m_sizeComboboxArr.Add(wxT("32")); m_sizeComboboxArr.Add(wxT("48")); m_sizeComboboxArr.Add(wxT("72")); m_sizeComboboxArr.Add(wxT("100")); m_sizeCombobox = new wxComboBox(m_toolbar, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(-1, -1), m_sizeComboboxArr, 0); #if wxVERSION_NUMBER >= 3000 m_sizeCombobox->SetHint(wxT("")); #endif m_sizeCombobox->SetSelection(6); m_toolbar->AddControl(m_sizeCombobox); m_toolbar->AddTool(COLOR_TOOL_ID, _("Color..."), wxXmlResource::Get()->LoadBitmap(wxT("error")), wxNullBitmap, wxITEM_NORMAL, _("Change the text color..."), wxT(""), NULL); m_toolbar->AddSeparator(); m_toolbar->AddTool(BOLD_TOOL_ID, wxT(""), wxXmlResource::Get()->LoadBitmap(wxT("bold16")), wxNullBitmap, wxITEM_CHECK, _("Bold"), _("Bold"), NULL); m_toolbar->AddTool(ITALIC_TOOL_ID, wxT(""), wxXmlResource::Get()->LoadBitmap(wxT("italic16")), wxNullBitmap, wxITEM_CHECK, _("Italic"), _("Italic"), NULL); m_toolbar->AddTool(UNDER_TOOL_ID, wxT(""), wxXmlResource::Get()->LoadBitmap(wxT("underline16")), wxNullBitmap, wxITEM_CHECK, _("Underline"), _("Underline"), NULL); m_toolbar->Realize(); m_centerPanel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL); m_auimgr->AddPane(m_centerPanel, wxAuiPaneInfo() .Direction(wxAUI_DOCK_CENTER) .Layer(0) .Row(0) .Position(0) .BestSize(480, 350) .MinSize(480, 250) .MaxSize(1000, 800) .Fixed() .CaptionVisible(false) .MaximizeButton(false) .CloseButton(false) .MinimizeButton(false) .PinButton(false)); m_auimgr->Update(); wxFlexGridSizer* flexGridSizer36 = new wxFlexGridSizer(0, 1, 0, 0); flexGridSizer36->SetFlexibleDirection(wxBOTH); flexGridSizer36->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); flexGridSizer36->AddGrowableCol(0); flexGridSizer36->AddGrowableRow(0); m_centerPanel->SetSizer(flexGridSizer36); m_textCtrl = new wxTextCtrl(m_centerPanel, wxID_ANY, wxT(""), wxDefaultPosition, wxSize(-1, -1), wxTE_MULTILINE | wxTE_DONTWRAP); flexGridSizer36->Add(m_textCtrl, 0, wxALL | wxEXPAND, 0); m_staticText62 = new wxStaticText(m_centerPanel, wxID_ANY, _("Note : the font can't be previewed."), wxDefaultPosition, wxSize(-1, -1), 0); wxFont m_staticText62Font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); m_staticText62Font.SetStyle(wxFONTSTYLE_ITALIC); m_staticText62->SetFont(m_staticText62Font); flexGridSizer36->Add(m_staticText62, 0, wxALL, 5); wxFlexGridSizer* flexGridSizer76 = new wxFlexGridSizer(0, 3, 0, 0); flexGridSizer76->SetFlexibleDirection(wxBOTH); flexGridSizer76->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); flexGridSizer76->AddGrowableCol(1); flexGridSizer76->AddGrowableRow(0); flexGridSizer36->Add(flexGridSizer76, 1, wxALL | wxEXPAND, 0); m_staticBitmap80 = new wxStaticBitmap(m_centerPanel, wxID_ANY, wxXmlResource::Get()->LoadBitmap(wxT("help16")), wxDefaultPosition, wxSize(-1, -1), 0); flexGridSizer76->Add( m_staticBitmap80, 0, wxALL | wxALIGN_CENTER | wxALIGN_CENTER_VERTICAL, 5); m_helpBt = new wxHyperlinkCtrl(m_centerPanel, wxID_ANY, _("Help for this object"), wxT(""), wxDefaultPosition, wxSize(-1, -1), wxHL_DEFAULT_STYLE); m_helpBt->SetNormalColour(wxColour(wxT("#0000FF"))); m_helpBt->SetHoverColour(wxColour(wxT("#0000FF"))); m_helpBt->SetVisitedColour(wxColour(wxT("#FF0000"))); flexGridSizer76->Add(m_helpBt, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_stdBtnSizer40 = new wxStdDialogButtonSizer(); flexGridSizer76->Add(m_stdBtnSizer40, 0, wxALL | wxALIGN_RIGHT, 5); m_okButton = new wxButton( m_centerPanel, wxID_OK, wxT(""), wxDefaultPosition, wxSize(-1, -1), 0); m_stdBtnSizer40->AddButton(m_okButton); m_cancelButton = new wxButton(m_centerPanel, wxID_CANCEL, wxT(""), wxDefaultPosition, wxSize(-1, -1), 0); m_stdBtnSizer40->AddButton(m_cancelButton); m_stdBtnSizer40->Realize(); SetName(wxT("TextObjectEditorBase")); SetMinSize(wxSize(480, 250)); SetSizeHints(-1, -1); if (GetSizer()) { GetSizer()->Fit(this); } CentreOnParent(wxBOTH); // Connect events this->Connect(CHANGE_FONT_BUTTON, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnChangeFontButton), NULL, this); m_sizeCombobox->Connect( wxEVT_COMMAND_COMBOBOX_SELECTED, wxCommandEventHandler( TextObjectEditorBase::OnSizeComboboxSelectionChanged), NULL, this); m_sizeCombobox->Connect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(TextObjectEditorBase::OnSizeComboboxUpdated), NULL, this); this->Connect(COLOR_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnColorToolClicked), NULL, this); this->Connect(BOLD_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnBoldToolClicked), NULL, this); this->Connect( ITALIC_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnItalicToolClicked), NULL, this); this->Connect( UNDER_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnUnderlineToolClicked), NULL, this); m_helpBt->Connect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler(TextObjectEditorBase::OnHelpBtClicked), NULL, this); m_okButton->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnOkBtClicked), NULL, this); } TextObjectEditorBase::~TextObjectEditorBase() { this->Disconnect( CHANGE_FONT_BUTTON, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnChangeFontButton), NULL, this); m_sizeCombobox->Disconnect( wxEVT_COMMAND_COMBOBOX_SELECTED, wxCommandEventHandler( TextObjectEditorBase::OnSizeComboboxSelectionChanged), NULL, this); m_sizeCombobox->Disconnect( wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(TextObjectEditorBase::OnSizeComboboxUpdated), NULL, this); this->Disconnect( COLOR_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnColorToolClicked), NULL, this); this->Disconnect( BOLD_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnBoldToolClicked), NULL, this); this->Disconnect( ITALIC_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnItalicToolClicked), NULL, this); this->Disconnect( UNDER_TOOL_ID, wxEVT_COMMAND_TOOL_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnUnderlineToolClicked), NULL, this); m_helpBt->Disconnect( wxEVT_COMMAND_HYPERLINK, wxHyperlinkEventHandler(TextObjectEditorBase::OnHelpBtClicked), NULL, this); m_okButton->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(TextObjectEditorBase::OnOkBtClicked), NULL, this); m_auimgr->UnInit(); delete m_auimgr; }
35.335196
80
0.553676
[ "object" ]
f5116f3184f22eade44c780edc9ec5649bb8d240
32,570
cpp
C++
sp/src/game/server/hl2/npc_zombie.cpp
atp-tha/source-sdk-2013
8adf94f37107ce9e7a2678d75b91deb51243c8cb
[ "Unlicense" ]
12
2019-03-26T21:15:57.000Z
2022-03-16T14:53:14.000Z
sp/src/game/server/hl2/npc_zombie.cpp
atp-tha/source-sdk-2013
8adf94f37107ce9e7a2678d75b91deb51243c8cb
[ "Unlicense" ]
8
2019-10-07T01:21:13.000Z
2022-03-26T16:53:42.000Z
sp/src/game/server/hl2/npc_zombie.cpp
atp-tha/source-sdk-2013
8adf94f37107ce9e7a2678d75b91deb51243c8cb
[ "Unlicense" ]
4
2019-10-03T14:09:14.000Z
2020-12-30T12:03:38.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: A slow-moving, once-human headcrab victim with only melee attacks. // //=============================================================================// #include "cbase.h" #include "doors.h" #include "simtimer.h" #include "npc_BaseZombie.h" #include "ai_hull.h" #include "ai_navigator.h" #include "ai_memory.h" #include "gib.h" #include "soundenvelope.h" #include "engine/IEngineSound.h" #include "ammodef.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // ACT_FLINCH_PHYSICS ConVar sk_zombie_health( "sk_zombie_health","0"); envelopePoint_t envZombieMoanVolumeFast[] = { { 7.0f, 7.0f, 0.1f, 0.1f, }, { 0.0f, 0.0f, 0.2f, 0.3f, }, }; envelopePoint_t envZombieMoanVolume[] = { { 1.0f, 1.0f, 0.1f, 0.1f, }, { 1.0f, 1.0f, 0.2f, 0.2f, }, { 0.0f, 0.0f, 0.3f, 0.4f, }, }; envelopePoint_t envZombieMoanVolumeLong[] = { { 1.0f, 1.0f, 0.3f, 0.5f, }, { 1.0f, 1.0f, 0.6f, 1.0f, }, { 0.0f, 0.0f, 0.3f, 0.4f, }, }; envelopePoint_t envZombieMoanIgnited[] = { { 1.0f, 1.0f, 0.5f, 1.0f, }, { 1.0f, 1.0f, 30.0f, 30.0f, }, { 0.0f, 0.0f, 0.5f, 1.0f, }, }; //============================================================================= //============================================================================= class CZombie : public CAI_BlendingHost<CNPC_BaseZombie> { DECLARE_DATADESC(); DECLARE_CLASS( CZombie, CAI_BlendingHost<CNPC_BaseZombie> ); public: CZombie() : m_DurationDoorBash( 2, 6), m_NextTimeToStartDoorBash( 3.0 ) { } void Spawn( void ); void Precache( void ); void SetZombieModel( void ); void MoanSound( envelopePoint_t *pEnvelope, int iEnvelopeSize ); bool ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold ); bool CanBecomeLiveTorso() { return !m_fIsHeadless; } void GatherConditions( void ); int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode ); int TranslateSchedule( int scheduleType ); #ifndef HL2_EPISODIC void CheckFlinches() {} // Zombie has custom flinch code #endif // HL2_EPISODIC Activity NPC_TranslateActivity( Activity newActivity ); void OnStateChange( NPC_STATE OldState, NPC_STATE NewState ); void StartTask( const Task_t *pTask ); void RunTask( const Task_t *pTask ); #ifndef EZ virtual const char *GetLegsModel( void ); virtual const char *GetTorsoModel( void ); #endif virtual const char *GetHeadcrabClassname( void ); virtual const char *GetHeadcrabModel( void ); virtual bool OnObstructingDoor( AILocalMoveGoal_t *pMoveGoal, CBaseDoor *pDoor, float distClear, AIMoveResult_t *pResult ); Activity SelectDoorBash(); void Ignite( float flFlameLifetime, bool bNPCOnly = true, float flSize = 0.0f, bool bCalledByLevelDesigner = false ); void Extinguish(); int OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo ); bool IsHeavyDamage( const CTakeDamageInfo &info ); bool IsSquashed( const CTakeDamageInfo &info ); void BuildScheduleTestBits( void ); void PrescheduleThink( void ); int SelectSchedule ( void ); void PainSound( const CTakeDamageInfo &info ); void DeathSound( const CTakeDamageInfo &info ); void AlertSound( void ); void IdleSound( void ); void AttackSound( void ); void AttackHitSound( void ); void AttackMissSound( void ); void FootstepSound( bool fRightFoot ); void FootscuffSound( bool fRightFoot ); const char *GetMoanSound( int nSound ); public: DEFINE_CUSTOM_AI; protected: static const char *pMoanSounds[]; #ifdef EZ static const char *pMoanSoundsRad[]; static const char *pMoanSoundsXen[]; #endif private: CHandle< CBaseDoor > m_hBlockingDoor; float m_flDoorBashYaw; CRandSimTimer m_DurationDoorBash; CSimTimer m_NextTimeToStartDoorBash; Vector m_vPositionCharged; }; LINK_ENTITY_TO_CLASS( npc_zombie, CZombie ); LINK_ENTITY_TO_CLASS( npc_zombie_torso, CZombie ); //--------------------------------------------------------- //--------------------------------------------------------- const char *CZombie::pMoanSounds[] = { "NPC_BaseZombie.Moan1", "NPC_BaseZombie.Moan2", "NPC_BaseZombie.Moan3", "NPC_BaseZombie.Moan4", }; #ifdef EZ const char *CZombie::pMoanSoundsRad[] = { "NPC_BaseGlowbie.Moan1", "NPC_BaseGlowbie.Moan2", "NPC_BaseGlowbie.Moan3", "NPC_BaseGlowbie.Moan4", }; const char *CZombie::pMoanSoundsXen[] = { "NPC_BaseXenbie.Moan1", "NPC_BaseXenbie.Moan2", "NPC_BaseXenbie.Moan3", "NPC_BaseXenbie.Moan4", }; #endif //========================================================= // Conditions //========================================================= enum { COND_BLOCKED_BY_DOOR = LAST_BASE_ZOMBIE_CONDITION, COND_DOOR_OPENED, COND_ZOMBIE_CHARGE_TARGET_MOVED, }; //========================================================= // Schedules //========================================================= enum { SCHED_ZOMBIE_BASH_DOOR = LAST_BASE_ZOMBIE_SCHEDULE, SCHED_ZOMBIE_WANDER_ANGRILY, SCHED_ZOMBIE_CHARGE_ENEMY, SCHED_ZOMBIE_FAIL, }; //========================================================= // Tasks //========================================================= enum { TASK_ZOMBIE_EXPRESS_ANGER = LAST_BASE_ZOMBIE_TASK, TASK_ZOMBIE_YAW_TO_DOOR, TASK_ZOMBIE_ATTACK_DOOR, TASK_ZOMBIE_CHARGE_ENEMY, }; //----------------------------------------------------------------------------- int ACT_ZOMBIE_TANTRUM; int ACT_ZOMBIE_WALLPOUND; BEGIN_DATADESC( CZombie ) DEFINE_FIELD( m_hBlockingDoor, FIELD_EHANDLE ), DEFINE_FIELD( m_flDoorBashYaw, FIELD_FLOAT ), DEFINE_EMBEDDED( m_DurationDoorBash ), DEFINE_EMBEDDED( m_NextTimeToStartDoorBash ), DEFINE_FIELD( m_vPositionCharged, FIELD_POSITION_VECTOR ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CZombie::Precache( void ) { #ifndef EZ BaseClass::Precache(); PrecacheModel( "models/zombie/classic.mdl" ); PrecacheModel( "models/zombie/classic_torso.mdl" ); PrecacheModel( "models/zombie/classic_legs.mdl" ); PrecacheScriptSound( "Zombie.FootstepRight" ); PrecacheScriptSound( "Zombie.FootstepLeft" ); PrecacheScriptSound( "Zombie.FootstepLeft" ); PrecacheScriptSound( "Zombie.ScuffRight" ); PrecacheScriptSound( "Zombie.ScuffLeft" ); PrecacheScriptSound( "Zombie.AttackHit" ); PrecacheScriptSound( "Zombie.AttackMiss" ); PrecacheScriptSound( "Zombie.Pain" ); PrecacheScriptSound( "Zombie.Die" ); PrecacheScriptSound( "Zombie.Alert" ); PrecacheScriptSound( "Zombie.Idle" ); PrecacheScriptSound( "Zombie.Attack" ); PrecacheScriptSound( "NPC_BaseZombie.Moan1" ); PrecacheScriptSound( "NPC_BaseZombie.Moan2" ); PrecacheScriptSound( "NPC_BaseZombie.Moan3" ); PrecacheScriptSound( "NPC_BaseZombie.Moan4" ); #else char * modelVariant; switch (m_tEzVariant) { case EZ_VARIANT_RAD: modelVariant = "glowbie"; PrecacheScriptSound( "Glowbie.FootstepRight" ); PrecacheScriptSound( "Glowbie.FootstepLeft" ); PrecacheScriptSound( "Glowbie.FootstepLeft" ); PrecacheScriptSound( "Glowbie.ScuffRight" ); PrecacheScriptSound( "Glowbie.ScuffLeft" ); PrecacheScriptSound( "Glowbie.AttackHit" ); PrecacheScriptSound( "Glowbie.AttackMiss" ); PrecacheScriptSound( "Glowbie.Pain" ); PrecacheScriptSound( "Glowbie.Die" ); PrecacheScriptSound( "Glowbie.Alert" ); PrecacheScriptSound( "Glowbie.Idle" ); PrecacheScriptSound( "Glowbie.Attack" ); break; case EZ_VARIANT_XEN: modelVariant = "xenbie"; PrecacheScriptSound( "Xenbie.FootstepRight" ); PrecacheScriptSound( "Xenbie.FootstepLeft" ); PrecacheScriptSound( "Xenbie.FootstepLeft" ); PrecacheScriptSound( "Xenbie.ScuffRight" ); PrecacheScriptSound( "Xenbie.ScuffLeft" ); PrecacheScriptSound( "Xenbie.AttackHit" ); PrecacheScriptSound( "Xenbie.AttackMiss" ); PrecacheScriptSound( "Xenbie.Pain" ); PrecacheScriptSound( "Xenbie.Die" ); PrecacheScriptSound( "Xenbie.Alert" ); PrecacheScriptSound( "Xenbie.Idle" ); PrecacheScriptSound( "Xenbie.Attack" ); break; default: modelVariant = "classic"; PrecacheScriptSound( "Zombie.FootstepRight" ); PrecacheScriptSound( "Zombie.FootstepLeft" ); PrecacheScriptSound( "Zombie.FootstepLeft" ); PrecacheScriptSound( "Zombie.ScuffRight" ); PrecacheScriptSound( "Zombie.ScuffLeft" ); PrecacheScriptSound( "Zombie.AttackHit" ); PrecacheScriptSound( "Zombie.AttackMiss" ); PrecacheScriptSound( "Zombie.Pain" ); PrecacheScriptSound( "Zombie.Die" ); PrecacheScriptSound( "Zombie.Alert" ); PrecacheScriptSound( "Zombie.Idle" ); PrecacheScriptSound( "Zombie.Attack" ); break; } if( GetModelName() == NULL_STRING ) { SetModelName( AllocPooledString( UTIL_VarArgs( "models/zombie/%s.mdl", modelVariant ) ) ); } if (GetTorsoModelName() == NULL_STRING) { SetTorsoModelName( AllocPooledString( UTIL_VarArgs( "models/zombie/%s_torso.mdl", modelVariant ) ) ); } if (GetLegsModelName() == NULL_STRING) { SetLegsModelName( AllocPooledString( UTIL_VarArgs( "models/zombie/%s_legs.mdl", modelVariant ) ) ); } PrecacheModel( STRING( GetModelName() ) ); PrecacheScriptSound( "NPC_BaseZombie.Moan1" ); PrecacheScriptSound( "NPC_BaseZombie.Moan2" ); PrecacheScriptSound( "NPC_BaseZombie.Moan3" ); PrecacheScriptSound( "NPC_BaseZombie.Moan4" ); BaseClass::Precache(); #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CZombie::Spawn( void ) { Precache(); if( FClassnameIs( this, "npc_zombie" ) ) { m_fIsTorso = false; } else { // This was placed as an npc_zombie_torso m_fIsTorso = true; } m_fIsHeadless = false; #ifdef EZ if ( m_tEzVariant == EZ_VARIANT_RAD ) { SetBloodColor( BLOOD_COLOR_BLUE ); } else { SetBloodColor( BLOOD_COLOR_ZOMBIE ); } #elif HL2_EPISODIC SetBloodColor(BLOOD_COLOR_ZOMBIE); #else SetBloodColor( BLOOD_COLOR_GREEN ); #endif // HL2_EPISODIC m_iHealth = sk_zombie_health.GetFloat(); m_flFieldOfView = 0.2; CapabilitiesClear(); //GetNavigator()->SetRememberStaleNodes( false ); BaseClass::Spawn(); m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 1.0, 4.0 ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CZombie::PrescheduleThink( void ) { if( gpGlobals->curtime > m_flNextMoanSound ) { if( CanPlayMoanSound() ) { // Classic guy idles instead of moans. IdleSound(); m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 2.0, 5.0 ); } else { m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 1.0, 2.0 ); } } BaseClass::PrescheduleThink(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CZombie::SelectSchedule ( void ) { if( HasCondition( COND_PHYSICS_DAMAGE ) && !m_ActBusyBehavior.IsActive() ) { return SCHED_FLINCH_PHYSICS; } return BaseClass::SelectSchedule(); } //----------------------------------------------------------------------------- // Purpose: Sound of a footstep //----------------------------------------------------------------------------- void CZombie::FootstepSound( bool fRightFoot ) { #ifdef EZ if ( m_tEzVariant == EZ_VARIANT_RAD && fRightFoot ) { EmitSound( "Glowbie.FootstepRight" ); } else if ( m_tEzVariant == EZ_VARIANT_RAD ) { EmitSound( "Glowbie.FootstepLeft" ); } else if ( m_tEzVariant == EZ_VARIANT_XEN && fRightFoot ) { EmitSound( "Xenbie.FootstepRight" ); } else if ( m_tEzVariant == EZ_VARIANT_XEN ) { EmitSound( "Xenbie.FootstepLeft" ); } else #endif if( fRightFoot ) { EmitSound( "Zombie.FootstepRight" ); } else { EmitSound( "Zombie.FootstepLeft" ); } } //----------------------------------------------------------------------------- // Purpose: Sound of a foot sliding/scraping //----------------------------------------------------------------------------- void CZombie::FootscuffSound( bool fRightFoot ) { #ifdef EZ if ( m_tEzVariant == EZ_VARIANT_RAD && fRightFoot ) { EmitSound( "Glowbie.ScuffRight" ); } else if ( m_tEzVariant == EZ_VARIANT_RAD ) { EmitSound( "Glowbie.ScuffLeft" ); } else if ( m_tEzVariant == EZ_VARIANT_XEN && fRightFoot ) { EmitSound( "Xenbie.ScuffRight" ); } else if ( m_tEzVariant == EZ_VARIANT_XEN ) { EmitSound( "Xenbie.ScuffLeft" ); } else #endif if( fRightFoot ) { EmitSound( "Zombie.ScuffRight" ); } else { EmitSound( "Zombie.ScuffLeft" ); } } //----------------------------------------------------------------------------- // Purpose: Play a random attack hit sound //----------------------------------------------------------------------------- void CZombie::AttackHitSound( void ) { #ifdef EZ switch( m_tEzVariant ) { case EZ_VARIANT_RAD: EmitSound( "Glowbie.AttackHit" ); break; case EZ_VARIANT_XEN: EmitSound( "Xenbie.AttackHit" ); break; default: EmitSound( "Zombie.AttackHit" ); break; } #else EmitSound( "Zombie.AttackHit" ); #endif } //----------------------------------------------------------------------------- // Purpose: Play a random attack miss sound //----------------------------------------------------------------------------- void CZombie::AttackMissSound( void ) { #ifdef EZ switch (m_tEzVariant) { case EZ_VARIANT_RAD: EmitSound( "Glowbie.AttackMiss" ); break; case EZ_VARIANT_XEN: EmitSound( "Xenbie.AttackMiss" ); break; default: EmitSound( "Zombie.AttackMiss" ); break; } #else // Play a random attack miss sound EmitSound( "Zombie.AttackMiss" ); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CZombie::PainSound( const CTakeDamageInfo &info ) { // We're constantly taking damage when we are on fire. Don't make all those noises! if ( IsOnFire() ) { return; } #ifdef EZ switch ( m_tEzVariant ) { case EZ_VARIANT_RAD: EmitSound( "Glowbie.Pain" ); break; case EZ_VARIANT_XEN: EmitSound( "Xenbie.Pain" ); break; default: EmitSound( "Zombie.Pain" ); break; } #else EmitSound( "Zombie.Pain" ); #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CZombie::DeathSound( const CTakeDamageInfo &info ) { #ifdef EZ switch (m_tEzVariant) { case EZ_VARIANT_RAD: EmitSound( "Glowbie.Die" ); break; case EZ_VARIANT_XEN: EmitSound( "Xenbie.Die" ); break; default: EmitSound( "Zombie.Die" ); break; } #else EmitSound( "Zombie.Die" ); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CZombie::AlertSound( void ) { #ifdef EZ switch (m_tEzVariant) { case EZ_VARIANT_RAD: EmitSound( "Glowbie.Alert" ); break; case EZ_VARIANT_XEN: EmitSound( "Xenbie.Alert" ); break; default: EmitSound( "Zombie.Alert" ); break; } #else EmitSound( "Zombie.Alert" ); #endif // Don't let a moan sound cut off the alert sound. m_flNextMoanSound += random->RandomFloat( 2.0, 4.0 ); } //----------------------------------------------------------------------------- // Purpose: Returns a moan sound for this class of zombie. //----------------------------------------------------------------------------- const char *CZombie::GetMoanSound( int nSound ) { #ifdef EZ switch (m_tEzVariant) { case EZ_VARIANT_RAD: return pMoanSounds[nSound % ARRAYSIZE( pMoanSoundsRad )]; case EZ_VARIANT_XEN: return pMoanSounds[nSound % ARRAYSIZE( pMoanSoundsXen )]; default: return pMoanSounds[nSound % ARRAYSIZE( pMoanSounds )]; } #else return pMoanSounds[ nSound % ARRAYSIZE( pMoanSounds ) ]; #endif } //----------------------------------------------------------------------------- // Purpose: Play a random idle sound. //----------------------------------------------------------------------------- void CZombie::IdleSound( void ) { if( GetState() == NPC_STATE_IDLE && random->RandomFloat( 0, 1 ) == 0 ) { // Moan infrequently in IDLE state. return; } if( IsSlumped() ) { // Sleeping zombies are quiet. return; } #ifdef EZ switch ( m_tEzVariant ) { case EZ_VARIANT_RAD: EmitSound( "Glowbie.Idle" ); break; case EZ_VARIANT_XEN: EmitSound( "Xenbie.Idle" ); break; default: EmitSound( "Zombie.Idle" ); break; } #else EmitSound( "Zombie.Idle" ); #endif MakeAISpookySound( 360.0f ); } //----------------------------------------------------------------------------- // Purpose: Play a random attack sound. //----------------------------------------------------------------------------- void CZombie::AttackSound( void ) { #ifdef EZ switch ( m_tEzVariant ) { case EZ_VARIANT_RAD: EmitSound( "Glowbie.Attack" ); break; default: EmitSound( "Zombie.Attack" ); break; } #else EmitSound( "Zombie.Attack" ); #endif } //----------------------------------------------------------------------------- // Purpose: Returns the classname (ie "npc_headcrab") to spawn when our headcrab bails. //----------------------------------------------------------------------------- const char *CZombie::GetHeadcrabClassname( void ) { return "npc_headcrab"; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- const char *CZombie::GetHeadcrabModel( void ) { switch (m_tEzVariant) { case EZ_VARIANT_RAD: return "models/glowcrabclassic.mdl"; case EZ_VARIANT_XEN: return "models/xencrabclassic.mdl"; default: return "models/headcrabclassic.mdl"; } } #ifndef EZ //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CZombie::GetLegsModel( void ) { return "models/zombie/classic_legs.mdl"; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- const char *CZombie::GetTorsoModel( void ) { return "models/zombie/classic_torso.mdl"; } #endif //--------------------------------------------------------- //--------------------------------------------------------- void CZombie::SetZombieModel( void ) { Hull_t lastHull = GetHullType(); if ( m_fIsTorso ) { #ifndef EZ SetModel( "models/zombie/classic_torso.mdl" ); #else SetModel( GetTorsoModel() ); #endif SetHullType( HULL_TINY ); } else { #ifndef EZ SetModel( "models/zombie/classic.mdl" ); #else SetModel( STRING( GetModelName() ) ); #endif SetHullType( HULL_HUMAN ); } SetBodygroup( ZOMBIE_BODYGROUP_HEADCRAB, !m_fIsHeadless ); SetHullSizeNormal( true ); SetDefaultEyeOffset(); SetActivity( ACT_IDLE ); // hull changed size, notify vphysics // UNDONE: Solve this generally, systematically so other // NPCs can change size if ( lastHull != GetHullType() ) { if ( VPhysicsGetObject() ) { SetupVPhysicsHull(); } } } //--------------------------------------------------------- // Classic zombie only uses moan sound if on fire. //--------------------------------------------------------- void CZombie::MoanSound( envelopePoint_t *pEnvelope, int iEnvelopeSize ) { if( IsOnFire() ) { BaseClass::MoanSound( pEnvelope, iEnvelopeSize ); } } //--------------------------------------------------------- //--------------------------------------------------------- bool CZombie::ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold ) { if( IsSlumped() ) { // Never break apart a slouched zombie. This is because the most fun // slouched zombies to kill are ones sleeping leaning against explosive // barrels. If you break them in half in the blast, the force of being // so close to the explosion makes the body pieces fly at ridiculous // velocities because the pieces weigh less than the whole. return false; } return BaseClass::ShouldBecomeTorso( info, flDamageThreshold ); } //--------------------------------------------------------- //--------------------------------------------------------- void CZombie::GatherConditions( void ) { BaseClass::GatherConditions(); static int conditionsToClear[] = { COND_BLOCKED_BY_DOOR, COND_DOOR_OPENED, COND_ZOMBIE_CHARGE_TARGET_MOVED, }; ClearConditions( conditionsToClear, ARRAYSIZE( conditionsToClear ) ); if ( m_hBlockingDoor == NULL || ( m_hBlockingDoor->m_toggle_state == TS_AT_TOP || m_hBlockingDoor->m_toggle_state == TS_GOING_UP ) ) { ClearCondition( COND_BLOCKED_BY_DOOR ); if ( m_hBlockingDoor != NULL ) { SetCondition( COND_DOOR_OPENED ); m_hBlockingDoor = NULL; } } else SetCondition( COND_BLOCKED_BY_DOOR ); if ( ConditionInterruptsCurSchedule( COND_ZOMBIE_CHARGE_TARGET_MOVED ) ) { if ( GetNavigator()->IsGoalActive() ) { const float CHARGE_RESET_TOLERANCE = 60.0; if ( !GetEnemy() || ( m_vPositionCharged - GetEnemyLKP() ).Length() > CHARGE_RESET_TOLERANCE ) { SetCondition( COND_ZOMBIE_CHARGE_TARGET_MOVED ); } } } } //--------------------------------------------------------- //--------------------------------------------------------- int CZombie::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode ) { if ( HasCondition( COND_BLOCKED_BY_DOOR ) && m_hBlockingDoor != NULL ) { ClearCondition( COND_BLOCKED_BY_DOOR ); if ( m_NextTimeToStartDoorBash.Expired() && failedSchedule != SCHED_ZOMBIE_BASH_DOOR ) return SCHED_ZOMBIE_BASH_DOOR; m_hBlockingDoor = NULL; } if ( failedSchedule != SCHED_ZOMBIE_CHARGE_ENEMY && IsPathTaskFailure( taskFailCode ) && random->RandomInt( 1, 100 ) < 50 ) { return SCHED_ZOMBIE_CHARGE_ENEMY; } if ( failedSchedule != SCHED_ZOMBIE_WANDER_ANGRILY && ( failedSchedule == SCHED_TAKE_COVER_FROM_ENEMY || failedSchedule == SCHED_CHASE_ENEMY_FAILED ) ) { return SCHED_ZOMBIE_WANDER_ANGRILY; } return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode ); } //--------------------------------------------------------- //--------------------------------------------------------- int CZombie::TranslateSchedule( int scheduleType ) { if ( scheduleType == SCHED_COMBAT_FACE && IsUnreachable( GetEnemy() ) ) return SCHED_TAKE_COVER_FROM_ENEMY; if ( !m_fIsTorso && scheduleType == SCHED_FAIL ) return SCHED_ZOMBIE_FAIL; return BaseClass::TranslateSchedule( scheduleType ); } //--------------------------------------------------------- Activity CZombie::NPC_TranslateActivity( Activity newActivity ) { newActivity = BaseClass::NPC_TranslateActivity( newActivity ); if ( newActivity == ACT_RUN ) return ACT_WALK; if ( m_fIsTorso && ( newActivity == ACT_ZOMBIE_TANTRUM ) ) return ACT_IDLE; return newActivity; } //--------------------------------------------------------- //--------------------------------------------------------- void CZombie::OnStateChange( NPC_STATE OldState, NPC_STATE NewState ) { BaseClass::OnStateChange( OldState, NewState ); } //--------------------------------------------------------- //--------------------------------------------------------- void CZombie::StartTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_ZOMBIE_EXPRESS_ANGER: { if ( random->RandomInt( 1, 4 ) == 2 ) { SetIdealActivity( (Activity)ACT_ZOMBIE_TANTRUM ); } else { TaskComplete(); } break; } case TASK_ZOMBIE_YAW_TO_DOOR: { AssertMsg( m_hBlockingDoor != NULL, "Expected condition handling to break schedule before landing here" ); if ( m_hBlockingDoor != NULL ) { GetMotor()->SetIdealYaw( m_flDoorBashYaw ); } TaskComplete(); break; } case TASK_ZOMBIE_ATTACK_DOOR: { m_DurationDoorBash.Reset(); SetIdealActivity( SelectDoorBash() ); break; } case TASK_ZOMBIE_CHARGE_ENEMY: { if ( !GetEnemy() ) TaskFail( FAIL_NO_ENEMY ); else if ( GetNavigator()->SetVectorGoalFromTarget( GetEnemy()->GetLocalOrigin() ) ) { m_vPositionCharged = GetEnemy()->GetLocalOrigin(); TaskComplete(); } else TaskFail( FAIL_NO_ROUTE ); break; } default: BaseClass::StartTask( pTask ); break; } } //--------------------------------------------------------- //--------------------------------------------------------- void CZombie::RunTask( const Task_t *pTask ) { switch( pTask->iTask ) { case TASK_ZOMBIE_ATTACK_DOOR: { if ( IsActivityFinished() ) { if ( m_DurationDoorBash.Expired() ) { TaskComplete(); m_NextTimeToStartDoorBash.Reset(); } else ResetIdealActivity( SelectDoorBash() ); } break; } case TASK_ZOMBIE_CHARGE_ENEMY: { break; } case TASK_ZOMBIE_EXPRESS_ANGER: { if ( IsActivityFinished() ) { TaskComplete(); } break; } default: BaseClass::RunTask( pTask ); break; } } //--------------------------------------------------------- //--------------------------------------------------------- bool CZombie::OnObstructingDoor( AILocalMoveGoal_t *pMoveGoal, CBaseDoor *pDoor, float distClear, AIMoveResult_t *pResult ) { if ( BaseClass::OnObstructingDoor( pMoveGoal, pDoor, distClear, pResult ) ) { if ( IsMoveBlocked( *pResult ) && pMoveGoal->directTrace.vHitNormal != vec3_origin ) { m_hBlockingDoor = pDoor; m_flDoorBashYaw = UTIL_VecToYaw( pMoveGoal->directTrace.vHitNormal * -1 ); } return true; } return false; } //--------------------------------------------------------- //--------------------------------------------------------- Activity CZombie::SelectDoorBash() { if ( random->RandomInt( 1, 3 ) == 1 ) return ACT_MELEE_ATTACK1; return (Activity)ACT_ZOMBIE_WALLPOUND; } //--------------------------------------------------------- // Zombies should scream continuously while burning, so long // as they are alive... but NOT IN GERMANY! //--------------------------------------------------------- void CZombie::Ignite( float flFlameLifetime, bool bNPCOnly, float flSize, bool bCalledByLevelDesigner ) { if( !IsOnFire() && IsAlive() ) { BaseClass::Ignite( flFlameLifetime, bNPCOnly, flSize, bCalledByLevelDesigner ); if ( !UTIL_IsLowViolence() ) { RemoveSpawnFlags( SF_NPC_GAG ); MoanSound( envZombieMoanIgnited, ARRAYSIZE( envZombieMoanIgnited ) ); if ( m_pMoanSound ) { ENVELOPE_CONTROLLER.SoundChangePitch( m_pMoanSound, 120, 1.0 ); ENVELOPE_CONTROLLER.SoundChangeVolume( m_pMoanSound, 1, 1.0 ); } } } } //--------------------------------------------------------- // If a zombie stops burning and hasn't died, quiet him down //--------------------------------------------------------- void CZombie::Extinguish() { if( m_pMoanSound ) { ENVELOPE_CONTROLLER.SoundChangeVolume( m_pMoanSound, 0, 2.0 ); ENVELOPE_CONTROLLER.SoundChangePitch( m_pMoanSound, 100, 2.0 ); m_flNextMoanSound = gpGlobals->curtime + random->RandomFloat( 2.0, 4.0 ); } BaseClass::Extinguish(); } //--------------------------------------------------------- //--------------------------------------------------------- int CZombie::OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo ) { #ifndef HL2_EPISODIC if ( inputInfo.GetDamageType() & DMG_BUCKSHOT ) { if( !m_fIsTorso && inputInfo.GetDamage() > (m_iMaxHealth/3) ) { // Always flinch if damaged a lot by buckshot, even if not shot in the head. // The reason for making sure we did at least 1/3rd of the zombie's max health // is so the zombie doesn't flinch every time the odd shotgun pellet hits them, // and so the maximum number of times you'll see a zombie flinch like this is 2.(sjb) AddGesture( ACT_GESTURE_FLINCH_HEAD ); } } #endif // HL2_EPISODIC return BaseClass::OnTakeDamage_Alive( inputInfo ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CZombie::IsHeavyDamage( const CTakeDamageInfo &info ) { #ifdef HL2_EPISODIC if ( info.GetDamageType() & DMG_BUCKSHOT ) { if ( !m_fIsTorso && info.GetDamage() > (m_iMaxHealth/3) ) return true; } // Randomly treat all damage as heavy if ( info.GetDamageType() & (DMG_BULLET | DMG_BUCKSHOT) ) { // Don't randomly flinch if I'm melee attacking if ( !HasCondition(COND_CAN_MELEE_ATTACK1) && (RandomFloat() > 0.5) ) { // Randomly forget I've flinched, so that I'll be forced to play a big flinch // If this doesn't happen, it means I may not fully flinch if I recently flinched if ( RandomFloat() > 0.75 ) { Forget(bits_MEMORY_FLINCHED); } return true; } } #endif // HL2_EPISODIC return BaseClass::IsHeavyDamage(info); } //--------------------------------------------------------- //--------------------------------------------------------- #define ZOMBIE_SQUASH_MASS 300.0f // Anything this heavy or heavier squashes a zombie good. (show special fx) bool CZombie::IsSquashed( const CTakeDamageInfo &info ) { if( GetHealth() > 0 ) { return false; } if( info.GetDamageType() & DMG_CRUSH ) { IPhysicsObject *pCrusher = info.GetInflictor()->VPhysicsGetObject(); if( pCrusher && pCrusher->GetMass() >= ZOMBIE_SQUASH_MASS && info.GetInflictor()->WorldSpaceCenter().z > EyePosition().z ) { // This heuristic detects when a zombie has been squashed from above by a heavy // item. Done specifically so we can add gore effects to Ravenholm cartraps. // The zombie must take physics damage from a 300+kg object that is centered above its eyes (comes from above) return true; } } return false; } //--------------------------------------------------------- //--------------------------------------------------------- void CZombie::BuildScheduleTestBits( void ) { BaseClass::BuildScheduleTestBits(); if( !m_fIsTorso && !IsCurSchedule( SCHED_FLINCH_PHYSICS ) && !m_ActBusyBehavior.IsActive() ) { SetCustomInterruptCondition( COND_PHYSICS_DAMAGE ); } } //============================================================================= AI_BEGIN_CUSTOM_NPC( npc_zombie, CZombie ) DECLARE_CONDITION( COND_BLOCKED_BY_DOOR ) DECLARE_CONDITION( COND_DOOR_OPENED ) DECLARE_CONDITION( COND_ZOMBIE_CHARGE_TARGET_MOVED ) DECLARE_TASK( TASK_ZOMBIE_EXPRESS_ANGER ) DECLARE_TASK( TASK_ZOMBIE_YAW_TO_DOOR ) DECLARE_TASK( TASK_ZOMBIE_ATTACK_DOOR ) DECLARE_TASK( TASK_ZOMBIE_CHARGE_ENEMY ) DECLARE_ACTIVITY( ACT_ZOMBIE_TANTRUM ); DECLARE_ACTIVITY( ACT_ZOMBIE_WALLPOUND ); DEFINE_SCHEDULE ( SCHED_ZOMBIE_BASH_DOOR, " Tasks" " TASK_SET_ACTIVITY ACTIVITY:ACT_ZOMBIE_TANTRUM" " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_TAKE_COVER_FROM_ENEMY" " TASK_ZOMBIE_YAW_TO_DOOR 0" " TASK_FACE_IDEAL 0" " TASK_ZOMBIE_ATTACK_DOOR 0" "" " Interrupts" " COND_ZOMBIE_RELEASECRAB" " COND_ENEMY_DEAD" " COND_NEW_ENEMY" " COND_DOOR_OPENED" ) DEFINE_SCHEDULE ( SCHED_ZOMBIE_WANDER_ANGRILY, " Tasks" " TASK_WANDER 480240" // 48 units to 240 units. " TASK_WALK_PATH 0" " TASK_WAIT_FOR_MOVEMENT 4" "" " Interrupts" " COND_ZOMBIE_RELEASECRAB" " COND_ENEMY_DEAD" " COND_NEW_ENEMY" " COND_DOOR_OPENED" ) DEFINE_SCHEDULE ( SCHED_ZOMBIE_CHARGE_ENEMY, " Tasks" " TASK_ZOMBIE_CHARGE_ENEMY 0" " TASK_WALK_PATH 0" " TASK_WAIT_FOR_MOVEMENT 0" " TASK_PLAY_SEQUENCE ACTIVITY:ACT_ZOMBIE_TANTRUM" /* placeholder until frustration/rage/fence shake animation available */ "" " Interrupts" " COND_ZOMBIE_RELEASECRAB" " COND_ENEMY_DEAD" " COND_NEW_ENEMY" " COND_DOOR_OPENED" " COND_ZOMBIE_CHARGE_TARGET_MOVED" ) DEFINE_SCHEDULE ( SCHED_ZOMBIE_FAIL, " Tasks" " TASK_STOP_MOVING 0" " TASK_SET_ACTIVITY ACTIVITY:ACT_ZOMBIE_TANTRUM" " TASK_WAIT 1" " TASK_WAIT_PVS 0" "" " Interrupts" " COND_CAN_RANGE_ATTACK1 " " COND_CAN_RANGE_ATTACK2 " " COND_CAN_MELEE_ATTACK1 " " COND_CAN_MELEE_ATTACK2" " COND_GIVE_WAY" " COND_DOOR_OPENED" ) AI_END_CUSTOM_NPC() //=============================================================================
25.645669
128
0.579521
[ "object", "vector" ]
f511f365d12a6a7bd818b14d909a2e900f6d1a98
5,956
cc
C++
projects/MeshResource/code/mesh_res.cc
Olaxan/ltu-lab-s0006e_env
5cf164fa5d664cb0181e2c88a59d91b433344fb2
[ "MIT" ]
null
null
null
projects/MeshResource/code/mesh_res.cc
Olaxan/ltu-lab-s0006e_env
5cf164fa5d664cb0181e2c88a59d91b433344fb2
[ "MIT" ]
null
null
null
projects/MeshResource/code/mesh_res.cc
Olaxan/ltu-lab-s0006e_env
5cf164fa5d664cb0181e2c88a59d91b433344fb2
[ "MIT" ]
null
null
null
#include "mesh_res.h" #include <GL/glew.h> namespace efiilj { mesh_resource::mesh_resource() : vbo_(0), ibo_(0), vao_(0), vertex_count_(0), index_count_(0) { } mesh_resource:: mesh_resource(vertex* vertex_list, const int vertex_count, unsigned int* index_list, const int index_count) : vbo_(0), ibo_(0), vao_(0) { this->vertex_count_ = vertex_count; this->index_count_ = index_count; init_array_object(); init_vertex_buffer(vertex_list, vertex_count); init_index_buffer(index_list, index_count); } mesh_resource mesh_resource::cube(float size, const float color) { size /= 2; vertex vertices[24] = { // Front = S vertex(vector3(-size, -size, size), vector3(0, 0, 1), vector4(color, color, color, color), vector2(0.25f, 0.33f)), // 0 vertex(vector3(size, -size, size), vector3(0, 0, 1), vector4(color, color, color, color), vector2(0.5f, 0.33f)), // 1 vertex(vector3(size, size, size), vector3(0, 0, 1), vector4(color, color, color, color), vector2(0.5f, 0.66f)), // 2 vertex(vector3(-size, size, size), vector3(0, 0, 1), vector4(color, color, color, color), vector2(0.25f, 0.66f)), // 3 // Back = N vertex(vector3(size, -size, -size), vector3(0, 0, -1), vector4(color, color, color, color), vector2(0.75, 0.33f)), // 4 vertex(vector3(-size, -size, -size), vector3(0, 0, -1), vector4(color, color, color, color), vector2(1.0f, 0.33f)), // 5 vertex(vector3(-size, size, -size), vector3(0, 0, -1), vector4(color, color, color, color), vector2(1.0f, 0.66f)), // 6 vertex(vector3(size, size, -size), vector3(0, 0, -1), vector4(color, color, color, color), vector2(0.75, 0.66f)), // 7 // Top vertex(vector3(-size, size, size), vector3(0, 1, 0), vector4(color, color, color, color), vector2(0.25f, 0.66f)), // 8 vertex(vector3(size, size, size), vector3(0, 1, 0), vector4(color, color, color, color), vector2(0.5f, 0.66f)), // 9 vertex(vector3(size, size, -size), vector3(0, 1, 0), vector4(color, color, color, color), vector2(0.5f, 1.0f)), // 10 vertex(vector3(-size, size, -size), vector3(0, 1, 0), vector4(color, color, color, color), vector2(0.25f, 1.0f)), // 11 // Bottom vertex(vector3(size, -size, size), vector3(0, -1, 0), vector4(color, color, color, color), vector2(0.25f, 0.0f)), // 12 vertex(vector3(-size, -size, size), vector3(0, -1, 0), vector4(color, color, color, color), vector2(0.5f, 0.0f)), // 13 vertex(vector3(-size, -size, -size), vector3(0, -1, 0), vector4(color, color, color, color), vector2(0.5f, 0.33f)), // 14 vertex(vector3(size, -size, -size), vector3(0, -1, 0), vector4(color, color, color, color), vector2(0.25f, 0.33f)), // 15 // Left = W vertex(vector3(-size, -size, -size), vector3(-1, 0, 0), vector4(color, color, color, color), vector2(0.0f, 0.33f)), // 16 vertex(vector3(-size, -size, size), vector3(-1, 0, 0), vector4(color, color, color, color), vector2(0.25f, 0.33f)), // 17 vertex(vector3(-size, size, size), vector3(-1, 0, 0), vector4(color, color, color, color), vector2(0.25f, 0.66f)), // 18 vertex(vector3(-size, size, -size), vector3(-1, 0, 0), vector4(color, color, color, color), vector2(0.0f, 0.66f)), // 19 // Right = E vertex(vector3(size, -size, size), vector3(1, 0, 0), vector4(color, color, color, color), vector2(0.5f, 0.33f)), // 20 vertex(vector3(size, -size, -size), vector3(1, 0, 0), vector4(color, color, color, color), vector2(0.75, 0.33f)), // 21 vertex(vector3(size, size, -size), vector3(1, 0, 0), vector4(color, color, color, color), vector2(0.75, 0.66f)), // 22 vertex(vector3(size, size, size), vector3(1, 0, 0), vector4(color, color, color, color), vector2(0.5f, 0.66f)), // 23 }; unsigned int indices[36] = { 0, 1, 3, 2, 3, 1, // Front 4, 5, 7, 6, 7, 5, // Back 8, 9, 11, 10, 11, 9, // Top 12, 13, 15, 14, 15, 13, // Bottom 16, 17, 19, 18, 19, 17, // Left 20, 21, 23, 22, 23, 21 // Right }; return mesh_resource(vertices, 24, indices, 36); } void mesh_resource::init_vertex_buffer(vertex* vertex_list, const int count) { if (vbo_ != 0) return; glGenBuffers(1, &vbo_); glBindBuffer(GL_ARRAY_BUFFER, vbo_); glBufferData(GL_ARRAY_BUFFER, count * sizeof(vertex), vertex_list, GL_STATIC_DRAW); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), nullptr); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offsetof(vertex, normal))); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offsetof(vertex, rgba))); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), reinterpret_cast<void*>(offsetof(vertex, uv))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); } void mesh_resource::init_index_buffer(unsigned int* index_list, const int count) { if (ibo_ != 0) return; glGenBuffers(1, &ibo_); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_); glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(unsigned int), index_list, GL_STATIC_DRAW); } void mesh_resource::init_array_object() { if (vao_ != 0) return; glGenVertexArrays(1, &vao_); glBindVertexArray(vao_); } void mesh_resource::update_vertex_buffer(vertex* vertex_list) const { glBindBuffer(GL_ARRAY_BUFFER, vbo_); glBufferSubData(GL_ARRAY_BUFFER, 0, vertex_count_ * sizeof(vertex), vertex_list); } void mesh_resource::bind() const { glBindVertexArray(vao_); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_); } void mesh_resource::unbind() { glBindVertexArray(0); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void mesh_resource::draw_elements() const { glDrawElements(GL_TRIANGLES, index_count_, GL_UNSIGNED_INT, nullptr); } mesh_resource::~mesh_resource() { std::cout << "Deleting mesh resource " << this << std::endl; unbind(); glDeleteBuffers(1, &vao_); glDeleteBuffers(1, &vbo_); glDeleteBuffers(1, &ibo_); } }
39.973154
136
0.667226
[ "mesh" ]
f51206b10425cc2cc158f9fb107b152714fec818
9,562
cpp
C++
inference-engine/tests/functional/inference_engine/lp_transformations/multiply_to_group_convolution_transformation.cpp
ddeuerme/openvino
ff0d0618ab940484056fe8452a3b8c0cb7164d87
[ "Apache-2.0" ]
1
2022-01-19T15:36:45.000Z
2022-01-19T15:36:45.000Z
inference-engine/tests/functional/inference_engine/lp_transformations/multiply_to_group_convolution_transformation.cpp
ddeuerme/openvino
ff0d0618ab940484056fe8452a3b8c0cb7164d87
[ "Apache-2.0" ]
22
2021-02-03T12:41:51.000Z
2022-02-21T13:04:48.000Z
inference-engine/tests/functional/inference_engine/lp_transformations/multiply_to_group_convolution_transformation.cpp
ddeuerme/openvino
ff0d0618ab940484056fe8452a3b8c0cb7164d87
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "layer_transformation.hpp" #include <string> #include <sstream> #include <memory> #include <gtest/gtest.h> #include <transformations/utils/utils.hpp> #include <transformations/init_node_info.hpp> #include "low_precision/multiply_to_group_convolution.hpp" #include "common_test_utils/ngraph_test_utils.hpp" #include "lpt_ngraph_functions/common/dequantization_operations.hpp" #include "simple_low_precision_transformer.hpp" #include "lpt_ngraph_functions/multiply_to_group_convolution_function.hpp" using namespace testing; using namespace ngraph::pass; using namespace ngraph::builder::subgraph; class MultiplyToGroupConvolutionTransformationTestValues { public: class Actual { public: ngraph::element::Type precisionBeforeDequantization; ngraph::builder::subgraph::DequantizationOperations dequantization; }; class Expected { public: ngraph::element::Type inputPrecision; std::shared_ptr<ngraph::opset1::Constant> weights; std::shared_ptr<ngraph::opset1::Constant> biases; ngraph::builder::subgraph::DequantizationOperations dequantization; }; ngraph::Shape inputShape; ngraph::pass::low_precision::LayerTransformation::Params params; bool transformed; bool haveMultiplyWithNoConstBeforeDequantization; Actual actual; Expected expected; }; template <typename T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& values) { os << "{ "; for (size_t i = 0; i < values.size(); ++i) { os << values[i]; if (i != (values.size() - 1ul)) { os << ", "; } } os << " }"; return os; } class MultiplyToGroupConvolutionTransformation : public LayerTransformation, public testing::WithParamInterface<MultiplyToGroupConvolutionTransformationTestValues> { public: void SetUp() override { const MultiplyToGroupConvolutionTransformationTestValues testValues = GetParam(); actualFunction = ngraph::builder::subgraph::MultiplyToGroupConvolutionFunction::getOriginal( testValues.inputShape, testValues.actual.precisionBeforeDequantization, testValues.actual.dequantization, testValues.haveMultiplyWithNoConstBeforeDequantization); SimpleLowPrecisionTransformer transformer; transformer.add<ngraph::pass::low_precision::MultiplyToGroupConvolutionTransformation, ngraph::opset1::Multiply>(testValues.params); transformer.transform(actualFunction); if (testValues.transformed) { referenceFunction = ngraph::builder::subgraph::MultiplyToGroupConvolutionFunction::getReference( testValues.inputShape, testValues.expected.inputPrecision, testValues.expected.weights, testValues.expected.biases, testValues.expected.dequantization); } else { referenceFunction = ngraph::builder::subgraph::MultiplyToGroupConvolutionFunction::getOriginal( testValues.inputShape, testValues.actual.precisionBeforeDequantization, testValues.actual.dequantization, testValues.haveMultiplyWithNoConstBeforeDequantization); } } static std::string getTestCaseName(testing::TestParamInfo<MultiplyToGroupConvolutionTransformationTestValues> obj) { const MultiplyToGroupConvolutionTransformationTestValues testValues = obj.param; std::ostringstream result; result << testValues.inputShape << "_" << testValues.actual.precisionBeforeDequantization << "_" << testValues.transformed << "_" << testValues.haveMultiplyWithNoConstBeforeDequantization << "_" << testValues.actual.dequantization; return result.str(); } }; const std::vector<MultiplyToGroupConvolutionTransformationTestValues> testValues = { // only multiply { ngraph::Shape{ 1, 4, 1, 1 }, LayerTransformation::createParamsU8I8(), true, false, { ngraph::element::u8, { {ngraph::element::f32}, {}, {{0.45f, 0.82f, 0.71f, 0.37f}} } }, { ngraph::element::u8, std::make_shared<ngraph::opset1::Constant>(ngraph::element::i8, ngraph::Shape{4, 1, 1, 1, 1}, std::vector<float>{1.f, 1.f, 1.f, 1.f}), nullptr, { {}, {}, {{0.45f, 0.82f, 0.71f, 0.37f}} } } }, // subtract + multiply { ngraph::Shape{ 1, 4, 1, 1 }, LayerTransformation::createParamsU8I8(), true, false, { ngraph::element::u8, { {ngraph::element::f32}, {{-0.77f, 0.8f, 0.1f, 1.5f}}, {{0.45f, 0.82f, 0.71f, 0.37f}} } }, { ngraph::element::u8, std::make_shared<ngraph::opset1::Constant>(ngraph::element::i8, ngraph::Shape{4, 1, 1, 1, 1}, std::vector<float>{1.f, 1.f, 1.f, 1.f}), std::make_shared<ngraph::opset1::Constant>(ngraph::element::f32, ngraph::Shape{1, 4, 1, 1}, std::vector<float>{0.77f, -0.8f, -0.1f, -1.5f}), { {}, {}, {{0.45f, 0.82f, 0.71f, 0.37f}} } } }, // without convert { ngraph::Shape{ 1, 4, 1, 1 }, LayerTransformation::createParamsU8I8(), true, false, { ngraph::element::u8, { {}, {{1.f, 2.f, 3.f, 4.f}, ngraph::element::f32}, {{0.45f, 0.82f, 0.71f, 0.37f}} } }, { ngraph::element::u8, std::make_shared<ngraph::opset1::Constant>(ngraph::element::i8, ngraph::Shape{4, 1, 1, 1, 1}, std::vector<float>{1.f, 1.f, 1.f, 1.f}), std::make_shared<ngraph::opset1::Constant>(ngraph::element::f32, ngraph::Shape{1, 4, 1, 1}, std::vector<float>{-1.f, -2.f, -3.f, -4.f}), { {}, {}, {{0.45f, 0.82f, 0.71f, 0.37f}} } } }, // 5d { ngraph::Shape{ 1, 4, 1, 1, 1 }, LayerTransformation::createParamsU8I8(), true, false, { ngraph::element::u8, { {}, {{1.f, 2.f, 3.f, 4.f}, ngraph::element::f32}, {{0.45f, 0.82f, 0.71f, 0.37f}} } }, { ngraph::element::u8, std::make_shared<ngraph::opset1::Constant>(ngraph::element::i8, ngraph::Shape{4, 1, 1, 1, 1, 1}, std::vector<float>{1.f, 1.f, 1.f, 1.f}), std::make_shared<ngraph::opset1::Constant>(ngraph::element::f32, ngraph::Shape{1, 4, 1, 1, 1}, std::vector<float>{-1.f, -2.f, -3.f, -4.f}), { {}, {}, {{0.45f, 0.82f, 0.71f, 0.37f}} } } }, // i8 (not transformed) { ngraph::Shape{ 1, 4, 1, 1 }, LayerTransformation::createParamsU8I8(), false, false, { ngraph::element::i8, { {}, {{1.f, 2.f, 3.f, 4.f}, ngraph::element::f32}, {{0.45f, 0.82f, 0.71f, 0.37f}} } }, {} }, // by spatial dimensions (not transformed) { ngraph::Shape{ 1, 1, 2, 2 }, LayerTransformation::createParamsU8I8(), false, false, { ngraph::element::u8, { {}, {{1.f, 2.f, 3.f, 4.f}, ngraph::element::f32, ngraph::Shape{ 1, 1, 2, 2 }}, {{0.45f, 0.82f, 0.71f, 0.37f}, ngraph::element::f32, ngraph::Shape{ 1, 1, 2, 2 }} } }, {} }, // 3d (not transformed) { ngraph::Shape{ 1, 4, 1 }, LayerTransformation::createParamsU8I8(), false, false, { ngraph::element::u8, { {}, {{1.f, 2.f, 3.f, 4.f}, ngraph::element::f32, ngraph::Shape{ 1, 4, 1 }}, {{0.45f, 0.82f, 0.71f, 0.37f}, ngraph::element::f32, ngraph::Shape{ 1, 4, 1 }} } }, {} }, { ngraph::Shape{ 1, 4, 1, 1 }, LayerTransformation::createParamsU8I8(), false, true, { ngraph::element::u8, { {}, {}, {{0.45f, 0.82f, 0.71f, 0.37f}} } }, { ngraph::element::u8, std::make_shared<ngraph::opset1::Constant>(ngraph::element::i8, ngraph::Shape{4, 1, 1, 1, 1}, std::vector<float>{1.f, 1.f, 1.f, 1.f}), nullptr, { {}, {}, {{0.45f, 0.82f, 0.71f, 0.37f}} } } }, }; TEST_P(MultiplyToGroupConvolutionTransformation, CompareFunctions) { actualFunction->validate_nodes_and_infer_types(); auto res = compare_functions(referenceFunction, actualFunction, true, true); ASSERT_TRUE(res.first) << res.second; } INSTANTIATE_TEST_CASE_P( smoke_LPT, MultiplyToGroupConvolutionTransformation, ::testing::ValuesIn(testValues), MultiplyToGroupConvolutionTransformation::getTestCaseName);
32.413559
152
0.538695
[ "shape", "vector", "transform", "3d" ]
f51391861350f602f0909bfc5237d7f029079b58
19,760
cc
C++
AICamera/app/src/main/cpp/caffe2/core/blob_serialization.cc
blackxer/AICamera
4f0a6a09a2288da2ec7140744b5c2862df114c78
[ "MIT" ]
1
2020-01-10T02:56:03.000Z
2020-01-10T02:56:03.000Z
AICamera/app/src/main/cpp/caffe2/core/blob_serialization.cc
blackxer/AICamera
4f0a6a09a2288da2ec7140744b5c2862df114c78
[ "MIT" ]
null
null
null
AICamera/app/src/main/cpp/caffe2/core/blob_serialization.cc
blackxer/AICamera
4f0a6a09a2288da2ec7140744b5c2862df114c78
[ "MIT" ]
null
null
null
#include "caffe2/core/blob_serialization.h" #include <sstream> #include <mutex> #include "caffe2/core/blob.h" #include "caffe2/utils/proto_utils.h" C10_DEFINE_int( caffe2_tensor_chunk_size, 1000000, "Chunk size to split tensor data into"); C10_DEFINE_int( caffe2_max_tensor_serializer_threads, 16, "Maximal number of threads that can be used for tensor serialization"); C10_DEFINE_bool( caffe2_serialize_fp16_as_bytes, false, "Serialize FLOAT16 tensors using byte_data field"); namespace caffe2 { /** * @brief StringSerializer is the serializer for String. * * StringSerializer takes in a blob that contains a String, and serializes it * into a BlobProto protocol buffer. */ class StringSerializer : public BlobSerializerBase { public: StringSerializer() {} ~StringSerializer() {} /** * Serializes a Blob. Note that this blob has to contain Tensor, * otherwise this function produces a fatal error. */ void Serialize( const void* pointer, TypeMeta typeMeta, const string& name, SerializationAcceptor acceptor) override { CAFFE_ENFORCE(typeMeta.Match<std::string>()); BlobProto blob_proto; blob_proto.set_name(name); blob_proto.set_type("std::string"); blob_proto.set_content(*static_cast<const std::string*>(pointer)); acceptor(name, SerializeBlobProtoAsString_EnforceCheck(blob_proto)); } }; /** * @brief StringDeserializer is the deserializer for Strings. * */ class StringDeserializer : public BlobDeserializerBase { public: void Deserialize(const BlobProto& proto, Blob* blob) override { *blob->GetMutable<std::string>() = proto.content(); } }; namespace { void SerializeBlob( const void* pointer, TypeMeta typeMeta, const string& name, BlobSerializerBase::SerializationAcceptor acceptor, int chunk_size) { std::unique_ptr<BlobSerializerBase> serializer( CreateSerializer(typeMeta.id())); CAFFE_ENFORCE(serializer, "No known serializer for ", typeMeta.name()); serializer->SerializeWithChunkSize( pointer, typeMeta, name, acceptor, chunk_size); } std::string SerializeBlob(const void* pointer, TypeMeta typeMeta, const string& name) { std::string data; BlobSerializerBase::SerializationAcceptor acceptor = [&data](const std::string&, const std::string& blob_str) { DCHECK(data.empty()); // should be called once with kNoChunking data = blob_str; }; SerializeBlob(pointer, typeMeta, name, acceptor, kNoChunking); return data; } } // namespace void SerializeBlob( const Blob& blob, const string& name, BlobSerializerBase::SerializationAcceptor acceptor, int chunk_size) { SerializeBlob(blob.GetRaw(), blob.meta(), name, acceptor, chunk_size); } std::string SerializeBlob(const Blob& blob, const string& name) { return SerializeBlob(blob.GetRaw(), blob.meta(), name); } void TensorSerializer::Serialize( const void* pointer, TypeMeta typeMeta, const string& name, BlobSerializerBase::SerializationAcceptor acceptor) { this->SerializeWithChunkSize( pointer, typeMeta, name, acceptor, kDefaultChunkSize); } void TensorSerializer::SerializeWithChunkSize( const void* pointer, TypeMeta typeMeta, const string& name, BlobSerializerBase::SerializationAcceptor acceptor, int chunk_size) { CAFFE_ENFORCE(typeMeta.Match<Tensor>()); const auto& tensor = *static_cast<const Tensor*>(pointer); if (chunk_size == kNoChunking) { chunk_size = tensor.numel() + 1; // to account for empty tensors } else if (chunk_size == kDefaultChunkSize) { chunk_size = FLAGS_caffe2_tensor_chunk_size; } auto processChunk = [&](int64_t chunkStart) { BlobProto blob_proto; blob_proto.set_name(name); blob_proto.set_type(kTensorBlobType); TensorProto& proto = *blob_proto.mutable_tensor(); proto.set_name(name); this->Serialize( tensor, name, blob_proto.mutable_tensor(), chunkStart, chunk_size); acceptor( c10::str(name, kChunkIdSeparator, chunkStart / chunk_size), SerializeBlobProtoAsString_EnforceCheck(blob_proto)); }; #ifndef __ANDROID__ std::vector<std::future<void>> futures; // Poorman's IOBound ThreadPool SimpleQueue<size_t> chunkQueue; auto task = [&]() { size_t chunkStart; while (chunkQueue.Pop(&chunkStart)) { processChunk(chunkStart); } }; if (tensor.numel() > chunk_size) { for (int i = 0; i < FLAGS_caffe2_max_tensor_serializer_threads; ++i) { futures.emplace_back(std::async(std::launch::async, task)); } } #endif VLOG(1) << "Serializing blob " << name; // Serialize whole vector. If vector is empty, it's shape still needs to be // serialized in empty proto for (size_t chunkBegin = 0; chunkBegin < std::max(tensor.numel(), static_cast<int64_t>(1)); chunkBegin += chunk_size) { VLOG(2) << "Starting a chunk at " << chunkBegin; #ifndef __ANDROID__ if (tensor.numel() > chunk_size) { chunkQueue.Push(chunkBegin); } else { // Sync mode for small tensors processChunk(chunkBegin); } #else // Since Android does not have std::future, we will always do sync mode processChunk(chunkBegin); #endif } #ifndef __ANDROID__ chunkQueue.NoMoreJobs(); for (auto& fut : futures) { fut.get(); } #endif } void TensorSerializer::Serialize( const Tensor& input, const string& name, TensorProto* proto_ptr, size_t chunkBegin, int32_t chunkSize) { CAFFE_ENFORCE( chunkBegin <= input.numel(), "Chunk begin is out of tensor: ", chunkBegin, ' ', input.numel()); if (chunkBegin + chunkSize > input.numel()) { chunkSize = input.numel() - chunkBegin; } if (chunkSize != 0) { CAFFE_ENFORCE( input.raw_data(), "The input does not have data input yet. This is probably because you " "created a tensor of non-zero shape but never filled its data via " "mutable_data() calls. This means that it makes no sense to serialize " "the tensor content."); } else if (!input.dtype_initialized()) { C10_LOG_EVERY_MS(WARNING, 1000) << "You're trying to serialize tensor with zero numel and no dtype. " << "This is a legacy behavior and it WILL BREAK. Contact PyTorch team " << "for details. Offending blob name: " << name; } TensorProto& proto = *proto_ptr; proto.mutable_segment()->set_begin(chunkBegin); proto.mutable_segment()->set_end(chunkBegin + chunkSize); for (int i = 0; i < input.dim(); ++i) { proto.add_dims(input.size(i)); } const TensorProto::DataType data_type = TypeMetaToDataType(input.dtype()); proto.set_data_type(data_type); StoreDeviceDetail(input, &proto); // TODO: use DeviceGuard here instead of context and employ explicit sync // copy auto uniq_ptr = CreateContext(input.GetDevice()); // A lot of copypaste is error prone. Should we create a macro for this? switch (data_type) { case TensorProto_DataType_FLOAT: detail::CopyToProtoAsIs( chunkSize, input.template data<float>() + chunkBegin, proto.mutable_float_data(), uniq_ptr.get()); break; case TensorProto_DataType_INT32: detail::CopyToProtoAsIs( chunkSize, input.template data<int>() + chunkBegin, proto.mutable_int32_data(), uniq_ptr.get()); break; case TensorProto_DataType_BYTE: LOG(FATAL) << "This should not happen. When serializing, " "BYTE is deprecated and moved to UINT8."; break; case TensorProto_DataType_STRING: { proto.mutable_string_data()->Reserve(chunkSize); const string* content = input.template data<string>(); for (int i = chunkBegin; i < chunkBegin + chunkSize; ++i) { proto.add_string_data(content[i]); } break; } case TensorProto_DataType_BOOL: detail::CopyToProtoWithCast( chunkSize, input.template data<bool>() + chunkBegin, proto.mutable_int32_data(), uniq_ptr.get()); break; case TensorProto_DataType_UINT8: detail::CopyToProtoWithCast( chunkSize, input.template data<uint8_t>() + chunkBegin, proto.mutable_int32_data(), uniq_ptr.get()); break; case TensorProto_DataType_INT8: detail::CopyToProtoWithCast( chunkSize, input.template data<int8_t>() + chunkBegin, proto.mutable_int32_data(), uniq_ptr.get()); break; case TensorProto_DataType_UINT16: detail::CopyToProtoWithCast( chunkSize, input.template data<uint16_t>() + chunkBegin, proto.mutable_int32_data(), uniq_ptr.get()); break; case TensorProto_DataType_INT16: detail::CopyToProtoWithCast( chunkSize, input.template data<int16_t>() + chunkBegin, proto.mutable_int32_data(), uniq_ptr.get()); break; case TensorProto_DataType_INT64: detail::CopyToProtoAsIs( chunkSize, input.template data<int64_t>() + chunkBegin, proto.mutable_int64_data(), uniq_ptr.get()); break; case TensorProto_DataType_FLOAT16: { if (FLAGS_caffe2_serialize_fp16_as_bytes) { const int kValue = 1; CAFFE_ENFORCE_EQ( reinterpret_cast<const char*>(&kValue)[0], 1, "Serialization of FLOAT16 on big endian platform " "is not written yet."); unique_ptr<char[]> buffer(new char[2 * chunkSize]); this->context_->template CopyToCPU<char>( 2 * chunkSize, reinterpret_cast<const char*>( input.template data<at::Half>() + chunkBegin), buffer.get()); this->context_->FinishDeviceComputation(); proto.set_byte_data(buffer.release(), 2 * chunkSize); } else { detail::CopyToProtoWithCast( chunkSize, reinterpret_cast<const uint16_t*>(input.template data<at::Half>()) + chunkBegin, proto.mutable_int32_data(), uniq_ptr.get()); } } break; case TensorProto_DataType_DOUBLE: detail::CopyToProtoAsIs( chunkSize, input.template data<double>() + chunkBegin, proto.mutable_double_data(), uniq_ptr.get()); break; case TensorProto_DataType_UNDEFINED: { proto.mutable_string_data()->Reserve(chunkSize); if (chunkSize > 0) { const char* raw_data = static_cast<const char*>(input.raw_data()); for (int i = chunkBegin; i < chunkBegin + chunkSize; ++i) { proto.add_string_data(SerializeBlob( raw_data + i * input.itemsize(), input.dtype(), "")); } } } break; // Note: we intentially do not provide "default:" so if any new data types // are added, the compiler should warn the user to add the case here. } } int GetGPUIDForPointer(const void* ptr); void TensorSerializer::StoreDeviceDetail( const Tensor& input, TensorProto* proto) { ExtractDeviceOption(proto->mutable_device_detail(), input.GetDevice()); } // The actual serialization registry objects. C10_DEFINE_TYPED_REGISTRY( BlobSerializerRegistry, TypeIdentifier, BlobSerializerBase, std::unique_ptr); C10_DEFINE_REGISTRY(BlobDeserializerRegistry, BlobDeserializerBase); void DeserializeBlob(const string& content, Blob* result) { BlobProto blob_proto; CAFFE_ENFORCE( blob_proto.ParseFromString(content), "Cannot parse content into a BlobProto."); DeserializeBlob(blob_proto, result); } void DeserializeBlob(const BlobProto& blob_proto, Blob* result) { if (blob_proto.type() == kTensorBlobType) { // This is a tensor object. Depending on the device type, we will // use the corresponding TensorDeserializer. auto deserializer = CreateDeserializer( "Tensor" + DeviceTypeName(blob_proto.tensor().device_detail().device_type())); // Tensor's deserializer should always be registered, but we will double // check if it is not null anyway. CAFFE_ENFORCE(deserializer.get()); deserializer->Deserialize(blob_proto, result); } else { auto deserializer = CreateDeserializer(blob_proto.type()); CAFFE_ENFORCE( deserializer.get(), "No registered deserializer for type ", blob_proto.type()); deserializer->Deserialize(blob_proto, result); } } void TensorDeserializer::Deserialize(const BlobProto& blob_proto, Blob* blob) { auto tensor_proto = blob_proto.tensor(); Deserialize( tensor_proto, BlobGetMutableTensor( blob, static_cast<DeviceType>(tensor_proto.device_detail().device_type()))); } void TensorDeserializer::Deserialize(const TensorProto& proto, Tensor* tensor) { // We create a local context for deserializing. Since Caffe2 contexts are // usually lightweight, this should not involve too much overhead. auto uniq_ptr = CreateContext(OptionToDevice(proto.device_detail())); auto context = uniq_ptr.get(); context->SwitchToDevice(0); vector<int64_t> dims; for (const int64_t d : proto.dims()) { dims.push_back(d); } tensor->Resize(dims); int64_t chunkBegin = 0; auto chunkEnd = tensor->numel(); if (proto.has_segment()) { chunkBegin = proto.segment().begin(); chunkEnd = proto.segment().end(); } CAFFE_ENFORCE( 0 <= chunkBegin && chunkBegin <= chunkEnd && chunkEnd <= tensor->numel(), "Invalid chunk ", chunkBegin, ' ', chunkEnd, " with total tensor size ", tensor->numel()); auto chunkSize = chunkEnd - chunkBegin; switch (proto.data_type()) { case TensorProto_DataType_FLOAT: detail::CopyFromProtoAsIs( chunkSize, proto.float_data(), tensor->template mutable_data<float>() + chunkBegin, context); break; case TensorProto_DataType_INT32: detail::CopyFromProtoAsIs( chunkSize, proto.int32_data(), tensor->template mutable_data<int>() + chunkBegin, context); break; case TensorProto_DataType_BYTE: // Since BYTE stores the data in a string field instead of a repreated // field we will have it special cased. CAFFE_ENFORCE_EQ( chunkSize, proto.byte_data().size(), "Incorrect proto field size."); context->template CopyToCPU<uint8_t>( chunkSize, reinterpret_cast<const uint8_t*>(proto.byte_data().data()), tensor->template mutable_data<uint8_t>() + chunkBegin); break; case TensorProto_DataType_STRING: // Special handing of string because it is a non-fundamental type. { string* content = tensor->template mutable_data<string>(); for (int i = 0; i < chunkSize; ++i) { content[i + chunkBegin] = proto.string_data(i); } } break; case TensorProto_DataType_BOOL: detail::CopyFromProtoWithCast( chunkSize, proto.int32_data(), tensor->template mutable_data<bool>() + chunkBegin, context); break; case TensorProto_DataType_UINT8: detail::CopyFromProtoWithCast( chunkSize, proto.int32_data(), tensor->template mutable_data<uint8_t>() + chunkBegin, context); break; case TensorProto_DataType_INT8: detail::CopyFromProtoWithCast( chunkSize, proto.int32_data(), tensor->template mutable_data<int8_t>() + chunkBegin, context); break; case TensorProto_DataType_UINT16: detail::CopyFromProtoWithCast( chunkSize, proto.int32_data(), tensor->template mutable_data<uint16_t>() + chunkBegin, context); break; case TensorProto_DataType_INT16: detail::CopyFromProtoWithCast( chunkSize, proto.int32_data(), tensor->template mutable_data<int16_t>() + chunkBegin, context); break; case TensorProto_DataType_INT64: detail::CopyFromProtoAsIs( chunkSize, proto.int64_data(), tensor->template mutable_data<int64_t>() + chunkBegin, context); break; case TensorProto_DataType_FLOAT16: if (proto.has_byte_data()) { const int kValue = 1; CAFFE_ENFORCE_EQ( reinterpret_cast<const char*>(&kValue)[0], 1, "Serialization of FLOAT16 on big endian platform " "is not written yet."); CAFFE_ENFORCE_EQ( 2 * chunkSize, proto.byte_data().size(), "Incorrect proto field size."); context->template CopyToCPU<at::Half>( chunkSize, reinterpret_cast<const at::Half*>(proto.byte_data().data()), tensor->template mutable_data<at::Half>() + chunkBegin); } else { // Backward compatibility with models which used int32_data field detail::CopyFromProtoWithCast( chunkSize, proto.int32_data(), reinterpret_cast<uint16_t*>( tensor->template mutable_data<at::Half>()) + chunkBegin, context); } break; case TensorProto_DataType_DOUBLE: detail::CopyFromProtoAsIs( chunkSize, proto.double_data(), tensor->template mutable_data<double>() + chunkBegin, context); break; case TensorProto_DataType_UNDEFINED: { Blob temp_blob; void* raw_ptr = nullptr; for (int i = 0; i < chunkSize; ++i) { DeserializeBlob(proto.string_data(i), &temp_blob); if (i == 0) { raw_ptr = tensor->raw_mutable_data(temp_blob.meta()); } temp_blob.meta().copy()( temp_blob.GetRaw(), static_cast<char*>(raw_ptr) + (i + chunkBegin) * temp_blob.meta().itemsize(), 1); } } break; // Note: we intentially do not provide "default:" so if any new data types } context->FinishDeviceComputation(); } //////////////////////////////////////////////////////////////////////////////// // Serialization Helpers //////////////////////////////////////////////////////////////////////////////// std::string SerializeAsString_EnforceCheck( const google::protobuf::MessageLite& msg, const char* error_location) { std::string serialize_output; bool result = msg.SerializeToString(&serialize_output); if (!error_location) { CAFFE_ENFORCE(result, "protobuf::SerializeToString failed"); } else { CAFFE_ENFORCE(result, "protobuf::SerializeToString failed for ", error_location); } return serialize_output; } namespace { // Serialize Tensor REGISTER_BLOB_SERIALIZER((TypeMeta::Id<Tensor>()), TensorSerializer); REGISTER_BLOB_DESERIALIZER(TensorCPU, TensorDeserializer); // Serialize std::string REGISTER_BLOB_SERIALIZER((TypeMeta::Id<std::string>()), StringSerializer); REGISTER_BLOB_DESERIALIZER(std::string, StringDeserializer); } // namespace } // namespace caffe2
33.777778
81
0.628745
[ "object", "shape", "vector" ]
f5139a7dbbbe48d3ec18f9363b7a335c95f62225
9,063
cc
C++
stats/rtc_stats.cc
Numbrs/WebRTC
d9348ec831b8a1f178ce1a92877f04b1fbd27a04
[ "BSD-3-Clause" ]
128
2019-10-07T14:03:15.000Z
2022-02-25T10:25:57.000Z
stats/rtc_stats.cc
Numbrs/WebRTC
d9348ec831b8a1f178ce1a92877f04b1fbd27a04
[ "BSD-3-Clause" ]
51
2019-10-19T04:58:30.000Z
2022-01-03T07:16:46.000Z
stats/rtc_stats.cc
Numbrs/WebRTC
d9348ec831b8a1f178ce1a92877f04b1fbd27a04
[ "BSD-3-Clause" ]
90
2019-10-16T06:13:14.000Z
2022-03-02T10:29:19.000Z
/* * Copyright 2016 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "api/stats/rtc_stats.h" #include <cstdio> #include "rtc_base/arraysize.h" #include "rtc_base/string_encode.h" #include "rtc_base/strings/string_builder.h" namespace webrtc { namespace { // Produces "[a,b,c]". Works for non-vector |RTCStatsMemberInterface::Type| // types. template <typename T> std::string VectorToString(const std::vector<T>& vector) { rtc::StringBuilder sb; sb << "["; const char* separator = ""; for (const T& element : vector) { sb << separator << rtc::ToString(element); separator = ","; } sb << "]"; return sb.Release(); } // Produces "[\"a\",\"b\",\"c\"]". Works for vectors of both const char* and // std::string element types. template <typename T> std::string VectorOfStringsToString(const std::vector<T>& strings) { rtc::StringBuilder sb; sb << "["; const char* separator = ""; for (const T& element : strings) { sb << separator << "\"" << rtc::ToString(element) << "\""; separator = ","; } sb << "]"; return sb.Release(); } template <typename T> std::string ToStringAsDouble(const T value) { // JSON represents numbers as floating point numbers with about 15 decimal // digits of precision. char buf[32]; const int len = std::snprintf(&buf[0], arraysize(buf), "%.16g", static_cast<double>(value)); RTC_DCHECK_LE(len, arraysize(buf)); return std::string(&buf[0], len); } template <typename T> std::string VectorToStringAsDouble(const std::vector<T>& vector) { rtc::StringBuilder sb; sb << "["; const char* separator = ""; for (const T& element : vector) { sb << separator << ToStringAsDouble<T>(element); separator = ","; } sb << "]"; return sb.Release(); } } // namespace bool RTCStats::operator==(const RTCStats& other) const { if (type() != other.type() || id() != other.id()) return false; std::vector<const RTCStatsMemberInterface*> members = Members(); std::vector<const RTCStatsMemberInterface*> other_members = other.Members(); RTC_DCHECK_EQ(members.size(), other_members.size()); for (size_t i = 0; i < members.size(); ++i) { const RTCStatsMemberInterface* member = members[i]; const RTCStatsMemberInterface* other_member = other_members[i]; RTC_DCHECK_EQ(member->type(), other_member->type()); RTC_DCHECK_EQ(member->name(), other_member->name()); if (*member != *other_member) return false; } return true; } bool RTCStats::operator!=(const RTCStats& other) const { return !(*this == other); } std::string RTCStats::ToJson() const { rtc::StringBuilder sb; sb << "{\"type\":\"" << type() << "\"," << "\"id\":\"" << id_ << "\"," << "\"timestamp\":" << timestamp_us_; for (const RTCStatsMemberInterface* member : Members()) { if (member->is_defined()) { sb << ",\"" << member->name() << "\":"; if (member->is_string()) sb << "\"" << member->ValueToJson() << "\""; else sb << member->ValueToJson(); } } sb << "}"; return sb.Release(); } std::vector<const RTCStatsMemberInterface*> RTCStats::Members() const { return MembersOfThisObjectAndAncestors(0); } std::vector<const RTCStatsMemberInterface*> RTCStats::MembersOfThisObjectAndAncestors(size_t additional_capacity) const { std::vector<const RTCStatsMemberInterface*> members; members.reserve(additional_capacity); return members; } #define WEBRTC_DEFINE_RTCSTATSMEMBER(T, type, is_seq, is_str, to_str, to_json) \ template <> \ const RTCStatsMemberInterface::Type RTCStatsMember<T>::kType = \ RTCStatsMemberInterface::type; \ template <> \ bool RTCStatsMember<T>::is_sequence() const { \ return is_seq; \ } \ template <> \ bool RTCStatsMember<T>::is_string() const { \ return is_str; \ } \ template <> \ std::string RTCStatsMember<T>::ValueToString() const { \ RTC_DCHECK(is_defined_); \ return to_str; \ } \ template <> \ std::string RTCStatsMember<T>::ValueToJson() const { \ RTC_DCHECK(is_defined_); \ return to_json; \ } WEBRTC_DEFINE_RTCSTATSMEMBER(bool, kBool, false, false, rtc::ToString(value_), rtc::ToString(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(int32_t, kInt32, false, false, rtc::ToString(value_), rtc::ToString(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(uint32_t, kUint32, false, false, rtc::ToString(value_), rtc::ToString(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(int64_t, kInt64, false, false, rtc::ToString(value_), ToStringAsDouble(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(uint64_t, kUint64, false, false, rtc::ToString(value_), ToStringAsDouble(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(double, kDouble, false, false, rtc::ToString(value_), ToStringAsDouble(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(std::string, kString, false, true, value_, value_) WEBRTC_DEFINE_RTCSTATSMEMBER(std::vector<bool>, kSequenceBool, true, false, VectorToString(value_), VectorToString(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(std::vector<int32_t>, kSequenceInt32, true, false, VectorToString(value_), VectorToString(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(std::vector<uint32_t>, kSequenceUint32, true, false, VectorToString(value_), VectorToString(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(std::vector<int64_t>, kSequenceInt64, true, false, VectorToString(value_), VectorToStringAsDouble(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(std::vector<uint64_t>, kSequenceUint64, true, false, VectorToString(value_), VectorToStringAsDouble(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(std::vector<double>, kSequenceDouble, true, false, VectorToString(value_), VectorToStringAsDouble(value_)) WEBRTC_DEFINE_RTCSTATSMEMBER(std::vector<std::string>, kSequenceString, true, false, VectorOfStringsToString(value_), VectorOfStringsToString(value_)) } // namespace webrtc
38.896996
80
0.471257
[ "vector" ]
f51556020ddc39a1e7fd0bb6c1b74156d6709f01
5,627
hpp
C++
nheqminer/3rdparty/boost/fiber/algo/detail/chase_lev_queue.hpp
EuroLine/nheqminer
81c7ef889bb502d16f7d1e7ef020d0592f8af945
[ "MIT" ]
886
2016-10-20T20:59:59.000Z
2022-03-12T07:47:52.000Z
ios/Pods/boost-for-react-native/boost/fiber/algo/detail/chase_lev_queue.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
369
2016-10-21T07:42:54.000Z
2020-11-19T10:49:29.000Z
ios/Pods/boost-for-react-native/boost/fiber/algo/detail/chase_lev_queue.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
534
2016-10-20T21:00:00.000Z
2022-03-29T10:02:27.000Z
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_ALGO_DETAIL_CHASE_LEV_QUEUE_H #define BOOST_FIBERS_ALGO_DETAIL_CHASE_LEV_QUEUE_H #include <atomic> #include <cstddef> #include <memory> #include <type_traits> #include <vector> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/fiber/detail/config.hpp> #include <boost/fiber/context.hpp> // David Chase and Yossi Lev. Dynamic circular work-stealing deque. // In SPAA ’05: Proceedings of the seventeenth annual ACM symposium // on Parallelism in algorithms and architectures, pages 21–28, // New York, NY, USA, 2005. ACM. // // Nhat Minh Lê, Antoniu Pop, Albert Cohen, and Francesco Zappa Nardelli. 2013. // Correct and efficient work-stealing for weak memory models. // In Proceedings of the 18th ACM SIGPLAN symposium on Principles and practice // of parallel programming (PPoPP '13). ACM, New York, NY, USA, 69-80. namespace boost { namespace fibers { namespace algo { namespace detail { class chase_lev_queue { private: class circular_buffer { private: typedef typename std::aligned_storage< sizeof( context *), alignof( context *) >::type storage_t; int64_t size_; context ** items; chase_lev_queue * queue_; public: circular_buffer( int64_t size, chase_lev_queue * queue) noexcept : size_{ size }, items{ reinterpret_cast< context ** >( new storage_t[size_] ) }, queue_{ queue } { } ~circular_buffer() { delete [] reinterpret_cast< storage_t * >( items); } int64_t size() const noexcept { return size_; } context * get( int64_t idx) noexcept { BOOST_ASSERT( 0 <= idx); return * (items + (idx & (size() - 1))); } void put( int64_t idx, context * ctx) noexcept { BOOST_ASSERT( 0 <= idx); * (items + (idx & (size() - 1))) = ctx; } circular_buffer * grow( int64_t top, int64_t bottom) { BOOST_ASSERT( 0 <= top); BOOST_ASSERT( 0 <= bottom); circular_buffer * buffer = new circular_buffer{ size() * 2, queue_ }; queue_->old_buffers_.push_back( this); for ( int64_t i = top; i != bottom; ++i) { buffer->put( i, get( i) ); } return buffer; } }; std::atomic< int64_t > top_{ 0 }; std::atomic< int64_t > bottom_{ 0 }; std::atomic< circular_buffer * > buffer_; std::vector< circular_buffer * > old_buffers_; public: chase_lev_queue() : buffer_{ new circular_buffer{ 1024, this } } { old_buffers_.resize( 10); } ~chase_lev_queue() { delete buffer_.load( std::memory_order_seq_cst); for ( circular_buffer * buffer : old_buffers_) { delete buffer; } } chase_lev_queue( chase_lev_queue const&) = delete; chase_lev_queue( chase_lev_queue &&) = delete; chase_lev_queue & operator=( chase_lev_queue const&) = delete; chase_lev_queue & operator=( chase_lev_queue &&) = delete; bool empty() const noexcept { int64_t bottom = bottom_.load( std::memory_order_relaxed); int64_t top = top_.load( std::memory_order_relaxed); return bottom <= top; } void push( context * ctx) { int64_t bottom = bottom_.load( std::memory_order_relaxed); int64_t top = top_.load( std::memory_order_acquire); circular_buffer * buffer = buffer_.load( std::memory_order_relaxed); if ( (bottom - top) > buffer->size() - 1) { // queue is full buffer = buffer->grow( top, bottom); buffer_.store( buffer, std::memory_order_release); } buffer->put( bottom, ctx); std::atomic_thread_fence( std::memory_order_release); bottom_.store( bottom + 1, std::memory_order_relaxed); } context * pop() { int64_t bottom = bottom_.load( std::memory_order_relaxed) - 1; circular_buffer * buffer = buffer_.load( std::memory_order_relaxed); bottom_.store( bottom, std::memory_order_relaxed); std::atomic_thread_fence( std::memory_order_seq_cst); int64_t top = top_.load( std::memory_order_relaxed); context * ctx = nullptr; if ( top <= bottom) { // queue is not empty ctx = buffer->get( bottom); // last element if ( top == bottom) { if ( ! top_.compare_exchange_strong( top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed) ) { return nullptr; } bottom_.store( bottom + 1, std::memory_order_relaxed); } } else { // queue is empty bottom_.store( bottom + 1, std::memory_order_relaxed); } return ctx; } context * steal() { int64_t top = top_.load( std::memory_order_acquire); std::atomic_thread_fence( std::memory_order_seq_cst); int64_t bottom = bottom_.load( std::memory_order_acquire); context * ctx = nullptr; if ( top < bottom) { // queue is not empty circular_buffer * buffer = buffer_.load( std::memory_order_consume); ctx = buffer->get( top); if ( ! top_.compare_exchange_strong( top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed) ) { return nullptr; } } return ctx; } }; }}}} #endif // #define BOOST_FIBERS_ALGO_DETAIL_CHASE_LEV_QUEUE_H
32.526012
110
0.617558
[ "vector" ]
f51561a0686225bed6e5fb75d2dc235d3113b83b
1,901
cpp
C++
src/count/tri_count.cpp
srom/nbias
be8cf8dd623038dcf08d38ed3d19f635ee2dbeae
[ "MIT" ]
null
null
null
src/count/tri_count.cpp
srom/nbias
be8cf8dd623038dcf08d38ed3d19f635ee2dbeae
[ "MIT" ]
null
null
null
src/count/tri_count.cpp
srom/nbias
be8cf8dd623038dcf08d38ed3d19f635ee2dbeae
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <future> #include "../codons/codons.cpp" using namespace std; int CountKmer(const string& content, const string& kmer, const bool overlap) { int count = 0; string::size_type pos = 0; for (;;) { pos = content.find(kmer, pos); if (pos == string::npos) { break; } ++count; if (overlap) { ++pos; } else { pos += kmer.size(); } } return count; } vector<int> CountTriNucleotidesAsync(const string& content, const bool overlap) { vector<future<int>> futures; for (auto& codon : CODONS) { futures.push_back(async(CountKmer, content, codon, overlap)); } vector<int> counts; for (auto& f : futures) { counts.push_back(f.get()); } return counts; } vector<int> CountTriNucleotidesSequential(const string& content, const bool overlap) { vector<int> counts; for (auto& codon : CODONS) { counts.push_back(CountKmer(content, codon, overlap)); } return counts; } vector<int> CountTriNucleotides(const string& content, const bool overlap, const bool use_async) { if (use_async) { return CountTriNucleotidesAsync(content, overlap); } else { return CountTriNucleotidesSequential(content, overlap); } } vector<int> CountAminoAcidsAsync(const string& content) { vector<future<int>> futures; for (auto& aa : AMINO_ACIDS_ONE_LETTER) { futures.push_back(async(CountKmer, content, aa, true)); } vector<int> counts; for (auto& f : futures) { counts.push_back(f.get()); } return counts; } vector<int> CountAminoAcidsSequential(const string& content) { vector<int> counts; for (auto& aa : AMINO_ACIDS_ONE_LETTER) { counts.push_back(CountKmer(content, aa, true)); } return counts; } vector<int> CountAminoAcids(const string& content, const bool use_async) { if (use_async) { return CountAminoAcidsAsync(content); } else { return CountAminoAcidsSequential(content); } }
23.469136
98
0.692267
[ "vector" ]
f515ca9a1ea5b573d5920b1fb5a7ca2dcd1ea949
47,461
cc
C++
src/evolution/dglapbuilder.cc
intrepid42/apfelxx
34b0bb4f134ddf42aa7eccceaa6c3b91b5414cd6
[ "MIT" ]
null
null
null
src/evolution/dglapbuilder.cc
intrepid42/apfelxx
34b0bb4f134ddf42aa7eccceaa6c3b91b5414cd6
[ "MIT" ]
null
null
null
src/evolution/dglapbuilder.cc
intrepid42/apfelxx
34b0bb4f134ddf42aa7eccceaa6c3b91b5414cd6
[ "MIT" ]
null
null
null
// // APFEL++ 2017 // // Authors: Valerio Bertone: valerio.bertone@cern.ch // #include "apfel/dglapbuilder.h" #include "apfel/timer.h" #include "apfel/constants.h" #include "apfel/tools.h" #include "apfel/messages.h" #include "apfel/splittingfunctions.h" #include "apfel/splittingfunctions_tl.h" #include "apfel/matchingconditions.h" #include "apfel/matchingconditions_tl.h" #include "apfel/evolutionbasisqcd.h" #include "apfel/matchingbasisqcd.h" namespace apfel { //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCD(Grid const& g, std::vector<double> const& Masses, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { report("Initializing DglapObjects for space-like QCD unpolarised evolution... "); Timer t; // Compute initial and final number of active flavours according // to the vector of thresholds (it assumes that the thresholds // vector entries are ordered). int nfi = 0; int nff = Thresholds.size(); for (auto const& v : Thresholds) if (v <= 0) nfi++; // Compute logs of muth2 / m2 needed for the the matching // conditions. std::vector<double> LogKth; for (int im = 0; im < (int) Thresholds.size(); im++) if (Thresholds[im] < eps12 || Masses[im] < eps12) LogKth.push_back(0); else LogKth.push_back(2 * log( Thresholds[im] / Masses[im] )); // Allocate needed operators (matching conditions and splitting // functions). By now the code is fast enough to precompute // everything at all available perturbative orders and the current // perturbative order is accounted for only when the actual // splitting functions and matching conditions (lambda) functions // are defined. // =============================================================== // LO Matching conditions. std::map<int, Operator> MatchLO; const Operator Id {g, Identity{}, IntEps}; const Operator Zero{g, Null{}, IntEps}; MatchLO.insert({MatchingBasisQCD::PNS, Id}); MatchLO.insert({MatchingBasisQCD::PQQ, Id}); MatchLO.insert({MatchingBasisQCD::PQG, Zero}); MatchLO.insert({MatchingBasisQCD::PGQ, Zero}); MatchLO.insert({MatchingBasisQCD::PGG, Id}); for (int i = MatchingBasisQCD::PT3Q; i <= MatchingBasisQCD::PT35Q; i++) MatchLO.insert({i, Id}); for (int i = MatchingBasisQCD::PT3G; i <= MatchingBasisQCD::PT35G; i++) MatchLO.insert({i, Zero}); // =============================================================== // LO splitting function operators. std::map<int, std::map<int, Operator>> OpMapLO; const Operator O0ns{g, P0ns{}, IntEps}; const Operator O0qg{g, P0qg{}, IntEps}; const Operator O0gq{g, P0gq{}, IntEps}; for (int nf = nfi; nf <= nff; nf++) { const Operator O0gg{g, P0gg{nf}, IntEps}; const Operator O0qgnf = nf * O0qg; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O0ns}); OM.insert({EvolutionBasisQCD::PNSM, O0ns}); OM.insert({EvolutionBasisQCD::PNSV, O0ns}); OM.insert({EvolutionBasisQCD::PQQ, O0ns}); OM.insert({EvolutionBasisQCD::PQG, O0qgnf}); OM.insert({EvolutionBasisQCD::PGQ, O0gq}); OM.insert({EvolutionBasisQCD::PGG, O0gg}); OpMapLO.insert({nf, OM}); } // =============================================================== // NLO Matching conditions. std::map<int, std::map<int, Operator>> MatchNLO; const Operator AS1HgL {g, AS1Hg_L{}, IntEps}; const Operator AS1ggHL{g, AS1ggH_L{}, IntEps}; for (int nf = nfi; nf <= nff; nf++) { const Operator AS1Hg = LogKth[nf-1] * AS1HgL; const Operator AS1ggH = LogKth[nf-1] * AS1ggHL; const Operator AS1Tg = - nf * AS1Hg; std::map<int, Operator> OM; OM.insert({MatchingBasisQCD::PNS, Zero}); OM.insert({MatchingBasisQCD::PQQ, Zero}); OM.insert({MatchingBasisQCD::PQG, AS1Hg}); OM.insert({MatchingBasisQCD::PGQ, Zero}); OM.insert({MatchingBasisQCD::PGG, AS1ggH}); for (int i = MatchingBasisQCD::PT3Q; i <= MatchingBasisQCD::PT35Q; i++) OM.insert({i, Zero}); for (int i = MatchingBasisQCD::PT3G; i <= MatchingBasisQCD::PT35G; i++) if (i > MatchingBasisQCD::PT3G + nf - 1) OM.insert({i, AS1Hg}); else if (i == MatchingBasisQCD::PT3G + nf - 1) OM.insert({i, AS1Tg}); else OM.insert({i, Zero}); MatchNLO.insert({nf, OM}); } // =============================================================== // NLO splitting function operators. std::map<int, std::map<int, Operator>> OpMapNLO; for (int nf = nfi; nf <= nff; nf++) { const Operator O1nsp{g, P1nsp{nf}, IntEps}; const Operator O1nsm{g, P1nsm{nf}, IntEps}; const Operator O1ps {g, P1ps{nf}, IntEps}; const Operator O1qg {g, P1qg{nf}, IntEps}; const Operator O1gq {g, P1gq{nf}, IntEps}; const Operator O1gg {g, P1gg{nf}, IntEps}; const Operator O1qq = O1nsp + O1ps; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O1nsp}); OM.insert({EvolutionBasisQCD::PNSM, O1nsm}); OM.insert({EvolutionBasisQCD::PNSV, O1nsm}); OM.insert({EvolutionBasisQCD::PQQ, O1qq}); OM.insert({EvolutionBasisQCD::PQG, O1qg}); OM.insert({EvolutionBasisQCD::PGQ, O1gq}); OM.insert({EvolutionBasisQCD::PGG, O1gg}); OpMapNLO.insert({nf, OM}); } // =============================================================== // NNLO Matching conditions. std::map<int, std::map<int, Operator>> MatchNNLO; const Operator APS2Hq0 {g, APS2Hq_0{}, IntEps}; const Operator APS2HqL {g, APS2Hq_L{}, IntEps}; const Operator APS2HqL2 {g, APS2Hq_L2{}, IntEps}; const Operator ANS2qqH0 {g, ANS2qqH_0{}, IntEps}; const Operator ANS2qqHL {g, ANS2qqH_L{}, IntEps}; const Operator ANS2qqHL2{g, ANS2qqH_L2{}, IntEps}; const Operator AS2Hg0 {g, AS2Hg_0{}, IntEps}; const Operator AS2HgL {g, AS2Hg_L{}, IntEps}; const Operator AS2HgL2 {g, AS2Hg_L2{}, IntEps}; const Operator AS2gqH0 {g, AS2gqH_0{}, IntEps}; const Operator AS2gqHL {g, AS2gqH_L{}, IntEps}; const Operator AS2gqHL2 {g, AS2gqH_L2{}, IntEps}; const Operator AS2ggH0 {g, AS2ggH_0{}, IntEps}; const Operator AS2ggHL {g, AS2ggH_L{}, IntEps}; const Operator AS2ggHL2 {g, AS2ggH_L2{}, IntEps}; const Operator AS2qqH0 = ANS2qqH0 + APS2Hq0; const Operator AS2qqHL = ANS2qqHL + APS2HqL; const Operator AS2qqHL2 = ANS2qqHL2 + APS2HqL2; for (int nf = nfi; nf <= nff; nf++) { const double lnk = LogKth[nf-1]; const double lnk2 = lnk * lnk; const Operator APS2Hq = APS2Hq0 + lnk * APS2HqL + lnk2 * APS2HqL2; const Operator ANS2qqH = ANS2qqH0 + lnk * ANS2qqHL + lnk2 * ANS2qqHL2; const Operator AS2Hg = AS2Hg0 + lnk * AS2HgL + lnk2 * AS2HgL2; const Operator AS2gqH = AS2gqH0 + lnk * AS2gqHL + lnk2 * AS2gqHL2; const Operator AS2ggH = AS2ggH0 + lnk * AS2ggHL + lnk2 * AS2ggHL2; const Operator AS2qqH = AS2qqH0 + lnk * AS2qqHL + lnk2 * AS2qqHL2; const Operator AS2TqH = ANS2qqH - nf * APS2Hq; const Operator AS2Tg = - nf * AS2Hg; std::map<int, Operator> OM; OM.insert({MatchingBasisQCD::PNS, ANS2qqH}); OM.insert({MatchingBasisQCD::PQQ, AS2qqH}); OM.insert({MatchingBasisQCD::PQG, AS2Hg}); OM.insert({MatchingBasisQCD::PGQ, AS2gqH}); OM.insert({MatchingBasisQCD::PGG, AS2ggH}); for (int i = MatchingBasisQCD::PT3Q; i <= MatchingBasisQCD::PT35Q; i++) if (i > MatchingBasisQCD::PT3Q + nf - 1) OM.insert({i, AS2qqH}); else if (i == MatchingBasisQCD::PT3Q + nf - 1) OM.insert({i, AS2TqH}); else OM.insert({i, ANS2qqH}); for (int i = MatchingBasisQCD::PT3G; i <= MatchingBasisQCD::PT35G; i++) if (i > MatchingBasisQCD::PT3G + nf - 1) OM.insert({i, AS2Hg}); else if (i == MatchingBasisQCD::PT3G + nf - 1) OM.insert({i, AS2Tg}); else OM.insert({i, Zero}); MatchNNLO.insert({nf, OM}); } // =============================================================== // NNLO splitting function operators. std::map<int, std::map<int, Operator>> OpMapNNLO; for (int nf = nfi; nf <= nff; nf++) { const Operator O2nsp{g, P2nsp{nf}, IntEps}; const Operator O2nsm{g, P2nsm{nf}, IntEps}; const Operator O2nss{g, P2nss{nf}, IntEps}; const Operator O2ps {g, P2ps{nf}, IntEps}; const Operator O2qg {g, P2qg{nf}, IntEps}; const Operator O2gq {g, P2gq{nf}, IntEps}; const Operator O2gg {g, P2gg{nf}, IntEps}; const Operator O2qq = O2nsp + O2ps; const Operator O2nsv = O2nsm + O2nss; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O2nsp}); OM.insert({EvolutionBasisQCD::PNSM, O2nsm}); OM.insert({EvolutionBasisQCD::PNSV, O2nsv}); OM.insert({EvolutionBasisQCD::PQQ, O2qq}); OM.insert({EvolutionBasisQCD::PQG, O2qg}); OM.insert({EvolutionBasisQCD::PGQ, O2gq}); OM.insert({EvolutionBasisQCD::PGG, O2gg}); OpMapNNLO.insert({nf, OM}); } // =============================================================== // NNNLO splitting function operators. For now only the // non-singlet splitting functions have been computed to leading // colour even though the subleading colour part is estimated // through an approximate parameterisation. std::map<int, std::map<int, Operator>> OpMapNNNLO; for (int nf = nfi; nf <= nff; nf++) { const Operator O3nsp{g, P3nsp{nf}, IntEps}; const Operator O3nsm{g, P3nsm{nf}, IntEps}; const Operator O3nss{g, P3nss{nf}, IntEps}; const Operator O3nsv = O3nsm + O3nss; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O3nsp}); OM.insert({EvolutionBasisQCD::PNSM, O3nsm}); OM.insert({EvolutionBasisQCD::PNSV, O3nsv}); OM.insert({EvolutionBasisQCD::PQQ, Zero}); OM.insert({EvolutionBasisQCD::PQG, Zero}); OM.insert({EvolutionBasisQCD::PGQ, Zero}); OM.insert({EvolutionBasisQCD::PGG, Zero}); OpMapNNNLO.insert({nf, OM}); } // Define object of the structure containing the DglapObjects. std::map<int, DglapObjects> DglapObj; // Allocate convolution maps for evolution and matching, and set // of operators. for (int nf = nfi; nf <= nff; nf++) { DglapObjects obj; obj.Threshold = Thresholds[nf-1]; if (OpEvol) { const EvolutionOperatorBasisQCD evopb{nf}; const MatchingOperatorBasisQCD mtopb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evopb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evopb, OpMapNLO.at(nf)}}); obj.SplittingFunctions.insert({2, Set<Operator>{evopb, OpMapNNLO.at(nf)}}); obj.SplittingFunctions.insert({3, Set<Operator>{evopb, OpMapNNNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtopb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtopb, MatchNLO.at(nf)}}); obj.MatchingConditions.insert({2, Set<Operator>{mtopb, MatchNNLO.at(nf)}}); } else { const EvolutionBasisQCD evb{nf}; const MatchingBasisQCD mtb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evb, OpMapNLO.at(nf)}}); obj.SplittingFunctions.insert({2, Set<Operator>{evb, OpMapNNLO.at(nf)}}); obj.SplittingFunctions.insert({3, Set<Operator>{evb, OpMapNNNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtb, MatchNLO.at(nf)}}); obj.MatchingConditions.insert({2, Set<Operator>{mtb, MatchNNLO.at(nf)}}); } DglapObj.insert({nf,obj}); } t.stop(); return DglapObj; } //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCD(Grid const& g, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { return InitializeDglapObjectsQCD(g, Thresholds, Thresholds, OpEvol, IntEps); } //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCDT(Grid const& g, std::vector<double> const& Masses, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { report("Initializing DglapObjects for time-like QCD unpolarised evolution... "); Timer t; // Compute initial and final number of active flavours according // to the vector of thresholds (it assumes that the thresholds // vector entries are ordered). int nfi = 0; int nff = Thresholds.size(); for (auto const& v : Thresholds) if (v <= 0) nfi++; // Compute logs of muth2 / m2 needed for the the matching // conditions. std::vector<double> LogKth; for (int im = 0; im < (int) Thresholds.size(); im++) if (Thresholds[im] < eps12 || Masses[im] < eps12) LogKth.push_back(0); else LogKth.push_back(2 * log( Thresholds[im] / Masses[im] )); // Allocate needed operators (matching conditions and splitting // functions). By now the code is fast enough to precompute // everything at all available perturbative orders and the current // perturbative order is accounted for only when the actual // splitting functions and matching conditions (lambda) functions // are defined. // =============================================================== // LO Matching conditions. std::map<int, Operator> MatchLO; const Operator Id {g, Identity{}, IntEps}; const Operator Zero{g, Null{}, IntEps}; MatchLO.insert({MatchingBasisQCD::PNS, Id}); MatchLO.insert({MatchingBasisQCD::PQQ, Id}); MatchLO.insert({MatchingBasisQCD::PQG, Zero}); MatchLO.insert({MatchingBasisQCD::PGQ, Zero}); MatchLO.insert({MatchingBasisQCD::PGG, Id}); for (int i = MatchingBasisQCD::PT3Q; i <= MatchingBasisQCD::PT35Q; i++) MatchLO.insert({i, Id}); for (int i = MatchingBasisQCD::PT3G; i <= MatchingBasisQCD::PT35G; i++) MatchLO.insert({i, Zero}); // =============================================================== // LO splitting function operators. std::map<int, std::map<int, Operator>> OpMapLO; const Operator O0ns{g, P0Tns{}, IntEps}; const Operator O0qg{g, P0Tqg{}, IntEps}; const Operator O0gq{g, P0Tgq{}, IntEps}; for (int nf = nfi; nf <= nff; nf++) { const Operator O0gg{g, P0Tgg{nf}, IntEps}; const Operator O0qgnf = nf * O0qg; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O0ns}); OM.insert({EvolutionBasisQCD::PNSM, O0ns}); OM.insert({EvolutionBasisQCD::PNSV, O0ns}); OM.insert({EvolutionBasisQCD::PQQ, O0ns}); OM.insert({EvolutionBasisQCD::PQG, O0qgnf}); OM.insert({EvolutionBasisQCD::PGQ, O0gq}); OM.insert({EvolutionBasisQCD::PGG, O0gg}); OpMapLO.insert({nf, OM}); } // =============================================================== // NLO Matching conditions. std::map<int, std::map<int, Operator>> MatchNLO; const Operator AS1Hg0 {g, ATS1Hg_0{}, IntEps}; const Operator AS1HgL {g, ATS1Hg_L{}, IntEps}; const Operator AS1ggHL{g, ATS1ggH_L{}, IntEps}; for (int nf = nfi; nf <= nff; nf++) { const Operator AS1Hg = AS1Hg0 + LogKth[nf-1] * AS1HgL; const Operator AS1ggH = LogKth[nf-1] * AS1ggHL; const Operator AS1Tg = - nf * AS1Hg; std::map<int, Operator> OM; OM.insert({MatchingBasisQCD::PNS, Zero}); OM.insert({MatchingBasisQCD::PQQ, Zero}); OM.insert({MatchingBasisQCD::PQG, AS1Hg}); OM.insert({MatchingBasisQCD::PGQ, Zero}); OM.insert({MatchingBasisQCD::PGG, AS1ggH}); for (int i = MatchingBasisQCD::PT3Q; i <= MatchingBasisQCD::PT35Q; i++) OM.insert({i, Zero}); for (int i = MatchingBasisQCD::PT3G; i <= MatchingBasisQCD::PT35G; i++) if (i > MatchingBasisQCD::PT3G + nf - 1) OM.insert({i, AS1Hg}); else if (i == MatchingBasisQCD::PT3G + nf - 1) OM.insert({i, AS1Tg}); else OM.insert({i, Zero}); MatchNLO.insert({nf, OM}); } // =============================================================== // NLO splitting function operators. std::map<int, std::map<int, Operator>> OpMapNLO; for (int nf = nfi; nf <= nff; nf++) { const Operator O1nsp{g, P1Tnsp{nf}, IntEps}; const Operator O1nsm{g, P1Tnsm{nf}, IntEps}; const Operator O1ps {g, P1Tps{nf}, IntEps}; const Operator O1qg {g, P1Tqg{nf}, IntEps}; const Operator O1gq {g, P1Tgq{nf}, IntEps}; const Operator O1gg {g, P1Tgg{nf}, IntEps}; const Operator O1qq = O1nsp + O1ps; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O1nsp}); OM.insert({EvolutionBasisQCD::PNSM, O1nsm}); OM.insert({EvolutionBasisQCD::PNSV, O1nsm}); OM.insert({EvolutionBasisQCD::PQQ, O1qq}); OM.insert({EvolutionBasisQCD::PQG, O1qg}); OM.insert({EvolutionBasisQCD::PGQ, O1gq}); OM.insert({EvolutionBasisQCD::PGG, O1gg}); OpMapNLO.insert({nf, OM}); } // =============================================================== // NNLO Matching conditions. Set to zero for now because they are // not know yet. std::map<int, std::map<int, Operator>> MatchNNLO; for (int nf = nfi; nf <= nff; nf++) { std::map<int, Operator> OM; for (int i = MatchingBasisQCD::PNS; i <= MatchingBasisQCD::PT35G; i++) OM.insert({i, Zero}); MatchNNLO.insert({nf, OM}); } // =============================================================== // NNLO splitting function operators. std::map<int, std::map<int, Operator>> OpMapNNLO; for (int nf = nfi; nf <= nff; nf++) { const Operator O2nsp{g, P2Tnsp{nf}, IntEps}; const Operator O2nsm{g, P2Tnsm{nf}, IntEps}; const Operator O2nss{g, P2Tnss{nf}, IntEps}; const Operator O2ps {g, P2Tps{nf}, IntEps}; const Operator O2qg {g, P2Tqg{nf}, IntEps}; const Operator O2gq {g, P2Tgq{nf}, IntEps}; const Operator O2gg {g, P2Tgg{nf}, IntEps}; const Operator O2qq = O2nsp + O2ps; const Operator O2nsv = O2nsm + O2nss; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O2nsp}); OM.insert({EvolutionBasisQCD::PNSM, O2nsm}); OM.insert({EvolutionBasisQCD::PNSV, O2nsv}); OM.insert({EvolutionBasisQCD::PQQ, O2qq}); OM.insert({EvolutionBasisQCD::PQG, O2qg}); OM.insert({EvolutionBasisQCD::PGQ, O2gq}); OM.insert({EvolutionBasisQCD::PGG, O2gg}); OpMapNNLO.insert({nf, OM}); } // Define object of the structure containing the DglapObjects. std::map<int, DglapObjects> DglapObj; // Allocate convolution maps for evolution and matching, and set // of operators. for (int nf = nfi; nf <= nff; nf++) { DglapObjects obj; obj.Threshold = Thresholds[nf-1]; if (OpEvol) { const EvolutionOperatorBasisQCD evopb{nf}; const MatchingOperatorBasisQCD mtopb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evopb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evopb, OpMapNLO.at(nf)}}); obj.SplittingFunctions.insert({2, Set<Operator>{evopb, OpMapNNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtopb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtopb, MatchNLO.at(nf)}}); obj.MatchingConditions.insert({2, Set<Operator>{mtopb, MatchNNLO.at(nf)}}); } else { const EvolutionBasisQCD evb{nf}; const MatchingBasisQCD mtb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evb, OpMapNLO.at(nf)}}); obj.SplittingFunctions.insert({2, Set<Operator>{evb, OpMapNNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtb, MatchNLO.at(nf)}}); obj.MatchingConditions.insert({2, Set<Operator>{mtb, MatchNNLO.at(nf)}}); } DglapObj.insert({nf,obj}); } t.stop(); return DglapObj; } //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCDT(Grid const& g, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { return InitializeDglapObjectsQCDT(g, Thresholds, Thresholds, OpEvol, IntEps); } //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCDtrans(Grid const& g, std::vector<double> const& Masses, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { report("Initializing DglapObjects for space-like QCD transversely polarised evolution... "); Timer t; // Compute initial and final number of active flavours according // to the vector of thresholds (it assumes that the thresholds // vector entries are ordered). int nfi = 0; int nff = Thresholds.size(); for (auto const& v : Thresholds) if (v <= 0) nfi++; // Compute logs of muth2 / m2 needed for the the matching // conditions (not possible for transversities yet). std::vector<double> LogKth; for (int im = 0; im < (int) Thresholds.size(); im++) if (Thresholds[im] < eps12 || Masses[im] < eps12) LogKth.push_back(0); else LogKth.push_back(2 * log( Thresholds[im] / Masses[im] )); // Allocate needed operators (matching conditions and splitting // functions). By now the code is fast enough to precompute // everything at all available perturbative orders and the current // perturbative order is accounted for only when the actual // splitting functions and matching conditions (lambda) functions // are defined. // =============================================================== // LO Matching conditions. std::map<int, Operator> MatchLO; const Operator Id {g, Identity{}, IntEps}; const Operator Zero{g, Null{}, IntEps}; MatchLO.insert({MatchingBasisQCD::PNS, Id}); MatchLO.insert({MatchingBasisQCD::PQQ, Id}); MatchLO.insert({MatchingBasisQCD::PQG, Zero}); MatchLO.insert({MatchingBasisQCD::PGQ, Zero}); MatchLO.insert({MatchingBasisQCD::PGG, Id}); for (int i = MatchingBasisQCD::PT3Q; i <= MatchingBasisQCD::PT35Q; i++) MatchLO.insert({i, Id}); for (int i = MatchingBasisQCD::PT3G; i <= MatchingBasisQCD::PT35G; i++) MatchLO.insert({i, Zero}); // =============================================================== // LO splitting function operators. std::map<int, std::map<int, Operator>> OpMapLO; const Operator O0ns{g, P0transns{}, IntEps}; for (int nf = nfi; nf <= nff; nf++) { std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O0ns}); OM.insert({EvolutionBasisQCD::PNSM, O0ns}); OM.insert({EvolutionBasisQCD::PNSV, O0ns}); OM.insert({EvolutionBasisQCD::PQQ, O0ns}); OM.insert({EvolutionBasisQCD::PQG, Zero}); OM.insert({EvolutionBasisQCD::PGQ, Zero}); OM.insert({EvolutionBasisQCD::PGG, Zero}); OpMapLO.insert({nf, OM}); } // =============================================================== // NLO Matching conditions (Null). std::map<int, Operator> MatchNLO; for (int i = MatchingBasisQCD::PNS; i <= MatchingBasisQCD::PT35G; i++) MatchNLO.insert({i, Zero}); // =============================================================== // NLO splitting function operators. std::map<int, std::map<int, Operator>> OpMapNLO; for (int nf = nfi; nf <= nff; nf++) { const Operator O1nsp{g, P1transnsp{nf}, IntEps}; const Operator O1nsm{g, P1transnsm{nf}, IntEps}; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O1nsp}); OM.insert({EvolutionBasisQCD::PNSM, O1nsm}); OM.insert({EvolutionBasisQCD::PNSV, O1nsm}); OM.insert({EvolutionBasisQCD::PQQ, O1nsp}); OM.insert({EvolutionBasisQCD::PQG, Zero}); OM.insert({EvolutionBasisQCD::PGQ, Zero}); OM.insert({EvolutionBasisQCD::PGG, Zero}); OpMapNLO.insert({nf, OM}); } // Define object of the structure containing the DglapObjects. std::map<int, DglapObjects> DglapObj; // Allocate convolution maps for evolution and matching, and set // of operators. for (int nf = nfi; nf <= nff; nf++) { DglapObjects obj; obj.Threshold = Thresholds[nf-1]; if (OpEvol) { const EvolutionOperatorBasisQCD evopb{nf}; const MatchingOperatorBasisQCD mtopb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evopb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evopb, OpMapNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtopb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtopb, MatchNLO}}); } else { const EvolutionBasisQCD evb{nf}; const MatchingBasisQCD mtb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evb, OpMapNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtb, MatchNLO}}); } DglapObj.insert({nf,obj}); } t.stop(); return DglapObj; } //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCDtrans(Grid const& g, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { return InitializeDglapObjectsQCDtrans(g, Thresholds, Thresholds, OpEvol, IntEps); } //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCDTtrans(Grid const& g, std::vector<double> const& Masses, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { report("Initializing DglapObjects for time-like QCD transversely polarised evolution... "); Timer t; // Compute initial and final number of active flavours according // to the vector of thresholds (it assumes that the thresholds // vector entries are ordered). int nfi = 0; int nff = Thresholds.size(); for (auto const& v : Thresholds) if (v <= 0) nfi++; // Compute logs of muth2 / m2 needed for the the matching // conditions (not possible for transversities yet). std::vector<double> LogKth; for (int im = 0; im < (int) Thresholds.size(); im++) if (Thresholds[im] < eps12 || Masses[im] < eps12) LogKth.push_back(0); else LogKth.push_back(2 * log( Thresholds[im] / Masses[im] )); // Allocate needed operators (matching conditions and splitting // functions). By now the code is fast enough to precompute // everything at all available perturbative orders and the current // perturbative order is accounted for only when the actual // splitting functions and matching conditions (lambda) functions // are defined. // =============================================================== // LO Matching conditions. std::map<int, Operator> MatchLO; const Operator Id {g, Identity{}, IntEps}; const Operator Zero{g, Null{}, IntEps}; MatchLO.insert({MatchingBasisQCD::PNS, Id}); MatchLO.insert({MatchingBasisQCD::PQQ, Id}); MatchLO.insert({MatchingBasisQCD::PQG, Zero}); MatchLO.insert({MatchingBasisQCD::PGQ, Zero}); MatchLO.insert({MatchingBasisQCD::PGG, Id}); for (int i = MatchingBasisQCD::PT3Q; i <= MatchingBasisQCD::PT35Q; i++) MatchLO.insert({i, Id}); for (int i = MatchingBasisQCD::PT3G; i <= MatchingBasisQCD::PT35G; i++) MatchLO.insert({i, Zero}); // =============================================================== // LO splitting function operators. std::map<int, std::map<int, Operator>> OpMapLO; const Operator O0ns{g, P0Ttransns{}, IntEps}; for (int nf = nfi; nf <= nff; nf++) { std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O0ns}); OM.insert({EvolutionBasisQCD::PNSM, O0ns}); OM.insert({EvolutionBasisQCD::PNSV, O0ns}); OM.insert({EvolutionBasisQCD::PQQ, O0ns}); OM.insert({EvolutionBasisQCD::PQG, Zero}); OM.insert({EvolutionBasisQCD::PGQ, Zero}); OM.insert({EvolutionBasisQCD::PGG, Zero}); OpMapLO.insert({nf, OM}); } // =============================================================== // NLO Matching conditions (Null). std::map<int, Operator> MatchNLO; for (int i = MatchingBasisQCD::PNS; i <= MatchingBasisQCD::PT35G; i++) MatchNLO.insert({i, Zero}); // =============================================================== // NLO splitting function operators. std::map<int, std::map<int, Operator>> OpMapNLO; for (int nf = nfi; nf <= nff; nf++) { const Operator O1nsp{g, P1Ttransnsp{nf}, IntEps}; const Operator O1nsm{g, P1Ttransnsm{nf}, IntEps}; std::map<int, Operator> OM; OM.insert({EvolutionBasisQCD::PNSP, O1nsp}); OM.insert({EvolutionBasisQCD::PNSM, O1nsm}); OM.insert({EvolutionBasisQCD::PNSV, O1nsm}); OM.insert({EvolutionBasisQCD::PQQ, O1nsp}); OM.insert({EvolutionBasisQCD::PQG, Zero}); OM.insert({EvolutionBasisQCD::PGQ, Zero}); OM.insert({EvolutionBasisQCD::PGG, Zero}); OpMapNLO.insert({nf, OM}); } // Define object of the structure containing the DglapObjects. std::map<int, DglapObjects> DglapObj; // Allocate convolution maps for evolution and matching, and set // of operators. for (int nf = nfi; nf <= nff; nf++) { DglapObjects obj; obj.Threshold = Thresholds[nf-1]; if (OpEvol) { const EvolutionOperatorBasisQCD evopb{nf}; const MatchingOperatorBasisQCD mtopb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evopb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evopb, OpMapNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtopb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtopb, MatchNLO}}); } else { const EvolutionBasisQCD evb{nf}; const MatchingBasisQCD mtb{nf}; obj.SplittingFunctions.insert({0, Set<Operator>{evb, OpMapLO.at(nf)}}); obj.SplittingFunctions.insert({1, Set<Operator>{evb, OpMapNLO.at(nf)}}); obj.MatchingConditions.insert({0, Set<Operator>{mtb, MatchLO}}); obj.MatchingConditions.insert({1, Set<Operator>{mtb, MatchNLO}}); } DglapObj.insert({nf,obj}); } t.stop(); return DglapObj; } //_____________________________________________________________________________ std::map<int, DglapObjects> InitializeDglapObjectsQCDTtrans(Grid const& g, std::vector<double> const& Thresholds, bool const& OpEvol, double const& IntEps) { return InitializeDglapObjectsQCDTtrans(g, Thresholds, Thresholds, OpEvol, IntEps); } // ============================================================================ std::function<Set<Operator>(int const&, double const&)> SplittingFunctions(std::map<int, DglapObjects> const& DglapObj, int const& PerturbativeOrder, std::function<double(double const&)> const& Alphas) { if (PerturbativeOrder == 0) return [=] (int const& nf, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; return cp * DglapObj.at(nf).SplittingFunctions.at(0); }; else if (PerturbativeOrder == 1) return [=] (int const& nf, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; const auto sf = DglapObj.at(nf).SplittingFunctions; return cp * ( sf.at(0) + cp * sf.at(1) ); }; else if (PerturbativeOrder == 2) return [=] (int const& nf, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; const auto sf = DglapObj.at(nf).SplittingFunctions; return cp * ( sf.at(0) + cp * ( sf.at(1) + cp * sf.at(2) ) ); }; else if (PerturbativeOrder == 3) return [=] (int const& nf, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; const auto sf = DglapObj.at(nf).SplittingFunctions; return cp * ( sf.at(0) + cp * ( sf.at(1) + cp * ( sf.at(2) + cp * sf.at(3) ) ) ); }; else throw std::runtime_error(error("SplittingFunctions","Perturbative order not allowed.")); } //_____________________________________________________________________________ std::function<Set<Operator>(bool const&, int const&)> MatchingConditions(std::map<int, DglapObjects> const& DglapObj, int const& PerturbativeOrder, std::function<double(double const&)> const& Alphas) { // Compute coupling above and below the thresholds. std::map<int, double> asThUp; std::map<int, double> asThDown; for (auto obj = std::next(DglapObj.begin()); obj != DglapObj.end(); ++obj) { const int nf = obj->first; const double thr = obj->second.Threshold; asThDown.insert({nf,Alphas(thr*(1-eps8))/FourPi}); asThUp.insert({nf,Alphas(thr*(1+eps8))/FourPi}); } if (PerturbativeOrder == 0) return [=] (bool const&, int const& nf) -> Set<Operator> { return DglapObj.at(nf).MatchingConditions.at(0); }; else if (PerturbativeOrder == 1) return [=] (bool const& Up, int const& nf) -> Set<Operator> { const double cp = ( Up ? asThUp.at(nf+1) : asThDown.at(nf+1) ); const auto mc = DglapObj.at(nf).MatchingConditions; return mc.at(0) + ( Up ? 1 : -1) * cp * mc.at(1); }; else if (PerturbativeOrder == 2) return [=] (bool const& Up, int const& nf) -> Set<Operator> { const double cp = ( Up ? asThUp.at(nf+1) : asThDown.at(nf+1) ); const auto mc = DglapObj.at(nf).MatchingConditions; return mc.at(0) + ( Up ? 1 : -1) * cp * ( mc.at(1) + cp * mc.at(2) ); }; else if (PerturbativeOrder == 3) return [=] (bool const& Up, int const& nf) -> Set<Operator> { const double cp = ( Up ? asThUp.at(nf+1) : asThDown.at(nf+1) ); const auto mc = DglapObj.at(nf).MatchingConditions; return mc.at(0) + ( Up ? 1 : -1) * cp * ( mc.at(1) + cp * mc.at(2) ); }; else throw std::runtime_error(error("MatchingConditions","Perturbative order not allowed.")); } //_____________________________________________________________________________ std::unique_ptr<Dglap<Distribution>> BuildDglap(std::map<int, DglapObjects> const& DglapObj, std::function<std::map<int, double>(double const&, double const&)> const& InDistFunc, double const& MuRef, int const& PerturbativeOrder, std::function<double(double const&)> const& Alphas, int const& nsteps) { // Collect thresholds. std::vector<double> Thresholds; for (auto const& obj : DglapObj) { const int nf = obj.first; const double thr = obj.second.Threshold; if ((int) Thresholds.size() < nf) Thresholds.resize(nf); Thresholds[nf-1] = thr; } // Create set of initial distributions. const Set<Distribution> InPDFs{DglapObj.at(NF(MuRef, Thresholds)).SplittingFunctions.at(0).GetMap(), DistributionMap(DglapObj.begin()->second.SplittingFunctions.at(0).at(0).GetGrid(), InDistFunc, MuRef)}; // Initialize DGLAP evolution. return std::unique_ptr<Dglap<Distribution>>(new Dglap<Distribution> {SplittingFunctions(DglapObj, PerturbativeOrder, Alphas), MatchingConditions(DglapObj, PerturbativeOrder, Alphas), InPDFs, MuRef, Thresholds, nsteps }); } //_____________________________________________________________________________ std::unique_ptr<Dglap<Operator>> BuildDglap(std::map<int, DglapObjects> const& DglapObj, double const& MuRef, int const& PerturbativeOrder, std::function<double(double const&)> const& Alphas, int const& nsteps) { // Collect thresholds. std::vector<double> Thresholds; for (auto const& obj : DglapObj) { const int nf = obj.first; const double thr = obj.second.Threshold; if ((int) Thresholds.size() < nf) Thresholds.resize(nf); Thresholds[nf-1] = thr; } // Allocate Identity and Zero operators. const Operator One{DglapObj.begin()->second.SplittingFunctions.at(0).at(0).GetGrid(), Identity{}}; const Operator Zero{DglapObj.begin()->second.SplittingFunctions.at(0).at(0).GetGrid(), Null{}}; // Create set of initial operators that represent the unity set of // operators. std::map<int, Operator> MapUnity; MapUnity.insert({0, One}); MapUnity.insert({1, Zero}); MapUnity.insert({2, Zero}); MapUnity.insert({3, One}); MapUnity.insert({4, One}); MapUnity.insert({5, One}); MapUnity.insert({6, Zero}); MapUnity.insert({7, One}); MapUnity.insert({8, One}); MapUnity.insert({9, Zero}); MapUnity.insert({10, One}); MapUnity.insert({11, One}); MapUnity.insert({12, Zero}); MapUnity.insert({13, One}); MapUnity.insert({14, One}); MapUnity.insert({15, Zero}); MapUnity.insert({16, One}); MapUnity.insert({17, One}); MapUnity.insert({18, Zero}); MapUnity.insert({19, One}); Set<Operator> Unity{DglapObj.at(NF(MuRef, Thresholds)).SplittingFunctions.at(0).GetMap(), MapUnity}; // Initialize DGLAP evolution. return std::unique_ptr<Dglap<Operator>>(new Dglap<Operator> {SplittingFunctions(DglapObj, PerturbativeOrder, Alphas), MatchingConditions(DglapObj, PerturbativeOrder, Alphas), Unity, MuRef, Thresholds, nsteps }); } //_____________________________________________________________________________ std::unique_ptr<Dglap<Distribution>> BuildDglap(std::function<DglapObjects(double const&)> const& DglapObj, std::vector<double> const& Thresholds, std::function<std::map<int, double>(double const&, double const&)> const& InDistFunc, double const& MuRef, int const& PerturbativeOrder, std::function<double(double const&)> const& Alphas, int const& nsteps) { // Compute initial and final number of active flavours according // to the vector of thresholds (it assumes that the thresholds // vector entries are ordered). int nfi = 0; int nff = Thresholds.size(); for (auto const& v : Thresholds) if (v <= 0) nfi++; // Compute coupling above and below the thresholds. std::map<int, double> asThUp; std::map<int, double> asThDown; for (int nf = nfi + 1; nf <= nff; nf++) { asThDown.insert({nf,Alphas(Thresholds[nf-1]*(1-eps8))/FourPi}); asThUp.insert({nf,Alphas(Thresholds[nf-1]*(1+eps8))/FourPi}); } // Create splitting functions and matching conditions lambda // functions according to the requested perturbative order. std::function<Set<Operator>(int const&, double const&)> SplittingFunctions; std::function<Set<Operator>(bool const&, int const&)> MatchingConditions; if (PerturbativeOrder == 0) { SplittingFunctions = [=] (int const&, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; return cp * DglapObj(mu).SplittingFunctions.at(0); }; MatchingConditions = [=] (bool const&, int const& nf) -> Set<Operator> { return DglapObj(Thresholds[nf-1]).MatchingConditions.at(0); }; } else if (PerturbativeOrder == 1) { SplittingFunctions = [=] (int const&, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; const auto sf = DglapObj(mu).SplittingFunctions; return cp * ( sf.at(0) + cp * sf.at(1) ); }; MatchingConditions = [=] (bool const&, int const& nf) -> Set<Operator> { return DglapObj(Thresholds[nf-1]).MatchingConditions.at(0); }; } else if (PerturbativeOrder == 2) { SplittingFunctions = [=] (int const&, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; const auto sf = DglapObj(mu).SplittingFunctions; return cp * ( sf.at(0) + cp * ( sf.at(1) + cp * sf.at(2) ) ); }; MatchingConditions = [=] (bool const& Up, int const& nf) -> Set<Operator> { const double cp = asThUp.at(nf+1); const auto mc = DglapObj(Thresholds[nf-1]).MatchingConditions; return mc.at(0) + ( Up ? 1 : -1) * cp * cp * mc.at(2); }; } else if (PerturbativeOrder == 3) { SplittingFunctions = [=] (int const&, double const& mu) -> Set<Operator> { const double cp = Alphas(mu) / FourPi; const auto sf = DglapObj(mu).SplittingFunctions; return cp * ( sf.at(0) + cp * ( sf.at(1) + cp * ( sf.at(2) + cp * sf.at(3) ) ) ); }; MatchingConditions = [=] (bool const& Up, int const& nf) -> Set<Operator> { const double cp = asThUp.at(nf+1); const auto mc = DglapObj(Thresholds[nf-1]).MatchingConditions; return mc.at(0) + ( Up ? 1 : -1) * cp * cp * mc.at(2); }; } // Create set of initial distributions. const Set<Distribution> InPDFs{DglapObj(MuRef).SplittingFunctions.at(0).GetMap(), DistributionMap(DglapObj(MuRef).SplittingFunctions.at(0).at(0).GetGrid(), InDistFunc, MuRef)}; // Initialize DGLAP evolution. return std::unique_ptr<Dglap<Distribution>>(new Dglap<Distribution> {SplittingFunctions, MatchingConditions, InPDFs, MuRef, Thresholds, nsteps}); } }
46.258285
163
0.551969
[ "object", "vector" ]
f5189623c56ee02038ad33038050e459262a9423
13,487
cxx
C++
PWGLF/FORWARD/analysis2/AliCopyHeaderTask.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGLF/FORWARD/analysis2/AliCopyHeaderTask.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGLF/FORWARD/analysis2/AliCopyHeaderTask.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/** * @file AliCopyHeaderTask.cxx * @author Christian Holm Christensen <cholm@dalsgaard.hehi.nbi.dk> * @date Tue Jul 12 10:59:32 2011 * * @brief Task to copy ESD header to AOD * * @ingroup pwglf_forward_tasks */ #include "AliCopyHeaderTask.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliCentrality.h" #include "AliInputEventHandler.h" #include "TFile.h" #include "AliEventplane.h" #include "AliESDVertex.h" #include "AliAODVertex.h" #include "AliESDtrackCuts.h" #include "AliAnalysisManager.h" #include "AliMultSelection.h" #include "AliAODHandler.h" ClassImp(AliCopyHeaderTask) #if 0 ; // for emacs - do not remove #endif //____________________________________________________________________ AliCopyHeaderTask& AliCopyHeaderTask::operator=(const AliCopyHeaderTask& other) { if (this == &other) return *this; AliAnalysisTaskSE::operator=(other); fCalculateRefMult = other.fCalculateRefMult; fCopyCentrality = other.fCopyCentrality; fCopyTracklets = other.fCopyTracklets; fCopyV0 = other.fCopyV0; fCopyAD = other.fCopyAD; fCopyZDC = other.fCopyZDC; if (fMultSelection) { delete fMultSelection; fMultSelection = 0; } if (other.fMultSelection) fMultSelection = new AliMultSelection(*other.fMultSelection); return *this; } //____________________________________________________________________ AliCopyHeaderTask::AliCopyHeaderTask(const AliCopyHeaderTask& other) : AliAnalysisTaskSE(other), fCalculateRefMult(other.fCalculateRefMult), fCopyCentrality(other.fCopyCentrality), fCopyTracklets(other.fCopyTracklets), fCopyV0(other.fCopyV0), fCopyAD(other.fCopyAD), fCopyZDC(other.fCopyZDC), fMultSelection(0) { if (other.fMultSelection) fMultSelection = new AliMultSelection(*other.fMultSelection); } //____________________________________________________________________ void AliCopyHeaderTask::SetCopyOptions(const TString& what) { TObjArray* tokens = what.Tokenize(","); TObject* token = 0; TIter next(tokens); while ((token = next())) { TString opt(token->GetName()); Bool_t enable = true; Int_t rem = 0; if (opt.BeginsWith("+")) { rem = 1; enable = true; } else if (opt.BeginsWith("-")) { rem = 1; enable = false; } if (rem > 0) opt.Remove(0,1); opt.ToLower(); if (opt.BeginsWith("cent")) SetCopyCentrality(enable); else if (opt.BeginsWith("trac")) SetCopyTracklets(enable); else if (opt.BeginsWith("v0") || opt.BeginsWith("vzero")) SetCopyV0(enable); else if (opt.BeginsWith("ad")) SetCopyAD(enable); else if (opt.BeginsWith("zdc")) SetCopyZDC(enable); else if (opt.BeginsWith("ref")) SetCalculateRefMult(enable); } tokens->Delete(); } //____________________________________________________________________ void AliCopyHeaderTask::UserCreateOutputObjects() { if (!fCopyCentrality) return; AliAnalysisManager* am = AliAnalysisManager::GetAnalysisManager(); AliAODHandler* ah = dynamic_cast<AliAODHandler*>(am->GetOutputEventHandler()); if (!ah) { AliWarning("No AOD output handler set in analysis manager"); return; } fMultSelection = new AliMultSelection("MultSelection"); ah->AddBranch("AliMultSelection", &fMultSelection); } //____________________________________________________________________ void AliCopyHeaderTask::UserExec(Option_t*) { // // Called at every event // // Copies information from ESD header to AOD header // // --- Get the I/O objects ----------------------------------------- AliESDEvent* esd = dynamic_cast<AliESDEvent*>(InputEvent()); AliAODEvent* aod = dynamic_cast<AliAODEvent*>(AODEvent()); if (!esd) { AliWarning("Missing ESD event"); return; } if (!aod) { AliWarning("Missing AOD event"); return; } // --- Load the data ----------------------------------------------- LoadBranches(); // --- Get or create the header ------------------------------------ AliAODHeader* aodHeader = dynamic_cast<AliAODHeader*>(aod->GetHeader()); if(!aodHeader) AliFatal("Not a standard AOD"); if (!aodHeader) { AliWarning("Missing AOD header"); aodHeader = new AliAODHeader(esd->GetRunNumber(), esd->GetBunchCrossNumber(), esd->GetOrbitNumber(), esd->GetPeriodNumber()); aod->AddHeader(aodHeader); } // --- Various event/run stuff ------------------------------------- aodHeader->SetRunNumber(esd->GetRunNumber()); aodHeader->SetOfflineTrigger(fInputHandler->IsEventSelected()); aodHeader->SetBunchCrossNumber(esd->GetBunchCrossNumber()); aodHeader->SetOrbitNumber(esd->GetOrbitNumber()); aodHeader->SetPeriodNumber(esd->GetPeriodNumber()); aodHeader->SetEventType(esd->GetEventType()); aodHeader->SetEventNumberESDFile(esd->GetHeader()->GetEventNumberInFile()); // --- Centrality -------------------------------------------------- if(esd->GetCentrality()) aodHeader->SetCentrality(esd->GetCentrality()); else aodHeader->SetCentrality(0); // --- Trigger ----------------------------------------------------- aodHeader->SetFiredTriggerClasses(esd->GetFiredTriggerClasses()); aodHeader->SetTriggerMask(esd->GetTriggerMask()); aodHeader->SetTriggerCluster(esd->GetTriggerCluster()); aodHeader->SetL0TriggerInputs(esd->GetHeader()->GetL0TriggerInputs()); aodHeader->SetL1TriggerInputs(esd->GetHeader()->GetL1TriggerInputs()); aodHeader->SetL2TriggerInputs(esd->GetHeader()->GetL2TriggerInputs()); // --- Magnetic field, ZDC signal ---------------------------------- aodHeader->SetMagneticField(esd->GetMagneticField()); aodHeader->SetMuonMagFieldScale(esd->GetCurrentDip()/6000.); aodHeader->SetZDCN1Energy(esd->GetZDCN1Energy()); aodHeader->SetZDCP1Energy(esd->GetZDCP1Energy()); aodHeader->SetZDCN2Energy(esd->GetZDCN2Energy()); aodHeader->SetZDCP2Energy(esd->GetZDCP2Energy()); aodHeader->SetZDCEMEnergy(esd->GetZDCEMEnergy(0),esd->GetZDCEMEnergy(1)); // --- V channel equalization factors ------------------------------ aodHeader->SetVZEROEqFactors(esd->GetVZEROEqFactors()); // --- Interacting beams ------------------------------------------- AliESDHeader* esdHeader = esd->GetHeader(); if (esdHeader) { aodHeader->SetIRInt2InteractionMap(esdHeader->GetIRInt2InteractionMap()); aodHeader->SetIRInt1InteractionMap(esdHeader->GetIRInt1InteractionMap()); } // --- ESD file name ----------------------------------------------- TTree* tree = fInputHandler->GetTree(); if (tree) { TFile* file = tree->GetCurrentFile(); if (file) aodHeader->SetESDFileName(file->GetName()); } // --- TPC event plane --------------------------------------------- AliEventplane* ep = esd->GetEventplane(); if (ep) aodHeader->SetEventplane(ep); // --- Copy primary vertices --------------------------------------- CopyVertex(*aod, esd->GetPrimaryVertex(), AliAODVertex::kPrimary); CopyVertex(*aod, esd->GetPrimaryVertexSPD(), AliAODVertex::kMainSPD); CopyVertex(*aod, esd->GetPrimaryVertexTPC(), AliAODVertex::kMainTPC); // --- Loop over pile-ups vertices --------------------------------- for (Int_t i = 0; i < esd->GetNumberOfPileupVerticesSPD(); i++) CopyVertex(*aod, esd->GetPileupVertexSPD(i), AliAODVertex::kPileupSPD); for (Int_t i = 0; i < esd->GetNumberOfPileupVerticesTracks(); i++) CopyVertex(*aod, esd->GetPileupVertexTracks(i),AliAODVertex::kPileupTracks); // --- Reference multiplicities ------------------------------------ if (fCalculateRefMult) { AliESDtrackCuts::MultEstTrackType estType = esd->GetPrimaryVertexTracks()->GetStatus() ? AliESDtrackCuts::kTrackletsITSTPC : AliESDtrackCuts::kTracklets; Int_t mult05 = AliESDtrackCuts::GetReferenceMultiplicity(esd,estType,0.5); Int_t mult08 = AliESDtrackCuts::GetReferenceMultiplicity(esd,estType,0.8); aodHeader->SetRefMultiplicityComb05(mult05); aodHeader->SetRefMultiplicityComb08(mult08); } // --- Copy multiplicity object ------------------------------------ // AliAnalysisTaskESDfilter::ConvertTracklets(const AliESDEvent& esd) if (fCopyTracklets) { AliMultiplicity* mul = esd->GetMultiplicity(); AliAODTracklets* tracklets = (aod->GetTracklets()); if (mul && mul->GetNumberOfTracklets() > 0 && tracklets) { Int_t nTracklets = mul->GetNumberOfTracklets(); tracklets->CreateContainer(nTracklets); for (Int_t i = 0; i < nTracklets; i++) { tracklets->SetTracklet(i, mul->GetTheta(i), mul->GetPhi(i), mul->GetDeltaPhi(i), mul->GetLabel(i, 0), mul->GetLabel(i, 1)); } tracklets->SetFiredChipMap (mul->GetFiredChipMap()); tracklets->SetFastOrFiredChipMap(mul->GetFastOrFiredChipMap()); tracklets->SetFiredChips (0, mul->GetNumberOfFiredChips(0)); tracklets->SetFiredChips (1, mul->GetNumberOfFiredChips(1)); } } // --- Copy V0 data ------------------------------------------------ if (fCopyV0) { AliAODVZERO* vzeroData = aod->GetVZEROData(); *vzeroData = *(esd->GetVZEROData()); } // --- Copy V0 data ------------------------------------------------ if (fCopyAD) { AliAODAD* adData = aod->GetADData(); *adData = *(esd->GetADData()); } // --- Copy ZDC data ------------------------------------------------ if (fCopyZDC) { AliESDZDC* esdZDC = esd->GetZDCData(); AliAODZDC* zdcAOD = aod->GetZDCData(); zdcAOD->SetZEM1Energy(esdZDC->GetZEM1Energy()); zdcAOD->SetZEM2Energy(esdZDC->GetZEM2Energy()); zdcAOD->SetZNCTowers(esdZDC->GetZNCTowerEnergy(), esdZDC->GetZNCTowerEnergyLR()); zdcAOD->SetZNATowers(esdZDC->GetZNATowerEnergy(), esdZDC->GetZNATowerEnergyLR()); zdcAOD->SetZPCTowers(esdZDC->GetZPCTowerEnergy(), esdZDC->GetZPCTowerEnergyLR()); zdcAOD->SetZPATowers(esdZDC->GetZPATowerEnergy(), esdZDC->GetZPATowerEnergyLR()); zdcAOD->SetZDCParticipants(esdZDC->GetZDCParticipants(), esdZDC->GetZDCPartSideA(), esdZDC->GetZDCPartSideC()); zdcAOD->SetZDCImpactParameter(esdZDC->GetImpactParameter(), esdZDC->GetImpactParamSideA(), esdZDC->GetImpactParamSideC()); zdcAOD->SetZDCTDCSum(esdZDC->GetZNTDCSum(0)); zdcAOD->SetZDCTDCDiff(esdZDC->GetZNTDCDiff(0)); if(esdZDC->IsZNChit()){ Int_t cable = 10; if(esdZDC->IsZDCTDCcablingSet()){ // RUN2 if(esdZDC->GetZNCTDCChannel()>0) cable = esdZDC->GetZNCTDCChannel(); else cable = 16; } zdcAOD->SetZNCTDC(esdZDC->GetZDCTDCCorrected(cable, 0)); //RUN1 } if(esdZDC->IsZNAhit()){ Int_t cable = 12; if(esdZDC->IsZDCTDCcablingSet()){ // RUN2 if(esdZDC->GetZNATDCChannel()>0) cable = esdZDC->GetZNATDCChannel(); else cable = 18; } zdcAOD->SetZNATDC(esdZDC->GetZDCTDCCorrected(cable, 0)); } if(esdZDC->IsZPChit()){ Int_t cable = 11; if(esdZDC->IsZDCTDCcablingSet()){ // RUN2 if(esdZDC->GetZPCTDCChannel()>0) cable = esdZDC->GetZPCTDCChannel(); else cable = 17; } zdcAOD->SetZPCTDC(esdZDC->GetZDCTDCCorrected(cable, 0)); } if(esdZDC->IsZPAhit()){ Int_t cable = 13; if(esdZDC->IsZDCTDCcablingSet()){ // RUN2 if(esdZDC->GetZPATDCChannel()>0) cable = esdZDC->GetZPATDCChannel(); else cable = 19; } zdcAOD->SetZPATDC(esdZDC->GetZDCTDCCorrected(cable, 0)); } } // --- Copy centrality estimates ----------------------------------- if (fMultSelection) { TObject* outO = InputEvent()->FindListObject("MultSelection"); if (outO) { AliMultSelection* outS = static_cast<AliMultSelection*>(outO); fMultSelection->Set(outS); } } } //____________________________________________________________________ void AliCopyHeaderTask::CopyVertex(AliAODEvent& aod, const AliESDVertex* vtx, Int_t type) { if (!vtx) return; // --- Get array of V0's from AOD ---------------------------------- TClonesArray* arr = aod.GetVertices(); if (!arr) return; // --- Now get some stuff vertex to copy to AOD -------------------- Int_t n = arr->GetEntriesFast(); Double_t pos[] = { 0., 0., 0. }; Double_t cov[] = { 0., 0., 0., 0., 0., 0. }; Double_t chi2 = vtx->GetChi2toNDF(); vtx->GetXYZ(pos); vtx->GetCovMatrix(cov); // --- Create new AOD vertex and set stuff ------------------------- AliAODVertex* out = new((*arr)[n]) AliAODVertex(pos, cov, chi2, 0, -1, type); out->SetName(vtx->GetName()); out->SetTitle(vtx->GetTitle()); out->SetBC(vtx->GetBC()); // --- If from a track vertex, make sure we set the contributors --- TString tit(out->GetTitle()); if (!tit.Contains("VertexerTracks")) out->SetNContributors(vtx->GetNContributors()); } //____________________________________________________________________ void AliCopyHeaderTask::Terminate(Option_t*) { // Called at the end of the job - does nothing } //____________________________________________________________________ Bool_t AliCopyHeaderTask::Connect() { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("Connect", "No analysis manager to connect to."); return false; } // Add to the manager mgr->AddTask(this); // Always connect input mgr->ConnectInput(this, 0, mgr->GetCommonInputContainer()); return true; } // // EOF //
34.144304
80
0.640839
[ "object" ]
f5189e238f2a126f16102ebd559f98fc3ef01c8d
10,736
cpp
C++
seminars/task_6/task_6_d.cpp
shevkunov/sgtl-and-others
573e8d57c8d0272c025d8509485bec0a26de3153
[ "BSD-3-Clause" ]
null
null
null
seminars/task_6/task_6_d.cpp
shevkunov/sgtl-and-others
573e8d57c8d0272c025d8509485bec0a26de3153
[ "BSD-3-Clause" ]
null
null
null
seminars/task_6/task_6_d.cpp
shevkunov/sgtl-and-others
573e8d57c8d0272c025d8509485bec0a26de3153
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <vector> #include <ios> #include <algorithm> #include <stdexcept> namespace sgtl { typedef long long int hash_t; template <hash_t base_ = 256, hash_t module_ = 1000000007> class HashedString { public: HashedString(char* c) : s_(std::string(c)) { buildPows_(); h_ = buildHash(s_); } HashedString(const std::string& s) : s_(s) { buildPows_(); h_ = buildHash(s_); } static std::vector<hash_t> buildHash(const std::string& s) { std::vector<hash_t> h_(s.length()); h_[0] = s[0]; for (size_t i = 1; i < s.length(); ++i) { h_[i] = (h_[i - 1] + s[i] * pows_[i]) % module_; } return h_; } hash_t getRawHash(size_t l, size_t r) { if ((l != r) && (r)) { if (!l) { return h_[r - 1]; } else { return (h_[r - 1] - h_[l - 1] + module_) % module_; } } else { return 0; } } hash_t getRightedHash(size_t l, size_t r) { return (getRawHash(l, r) * pows_[h_.size() - r]) % module_; } hash_t moveHashRight(hash_t hash, size_t dist) { return (hash * pows_[dist]) % module_; } bool compareSubStrings(size_t l, size_t r, HashedString<base_, module_> &hs, size_t sl, size_t sr) { if ((r - l) != (sr - sl)) { return false; } else { if (l <= sl) { return (getRawHash(l, r) * pows_[sl - l]) % module_ == hs.getRawHash(sl, sr); } else { return (hs.getRawHash(sl, sr) * pows_[l - sl]) % module_ == getRawHash(l, r); } } } private: std::string s_; std::vector<hash_t> h_; static std::vector<hash_t> pows_; void buildPows_() { size_t old_size = pows_.size(); if (old_size < s_.size()) { pows_.resize(s_.length() + 1); pows_[0] = 1; for (size_t i = std::max(old_size, (size_t)1); i < pows_.size(); ++i) { pows_[i] = (pows_[i - 1] * base_) % module_; } } } }; template <sgtl::hash_t base_, sgtl::hash_t module_> std::vector<sgtl::hash_t> sgtl::HashedString<base_, module_>::pows_; } namespace sgtl { // @Tested /// Vector is something, which has [] and .size(), std::string for example template <class Vector> // TODO : len_t like in prefixFunction std::vector<size_t> zFunction(const Vector &s) { std::vector<size_t> z(s.size()); z[0] = s.size(); size_t rightestBound = 0; /// ) size_t rightestBoundIndex = 0; for (size_t i = 1; i < s.size(); ++i) { if (i < rightestBound) { z[i] = z[i - rightestBoundIndex]; if (i + z[i] > rightestBound) { z[i] = rightestBound - i; } } while ((i + z[i] < s.size()) && (s[i + z[i]] == s[z[i]])) { ++z[i]; } if (i + z[i] > rightestBound) { rightestBoundIndex = i; rightestBound = i + z[i]; } } return z; } namespace sgtl { // @Tested std::vector<size_t> zFunctionPure(std::string &s, std::vector<size_t> &z, size_t start = 0) { z.assign(s.length(), 0); z[start] = s.length() - start; size_t rightestBound = start; /// ) size_t rightestBoundIndex = start; for (size_t i = start + 1; i < s.length(); ++i) { if (i < rightestBound) { z[i] = z[i - rightestBoundIndex + start]; if (i + z[i] > rightestBound) { z[i] = rightestBound - i; } } while ((i + z[i] < s.length()) && (s[i + z[i]] == s[z[i] + start])) { ++z[i]; } if (i + z[i] > rightestBound) { rightestBoundIndex = i; rightestBound = i + z[i]; } } return z; } } } namespace sgtl { std::vector<size_t> reversePrefixFunction(const std::vector<size_t>& p) { std::vector<size_t> s(1, 0); size_t newChar = 0; for (size_t i = 1; i < p.size(); ++i) { if (p[i] == 0) { s.push_back(++newChar); } else { s.push_back(s[p[i] - 1]); } } return s; } } namespace sgtl { /** Kasai, Arimura, Arikawa, Lee, Park algorithm. * suffix array should be 0-nimerated and correct **/ std::vector<size_t> buildLCPfromSufArr(const std::string& s, const std::vector<size_t>& sufArr) { if (s.size() != sufArr.size()) { throw std::runtime_error("sgtl::buildLCPfromSufArr - Bad suffix array"); } std::vector<size_t> lcp(s.size() - 1, 0); std::vector<size_t> revSufArr(sufArr.size()); for (size_t i = 0; i < sufArr.size(); ++i) { revSufArr[sufArr[i]] = i; } size_t k = 0; for (size_t i = 0; i < s.size(); ++i) { if (k) { --k; } if (revSufArr[i] == s.size() - 1) { k = 0; } else { int next = sufArr[revSufArr[i] + 1]; while ((std::max(i + k, next + k) < s.size()) && (s[i + k] == s[next+k])) { ++k; } lcp[revSufArr[i]] = k; } } return lcp; } } namespace sgtl { template <class C, C lo, C hi> class PrefixTreeNode { public: PrefixTreeNode() : leaf_(false), size_(0), links_(std::vector<PrefixTreeNode*>(hi - lo + 1, nullptr)) { } ~PrefixTreeNode() { for (PrefixTreeNode* node : links_) { if (node != nullptr) { delete node; } } } PrefixTreeNode(PrefixTreeNode& other) = delete; PrefixTreeNode* go(const C& ch) { if (links_[ch - lo] == nullptr) { links_[ch - lo] = new PrefixTreeNode(); } return links_[ch - lo]; } PrefixTreeNode* tryGo(const C& ch) { return links_[ch - lo]; } void setLeaf() { if (!leaf_) { ++size_; } leaf_ = true; } bool isLeaf() const { return leaf_; } void recalcSize() { size_ = isLeaf(); for (PrefixTreeNode* node : links_) { if (node != nullptr) { size_ += node->size(); } } } size_t size() const { return size_; } private: bool leaf_; size_t size_; std::vector<PrefixTreeNode*> links_; }; template <class C, C lo, C hi> class PrefixTree { public: PrefixTree() : root(new PrefixTreeNode<C, lo, hi>) { } ~PrefixTree() { delete root; } PrefixTree(PrefixTree& other) = delete; template<class Vector> void insert(const Vector& s) { std::vector<PrefixTreeNode<C, lo, hi>*> ptr; ptr.push_back(root); for (C ch : s) { ptr.push_back(ptr.back()->go(ch)); } ptr.back()->setLeaf(); while (!ptr.empty()) { ptr.back()->recalcSize(); ptr.pop_back(); } } template<class Vector> bool check(const Vector& s) { PrefixTreeNode<C, lo, hi>* ptr = root; for (C ch : s) { ptr = ptr->tryGo(ch); if (ptr == nullptr) { return false; } } return ptr->isLeaf(); } template<class Vector> Vector nth(size_t indx) { Vector ans; PrefixTreeNode<C, lo, hi>* ptr = root; if (indx >= ptr->size()) { throw std::runtime_error("sgtl::PrefixTree::nth - Bad index"); } ++indx; while (!((indx <= 0) && (ptr->isLeaf()))) { C last = lo; size_t lastLeftSize = 0; size_t leftSize = 0; for (C i = lo; i < hi; ++i) { PrefixTreeNode<C, lo, hi>* tryGo = ptr->tryGo(i); if (tryGo != nullptr) { if (leftSize < indx) { last = i; lastLeftSize = leftSize; } else { break; } leftSize += tryGo->size(); } } indx -= lastLeftSize + ptr->tryGo(last)->isLeaf(); leftSize = 0; ptr = ptr->tryGo(last); ans.push_back(last); } return ans; } private: PrefixTreeNode<C, lo, hi>* root; }; } namespace sgtl { /// Vector is something, which has [] and .size(), std::string for example template <class Vector, class len_t = size_t> std::vector<len_t> prefixFunction(const Vector &s) { std::vector<len_t> p(s.size()); len_t k = 0; for (size_t i = 1; i < s.length(); ++i) { while ((k > 0) && (s[i] != s[k])) { k = p[k - 1]; } if (s[i] == s[k]) { ++k; } p[i] = k; } return p; } } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::string s; std::cin >> s; std::vector<int> p = sgtl::prefixFunction<std::string, int>(s); std::vector<int> q(s.length()), r(s.length()); for (size_t i = 1; i < s.length(); ++i) { if ((p[i] != 0) && (r[q[p[i] - 1]] + q[p[i] - 1] + 1 >= i)) { q[i] = q[p[i] - 1]; r[q[i]] = i; } else { q[i] = i; r[i] = i; } } for (auto v : q) { std::cout << v + 1 << " "; } return 0; }
28.782842
101
0.412537
[ "vector" ]
f52825aedf00d6b2797ab4d4329471b15a0774d1
924
hh
C++
cxx/satellite/include/SensitiveScoredDetector.hh
Zelenyy/phd-code
d5b8bfefd2418a915dde89f7da2cb6683f438556
[ "MIT" ]
null
null
null
cxx/satellite/include/SensitiveScoredDetector.hh
Zelenyy/phd-code
d5b8bfefd2418a915dde89f7da2cb6683f438556
[ "MIT" ]
null
null
null
cxx/satellite/include/SensitiveScoredDetector.hh
Zelenyy/phd-code
d5b8bfefd2418a915dde89f7da2cb6683f438556
[ "MIT" ]
null
null
null
// // Created by zelenyy on 18.10.17. // #ifndef GEANT4_THUNDERSTORM_SENSITIVESCOREDDETECTOR_HH #define GEANT4_THUNDERSTORM_SENSITIVESCOREDDETECTOR_HH #include "G4VSensitiveDetector.hh" #include "iostream" #include "fstream" #include "DataFileManager.hh" #include "DataFile.hh" #include "vector" #include "Settings.hh" #include "DataSatellite.hh" #include "satellite.pb.h" using namespace CLHEP; using namespace std; class G4Step; class G4HCofThisEvent; class G4TouchableHistory; class SensitiveScoredDetector : public G4VSensitiveDetector { public: SensitiveScoredDetector(G4String name, Settings *settings); void Initialize(G4HCofThisEvent *) override; G4bool ProcessHits(G4Step *aStep, G4TouchableHistory *ROhist) override; void EndOfEvent(G4HCofThisEvent *) override; private: Settings* fSettings; vector<double> deposit; }; #endif //GEANT4_THUNDERSTORM_SENSITIVESCOREDDETECTOR_HH
20.086957
75
0.786797
[ "vector" ]
f52e0327791f78db63f98d7a660f603c26cc7e93
6,805
cpp
C++
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionStateInterpretedUtility.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionStateInterpretedUtility.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/Interpreted/ExecutionStateInterpretedUtility.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Script/ScriptContext.h> #include <AzCore/Script/ScriptSystemBus.h> #include <AzCore/Script/lua/lua.h> #include <ScriptCanvas/Data/DataRegistry.h> #include <ScriptCanvas/Grammar/DebugMap.h> #include <ScriptCanvas/Execution/ExecutionStateDeclarations.h> #include <ScriptCanvas/Execution/Interpreted/ExecutionStateInterpretedUtility.h> namespace ExecutionStateInterpretedUtilityCpp { using namespace ScriptCanvas; using namespace ScriptCanvas::Grammar; void InitializeFromLuaStackFunctions(AZ::BehaviorContext* behaviorContext, AZStd::vector<DebugDataSource>& symbols) { for (auto& debugDataSource : symbols) { if (debugDataSource.m_sourceType != DebugDataSourceType::Internal || debugDataSource.m_slotDatumType.IsValid()) { AZ::BehaviorClass* behaviorClassUnused{}; AZ::BehaviorParameter param; param.m_typeId = debugDataSource.m_slotDatumType.GetAZType(); debugDataSource.m_fromStack = FromLuaStack(behaviorContext, &param, behaviorClassUnused); SC_RUNTIME_CHECK(debugDataSource.m_fromStack, "LuaLoadFromStack function not found") } } } void InitializeFromLuaStackFunctions(AZ::BehaviorContext* behaviorContext, AZStd::vector<Grammar::DebugExecution>& symbols) { for (auto& debugExecution : symbols) { InitializeFromLuaStackFunctions(behaviorContext, debugExecution.m_data); } } } namespace ScriptCanvas { namespace Execution { void InitializeFromLuaStackFunctions(Grammar::DebugSymbolMap& debugMap) { AZ::ScriptContext* scriptContext{}; AZ::ScriptSystemRequestBus::BroadcastResult(scriptContext, &AZ::ScriptSystemRequests::GetContext, AZ::ScriptContextIds::DefaultScriptContextId); SC_RUNTIME_CHECK_RETURN(scriptContext, "Must have a default script context"); auto behaviorContext = scriptContext->GetBoundContext(); ExecutionStateInterpretedUtilityCpp::InitializeFromLuaStackFunctions(behaviorContext, debugMap.m_ins); ExecutionStateInterpretedUtilityCpp::InitializeFromLuaStackFunctions(behaviorContext, debugMap.m_outs); ExecutionStateInterpretedUtilityCpp::InitializeFromLuaStackFunctions(behaviorContext, debugMap.m_returns); ExecutionStateInterpretedUtilityCpp::InitializeFromLuaStackFunctions(behaviorContext, debugMap.m_variables); } bool IsLuaValueType(Data::eType etype) { switch (etype) { case ScriptCanvas::Data::eType::Boolean: case ScriptCanvas::Data::eType::EntityID: case ScriptCanvas::Data::eType::NamedEntityID: case ScriptCanvas::Data::eType::Number: case ScriptCanvas::Data::eType::String: return true; case ScriptCanvas::Data::eType::AABB: case ScriptCanvas::Data::eType::BehaviorContextObject: case ScriptCanvas::Data::eType::CRC: case ScriptCanvas::Data::eType::Color: case ScriptCanvas::Data::eType::Matrix3x3: case ScriptCanvas::Data::eType::Matrix4x4: case ScriptCanvas::Data::eType::OBB: case ScriptCanvas::Data::eType::Plane: case ScriptCanvas::Data::eType::Quaternion: case ScriptCanvas::Data::eType::Transform: case ScriptCanvas::Data::eType::Vector2: case ScriptCanvas::Data::eType::Vector3: case ScriptCanvas::Data::eType::Vector4: return false; case ScriptCanvas::Data::eType::Invalid: default: SC_RUNTIME_CHECK(false, "Invalid type in ScriptCanvas runtime"); return false; } } AZ::Outcome<void, AZStd::string> PushValue(lua_State* lua, const Datum& datum) { auto etype = datum.GetType().GetType(); switch (etype) { case ScriptCanvas::Data::eType::Boolean: AZ::ScriptValue<Data::BooleanType>::StackPush(lua, *datum.GetAs<Data::BooleanType>()); break; case ScriptCanvas::Data::eType::EntityID: AZ::ScriptValue<Data::EntityIDType>::StackPush(lua, *datum.GetAs<Data::EntityIDType>()); break; case ScriptCanvas::Data::eType::NamedEntityID: AZ::ScriptValue<Data::EntityIDType>::StackPush(lua, *datum.GetAs<Data::NamedEntityIDType>()); break; case ScriptCanvas::Data::eType::Number: AZ::ScriptValue<Data::NumberType>::StackPush(lua, *datum.GetAs<Data::NumberType>()); break; case ScriptCanvas::Data::eType::String: { auto stringPtr = datum.GetAs<Data::StringType>(); if (!stringPtr || stringPtr->empty()) { AZ::ScriptValue<const char*>::StackPush(lua, ""); } else { AZ::ScriptValue<const char*>::StackPush(lua, stringPtr->data()); } } break; case ScriptCanvas::Data::eType::AABB: case ScriptCanvas::Data::eType::BehaviorContextObject: case ScriptCanvas::Data::eType::CRC: case ScriptCanvas::Data::eType::Color: case ScriptCanvas::Data::eType::Matrix3x3: case ScriptCanvas::Data::eType::Matrix4x4: case ScriptCanvas::Data::eType::OBB: case ScriptCanvas::Data::eType::Plane: case ScriptCanvas::Data::eType::Quaternion: case ScriptCanvas::Data::eType::Transform: case ScriptCanvas::Data::eType::Vector2: case ScriptCanvas::Data::eType::Vector3: case ScriptCanvas::Data::eType::Vector4: AZ::Internal::LuaScriptValueStackPush ( lua , const_cast<void*>(datum.GetAsDanger()) , (datum.GetType().GetAZType()) , AZ::ObjectToLua::ByValue); break; case ScriptCanvas::Data::eType::Invalid: default: SC_RUNTIME_CHECK(false, "Invalid type in ScriptCanvas"); return AZ::Failure(AZStd::string("Invalid type in ScriptCanvas")); } return AZ::Success(); } } }
41.242424
156
0.608229
[ "vector", "transform", "3d" ]
f530120cb863f9d77e0ba614ee44a8f0b9baa333
6,979
cpp
C++
test/test-params.cpp
tuket/libpqmxx
3a21ca3ad5fb4b1822690b074b2170b28adfa185
[ "MIT" ]
30
2016-07-04T03:38:02.000Z
2021-02-16T13:03:46.000Z
test/test-params.cpp
tuket/libpqmxx
3a21ca3ad5fb4b1822690b074b2170b28adfa185
[ "MIT" ]
9
2016-07-04T03:39:29.000Z
2019-09-06T21:23:46.000Z
test/test-params.cpp
tuket/libpqmxx
3a21ca3ad5fb4b1822690b074b2170b28adfa185
[ "MIT" ]
10
2016-07-14T14:19:07.000Z
2021-02-16T13:00:51.000Z
/** * Copyright (c) 2016 Philippe FERDINAND * * 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 "gtest/gtest.h" #include "postgres-connection.h" #include "postgres-exceptions.h" using namespace db::postgres; TEST(params_sync, datatypes) { Connection cnx; cnx.connect(); EXPECT_EQ(32767, cnx.execute("SELECT $1::smallint", int16_t(32767)).as<int16_t>(0)); EXPECT_EQ(2147483647, cnx.execute("SELECT $1", 2147483647).as<int32_t>(0)); EXPECT_EQ(9223372036854775807, cnx.execute("SELECT $1", int64_t(9223372036854775807)).as<int64_t>(0)); EXPECT_FLOAT_EQ(0.45567f, cnx.execute("SELECT $1", 0.45567f).as<float>(0)); EXPECT_DOUBLE_EQ(0.45567, cnx.execute("SELECT $1", 0.45567).as<double>(0)); EXPECT_TRUE(cnx.execute("SELECT $1", true).as<bool>(0)); EXPECT_FALSE(cnx.execute("SELECT $1", false).as<bool>(0)); EXPECT_STREQ("hello", cnx.execute("SELECT $1", "hello").as<std::string>(0).c_str()); EXPECT_STREQ("hello", cnx.execute("SELECT $1", std::string("hello")).as<std::string>(0).c_str()); EXPECT_EQ('X', cnx.execute("SELECT $1", 'X').as<char>(0)); } TEST(params_sync, utf8) { Connection cnx; cnx.connect(); EXPECT_STREQ(u8"Günter", cnx.execute("SELECT $1", u8"Günter").as<std::string>(0).c_str()); EXPECT_STREQ(u8"メインページ", cnx.execute("SELECT $1", u8"メインページ").as<std::string>(0).c_str()); } TEST(params_sync, date_time) { Connection cnx; cnx.connect(); EXPECT_STREQ("1970-01-01", cnx.execute("SELECT to_char($1, 'YYYY-MM-DD')", date_t {0}).as<std::string>(0).c_str()); EXPECT_STREQ("2014-11-01 05:14:00", cnx.execute("SELECT to_char($1 at time zone 'America/New_York', 'YYYY-MM-DD HH24:MI:SS')", timestamptz_t {1414833240000000}).as<std::string>(0).c_str()); auto timetz = cnx.execute("SELECT $1", timetz_t{860123, 7*3600}).as<timetz_t>(0); EXPECT_EQ(860123, timetz.time); EXPECT_EQ(25200, timetz.offset); EXPECT_EQ(39602000101, cnx.execute("SELECT $1", db::postgres::time_t{39602000101}).as<db::postgres::time_t>(0)); auto interval = cnx.execute("SELECT $1", interval_t {7384000000, 7, 4}).as<interval_t>(0); EXPECT_EQ(7384000000, interval.time); EXPECT_EQ(7, interval.days); EXPECT_EQ(4, interval.months); cnx.execute("set timezone TO 'America/New_York'"); EXPECT_STREQ("2014-11-01 05:14:00", cnx.execute("SELECT to_char($1, 'YYYY-MM-DD HH24:MI:SS')", timestamp_t {1414818840000000}).as<std::string>(0).c_str()); } TEST(param_sync, bytea_type) { Connection cnx; cnx.connect(); std::vector<uint8_t> expected; expected.push_back(0xDE); expected.push_back(0xAD); expected.push_back(0xBE); expected.push_back(0xEF); std::vector<uint8_t> actual = cnx.execute("SELECT $1::bytea", expected).as<std::vector<uint8_t>>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } TEST(param_sync, array_types) { Connection cnx; cnx.connect(); { array_bool_t expected({{false}, nullptr, {true}}); auto actual = cnx.execute("SELECT $1", expected).asArray<bool>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_int16_t expected({{1}, nullptr, {3}}); auto actual = cnx.execute("SELECT $1", expected).asArray<int16_t>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_int32_t expected({{320000}, nullptr, {-1000}}); auto actual = cnx.execute("SELECT $1", expected).asArray<int32_t>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_int64_t expected({{7000000000}, nullptr, {-7000000000}}); auto actual = cnx.execute("SELECT $1", expected).asArray<int64_t>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_float_t expected({{7.1f}, nullptr, {-23.8f}}); auto actual = cnx.execute("SELECT $1", expected).asArray<float>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_double_t expected({{877.198f}, nullptr, {-2300.8008f}}); auto actual = cnx.execute("SELECT $1", expected).asArray<double>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_string_t expected({{"hello"}, nullptr, {u8"メインページ"}}); auto actual = cnx.execute("SELECT $1", expected).asArray<std::string>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_date_t expected({date_t({1470960000}), nullptr, date_t({0})}); auto actual = cnx.execute("SELECT $1", expected).asArray<date_t>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_time_t expected({db::postgres::time_t({3600000000}), nullptr, db::postgres::time_t({0})}); auto actual = cnx.execute("SELECT $1", expected).asArray<db::postgres::time_t>(0); EXPECT_TRUE(expected.size() == actual.size() && std::equal(actual.begin(), actual.end(), expected.begin())); } { array_timetz_t expected({timetz_t({4321000001, 25200}), nullptr, timetz_t({0, 0})}); auto actual = cnx.execute("SELECT $1", expected).asArray<timetz_t>(0); if (expected.size() == actual.size()) { for (int i = 0; i < expected.size(); i++) { if (expected[i].isNull) { EXPECT_TRUE(actual[i].isNull); } else { EXPECT_EQ(expected[i].value.time, actual[i].value.time); EXPECT_EQ(expected[i].value.offset, actual[i].value.offset); } } } else { EXPECT_TRUE(false); } } } TEST(param_sync, multi) { Connection cnx; cnx.connect(); cnx.execute("SELECT $1, $2", 1, 2); }
37.320856
191
0.671156
[ "vector" ]
f5313fc4739d671f55e14d963615b2fc6e4b5d22
17,593
cpp
C++
tests/test-seeded/test-crypto.cpp
dicekeys/seeded-crypto
8e1d1965c1720b8964e3ee1880163f7a6b221781
[ "MIT" ]
3
2020-09-25T16:08:39.000Z
2022-02-25T04:39:26.000Z
tests/test-seeded/test-crypto.cpp
dicekeys/seeded-crypto
8e1d1965c1720b8964e3ee1880163f7a6b221781
[ "MIT" ]
3
2020-10-03T11:45:05.000Z
2021-09-21T00:28:53.000Z
tests/test-seeded/test-crypto.cpp
dicekeys/seeded-crypto
8e1d1965c1720b8964e3ee1880163f7a6b221781
[ "MIT" ]
3
2020-09-10T15:31:46.000Z
2021-03-14T07:01:17.000Z
#include "gtest/gtest.h" #include <string> #include <iostream> #include "lib-seeded.hpp" #include "../lib-seeded/convert.hpp" // Not included in Password.hpp const std::vector<std::string> asWordVector( const Recipe& recipe, const SodiumBuffer& secretBytes, const std::string& wordListAsSingleString = "" ); const std::string orderedTestKey = "A1tB2rC3bD4lE5tF6bG1tH1tI1tJ1tK1tL1tM1tN1tO1tP1tR1tS1tT1tU1tV1tW1tX1tY1tZ1t"; std::string defaultTestPublicRecipeJson = R"KGO({ "type": "UnsealingKey", "additionalSalt": "1" })KGO"; std::string defaultTestSymmetricRecipeJson = R"KGO({ "type": "SymmetricKey", "additionalSalt": "1" })KGO"; std::string defaultTestSigningRecipeJson = R"KGO({ "type": "SigningKey", "additionalSalt": "1" })KGO"; TEST(Secret, FidoUseCase) { std::string kdo = R"KDO({ "type": "Secret", "hashFunction": "Argon2id", "lengthInBytes": 96 })KDO"; Secret seed( orderedTestKey, kdo ); const std::string seedAsHex = toHexStr(seed.secretBytes.toVector()); ASSERT_EQ( seedAsHex, "6147ed347b3308c3a47bb5f3f05131fab59cbe08d7c26c7af7f2b54eb9a0d8da485907907a1abfe833575e8598364f4a8ba99c88022513fa464f364e6f0662119358c15dfcbef102656d0ec993beb2bf661138e2808384b48c689b8aebee32cd" ); } const std::string fastSeedJsonRecipe = R"KDO({ "type": "Secret", "hashFunction": "BLAKE2b", "lengthInBytes": 96 })KDO"; TEST(Secret, ConvertsToJsonAndBack) { Secret seed(orderedTestKey, fastSeedJsonRecipe); const auto serialized = seed.toJson(1, '\t'); const auto replica = Secret::fromJson(serialized); ASSERT_EQ(replica.recipe, seed.recipe); ASSERT_STREQ(replica.secretBytes.toHexString().c_str(), seed.secretBytes.toHexString().c_str()); } TEST(Secret, ConvertsToSerializedFormAndBack) { Secret seed(orderedTestKey, fastSeedJsonRecipe); const auto serialized = seed.toSerializedBinaryForm(); const auto replica = Secret::fromSerializedBinaryForm(serialized); ASSERT_EQ(replica.recipe, seed.recipe); ASSERT_STREQ(replica.secretBytes.toHexString().c_str(), seed.secretBytes.toHexString().c_str()); } TEST(Secret, fromJsonWithoutRecipe) { Secret seed = Secret::fromJson(R"JSON({ "secretBytes": "0xffFE" })JSON"); ASSERT_EQ(seed.secretBytes.length, 2); ASSERT_EQ(seed.secretBytes.data[0], 0xff); ASSERT_EQ(seed.secretBytes.data[1], 0xfe); ASSERT_EQ(seed.recipe.length(), 0); } TEST(Password, LengthInChars) { Password password = Password::deriveFromSeed(orderedTestKey, R"KDO({ "lengthInBits": 300, "lengthInChars": 64 })KDO"); const std::string pw = password.password; const auto serialized = password.toSerializedBinaryForm(); const auto replica = Password::fromSerializedBinaryForm(serialized); std::string rpw = replica.password; ASSERT_STREQ("34-", pw.substr(0, 3).c_str()); ASSERT_EQ(64, pw.size()); } TEST(Password, LengthInChars2) { Password password = Password::deriveFromSeed(orderedTestKey, R"KDO({ "lengthInChars": 64 })KDO"); const std::string pw = password.password; const auto serialized = password.toSerializedBinaryForm(); const auto replica = Password::fromSerializedBinaryForm(serialized); std::string rpw = replica.password; ASSERT_STREQ("15-", pw.substr(0, 3).c_str()); ASSERT_EQ(64, pw.size()); } TEST(Password, GeneratesExtraBytes) { Password password = Password::deriveFromSeed(orderedTestKey, R"KDO({ "lengthInBits": 300 })KDO"); const std::string pw = password.password; const auto serialized = password.toSerializedBinaryForm(); const auto replica = Password::fromSerializedBinaryForm(serialized); std::string rpw = replica.password; ASSERT_STREQ(rpw.c_str(), pw.c_str()); ASSERT_STREQ("34-", pw.substr(0, 3).c_str()); } TEST(Password, TenWordsViaLengthInBits) { Password password = Password::deriveFromSeed(orderedTestKey, R"KDO({ "type": "Password", "lengthInBits": 90 })KDO"); const std::string pw = password.password; ASSERT_STREQ(pw.c_str(), "10-Ionic-buzz-shine-theme-paced-bulge-cache-water-shown-baggy"); } TEST(Password, ElevenWordsViaLengthInWords) { Password password = Password::deriveFromSeed(orderedTestKey, R"KDO({ "type": "Password", "lengthInWords": 11 })KDO"); const std::string pw = password.password; ASSERT_STREQ(pw.c_str(), "11-Clean-snare-donor-petty-grimy-payee-limbs-stole-roman-aloha-dense"); } TEST(Password, ThirteenWordsViaDefaultWithAltWordList) { Password password = Password::deriveFromSeed(orderedTestKey, R"KDO({ "wordList": "EN_1024_words_6_chars_max_ed_4_20200917" })KDO"); const std::string pw = password.password; ASSERT_STREQ(pw.c_str(), "13-Curtsy-jersey-juror-anchor-catsup-parole-kettle-floral-agency-donor-dealer-plural-accent"); } TEST(Password, FifteenWordsViaDefaults) { Password password = Password::deriveFromSeed(orderedTestKey, R"KDO({})KDO"); const std::string pw = password.password; ASSERT_STREQ(pw.c_str(), "15-Unwed-agent-genre-stump-could-limit-shrug-shout-udder-bring-koala-essay-plaza-chaos-clerk"); } TEST(Password, CustomListOfSevenWords) { Password password = Password::deriveFromSeedAndWordList(orderedTestKey, R"KDO({"lengthInWords": 10})KDO", R"WL( yo llama, delimits this prime sized\ list )WL"); const std::string pw = password.password; ASSERT_STREQ(pw.c_str(), "10-This-yo-yo-this-delimits-sized-list-list-this-llama"); } TEST(SealingKey, GetsSealingKey) { const UnsealingKey testUnsealingKey(orderedTestKey, defaultTestPublicRecipeJson); const SealingKey testSealingKey = testUnsealingKey.getSealingKey(); ASSERT_EQ(testSealingKey.getSealingKeyBytes().size(), 32); } TEST(SealingKey, GetsSealingKeyFromEmptyOptions) { const UnsealingKey testUnsealingKey(orderedTestKey, "{}"); const SealingKey testSealingKey = testUnsealingKey.getSealingKey(); ASSERT_EQ(toHexStr(testSealingKey.getSealingKeyBytes()).length(), 64); } TEST(UnsealingKey, ConvertsToJsonAndBack) { const UnsealingKey testUnsealingKey(orderedTestKey, defaultTestPublicRecipeJson); const std::string json = testUnsealingKey.toJson(1, '\t'); const UnsealingKey replica = UnsealingKey::fromJson(json); ASSERT_EQ(replica.recipe, defaultTestPublicRecipeJson); ASSERT_EQ(toHexStr(replica.sealingKeyBytes), toHexStr(testUnsealingKey.sealingKeyBytes)); ASSERT_EQ(replica.unsealingKeyBytes.toHexString(), testUnsealingKey.unsealingKeyBytes.toHexString()); } TEST(UnsealingKey, ConvertsToSerializedFormAndBack) { const UnsealingKey testUnsealingKey(orderedTestKey, defaultTestPublicRecipeJson); auto serialized = testUnsealingKey.toSerializedBinaryForm(); const UnsealingKey replica = UnsealingKey::fromSerializedBinaryForm(serialized); ASSERT_EQ(replica.recipe, defaultTestPublicRecipeJson); ASSERT_EQ(toHexStr(replica.sealingKeyBytes), toHexStr(testUnsealingKey.sealingKeyBytes)); ASSERT_EQ(replica.unsealingKeyBytes.toHexString(), testUnsealingKey.unsealingKeyBytes.toHexString()); } TEST(SealingKey, ConvertsToJsonAndBack) { const UnsealingKey testUnsealingKey(orderedTestKey, defaultTestPublicRecipeJson); const SealingKey testSealingKey = testUnsealingKey.getSealingKey(); const std::string json = testSealingKey.toJson(1, '\t'); const SealingKey replica = SealingKey::fromJson(json); ASSERT_EQ(replica.getRecipeJson(), defaultTestPublicRecipeJson); ASSERT_EQ(toHexStr(replica.getSealingKeyBytes()), toHexStr(testSealingKey.getSealingKeyBytes())); } TEST(SealingKey, ConvertsToSerializedFormAndBack) { const UnsealingKey testUnsealingKey(orderedTestKey, defaultTestPublicRecipeJson); const SealingKey testSealingKey = testUnsealingKey.getSealingKey(); const auto serialized = testSealingKey.toSerializedBinaryForm(); const SealingKey replica = SealingKey::fromSerializedBinaryForm(serialized); ASSERT_EQ(replica.getRecipeJson(), defaultTestPublicRecipeJson); ASSERT_EQ(toHexStr(replica.getSealingKeyBytes()), toHexStr(testSealingKey.getSealingKeyBytes())); } TEST(SealingKey, EncryptsAndDecrypts) { const UnsealingKey testUnsealingKey(orderedTestKey, defaultTestPublicRecipeJson); const SealingKey testSealingKey = testUnsealingKey.getSealingKey(); const std::vector<unsigned char> messageVector = { 'y', 'o', 't', 'o' }; const std::string unsealingInstructions = "{}"; SodiumBuffer messageBuffer(messageVector); const auto sealedMessage = testSealingKey.sealToCiphertextOnly(messageBuffer, unsealingInstructions); const auto unsealedMessage = testUnsealingKey.unseal(sealedMessage, unsealingInstructions); const auto unsealedPlaintext = unsealedMessage.toVector(); ASSERT_EQ(messageVector, unsealedPlaintext); } TEST(SealingKey, EncryptsAndDecryptsPackaged) { const UnsealingKey testUnsealingKey(orderedTestKey, defaultTestPublicRecipeJson); const SealingKey testSealingKey = testUnsealingKey.getSealingKey(); const std::vector<unsigned char> messageVector = { 'y', 'o', 't', 'o' }; const std::string unsealingInstructions = "{}"; SodiumBuffer messageBuffer(messageVector); const auto sealedMessage = testSealingKey.seal(messageBuffer, unsealingInstructions); const auto unsealedMessage = UnsealingKey::unseal(sealedMessage, orderedTestKey); const auto unsealedPlaintext = unsealedMessage.toVector(); ASSERT_EQ(messageVector, unsealedPlaintext); } TEST(SigningKey, GetsSigningKey) { SigningKey testSigningKey(orderedTestKey, defaultTestSigningRecipeJson); const SignatureVerificationKey testSignatureVerificationKey = testSigningKey.getSignatureVerificationKey(); ASSERT_EQ(testSignatureVerificationKey.getKeyBytesAsHexDigits().length(), 64); } TEST(SigningKey, GetsSigningKeyFromEmptyOptions) { SigningKey testSigningKey(orderedTestKey, "{}"); const SignatureVerificationKey testSignatureVerificationKey = testSigningKey.getSignatureVerificationKey(); ASSERT_EQ(testSignatureVerificationKey.getKeyBytesAsHexDigits().length(), 64); } TEST(SigningKey, ConvertsToJsonAndBack) { SigningKey testKey(orderedTestKey, defaultTestSigningRecipeJson); const std::string json = testKey.toJson(1, '\t'); SigningKey replica = SigningKey::fromJson(json); ASSERT_EQ(replica.recipe, defaultTestSigningRecipeJson); ASSERT_STREQ(replica.signingKeyBytes.toHexString().c_str(), testKey.signingKeyBytes.toHexString().c_str()); ASSERT_STREQ(toHexStr(replica.getSignatureVerificationKeyBytes()).c_str(), toHexStr(testKey.getSignatureVerificationKeyBytes()).c_str()); } TEST(SigningKey, ConvertsToSerializedFormAndBack) { SigningKey testKey(orderedTestKey, defaultTestSigningRecipeJson); auto serializedBinaryForm = testKey.toSerializedBinaryForm(); auto copy = SigningKey::fromSerializedBinaryForm(serializedBinaryForm); ASSERT_EQ(copy.recipe, testKey.recipe); ASSERT_STREQ(copy.signingKeyBytes.toHexString().c_str(), testKey.signingKeyBytes.toHexString().c_str()); ASSERT_STREQ(toHexStr(copy.getSignatureVerificationKeyBytes()).c_str(), toHexStr(testKey.getSignatureVerificationKeyBytes()).c_str()); } TEST(SignatureVerificationKey, ConvertsToJsonAndBack) { SigningKey testSigningKey(orderedTestKey, defaultTestSigningRecipeJson); const SignatureVerificationKey testSignatureVerificationKey = testSigningKey.getSignatureVerificationKey(); const std::string serialized = testSignatureVerificationKey.toJson(1, '\t'); const SignatureVerificationKey replica = SignatureVerificationKey::fromJson(serialized); ASSERT_EQ(replica.getRecipeJson(), defaultTestSigningRecipeJson); ASSERT_STREQ(replica.getKeyBytesAsHexDigits().c_str(), testSignatureVerificationKey.getKeyBytesAsHexDigits().c_str()); } TEST(SignatureVerificationKey, ConvertsToSerializedFormAndBack) { SigningKey testSigningKey(orderedTestKey, defaultTestSigningRecipeJson); const SignatureVerificationKey testSignatureVerificationKey = testSigningKey.getSignatureVerificationKey(); const auto serialized = testSignatureVerificationKey.toSerializedBinaryForm(); const SignatureVerificationKey replica = SignatureVerificationKey::fromSerializedBinaryForm(serialized); ASSERT_EQ(replica.getRecipeJson(), defaultTestSigningRecipeJson); ASSERT_STREQ(replica.getKeyBytesAsHexDigits().c_str(), testSignatureVerificationKey.getKeyBytesAsHexDigits().c_str()); } TEST(SigningKey, Verification) { SigningKey testSigningKey(orderedTestKey, defaultTestSigningRecipeJson); const SignatureVerificationKey testSignatureVerificationKey = testSigningKey.getSignatureVerificationKey(); const std::vector<unsigned char> messageVector = { 'y', 'o', 't', 'o' }; const auto signature = testSigningKey.generateSignature(messageVector); const auto shouldVerifyAsTrue = testSignatureVerificationKey.verify(messageVector, signature); ASSERT_TRUE(shouldVerifyAsTrue); const std::vector<unsigned char> invalidMessageVector = { 'y', 'o', 'l', 'o' }; const auto shouldVerifyAsFalse = testSignatureVerificationKey.verify(invalidMessageVector, signature); ASSERT_FALSE(shouldVerifyAsFalse); } TEST(SymmetricKey, EncryptsAndDecryptsWithoutUnsealingInstructions) { const SymmetricKey testSymmetricKey(orderedTestKey, defaultTestSymmetricRecipeJson); const std::vector<unsigned char> messageVector = { 'y', 'o', 't', 'o' }; const std::string unsealingInstructions = {}; SodiumBuffer messageBuffer(messageVector); const auto sealedMessage = testSymmetricKey.sealToCiphertextOnly(messageBuffer); const auto unsealedMessage = testSymmetricKey.unseal(sealedMessage); const auto unsealedPlaintext = unsealedMessage.toVector(); ASSERT_EQ(messageVector, unsealedPlaintext); } TEST(SymmetricKey, ConvertsToSerializedFormAndBack) { const SymmetricKey testKey(orderedTestKey, defaultTestSymmetricRecipeJson); const auto serializedBinaryForm = testKey.toSerializedBinaryForm(); const auto copy = SymmetricKey::fromSerializedBinaryForm(serializedBinaryForm); ASSERT_EQ(copy.recipe, defaultTestSymmetricRecipeJson); ASSERT_STREQ(copy.keyBytes.toHexString().c_str(), testKey.keyBytes.toHexString().c_str()); } TEST(SymmetricKey, ConvertsToJsonAndBack) { const SymmetricKey testKey(orderedTestKey, defaultTestSymmetricRecipeJson); const std::string json = testKey.toJson(1, '\t'); const SymmetricKey replica = SymmetricKey::fromJson(json); ASSERT_EQ(replica.recipe, defaultTestSymmetricRecipeJson); ASSERT_STREQ(replica.keyBytes.toHexString().c_str(), testKey.keyBytes.toHexString().c_str()); } TEST(SymmetricKey, EncryptsAndDecrypts) { const SymmetricKey testSymmetricKey(orderedTestKey, defaultTestSymmetricRecipeJson); const std::vector<unsigned char> messageVector = { 'y', 'o', 't', 'o' }; const std::string unsealingInstructions = "{\"userMustAcknowledgeThisMessage\": \"yoto mofo\"}"; SodiumBuffer messageBuffer(messageVector); const auto sealedMessage = testSymmetricKey.sealToCiphertextOnly(messageBuffer, unsealingInstructions); const auto unsealedMessage = testSymmetricKey.unseal(sealedMessage, unsealingInstructions); const std::vector<unsigned char> unsealedPlaintext = unsealedMessage.toVector(); ASSERT_EQ(messageVector, unsealedPlaintext); } TEST(SymmetricKey, ThrowsOnEncryptEmptyMessage) { const SymmetricKey testSymmetricKey(orderedTestKey, defaultTestSymmetricRecipeJson); const std::vector<unsigned char> messageVector = {}; const std::string unsealingInstructions = ""; SodiumBuffer messageBuffer(messageVector); ASSERT_ANY_THROW( const auto sealedMessage = testSymmetricKey.sealToCiphertextOnly(messageBuffer, unsealingInstructions); ); } TEST(SymmetricKey, EncryptsAndDecryptsPackaged) { const SymmetricKey testSymmetricKey(orderedTestKey, defaultTestSymmetricRecipeJson); const std::vector<unsigned char> messageVector = { 'y', 'o', 't', 'o' }; const std::string unsealingInstructions = "{\"userMustAcknowledgeThisMessage\": \"yoto mofo\"}"; SodiumBuffer messageBuffer(messageVector); const auto sealedMessage = testSymmetricKey.seal(messageBuffer, unsealingInstructions); const auto unsealedMessage = SymmetricKey::unseal(sealedMessage, orderedTestKey); const std::vector<unsigned char> unsealedPlaintext = unsealedMessage.toVector(); ASSERT_EQ(messageVector, unsealedPlaintext); } TEST(SymmetricKey, EncryptsAndDecryptsPackagedAndDecryptsWithoutRederiving) { const SymmetricKey testSymmetricKey(orderedTestKey, defaultTestSymmetricRecipeJson); const std::vector<unsigned char> messageVector = { 'y', 'o', 't', 'o' }; const std::string unsealingInstructions = "{\"userMustAcknowledgeThisMessage\": \"yoto mofo\"}"; SodiumBuffer messageBuffer(messageVector); const auto sealedMessage = testSymmetricKey.seal(messageBuffer, unsealingInstructions); const auto unsealedMessage = testSymmetricKey.unseal(sealedMessage); const std::vector<unsigned char> unsealedPlaintext = unsealedMessage.toVector(); ASSERT_EQ(messageVector, unsealedPlaintext); } TEST(PackagedSealedMessage, ConvertsToSerializedFormAndBack) { std::vector<unsigned char> testCiphertext({ 42 }); PackagedSealedMessage message(testCiphertext, "no", "way"); auto serialized = message.toSerializedBinaryForm(); auto replica = PackagedSealedMessage::fromSerializedBinaryForm(serialized); ASSERT_EQ(replica.ciphertext.size(), 1); ASSERT_EQ(replica.ciphertext.data()[0], 42); ASSERT_STREQ(replica.recipe.c_str(), message.recipe.c_str()); ASSERT_STREQ(replica.unsealingInstructions.c_str(), message.unsealingInstructions.c_str()); } TEST(PackagedSealedMessage, ConvertsToJsonAndBack) { std::vector<unsigned char> testCiphertext({ 42 }); PackagedSealedMessage message(testCiphertext, "no", "way"); auto serialized = message.toJson(); auto replica = PackagedSealedMessage::fromJson(serialized); ASSERT_EQ(replica.ciphertext.size(), 1); ASSERT_EQ(replica.ciphertext.data()[0], 42); ASSERT_STREQ(replica.recipe.c_str(), message.recipe.c_str()); ASSERT_STREQ(replica.unsealingInstructions.c_str(), message.unsealingInstructions.c_str()); }
39.893424
196
0.799011
[ "vector" ]
f5323a3df839af23136e5413224cd44b7532d824
7,909
cpp
C++
pkg/BfsdlTests/source/ObjectDataTest.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
1
2018-07-27T17:20:59.000Z
2018-07-27T17:20:59.000Z
pkg/BfsdlTests/source/ObjectDataTest.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
10
2018-07-28T03:21:05.000Z
2019-02-21T07:09:36.000Z
pkg/BfsdlTests/source/ObjectDataTest.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
null
null
null
/** BFDP Object Data Tests Copyright 2019, Daniel Kristensen, Garmin Ltd, or its subsidiaries. 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 copyright holder 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 "gtest/gtest.h" #include "BfsdlParser/Objects/FStringField.hpp" #include "BfsdlParser/Objects/NumericField.hpp" #include "BfsdlParser/Objects/PStringField.hpp" #include "BfsdlParser/Objects/StringField.hpp" #include "BfsdlParser/Objects/Tree.hpp" #include "BfsdlTests/TestUtil.hpp" namespace BfsdlTests { using Bfdp::Unicode::GetCodingId; using BfsdlParser::Objects::Field; using BfsdlParser::Objects::FieldPtr; using BfsdlParser::Objects::FieldType; using BfsdlParser::Objects::FStringField; using BfsdlParser::Objects::IObject; using BfsdlParser::Objects::IObjectPtr; using BfsdlParser::Objects::NumericField; using BfsdlParser::Objects::NumericFieldProperties; using BfsdlParser::Objects::NumericFieldPtr; using BfsdlParser::Objects::ObjectType; using BfsdlParser::Objects::PStringField; using BfsdlParser::Objects::StringField; using BfsdlParser::Objects::StringFieldPtr; using BfsdlParser::Objects::Tree; class ObjectDataTest : public ::testing::Test { public: void SetUp() { SetDefaultErrorHandlers(); } }; TEST_F( ObjectDataTest, FStringField ) { IObjectPtr op = std::make_shared< FStringField >( "test", 0U, false, GetCodingId( "UTF8" ), 30U ); ASSERT_TRUE( op != NULL ); ASSERT_EQ( ObjectType::Field, op->GetType() ); ASSERT_STREQ( "test", op->GetName().c_str() ); ASSERT_STREQ( "test", op->GetId().GetStr().c_str() ); FieldPtr fp = Field::StaticCast( op ); ASSERT_TRUE( fp != NULL ); ASSERT_STREQ( "test", fp->GetName().c_str() ); ASSERT_STREQ( "string:f30:t0;utf8", fp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::String, fp->GetFieldType() ); StringFieldPtr sfp = StringField::StaticCast( op ); ASSERT_TRUE( sfp != NULL ); ASSERT_STREQ( "test", sfp->GetName().c_str() ); ASSERT_STREQ( "string:f30:t0;utf8", sfp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::String, sfp->GetFieldType() ); } TEST_F( ObjectDataTest, NumericField ) { static NumericFieldProperties const sNumericProps1 = { true, 24, 8 }; static NumericFieldProperties const sNumericProps2 = { false, 16, 0 }; IObjectPtr op = std::make_shared< NumericField >( "test", sNumericProps1 ); ASSERT_TRUE( op != NULL ); ASSERT_EQ( ObjectType::Field, op->GetType() ); ASSERT_STREQ( "test", op->GetName().c_str() ); ASSERT_STREQ( "test", op->GetId().GetStr().c_str() ); FieldPtr fp = Field::StaticCast( op ); ASSERT_TRUE( fp != NULL ); ASSERT_STREQ( "test", fp->GetName().c_str() ); ASSERT_STREQ( "s24.8", fp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::Numeric, fp->GetFieldType() ); NumericFieldPtr nfp = NumericField::StaticCast( op ); ASSERT_TRUE( nfp != NULL ); ASSERT_STREQ( "test", nfp->GetName().c_str() ); ASSERT_STREQ( "s24.8", nfp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::Numeric, nfp->GetFieldType() ); NumericFieldPtr fp2 = std::make_shared< NumericField >( "abc", sNumericProps2 ); ASSERT_STREQ( "abc", fp2->GetName().c_str() ); ASSERT_STREQ( "u16", fp2->GetTypeStr().c_str() ); } TEST_F( ObjectDataTest, PStringField ) { IObjectPtr op = std::make_shared< PStringField >( "test", 0U, true, GetCodingId( "MS-1252" ), 8U ); ASSERT_TRUE( op != NULL ); ASSERT_EQ( ObjectType::Field, op->GetType() ); ASSERT_STREQ( "test", op->GetName().c_str() ); ASSERT_STREQ( "test", op->GetId().GetStr().c_str() ); FieldPtr fp = Field::StaticCast( op ); ASSERT_TRUE( fp != NULL ); ASSERT_STREQ( "test", fp->GetName().c_str() ); ASSERT_STREQ( "string:p8:t0:tu;ms1252", fp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::String, fp->GetFieldType() ); StringFieldPtr sfp = StringField::StaticCast( op ); ASSERT_TRUE( sfp != NULL ); ASSERT_STREQ( "test", sfp->GetName().c_str() ); ASSERT_STREQ( "string:p8:t0:tu;ms1252", sfp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::String, sfp->GetFieldType() ); } TEST_F( ObjectDataTest, StringField ) { IObjectPtr op = std::make_shared< StringField >( "test", 0U, false, GetCodingId( "ASCII" ) ); ASSERT_TRUE( op != NULL ); ASSERT_EQ( ObjectType::Field, op->GetType() ); ASSERT_STREQ( "test", op->GetName().c_str() ); ASSERT_STREQ( "test", op->GetId().GetStr().c_str() ); FieldPtr fp = Field::StaticCast( op ); ASSERT_TRUE( fp != NULL ); ASSERT_STREQ( "test", fp->GetName().c_str() ); ASSERT_STREQ( "string:b:t0;ascii", fp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::String, fp->GetFieldType() ); StringFieldPtr sfp = StringField::StaticCast( op ); ASSERT_TRUE( sfp != NULL ); ASSERT_STREQ( "test", sfp->GetName().c_str() ); ASSERT_STREQ( "string:b:t0;ascii", sfp->GetTypeStr().c_str() ); ASSERT_EQ( FieldType::String, sfp->GetFieldType() ); } TEST_F( ObjectDataTest, Tree ) { static NumericFieldProperties const sNumericProps = { false, 16, 0 }; Tree tree; ASSERT_EQ( ObjectType::Tree, tree.GetType() ); ASSERT_STREQ( "", tree.GetName().c_str() ); IObjectPtr op = tree.Add( std::make_shared< NumericField >( "One", sNumericProps ) ); ASSERT_TRUE( op != NULL ); ASSERT_STREQ( "One", op->GetName().c_str() ); op = tree.Add( std::make_shared< NumericField >( "Two", sNumericProps ) ); ASSERT_TRUE( op != NULL ); ASSERT_STREQ( "Two", op->GetName().c_str() ); op = tree.Find( "doesNotExist" ); ASSERT_TRUE( op == NULL ); op = tree.Find( "Two" ); ASSERT_TRUE( op != NULL ); ASSERT_STREQ( "Two", op->GetName().c_str() ); op = tree.Find( "One" ); ASSERT_TRUE( op != NULL ); ASSERT_STREQ( "One", op->GetName().c_str() ); op = tree.Find( "Two" ); ASSERT_TRUE( op != NULL ); ASSERT_STREQ( "Two", op->GetName().c_str() ); } } // namespace BfsdlTests
39.545
107
0.638134
[ "object" ]
f536642709be8ad92de01fcd10d57e759e84f138
1,372
hpp
C++
src/mbgl/layout/symbol_feature.hpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
4,234
2015-01-09T08:10:16.000Z
2022-03-30T14:13:55.000Z
src/mbgl/layout/symbol_feature.hpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
12,771
2015-01-01T20:27:42.000Z
2022-03-24T18:14:44.000Z
src/mbgl/layout/symbol_feature.hpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
1,571
2015-01-08T08:24:53.000Z
2022-03-28T06:30:53.000Z
#pragma once #include <mbgl/style/expression/image.hpp> #include <mbgl/text/tagged_string.hpp> #include <mbgl/tile/geometry_tile_data.hpp> #include <mbgl/util/optional.hpp> #include <array> #include <string> namespace mbgl { class SymbolFeature : public GeometryTileFeature { public: SymbolFeature(std::unique_ptr<GeometryTileFeature> feature_) : feature(std::move(feature_)), geometry(feature->getGeometries().clone()) // we need a mutable copy of the geometry for mergeLines() {} FeatureType getType() const override { return feature->getType(); } optional<Value> getValue(const std::string& key) const override { return feature->getValue(key); } const PropertyMap& getProperties() const override { return feature->getProperties(); } FeatureIdentifier getID() const override { return feature->getID(); }; const GeometryCollection& getGeometries() const override { return feature->getGeometries(); } friend bool operator < (const SymbolFeature& lhs, const SymbolFeature& rhs) { return lhs.sortKey < rhs.sortKey; } std::unique_ptr<GeometryTileFeature> feature; GeometryCollection geometry; optional<TaggedString> formattedText; optional<style::expression::Image> icon; float sortKey = 0.0f; std::size_t index; bool allowsVerticalWritingMode = false; }; } // namespace mbgl
34.3
111
0.721574
[ "geometry" ]
f536fb08938df4f347c9550698f107310a656536
505
cpp
C++
0735-Asteroid Collision/0735-Asteroid Collision.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0701-0800/0735-Asteroid Collision/0735-Asteroid Collision.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0701-0800/0735-Asteroid Collision/0735-Asteroid Collision.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { vector<int> St; for (int a : asteroids) { while (!St.empty() && St.back() > 0 && St.back() < -a) { St.pop_back(); } if (St.empty() || St.back() < 0 || a > 0) { St.push_back(a); } else if (St.back() == -a) { St.pop_back(); } } return St; } };
24.047619
68
0.370297
[ "vector" ]
f537e415f5804cc473861c7492afa9ba8a36ab18
434
cpp
C++
src/osam2020/1.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
1
2020-06-01T12:19:31.000Z
2020-06-01T12:19:31.000Z
src/osam2020/1.cpp
ginami0129g/my-study-history
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
23
2020-11-08T07:14:02.000Z
2021-02-11T11:16:00.000Z
src/osam2020/1.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
null
null
null
#include <string> #include <vector> #include <algorithm> using namespace std; int solution(int n,int m) { int answer = 0; bool flag = false; for (int i = 1; ; ++i) { flag = (i % m == 0) ? true : false; if (flag == false) { --n; } if (flag == true && n == 0) n = 1; if (flag == false && n == 0) { answer = i; break; } } return answer; }
19.727273
43
0.435484
[ "vector" ]
f539289d656baf33d842123f9a24e572843d6d47
3,930
hpp
C++
include/autotune/fixed_set_parameter.hpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
5
2019-11-06T15:02:41.000Z
2022-01-14T20:25:50.000Z
include/autotune/fixed_set_parameter.hpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
3
2018-01-25T21:25:22.000Z
2022-03-14T17:35:27.000Z
include/autotune/fixed_set_parameter.hpp
DavidPfander-UniStuttgart/AutoTuneTMP
f5fb836778b04c2ab0fbcc4d36c466e577e96e65
[ "BSD-3-Clause" ]
1
2020-07-15T11:05:43.000Z
2020-07-15T11:05:43.000Z
#pragma once #include <memory> #include <vector> #include "parameter_value_set.hpp" namespace autotune { template <typename T> class fixed_set_parameter { private: std::string name; size_t cur_index; std::vector<T> values; public: fixed_set_parameter(const std::string &name, const std::vector<T> &values) : name(name), cur_index(0), values(values) {} fixed_set_parameter(const fixed_set_parameter<T> &other) : name(other.name), cur_index(other.cur_index), values(other.values) {} const std::string &get_name() const { return this->name; } const std::vector<std::string> &get_values() const { return this->values; } void set_index(size_t new_index) { cur_index = new_index; }; const std::string get_value() const { if constexpr (std::is_same<T, bool>::value) { if (this->values[cur_index]) { return "true"; } else { return "false"; } } else { return std::to_string(this->values[cur_index]); } } T get_raw_value() { return values[cur_index]; }; size_t count_values() const { return values.size(); } bool next() { if (cur_index + 1 < values.size()) { cur_index += 1; return true; } else { return false; } } bool prev() { if (cur_index > 0) { cur_index -= 1; return true; } else { return false; } } void set_min() { cur_index = 0; }; virtual void set_initial() { // TODO: should be extended, so that an initial guess can be supplied cur_index = 0; } void set_random_value() { auto random_gen = detail::make_uniform_int_generator(0ul, this->values.size() - 1ul); cur_index = random_gen(); } void set_value_unsafe(const std::string &v) { this->set_min(); while (true) { if (this->get_value().compare(v) == 0) { break; } if (!this->next()) { throw; } } } }; template <> class fixed_set_parameter<std::string> { private: std::string name; size_t cur_index; std::vector<std::string> values; bool quote_string; public: fixed_set_parameter(const std::string &name, const std::vector<std::string> &values, bool quote_string = true) : name(name), cur_index(0), values(values), quote_string(quote_string) {} const std::string &get_name() const { return this->name; } const std::vector<std::string> &get_values() const { return this->values; } void set_index(size_t new_index) { cur_index = new_index; }; const std::string get_value() const { if (quote_string) { return std::string("\"") + this->values[cur_index] + std::string("\""); } else { return this->values[cur_index]; } } std::string get_raw_value() { return values[cur_index]; }; size_t count_values() const { return values.size(); } bool next() { if (cur_index + 1 < values.size()) { cur_index += 1; return true; } else { return false; } } bool prev() { if (cur_index > 0) { cur_index -= 1; return true; } else { return false; } } void set_min() { cur_index = 0; }; virtual void set_initial() { // TODO: should be extended, so that an initial guess can be supplied cur_index = 0; } void set_quote_string(bool quote_string) { this->quote_string = quote_string; } void set_random_value() { // randomize index std::uniform_int_distribution<size_t> distribution(0, this->values.size() - 1); std::random_device rd; std::default_random_engine generator(rd()); cur_index = distribution(generator); } void set_value_unsafe(const std::string &v) { this->set_min(); while (true) { if (this->get_value().compare(v) == 0) { break; } if (!this->next()) { throw; } } } }; } // namespace autotune
22.982456
80
0.596438
[ "vector" ]
f53e638594e2ccd374eea3b95ae659ebeb00b9b0
13,872
cc
C++
mace/ops/space_to_batch.cc
hanhan9449/mace
63feaf5055bab6a081d36edfab8f963a624899aa
[ "Apache-2.0" ]
1
2021-08-02T12:17:58.000Z
2021-08-02T12:17:58.000Z
mace/ops/space_to_batch.cc
hanhan9449/mace
63feaf5055bab6a081d36edfab8f963a624899aa
[ "Apache-2.0" ]
null
null
null
mace/ops/space_to_batch.cc
hanhan9449/mace
63feaf5055bab6a081d36edfab8f963a624899aa
[ "Apache-2.0" ]
1
2021-08-02T12:18:00.000Z
2021-08-02T12:18:00.000Z
// Copyright 2018 The MACE 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 <algorithm> #include <memory> #include "mace/core/ops/operator.h" #include "mace/core/registry/ops_registry.h" #ifdef MACE_ENABLE_OPENCL #include "mace/ops/opencl/image/space_to_batch.h" #endif // MACE_ENABLE_OPENCL #include "mace/utils/memory.h" namespace mace { namespace ops { class SpaceToBatchOpBase : public Operation { public: explicit SpaceToBatchOpBase(OpConstructContext *context) : Operation(context), paddings_(Operation::GetRepeatedArgs<int>("paddings", {0, 0, 0, 0})), block_shape_(Operation::GetRepeatedArgs<int>("block_shape", {1, 1})) { MACE_CHECK( block_shape_.size() == 2 && block_shape_[0] > 1 && block_shape_[1] > 1, "Block's shape should be 1D, and greater than 1"); MACE_CHECK(paddings_.size() == 4, "Paddings' shape should be 2D"); } protected: std::vector<int> paddings_; std::vector<int> block_shape_; protected: void CalculateSpaceToBatchOutputShape(const Tensor *input_tensor, const DataFormat data_format, index_t *output_shape) { MACE_CHECK(input_tensor->dim_size() == 4, "Input's shape should be 4D"); index_t batch = input_tensor->dim(0); index_t channels = 0; index_t height = 0; index_t width = 0; if (data_format == DataFormat::NHWC) { height = input_tensor->dim(1); width = input_tensor->dim(2); channels = input_tensor->dim(3); } else if (data_format == DataFormat::NCHW) { height = input_tensor->dim(2); width = input_tensor->dim(3); channels = input_tensor->dim(1); } else { MACE_NOT_IMPLEMENTED; } index_t padded_height = height + paddings_[0] + paddings_[1]; index_t padded_width = width + paddings_[2] + paddings_[3]; MACE_CHECK(padded_height % block_shape_[0] == 0, "padded input height", padded_height, " is not divisible by block height"); MACE_CHECK(padded_width % block_shape_[1] == 0, "padded input width", padded_height, " is not divisible by block width"); index_t new_batch = batch * block_shape_[0] * block_shape_[1]; index_t new_height = padded_height / block_shape_[0]; index_t new_width = padded_width / block_shape_[1]; if (data_format == DataFormat::NHWC) { output_shape[0] = new_batch; output_shape[1] = new_height; output_shape[2] = new_width; output_shape[3] = channels; } else { output_shape[0] = new_batch; output_shape[1] = channels; output_shape[2] = new_height; output_shape[3] = new_width; } } }; template<DeviceType D, class T> class SpaceToBatchNDOp; template<class T> class SpaceToBatchNDOp<DeviceType::CPU, T> : public SpaceToBatchOpBase { public: explicit SpaceToBatchNDOp(OpConstructContext *context) : SpaceToBatchOpBase(context) {} MaceStatus Run(OpContext *context) override { MACE_UNUSED(context); const Tensor *space_tensor = this->Input(0); Tensor *batch_tensor = this->Output(0); std::vector<index_t> output_shape(4, 0); CalculateSpaceToBatchOutputShape(space_tensor, DataFormat::NCHW, output_shape.data()); MACE_RETURN_IF_ERROR(batch_tensor->Resize(output_shape)); Tensor::MappingGuard input_guard(space_tensor); Tensor::MappingGuard output_guard(batch_tensor); int pad_top = paddings_[0]; int pad_left = paddings_[2]; int block_shape_h = block_shape_[0]; int block_shape_w = block_shape_[1]; const T *input_data = space_tensor->data<T>(); T *output_data = batch_tensor->mutable_data<T>(); index_t in_batches = space_tensor->dim(0); index_t in_height = space_tensor->dim(2); index_t in_width = space_tensor->dim(3); index_t out_batches = batch_tensor->dim(0); index_t channels = batch_tensor->dim(1); index_t out_height = batch_tensor->dim(2); index_t out_width = batch_tensor->dim(3); index_t block_h_size = std::max(static_cast<index_t>(1), 8 * 1024 / block_shape_w / in_width); // make channel outter loop so we can make best use of cache for (index_t c = 0; c < channels; ++c) { for (index_t block_h = 0; block_h < out_height; block_h += block_h_size) { for (index_t b = 0; b < out_batches; ++b) { const index_t in_b = b % in_batches; const index_t tile_index = b / in_batches; const index_t tile_h = tile_index / block_shape_w; const index_t tile_w = tile_index % block_shape_w; const index_t valid_h_start = std::max(block_h, (pad_top - tile_h + block_shape_h - 1) / block_shape_h); const index_t valid_h_end = std::min(out_height, std::min( block_h + block_h_size, (in_height + pad_top - tile_h + block_shape_h - 1) / block_shape_h)); const index_t valid_w_start = std::max(static_cast<index_t>(0), (pad_left - tile_w + block_shape_w - 1) / block_shape_w); const index_t valid_w_end = std::min(out_width, (in_width + pad_left - tile_w + block_shape_w - 1) / block_shape_w); const T *input_base = input_data + (in_b * channels + c) * in_height * in_width; T *output_base = output_data + (b * channels + c) * out_height * out_width; memset(static_cast<void *>(output_base + block_h * out_width), 0, (valid_h_start - block_h) * out_width * sizeof(T)); index_t in_h = valid_h_start * block_shape_h + tile_h - pad_top; for (index_t h = valid_h_start; h < valid_h_end; ++h) { memset(static_cast<void *>(output_base + h * out_width), 0, valid_w_start * sizeof(T)); index_t in_w = valid_w_start * block_shape_w + tile_w - pad_left; for (index_t w = valid_w_start; w < valid_w_end; ++w) { output_base[h * out_width + w] = input_base[in_h * in_width + in_w]; in_w += block_shape_w; } // w in_h += block_shape_h; memset( static_cast<void *>(output_base + h * out_width + valid_w_end), 0, (out_width - valid_w_end) * sizeof(T)); } // h memset(static_cast<void *>(output_base + valid_h_end * out_width), 0, (std::min(out_height, block_h + block_h_size) - valid_h_end) * out_width * sizeof(T)); } // b } // block_h } // c return MaceStatus::MACE_SUCCESS; } }; #ifdef MACE_ENABLE_QUANTIZE template <> class SpaceToBatchNDOp<DeviceType::CPU, uint8_t> : public SpaceToBatchOpBase { public: explicit SpaceToBatchNDOp(OpConstructContext *context) : SpaceToBatchOpBase(context) {} MaceStatus Run(OpContext *context) override { MACE_UNUSED(context); const Tensor *space_tensor = this->Input(0); Tensor *batch_tensor = this->Output(0); std::vector<index_t> output_shape(4, 0); CalculateSpaceToBatchOutputShape(space_tensor, DataFormat::NHWC, output_shape.data()); MACE_RETURN_IF_ERROR(batch_tensor->Resize(output_shape)); int zero_point = space_tensor->zero_point(); Tensor::MappingGuard input_guard(space_tensor); Tensor::MappingGuard output_guard(batch_tensor); int pad_top = paddings_[0]; int pad_left = paddings_[2]; int block_shape_h = block_shape_[0]; int block_shape_w = block_shape_[1]; batch_tensor->SetScale(space_tensor->scale()); batch_tensor->SetZeroPoint(space_tensor->zero_point()); const uint8_t *input_data = space_tensor->data<uint8_t>(); uint8_t *output_data = batch_tensor->mutable_data<uint8_t>(); index_t in_batches = space_tensor->dim(0); index_t in_height = space_tensor->dim(1); index_t in_width = space_tensor->dim(2); index_t out_batches = batch_tensor->dim(0); index_t out_height = batch_tensor->dim(1); index_t out_width = batch_tensor->dim(2); index_t channels = batch_tensor->dim(3); for (index_t b = 0; b < out_batches; ++b) { const index_t in_b = b % in_batches; const index_t tile_index = b / in_batches; const index_t tile_h = tile_index / block_shape_w; const index_t tile_w = tile_index % block_shape_w; const index_t valid_h_start = std::max(static_cast<index_t>(0), (pad_top - tile_h + block_shape_h - 1) / block_shape_h); const index_t valid_h_end = std::min(out_height, (in_height + pad_top - tile_h + block_shape_h - 1) / block_shape_h); const index_t valid_w_start = std::max(static_cast<index_t>(0), (pad_left - tile_w + block_shape_w - 1) / block_shape_w); const index_t valid_w_end = std::min(out_width, (in_width + pad_left - tile_w + block_shape_w - 1) / block_shape_w); const uint8_t *input_base = input_data + in_b * channels * in_height * in_width; uint8_t *output_base = output_data + b * channels * out_height * out_width; memset(output_base, zero_point, valid_h_start * out_width * channels * sizeof(uint8_t)); index_t in_h = valid_h_start * block_shape_h + tile_h - pad_top; for (index_t h = valid_h_start; h < valid_h_end; ++h) { memset(output_base + h * out_width * channels, zero_point, valid_w_start * channels * sizeof(uint8_t)); index_t in_w = valid_w_start * block_shape_w + tile_w - pad_left; for (index_t w = valid_w_start; w < valid_w_end; ++w) { memcpy(output_base + (h * out_width + w) * channels, input_base + (in_h * in_width + in_w) * channels, sizeof(uint8_t) * channels); in_w += block_shape_w; } // w in_h += block_shape_h; memset(output_base + (h * out_width + valid_w_end) * channels, zero_point, (out_width - valid_w_end) * channels * sizeof(uint8_t)); } // h memset(output_base + valid_h_end * out_width * channels, zero_point, (out_height - valid_h_end) * out_width * channels * sizeof(uint8_t)); } // b return MaceStatus::MACE_SUCCESS; } }; #endif // MACE_ENABLE_QUANTIZE #ifdef MACE_ENABLE_OPENCL template<> class SpaceToBatchNDOp<DeviceType::GPU, float> : public SpaceToBatchOpBase { public: explicit SpaceToBatchNDOp(OpConstructContext *context) : SpaceToBatchOpBase(context) { if (context->GetOpMemoryType() == MemoryType::GPU_IMAGE) { kernel_ = make_unique<opencl::image::SpaceToBatchKernel>(); } else { MACE_NOT_IMPLEMENTED; } } MaceStatus Run(OpContext *context) override { const Tensor *space_tensor = this->Input(0); Tensor *batch_tensor = this->Output(0); std::vector<index_t> output_shape(4, 0); CalculateSpaceToBatchOutputShape(space_tensor, DataFormat::NHWC, output_shape.data()); return kernel_->Compute(context, space_tensor, paddings_, block_shape_, output_shape, batch_tensor); } private: std::unique_ptr<OpenCLSpaceToBatchKernel> kernel_; }; #endif // MACE_ENABLE_OPENCL void RegisterSpaceToBatchND(OpRegistry *op_registry) { MACE_REGISTER_OP(op_registry, "SpaceToBatchND", SpaceToBatchNDOp, DeviceType::CPU, float); MACE_REGISTER_BF16_OP(op_registry, "SpaceToBatchND", SpaceToBatchNDOp, DeviceType::CPU); #ifdef MACE_ENABLE_QUANTIZE MACE_REGISTER_OP(op_registry, "SpaceToBatchND", SpaceToBatchNDOp, DeviceType::CPU, uint8_t); #endif // MACE_ENABLE_QUANTIZE MACE_REGISTER_GPU_OP(op_registry, "SpaceToBatchND", SpaceToBatchNDOp); } } // namespace ops } // namespace mace
39.862069
79
0.580666
[ "shape", "vector" ]
f53f63162bda8e93364065728b2251589f6e507a
19,105
cpp
C++
src/main.cpp
wkhattak/Path-Planning-v2-Work-In-Progress
c76bc260f89461f5c0595b35a401241fe15f9888
[ "MIT" ]
null
null
null
src/main.cpp
wkhattak/Path-Planning-v2-Work-In-Progress
c76bc260f89461f5c0595b35a401241fe15f9888
[ "MIT" ]
null
null
null
src/main.cpp
wkhattak/Path-Planning-v2-Work-In-Progress
c76bc260f89461f5c0595b35a401241fe15f9888
[ "MIT" ]
null
null
null
#include <fstream> #include <math.h> #include <uWS/uWS.h> #include <chrono> #include <iostream> #include <thread> #include <vector> #include "Eigen-3.3/Eigen/Core" #include "Eigen-3.3/Eigen/QR" #include "json.hpp" #include "spline.h" #include "car.h" #include "helpers.h" using namespace std; // for convenience using json = nlohmann::json; // For converting back and forth between radians and degrees. constexpr double pi() { return M_PI; } double deg2rad(double x) { return x * pi() / 180; } double rad2deg(double x) { return x * 180 / pi(); } // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. string hasData(string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_first_of("}"); if (found_null != string::npos) { return ""; } else if (b1 != string::npos && b2 != string::npos) { return s.substr(b1, b2 - b1 + 2); } return ""; } double distance(double x1, double y1, double x2, double y2) { return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y) { double closestLen = 100000; //large number int closestWaypoint = 0; for(int i = 0; i < maps_x.size(); i++) { double map_x = maps_x[i]; double map_y = maps_y[i]; double dist = distance(x,y,map_x,map_y); if(dist < closestLen) { closestLen = dist; closestWaypoint = i; } } return closestWaypoint; } int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y) { int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y); double map_x = maps_x[closestWaypoint]; double map_y = maps_y[closestWaypoint]; double heading = atan2((map_y-y),(map_x-x)); double angle = fabs(theta - heading); angle = min(2*pi() - angle, angle); if(angle > pi()/4) { closestWaypoint++; if (closestWaypoint == maps_x.size()) { closestWaypoint = 0; } } return closestWaypoint; } // Transform from Cartesian x,y coordinates to Frenet s,d coordinates vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y) { int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y); int prev_wp; prev_wp = next_wp-1; if(next_wp == 0) { prev_wp = maps_x.size()-1; } double n_x = maps_x[next_wp]-maps_x[prev_wp]; double n_y = maps_y[next_wp]-maps_y[prev_wp]; double x_x = x - maps_x[prev_wp]; double x_y = y - maps_y[prev_wp]; // find the projection of x onto n double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y); double proj_x = proj_norm*n_x; double proj_y = proj_norm*n_y; double frenet_d = distance(x_x,x_y,proj_x,proj_y); //see if d value is positive or negative by comparing it to a center point double center_x = 1000-maps_x[prev_wp]; double center_y = 2000-maps_y[prev_wp]; double centerToPos = distance(center_x,center_y,x_x,x_y); double centerToRef = distance(center_x,center_y,proj_x,proj_y); if(centerToPos <= centerToRef) { frenet_d *= -1; } // calculate s value double frenet_s = 0; for(int i = 0; i < prev_wp; i++) { frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]); } frenet_s += distance(0,0,proj_x,proj_y); return {frenet_s,frenet_d}; } // Transform from Frenet s,d coordinates to Cartesian x,y vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y) { int prev_wp = -1; while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) )) { prev_wp++; } int wp2 = (prev_wp+1)%maps_x.size(); double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),(maps_x[wp2]-maps_x[prev_wp])); // the x,y,s along the segment double seg_s = (s-maps_s[prev_wp]); double seg_x = maps_x[prev_wp]+seg_s*cos(heading); double seg_y = maps_y[prev_wp]+seg_s*sin(heading); double perp_heading = heading-pi()/2; double x = seg_x + d*cos(perp_heading); double y = seg_y + d*sin(perp_heading); return {x,y}; } int main() { uWS::Hub h; // Load up map values for waypoint's x,y,s and d normalized normal vectors vector<double> map_waypoints_x; vector<double> map_waypoints_y; vector<double> map_waypoints_s; vector<double> map_waypoints_dx; vector<double> map_waypoints_dy; // Waypoint map to read from string map_file_ = "../data/highway_map.csv"; // The max s value before wrapping around the track back to 0 double max_s = 6945.554; //int lane = 1; // centre lane >> Lanes = 0,1,2 & Lane centres = 2,6,10 (left lane is 0) //const double SAFE_VELOCITY = 49.5; //double velocity = 5.0; // start with 5 & slowly build up to SAFE_VELOCITY when possible //const double DISTANCE_AHEAD = 30; // comfortable driving distance in front bool first_cycle = true; /* * Ego car */ Car ego_car = Car(); ego_car.id = EGO_CAR_ID; ifstream in_map_(map_file_.c_str(), ifstream::in); string line; while (getline(in_map_, line)) { istringstream iss(line); double x; double y; float s; float d_x; float d_y; iss >> x; iss >> y; iss >> s; iss >> d_x; iss >> d_y; map_waypoints_x.push_back(x); map_waypoints_y.push_back(y); map_waypoints_s.push_back(s); map_waypoints_dx.push_back(d_x); map_waypoints_dy.push_back(d_y); } h.onMessage([&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,&map_waypoints_dx,&map_waypoints_dy,&first_cycle,&ego_car](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event //auto sdata = string(data).substr(0, length); //cout << sdata << endl; if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(data); if (s != "") { auto j = json::parse(s); string event = j[0].get<string>(); if (event == "telemetry") { // j[1] is the data JSON object // Main car's localization Data double car_x = j[1]["x"]; double car_y = j[1]["y"]; double car_s = j[1]["s"]; double car_d = j[1]["d"]; double car_yaw = j[1]["yaw"]; double car_speed = j[1]["speed"]; // Previous path data given to the Planner auto previous_path_x = j[1]["previous_path_x"]; auto previous_path_y = j[1]["previous_path_y"]; // Previous path's end s and d values double end_path_s = j[1]["end_path_s"]; double end_path_d = j[1]["end_path_d"]; // Sensor Fusion Data, a list of all other cars on the same side of the road. // A 2D vector of cars and then those cars' [ id, x, y, vx, vy, s, d]: // unique id, x position in map coordinates, y position in map coordinates, // x velocity in m/s, y velocity in m/s, // s position in frenet coordinates, d position in frenet coordinates. auto sensor_fusion = j[1]["sensor_fusion"]; json msgJson; vector<double> next_x_vals; vector<double> next_y_vals; // £££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££ cout << "************START************" << endl; int prev_path_size = previous_path_x.size(); /* * Create car objects */ vector<Car> normal_cars; for (auto s_f: sensor_fusion) {// go through sensor fusion data Car normal_car = Car(); normal_car.id = s_f[0]; normal_car.s = s_f[5]; double vx = s_f[3]; double vy = s_f[4]; normal_car.s_dot = sqrt(vx*vx + vy*vy); normal_car.d = s_f[6]; normal_car.x = s_f[1]; normal_car.y = s_f[2]; normal_car.lane = (int)normal_car.d/4; normal_car.predictTrajectory(prev_path_size); //normal_car.printPredictedTrajectoryLastPoint(); //vector<double> computedState = normal_car.computeStateAtTime(PREDICTION_HORIZON_TIMESTEPS * PREDICTION_HORIZON_TIME_DELTA); //cout << "Computed State At Time T: s=" << computedState[0] << ", s_dot=" << computedState[1] << ", d=" << computedState[3] << endl; normal_cars.push_back(normal_car); } /* * Ego car */ ego_car.s = ((prev_path_size > 0 ) ? (double)end_path_s : car_s); ego_car.s_dot = (first_cycle ? EGO_CAR_START_VELOCITY : car_speed); ego_car.d = ((prev_path_size > 0 ) ? (double)end_path_d : car_d); ego_car.x = ((prev_path_size > 0 ) ? (double)previous_path_x[prev_path_size-1] : car_x); ego_car.y = ((prev_path_size > 0 ) ? (double)previous_path_y[prev_path_size-1] : car_y); ego_car.lane = (first_cycle ? EGO_CAR_START_LANE : (int)ego_car.d/4); ego_car.state = Helpers::KEEP_LANE; ego_car.checkProximity(normal_cars); ego_car.computeFutureStates(); //ego_car.printFutureStates(); ego_car.computeFutureStatesTargetSD(normal_cars, prev_path_size); //ego_car.printFutureStatesTargetSD(); ego_car.generateFutureStatesTrajectory(); //ego_car.printFutureStatesTrajectoryLastSD(); //ego_car.printCar(); /* * Trajectory generation w/o JMT but using spline + method in walkthrough to avoid jerk */ // Sparse x,y waypoints evenly spaced at DISTANCE_AHEAD metres used as anchors for spline // Later on, more wapoints will be generated via spline's interpolation for a smoother path vector<double> ptsx; vector<double> ptsy; // Refeence x,y,yaw to be used later // These are either set to either current state or previous (if we have prev state) double ref_x = car_x; double ref_y = car_y; double ref_yaw = deg2rad(car_yaw); if(prev_path_size == 0) { // if the simulator utilised all points in the previous run or the first run double prev_car_x = car_x - cos(car_yaw); // calculate previous x double prev_car_y = car_y - sin(car_yaw); // calculate previous y ptsx.push_back(prev_car_x); ptsy.push_back(prev_car_y); ptsx.push_back(car_x); ptsy.push_back(car_y); //cout << "prev_path_size == 0" << endl; } else if(prev_path_size == 1) { // only 1 point left from previous run ptsx.push_back(previous_path_x[0]); // get previous x ptsy.push_back(previous_path_y[0]); // get previous y ptsx.push_back(car_x); ptsy.push_back(car_y); //cout << "prev_path_size == 1" << endl; } else {// atleast 2 previous points available so use prev path's last point as the starting point // Update ref with the last point ref_x = previous_path_x[prev_path_size-1]; ref_y = previous_path_y[prev_path_size-1]; double ref_prev_x = previous_path_x[prev_path_size-2]; double ref_prev_y = previous_path_y[prev_path_size-2]; ref_yaw = atan2(ref_y-ref_prev_y, ref_x-ref_prev_x); // find the angle tangent to last point ptsx.push_back(ref_prev_x); ptsy.push_back(ref_prev_y); ptsx.push_back(ref_x); ptsy.push_back(ref_y); //cout << "prev_path_size > 1" << endl; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Helpers::State target_state = Helpers::KEEP_LANE; vector<double> s_trajectory; vector<double> d_trajectory; for (auto future_state_trajectory : ego_car.future_states_trajectory) { Helpers::State state = future_state_trajectory.first; if (state == target_state){ vector<vector<double>> trajectory = future_state_trajectory.second; s_trajectory = trajectory[0]; d_trajectory = trajectory[1]; } } double velocity = ego_car.future_states_target_sd[target_state][1] ; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Add 3 points that are PREDICTION_HORIZON_TIMESTEPS metres apart in s,d coord & then get the corresponding x,y pair vector<double> next_wp0 = getXY(s_trajectory[s_trajectory.size()-1], d_trajectory[d_trajectory.size()-1], map_waypoints_s, map_waypoints_x, map_waypoints_y); vector<double> next_wp1 = getXY(s_trajectory[s_trajectory.size()-1]+30, d_trajectory[d_trajectory.size()-1], map_waypoints_s, map_waypoints_x, map_waypoints_y); vector<double> next_wp2 = getXY(s_trajectory[s_trajectory.size()-1]+60, d_trajectory[d_trajectory.size()-1], map_waypoints_s, map_waypoints_x, map_waypoints_y); ptsx.push_back(next_wp0[0]); ptsy.push_back(next_wp0[1]); ptsx.push_back(next_wp1[0]); ptsy.push_back(next_wp1[1]); ptsx.push_back(next_wp2[0]); ptsy.push_back(next_wp2[1]); // Shift car ref angle to 0 degrees for easy caculations for(int i = 0; i < ptsx.size(); i++) { //cout << "Anchor points (unshifted) " << i << ": x=" << ptsx[i] << ", y=" << ptsy[i] << endl; double shift_x = ptsx[i] - ref_x; double shift_y = ptsy[i] - ref_y; ptsx[i] = shift_x*cos(0-ref_yaw) - shift_y*sin(0-ref_yaw); ptsy[i] = shift_x*sin(0-ref_yaw) + shift_y*cos(0-ref_yaw); //cout << "Anchor points (shifted) " << i << ": x=" << ptsx[i] << ", y=" << ptsy[i] << endl; } //if (prev_path_size > 0) cout << "Previous path first coords: x=" << previous_path_x[0] << ", y=" << previous_path_y[0] << endl; //if (prev_path_size > 0) cout << "Previous path last coords: x=" << previous_path_x[prev_path_size-1] << ", y=" << previous_path_y[prev_path_size-1] << endl; tk::spline s; s.set_points(ptsx, ptsy); // specify anchor points (5 in total) // Start with adding points not utilised last time i.e. the left over points (the simulator doesn't always utilise all the points) for(int i = 0; i < previous_path_x.size(); i++) { next_x_vals.push_back(previous_path_x[i]); next_y_vals.push_back(previous_path_y[i]); } // Calculate how to break up spline points so that we achieve desired velocity + jerk free trajectory double target_x = EGO_CAR_SAFE_DISTANCE; double target_y = s(target_x); // use spline to get the corresponding y double target_dist = sqrt(pow(0-target_x,2) + pow(0-target_y,2)); double x_add_on = 0; // origin where the car is now but will keep on changing as we add more points // target_distance = N*0.02*veloctiy OR N = target_distance/(0.02*veloctiy) // N is the no. of segments required from origin to target_distance when travelling at velocity // 0.02 is used because the simulator picks a point every 0.02 sec // 2.24 is the conversion factor for miles/hour to meter/sec double N = target_dist/(0.02*velocity/2.24); // N is the total no. of road sections from current location to PREDICTION_HORIZON_TIMESTEPS metres ahead double x_increment = target_x/N; // length of each road section in x-axis // Add new x,y points to complete 50 points for (int i = 1; i <= 50-previous_path_x.size(); i++) { double x_point = x_add_on + x_increment; // start location + length of each road section in x-axis double y_point = s(x_point); // find corresponding y x_add_on = x_point; // current point becomes the start for next point generation in the loop double x_ref = x_point; double y_ref = y_point; // rotate back to global coord from local coord x_point = x_ref*cos(ref_yaw) - y_ref*sin(ref_yaw); y_point = x_ref*sin(ref_yaw) + y_ref*cos(ref_yaw); x_point += ref_x; // keep the car ahead of the last point y_point += ref_y; next_x_vals.push_back(x_point); next_y_vals.push_back(y_point); //cout << "Newly added point " << i << " coords: x=" << x_point << ", y=" << y_point << endl; } ego_car.printCar(); first_cycle = false; cout << "************END************" << endl; // £££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££££ // TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds msgJson["next_x"] = next_x_vals; msgJson["next_y"] = next_y_vals; auto msg = "42[\"control\","+ msgJson.dump()+"]"; //this_thread::sleep_for(chrono::milliseconds(1000)); ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { // Manual driving std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); // We don't need this since we're not using HTTP but if it's removed the program doesn't compile :-( h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) { const std::string s = "<h1>Hello world!</h1>"; if (req.getUrl().valueLength == 1) { res->end(s.data(), s.length()); } else { // i guess this should be done more gracefully? res->end(nullptr, 0); } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
39.802083
205
0.582936
[ "object", "vector", "transform" ]
f540506f4608d28e69634038cf98bc387b3d4952
84,331
cpp
C++
lib/Arch/SPARC64/Extract.cpp
fengjixuchui/remill
51cfa0a996ddd1f077615c071d4158c476e5374a
[ "Apache-2.0" ]
null
null
null
lib/Arch/SPARC64/Extract.cpp
fengjixuchui/remill
51cfa0a996ddd1f077615c071d4158c476e5374a
[ "Apache-2.0" ]
null
null
null
lib/Arch/SPARC64/Extract.cpp
fengjixuchui/remill
51cfa0a996ddd1f077615c071d4158c476e5374a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <glog/logging.h> #include <bitset> #include "Decode.h" #include "../SPARC32/Decode.h" namespace remill { using namespace remill::sparc; namespace sparc64 { namespace { static const std::string_view kFpuRegName_fN[] = { "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39", "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49", "f50", "f51", "f52", "f53", "f54", "f55", "f56", "f57", "f58", "f59", "f60", "f61", "f62", "f63" }; static constexpr unsigned kAddressSize32 = 32; static constexpr unsigned kAddressSize = 64; static void AddBranchTaken(Instruction &inst) { if (!inst.in_delay_slot) { AddDestRegop(inst, "BRANCH_TAKEN", 8); } else { AddDestRegop(inst, "IGNORE_BRANCH_TAKEN", 8); } } static void AddPCDest(Instruction &inst) { if (!inst.in_delay_slot) { AddDestRegop(inst, "PC", kAddressSize); } else { AddDestRegop(inst, "IGNORE_PC", kAddressSize); } } static void AddNPCDest(Instruction &inst) { if (!inst.in_delay_slot) { AddDestRegop(inst, "NEXT_PC", kAddressSize); } else { AddDestRegop(inst, "IGNORE_NEXT_PC", kAddressSize); } } static void AddReturnPCDest(Instruction &inst) { if (!inst.in_delay_slot) { AddDestRegop(inst, "RETURN_PC", kAddressSize); } else { AddDestRegop(inst, "IGNORE_RETURN_PC", kAddressSize); } } static void AddIntRegop(Instruction &inst, unsigned index, unsigned size, Operand::Action action) { inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeRegister; op.size = size; op.action = action; op.reg.size = size; if (Operand::kActionRead == action) { if (!index) { op.type = Operand::kTypeImmediate; op.imm.is_signed = false; op.imm.val = 0; } else { op.reg.name = kReadIntRegName[index]; } } else { op.reg.name = kWriteIntRegName[index]; } } static bool AddFpuRegOp(Instruction &inst, unsigned index, unsigned size, Operand::Action action) { inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeRegister; op.size = size; op.action = action; op.reg.size = size; if (op.reg.size == 32) { op.reg.name = kFpuRegName_fN[index]; } else if (size == 64) { auto new_index = ((index >> 1u) | ((index & 1) << 4u)) << 1u; op.reg.name = kFpuRegName_fN[new_index]; op.reg.name[0] = 'd'; } else if (size == 128) { if (index & 2) { return false; } auto new_index = ((index >> 2u) | ((index & 1) << 3u)) << 2u; op.reg.name = kFpuRegName_fN[new_index]; op.reg.name[0] = 'q'; } return true; } static void AddPCRelop(Instruction &inst, int64_t disp) { inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeAddress; op.size = kAddressSize; op.action = Operand::kActionRead; op.addr.kind = Operand::Address::kControlFlowTarget; op.addr.address_size = kAddressSize; op.addr.base_reg.name = "PC"; op.addr.base_reg.size = kAddressSize; op.addr.displacement = disp; } static void AddNextPCRelop(Instruction &inst, int64_t disp) { inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeAddress; op.size = kAddressSize; op.action = Operand::kActionRead; op.addr.kind = Operand::Address::kControlFlowTarget; op.addr.address_size = kAddressSize; op.addr.base_reg.name = "NEXT_PC"; op.addr.base_reg.size = kAddressSize; op.addr.displacement = disp; } static void AddBasePlusOffsetMemop(Instruction &inst, Operand::Action action, uint32_t access_size, uint32_t base_reg, uint32_t index_reg, int64_t disp) { inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeAddress; op.size = access_size; op.action = action; op.addr.kind = action == Operand::kActionRead ? Operand::Address::kMemoryRead : Operand::Address::kMemoryWrite; op.addr.address_size = kAddressSize; if (base_reg && index_reg) { op.addr.base_reg.name = kReadIntRegName[base_reg]; op.addr.base_reg.size = kAddressSize; op.addr.index_reg.name = kReadIntRegName[index_reg]; op.addr.index_reg.size = kAddressSize; op.addr.scale = 1; } else if (base_reg) { op.addr.base_reg.name = kReadIntRegName[base_reg]; op.addr.base_reg.size = kAddressSize; } else if (index_reg) { op.addr.base_reg.name = kReadIntRegName[index_reg]; op.addr.base_reg.size = kAddressSize; } op.addr.displacement = disp; } static bool TryDecodeRDasr(Instruction &inst, uint32_t bits) { Format3 enc = {bits}; inst.category = Instruction::kCategoryNormal; switch (enc.rs1) { case 0: // rd %y, rd inst.function = "RDY"; break; case 2: // rd %ccr, rd inst.function = "RDCCR"; break; case 3: // rd %asi, rd inst.function = "RDASI"; break; case 4: // rd %tick, rd inst.function = "RDTICK"; break; case 5: // rd %pc, rd inst.function = "RDPC"; break; case 6: // rd %fprs, rd inst.function = "RDFPRS"; break; case 19: // rd %gsr, rd inst.function = "RDGSR"; break; case 22: // rd %softint, rd inst.function = "RDSOFTINT"; break; case 24: // rd %stick, rd inst.function = "RDSTICK"; break; case 25: // rd %stick_cmpr, rd inst.function = "RDSICK_CMPR"; break; case 26: // rd %cfr, rd inst.function = "RDCFR"; break; default:return false; } AddIntRegop(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeRDPr(Instruction &inst, uint32_t bits) { Format3 enc = {bits}; inst.category = Instruction::kCategoryNormal; switch (enc.rs1) { case 0: // rdpr %tpc, rd inst.function = "RDPR_TPC"; break; case 1: // rdpr %tnpc, rd inst.function = "RDPR_TNPC"; break; case 2: // rdpr %tstate, rd inst.function = "RDPR_TSTATE"; break; case 3: // rdpr %tt, rd inst.function = "RDPR_TT"; break; case 4: // rdpr %tick, rd inst.function = "RDPR_TICK"; break; case 5: // rdpr %tba, rd inst.function = "RDPR_TBA"; break; case 6: // rdpr %pstate, rd inst.function = "RDPR_PSTATE"; break; case 7: // rdpr %tl, rd inst.function = "RDPR_TL"; break; case 8: // rdpr %pil, rd inst.function = "RDPR_PIL"; break; case 9: // rdpr %cwp, rd inst.function = "RDPR_CWP"; break; case 10: // rdpr %cansave, rd inst.function = "RDPR_CANSAVE"; break; case 11: // rdpr %canrestore, rd inst.function = "RDPR_CANRESTORE"; break; case 12: // rdpr %cleanwin, rd inst.function = "RDPR_CLEANWIN"; break; case 13: // rdpr %otherwin, rd inst.function = "RDPR_OTHERWIN"; break; case 14: // rdpr %wstate, rd inst.function = "RDPR_WSTATE"; break; case 16: // rdpr %gl, rd inst.function = "RDPR_GL"; break; default:return false; } AddIntRegop(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeWRasr(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.category = Instruction::kCategoryNormal; switch (enc_i0.rd) { case 0: // wr rs1, reg_or_imm, %y inst.function = "WRY"; break; case 2: // wr rs1, reg_or_imm, %ccr inst.function = "WRCCR"; break; case 3: // wr rs1, reg_or_imm, %asi inst.function = "WRASI"; break; case 6: // wr rs1, reg_or_imm, %fpsr inst.function = "WRFPRS"; break; case 19: // wr rs1, reg_or_imm, %gsr inst.function = "WRGSR"; break; case 20: // wr rs1, reg_or_imm, %softint_set inst.function = "WRSOFTINT_SET"; break; case 21: // wr rs1, reg_or_imm, %softint_clr inst.function = "WRSOFTINT_CLR"; break; case 22: // wr rs1, reg_or_imm, %softint inst.function = "WRSOFTINT"; break; case 25: // wr rs1, reg_or_imm, %stick_cmpr inst.function = "WRSTICK_CMPR"; break; case 27: // wr rs1, reg_or_imm, %pause inst.function = "WRPAUSE"; break; default:return false; } AddIntRegop(inst, enc_i0.rs1, kAddressSize, Operand::kActionRead); if (enc_i1.i) { AddImmop(inst, enc_i1.simm13, kAddressSize, true); } else { AddIntRegop(inst, enc_i0.rs2, kAddressSize, Operand::kActionRead); } return true; } static bool TryDecodeCALL(Instruction &inst, uint32_t bits) { union { uint32_t flat; struct { int32_t disp30:30; uint32_t op:2; } __attribute__((packed)); } __attribute__((packed)) enc; enc.flat = bits; inst.function = "CALL"; int64_t disp = enc.disp30 << 2; if (inst.in_delay_slot) { inst.category = Instruction::kCategoryNormal; inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; } else { inst.category = Instruction::kCategoryDirectFunctionCall; inst.delayed_pc = inst.next_pc; inst.has_branch_taken_delay_slot = true; inst.has_branch_not_taken_delay_slot = false; inst.branch_taken_pc = static_cast<uint32_t>( static_cast<int64_t>(inst.pc) + disp); inst.next_pc += 4; // NOTE(pag): This is `pc + 8`, which follows the convention that `ret` // instructions (actually `jmpl`s) will return to the address // of the `call` plus `8`. inst.branch_not_taken_pc = inst.next_pc; // pc+8. } AddSrcRegop(inst, "PC", kAddressSize); // Old PC. AddSrcRegop(inst, "NEXT_PC", kAddressSize); // New PC. AddPCRelop(inst, disp); // New NPC. AddIntRegop(inst, 15 /* %o7 */, kAddressSize, Operand::kActionWrite); AddPCDest(inst); AddNPCDest(inst); AddReturnPCDest(inst); // Return address stored into `RETURN_PC`. if (inst.in_delay_slot) { inst.function = "UNSUPPORTED_DCTI"; inst.operands.clear(); inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; inst.category = Instruction::kCategoryNormal; inst.next_pc = inst.pc + 4; } return true; } static bool TryDecodeJMPL(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; AddSrcRegop(inst, "PC", kAddressSize); // Old PC. AddSrcRegop(inst, "NEXT_PC", kAddressSize); // New PC. inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeAddress; op.size = kAddressSize; op.action = Operand::kActionRead; op.addr.kind = Operand::Address::kControlFlowTarget; op.addr.address_size = kAddressSize; op.addr.base_reg.name = kReadIntRegName[enc_i1.rs1]; op.addr.base_reg.size = kAddressSize; if (enc_i1.i) { op.addr.displacement = enc_i1.simm13; } else if (enc_i0.rs2) { op.addr.index_reg.name = kReadIntRegName[enc_i0.rs2]; op.addr.index_reg.size = kAddressSize; op.addr.scale = 1; } if (!enc_i0.rd) { // NOTE(pag): This is stricter than what is in the manual, but is more in // line with how we deal with function calls, and how actual // software operates. // // NOTE(pag): The `8` byte displacement is common for functions returning // values that can fit into registers. When RVO comes into play, // an `unimp <struct size>` might be placed after the call's // delay slot, which the callee must skip past in its return. if ((enc_i1.simm13 == 8 || enc_i1.simm13 == 12) && (enc_i1.rs1 == 15 /* %o7 */ || enc_i1.rs1 == 31 /* %i7 */)) { inst.function = "RETL"; inst.category = Instruction::kCategoryFunctionReturn; } else { inst.function = "JMPL"; inst.category = Instruction::kCategoryIndirectJump; } } else if (enc_i0.rd == 15) { inst.function = "CALL_INDIRECT"; inst.category = Instruction::kCategoryIndirectFunctionCall; // NOTE(pag): This is technically a lie; it is typical for functions to do // `ret` which is a `jmpl %i7+8`. inst.branch_not_taken_pc = inst.pc + 8; } else { inst.function = "JMPL"; inst.category = Instruction::kCategoryIndirectJump; } inst.has_branch_taken_delay_slot = true; inst.has_branch_not_taken_delay_slot = false; inst.delayed_pc = inst.next_pc; inst.next_pc += 4; AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); AddPCDest(inst); AddNPCDest(inst); if (inst.IsFunctionCall()) { AddReturnPCDest(inst); } if (inst.in_delay_slot) { inst.function = "UNSUPPORTED_DCTI"; inst.operands.clear(); inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; inst.category = Instruction::kCategoryNormal; inst.next_pc = inst.pc + 4; } return true; } static bool TryDecodeTcc(Instruction &inst, uint32_t bits) { union { uint32_t flat; struct { uint32_t rs2:5; uint32_t _0:6; uint32_t cc0:1; uint32_t cc1:1; uint32_t i:1; uint32_t rs1:5; uint32_t op3:6; uint32_t cond:4; uint32_t _1:1; uint32_t op:2; } __attribute__((packed)); } __attribute__((packed)) enc_i0 = {bits}; static_assert(sizeof(enc_i0) == 4); union { uint32_t flat; struct { uint32_t imm7:7; uint32_t _0:4; uint32_t cc0:1; uint32_t cc1:1; uint32_t i:1; uint32_t rs1:5; uint32_t op3:6; uint32_t cond:4; uint32_t _1:1; uint32_t op:2; } __attribute__((packed)); } __attribute__((packed)) enc_i1 = {bits}; static_assert(sizeof(enc_i1) == 4); inst.delayed_pc = 0; inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; inst.function.reserve(5); inst.function.push_back('T'); inst.function += kCondName[enc_i0.cond]; // Add in a suffix of either `icc` or `xcc`. const auto cc = kCCRName[(enc_i0.cc1 << 1u) | enc_i0.cc0]; if (cc.empty()) { return false; } inst.function.push_back('_'); inst.function += cc; // Trap always; handled by a *syncrhonous* hyper call. This way traps can // be raised inside of delay slots. if (enc_i1.cond == 0b1000) { if (inst.in_delay_slot) { inst.function += "_sync"; inst.category = Instruction::kCategoryNormal; } else { inst.category = Instruction::kCategoryAsyncHyperCall; inst.branch_taken_pc = inst.next_pc; } // Trap never. } else if (enc_i1.cond == 0b0000) { if (inst.in_delay_slot) { inst.category = Instruction::kCategoryNoOp; } else { inst.category = Instruction::kCategoryDirectJump; inst.branch_taken_pc = inst.next_pc; } // Conditional trap. } else { // Conditional traps inside of a delay slot will turn into synchronous // hyper calls. if (inst.in_delay_slot) { inst.function += "_sync"; inst.category = Instruction::kCategoryNormal; // Otherwise they induce their own control-flow. } else { inst.category = Instruction::kCategoryConditionalAsyncHyperCall; inst.branch_not_taken_pc = inst.next_pc; } } // TODO(pag): Handle write to TBR on `trap_instruction`. AddBranchTaken(inst); AddSrcRegop(inst, "NEXT_PC", kAddressSize); // New PC on taken. AddNextPCRelop(inst, 4); // New NPC on taken. // Trap vector number. AddIntRegop(inst, enc_i0.rs1, kAddressSize32, Operand::kActionRead); if (enc_i1.i) { AddImmop(inst, enc_i1.imm7, kAddressSize32, false); } else { AddIntRegop(inst, enc_i0.rs2, kAddressSize32, Operand::kActionRead); } AddPCDest(inst); AddNPCDest(inst); return true; } // Generic decoder for conditional branches (Bcc, BPcc). static bool TryDecode_Branch( Instruction &inst, unsigned cond, bool anul, int64_t disp, std::string_view iform, std::string_view ccr, bool is_fcc = false) { // Branch always. if (cond == 0b1000) { inst.category = Instruction::kCategoryDirectJump; inst.branch_taken_pc = inst.pc + disp; inst.has_branch_not_taken_delay_slot = false; if (!anul) { AddSrcRegop(inst, "NEXT_PC", kAddressSize); // New PC. AddPCRelop(inst, disp); // New NPC. inst.has_branch_taken_delay_slot = true; inst.delayed_pc = inst.next_pc; inst.next_pc += 4; } else { AddPCRelop(inst, disp); // New PC. AddPCRelop(inst, disp + 4); // New NPC. inst.has_branch_taken_delay_slot = false; } // Branch never. } else if (cond == 0b0000) { inst.category = Instruction::kCategoryDirectJump; if (!anul) { AddSrcRegop(inst, "NEXT_PC", kAddressSize); // New PC. AddNextPCRelop(inst, 4); // New NPC. inst.has_branch_taken_delay_slot = true; inst.has_branch_not_taken_delay_slot = false; inst.delayed_pc = inst.next_pc; } else { AddNextPCRelop(inst, 4); // New PC. AddNextPCRelop(inst, 8); // New NPC. inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; } inst.next_pc += 4; inst.branch_taken_pc = inst.next_pc; // Conditional branch. } else { AddBranchTaken(inst); AddSrcRegop(inst, "NEXT_PC", kAddressSize); // PC if taken. AddPCRelop(inst, disp); // NPC if taken. inst.category = Instruction::kCategoryConditionalBranch; inst.branch_taken_pc = inst.pc + disp; inst.has_branch_taken_delay_slot = true; inst.delayed_pc = inst.next_pc; inst.next_pc += 4; inst.branch_not_taken_pc = inst.next_pc; // Skip delayed instruction. // Not anulled means that the delayed instruction is executed on the taken // and not-taken paths. if (!anul) { AddSrcRegop(inst, "NEXT_PC", kAddressSize); // PC if not taken. AddNextPCRelop(inst, 4); // NPC if not taken. inst.has_branch_not_taken_delay_slot = true; // Anulled means that the delayed instruction is executed on the taken // path, but not on the not-taken path. } else { AddNextPCRelop(inst, 4); // PC if not taken. AddNextPCRelop(inst, 8); // NPC if not taken. inst.has_branch_not_taken_delay_slot = false; } } AddPCDest(inst); AddNPCDest(inst); // NOTE(pag): This is part of a SPARC idiom of `jmpl,rett`, but we don't // have elaborate pipeline support to handle things. See // semantics of `UNSUPPORTED_DCTI`. if (inst.in_delay_slot) { inst.function = "UNSUPPORTED_DCTI"; inst.operands.clear(); inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; inst.category = Instruction::kCategoryNormal; inst.next_pc = inst.pc + 4; } else { inst.function.reserve(9); inst.function += iform; auto cond_name = !is_fcc ? kCondName[cond] : kFCondName[cond]; inst.function += cond_name; inst.function.push_back('_'); inst.function += ccr; // `icc` or `xcc`. } return true; } static bool TryDecodeBcc(Instruction &inst, uint32_t bits) { Format0b enc = {bits}; int64_t disp = enc.disp22 << 2; return TryDecode_Branch(inst, enc.cond, enc.a, disp, "B", "icc"); } // SPARC v8+ instruction, found in v9 manual. static bool TryDecodeBPcc(Instruction &inst, uint32_t bits) { Format0c enc = {bits}; int64_t disp = enc.disp19 << 2; const auto cc = kCCRName[(enc.cc1 << 1u) | enc.cc0]; if (cc.empty()) { return false; // Reserved. } return TryDecode_Branch(inst, enc.cond, enc.a, disp, "B", cc); } // SPARC v8plus instruction, found in v9 manual. static bool TryDecodeFBcc(Instruction &inst, uint32_t bits) { Format0b enc = {bits}; int64_t disp = enc.disp22 << 2; return TryDecode_Branch(inst, enc.cond, enc.a, disp, "FB", "fcc0", true); } static bool TryDecodeFBPcc(Instruction &inst, uint32_t bits) { Format0c enc = {bits}; int64_t disp = enc.disp19 << 2; const auto cc = kFCCRName[(enc.cc1 << 1u) | enc.cc0]; if (cc.empty()) { return false; // Reserved. } return TryDecode_Branch(inst, enc.cond, enc.a, disp, "FB", cc, true); } static bool TryDecodeBPr(Instruction &inst, uint32_t bits) { Format0d enc = {bits}; if (enc.must_be_zero) { return false; } int64_t disp = static_cast<int16_t>((enc.d16hi << 14) | enc.d16lo); disp <<= 2; if (!enc.rcond || (enc.rcond == 0b100)) { return false; // Reserved. } AddBranchTaken(inst); // Condition register AddIntRegop(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddSrcRegop(inst, "NEXT_PC", kAddressSize); // PC if taken. AddPCRelop(inst, disp); // NPC if taken. inst.category = Instruction::kCategoryConditionalBranch; inst.branch_taken_pc = inst.pc + disp; inst.has_branch_taken_delay_slot = true; inst.delayed_pc = inst.next_pc; inst.next_pc += 4; inst.branch_not_taken_pc = inst.next_pc; // Skip delayed instruction. // Not anulled means that the delayed instruction is executed on the taken // and not-taken paths. if (!enc.a) { AddSrcRegop(inst, "NEXT_PC", kAddressSize); // PC if not taken. AddNextPCRelop(inst, 4); // NPC if not taken. inst.has_branch_not_taken_delay_slot = true; // Anulled means that the delayed instruction is executed on the taken // path, but not on the not-taken path. } else { AddNextPCRelop(inst, 4); // PC if not taken. AddNextPCRelop(inst, 8); // NPC if not taken. inst.has_branch_not_taken_delay_slot = false; } AddPCDest(inst); AddNPCDest(inst); // NOTE(pag): This is part of a SPARC idiom of `jmpl,rett`, but we don't // have elaborate pipeline support to handle things. See // semantics of `UNSUPPORTED_DCTI`. if (inst.in_delay_slot) { inst.function = "UNSUPPORTED_DCTI"; inst.operands.clear(); inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; inst.category = Instruction::kCategoryNormal; inst.next_pc = inst.pc + 4; } else { inst.function.reserve(9); inst.function.insert(0, "BR"); inst.function += kRCondName[enc.rcond]; } return true; } static bool TryDecodeUNIMP(Instruction &inst, uint32_t bits) { Format0a enc = {bits}; if (inst.in_delay_slot) { inst.function = "ILLTRAP_SYNC"; inst.category = Instruction::kCategoryNormal; } else { inst.function = "ILLTRAP_ASYNC"; inst.category = Instruction::kCategoryError; inst.next_pc = 1; // Never valid, as it's odd. } AddImmop(inst, enc.imm22, kAddressSize, false); return true; } static bool TryDecodeSETHI(Instruction &inst, uint32_t bits) { Format0a enc = {bits}; if (enc.rd || enc.imm22) { inst.category = Instruction::kCategoryNormal; inst.function = "SETHI"; AddImmop(inst, enc.imm22 << 10ull, kAddressSize, false); AddIntRegop(inst, enc.rd, kAddressSize, Operand::kActionWrite); } else { inst.category = Instruction::kCategoryNoOp; inst.function = "NOP"; } return true; } static bool TryDecodeSET_IDIOM( Instruction &inst, uint32_t bits1, uint32_t bits2, const char *base, const char *multi) { Format0a enc1 = {bits1}; Format3ai0 enc2_i0 = {bits2}; Format3ai1 enc2_i1 = {bits2}; const int32_t imm_high = enc1.imm22 << 10; if (enc2_i1.i) { const int32_t imm_low = enc2_i1.simm13; if (enc1.rd == enc2_i1.rd) { // This is the usual `SET` idiom: // sethi imm_high, rd // or rd, imm_low, rd if (enc2_i1.rs1 == enc1.rd) { //const auto imm = static_cast<uint32_t>(imm_low | imm_high); inst.function = "SET"; AddImmop(inst, static_cast<uint32_t>(imm_high), kAddressSize, false); AddImmop(inst, static_cast<uint32_t>(imm_low), kAddressSize, false); AddIntRegop(inst, enc1.rd, kAddressSize, Operand::kActionWrite); // This is a possible variant, where the `sethi` is ultimately useless. // sethi imm, rd // or rs1, imm, rd } else { inst.function = base; AddIntRegop(inst, enc2_i1.rs1, kAddressSize, Operand::kActionRead); AddImmop(inst, imm_low, kAddressSize, false); AddIntRegop(inst, enc2_i1.rd, kAddressSize, Operand::kActionWrite); } // This is a variant of the `SET` idiom: // sethi imm_high, rd1 // or rd1, imm_low, rd2 // // This idiom can come up when multple XREFs share the same high bits and // can thus be built off of `rd1`. } else if (enc1.rd == enc2_i1.rs1) { inst.function = multi; AddImmop(inst, imm_high, kAddressSize, false); AddImmop(inst, imm_low, kAddressSize, false); AddIntRegop(inst, enc1.rd, kAddressSize, Operand::kActionWrite); AddIntRegop(inst, enc2_i1.rd, kAddressSize, Operand::kActionWrite); // This is not a SET idiom. } else { return false; } } else { if (enc1.rd == enc2_i0.rd) { // This is a variable `SET` idiom: // sethi imm_high, rd // or rd, rs2, rd if (enc2_i0.rs1 == enc1.rd) { inst.function = base; AddImmop(inst, imm_high, kAddressSize, false); AddIntRegop(inst, enc2_i0.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc1.rd, kAddressSize, Operand::kActionWrite); // Another variant of a vairable `SET` idiom: // sethi imm_high, rd // or rs1, rd, rd } else if (enc2_i0.rs2 == enc1.rd) { inst.function = base; AddIntRegop(inst, enc2_i0.rs1, kAddressSize, Operand::kActionRead); AddImmop(inst, imm_high, kAddressSize, false); AddIntRegop(inst, enc1.rd, kAddressSize, Operand::kActionWrite); // This is a possible variant, where the `sethi` is ultimately useless. // sethi imm, rd // or rs1, rs2, rd } else { inst.function = base; AddIntRegop(inst, enc2_i0.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc2_i0.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc1.rd, kAddressSize, Operand::kActionWrite); } // This is a variant of the `SET` idiom: // sethi imm_high, rd1 // or rd1, rs2, rd2 // // This idiom can come up when multple XREFs share the same high bits and // can thus be built off of `rd1`. } else if (enc1.rd == enc2_i0.rs1) { inst.function = multi; AddImmop(inst, imm_high, kAddressSize, false); AddIntRegop(inst, enc2_i0.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc1.rd, kAddressSize, Operand::kActionWrite); AddIntRegop(inst, enc2_i0.rd, kAddressSize, Operand::kActionWrite); // This is a variant of the `SET` idiom: // sethi imm_high, rd1 // or rs1, rd1, rd2 // // This idiom can come up when multple XREFs share the same high bits and // can thus be built off of `rd1`. } else if (enc1.rd == enc2_i0.rs2) { inst.function = multi; AddImmop(inst, imm_high, kAddressSize, false); AddIntRegop(inst, enc2_i0.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc1.rd, kAddressSize, Operand::kActionWrite); AddIntRegop(inst, enc2_i0.rd, kAddressSize, Operand::kActionWrite); // This is not a SET idiom. } else { return false; } } inst.category = Instruction::kCategoryNormal; return true; } static bool TryDecodeSET_SETHI_OR( Instruction &inst, uint32_t bits1, uint32_t bits2) { return TryDecodeSET_IDIOM(inst, bits1, bits2, "OR", "SETHI_OR"); } static bool TryDecodeSET_SETHI_ADD( Instruction &inst, uint32_t bits1, uint32_t bits2) { return TryDecodeSET_IDIOM(inst, bits1, bits2, "ADD", "SETHI_ADD"); } static bool TryDecodeRETURN(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.category = Instruction::kCategoryFunctionReturn; AddSrcRegop(inst, "NEXT_PC", kAddressSize); // New PC. inst.operands.emplace_back(); auto &dst_op = inst.operands.back(); dst_op.type = Operand::kTypeAddress; dst_op.action = Operand::kActionRead; dst_op.size = kAddressSize; dst_op.addr.kind = Operand::Address::kControlFlowTarget; dst_op.addr.address_size = kAddressSize; if (enc_i1.i) { if (enc_i1.rs1) { if (enc_i1.simm13) { // `r[rs1] + simm13`. dst_op.addr.base_reg.name = kReadIntRegName[enc_i1.rs1]; dst_op.addr.base_reg.size = kAddressSize; dst_op.addr.displacement = enc_i1.simm13; } else { dst_op.type = Operand::kTypeRegister; dst_op.reg.name = kReadIntRegName[enc_i1.rs1]; dst_op.reg.size = kAddressSize; } } else if (enc_i1.simm13) { // `%g0 + simm13`. dst_op.type = Operand::kTypeImmediate; dst_op.imm.val = static_cast<int64_t>(enc_i1.simm13); } else { return false; // RETT to `0`. } } else { if (enc_i0.rs1 && enc_i0.rs2) { // `r[rs1] + r[rs2]`. dst_op.addr.base_reg.name = kReadIntRegName[enc_i0.rs1]; dst_op.addr.base_reg.size = kAddressSize; dst_op.addr.index_reg.name = kReadIntRegName[enc_i0.rs2]; dst_op.addr.index_reg.size = kAddressSize; dst_op.addr.scale = 1; } else if (enc_i0.rs1) { dst_op.type = Operand::kTypeRegister; dst_op.reg.name = kReadIntRegName[enc_i0.rs1]; dst_op.reg.size = kAddressSize; } else if (enc_i0.rs2) { dst_op.type = Operand::kTypeRegister; dst_op.reg.name = kReadIntRegName[enc_i0.rs2]; dst_op.reg.size = kAddressSize; } else { return false; // RETT to `0`. } } AddPCDest(inst); AddNPCDest(inst); // Smuggle a stack-allocated register window into the semantics. AddDestRegop(inst, "PREV_WINDOW", kAddressSize); inst.function = "RETURN"; inst.has_branch_taken_delay_slot = true; inst.has_branch_not_taken_delay_slot = false; inst.delayed_pc = inst.next_pc; inst.next_pc += 4; // NOTE(pag): This is part of a SPARC idiom of `jmpl,rett`, but we don't // have elaborate pipeline support to handle things. See // semantics of `UNSUPPORTED_DCTI`. if (inst.in_delay_slot) { inst.function = "UNSUPPORTED_DCTI"; inst.operands.clear(); inst.has_branch_taken_delay_slot = false; inst.has_branch_not_taken_delay_slot = false; inst.category = Instruction::kCategoryNormal; inst.next_pc = inst.pc + 4; } return true; } static bool TryDecode_rs1_simm32_op_rs2_rd( Instruction &inst, uint32_t bits, const char *iform) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.function = iform; inst.category = Instruction::kCategoryNormal; AddIntRegop(inst, enc_i0.rs1, kAddressSize, Operand::kActionRead); if (enc_i1.i) { AddImmop(inst, enc_i1.simm13, kAddressSize, true); } else { AddIntRegop(inst, enc_i0.rs2, kAddressSize, Operand::kActionRead); } AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeMOVcc(Instruction &inst, uint32_t bits) { Format4c enc_i0 = {bits}; Format4d enc_i1 = {bits}; auto cc_index = (enc_i0.cc2 << 2u) | (enc_i0.cc1 << 1u) | enc_i0.cc0; const auto cc = kFCCRName[cc_index]; if (cc.empty()) { return false; // Reserved. } if (enc_i1.i) { AddImmop(inst, static_cast<int64_t>(enc_i1.simm11), kAddressSize, true); } else { AddIntRegop(inst, enc_i0.rs2, kAddressSize, Operand::kActionRead); } AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); inst.category = Instruction::kCategoryNormal; inst.function.reserve(12); inst.function.insert(0, "MOV"); if (cc_index < 0b100) { inst.function += kFCondName[enc_i0.cond]; } else { inst.function += kCondName[enc_i0.cond]; } inst.function.push_back('_'); inst.function += cc; return true; } static bool TryDecodeMOVr(Instruction &inst, uint32_t bits) { Format3di0 enc_i0 = {bits}; Format3di1 enc_i1 = {bits}; const auto cc = kRCondName[enc_i0.rcond]; if (cc.empty()) { return false; // Reserved. } if (enc_i1.i) { AddIntRegop(inst, enc_i1.rs1, kAddressSize, Operand::kActionRead); AddImmop(inst, static_cast<int64_t>(enc_i1.simm10), kAddressSize, true); } else { AddIntRegop(inst, enc_i0.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc_i0.rs2, kAddressSize, Operand::kActionRead); } AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); inst.category = Instruction::kCategoryNormal; inst.function.reserve(12); inst.function.insert(0, "MOVR"); inst.function += cc; return true; } static bool TryDecodeSave(Instruction &inst, uint32_t bits) { if (!TryDecode_rs1_simm32_op_rs2_rd(inst, bits, "SAVE")) { return false; } // Smuggle a stack-allocated register window into the semantics. AddDestRegop(inst, "WINDOW", kAddressSize); AddDestRegop(inst, "PREV_WINDOW", kAddressSize); return true; } static bool TryDecodeRestore(Instruction &inst, uint32_t bits) { if (!TryDecode_rs1_simm32_op_rs2_rd(inst, bits, "RESTORE")) { return false; } // Smuggle a stack-allocated register window into the semantics. AddDestRegop(inst, "PREV_WINDOW", kAddressSize); return true; } static bool TryDecodeALIGNADDRESS(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "ALIGNADDRESS"; inst.category = Instruction::kCategoryNormal; AddIntRegop(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeALIGNADDRESS_LITTLE(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "ALIGNADDRESS_LITTLE"; inst.category = Instruction::kCategoryNormal; AddIntRegop(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeFALIGNDATA(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "FALIGNDATAG"; inst.category = Instruction::kCategoryNormal; AddFpuRegOp(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddFpuRegOp(inst, enc.rs2, kAddressSize, Operand::kActionRead); AddFpuRegOp(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } struct fpu_opcode { std::string_view iform; uint32_t size; }; static const fpu_opcode Opf05[1 << 4U] = { [0b0000] = {{}, 0}, [0b0001] = {"FCMPS", 0x00002020}, [0b0010] = {"FCMPD", 0x00004040}, [0b0011] = {"FCMPQ", 0x00008080}, [0b0100] = {{}, 0}, [0b0101] = {"FCMPES", 0x00002020}, [0b0110] = {"FCMPED", 0x00004040}, [0b0111] = {"FCMPEQ", 0x00008080}, [0b1000] = {{}, 0}, [0b1001] = {{}, 0}, [0b1010] = {{}, 0}, [0b1011] = {{}, 0}, [0b1100] = {{}, 0}, [0b1101] = {{}, 0}, [0b1110] = {{}, 0}, [0b1111] = {{}, 0}, }; static bool TryDecodeFCMP(Instruction &inst, uint32_t bits) { Format3c enc = {bits}; union { uint32_t flat; struct { uint32_t rs1:8; uint32_t rs2:8; uint32_t rd:8; uint32_t _1:8; } __attribute__((packed)); } __attribute__((packed)) opd_size = {Opf05[enc.opf & 0b1111].size}; const auto cc = kFCCRName[(enc.cc1 << 1u) | enc.cc0]; if (cc.empty()) { return false; // Reserved. } if (opd_size.rs1) { AddFpuRegOp(inst, enc.rs1, opd_size.rs1, Operand::kActionRead); } if (opd_size.rs2) { AddFpuRegOp(inst, enc.rs2, opd_size.rs2, Operand::kActionRead); } inst.category = Instruction::kCategoryNormal; inst.function.reserve(11); inst.function += Opf05[enc.opf & 0b1111].iform; inst.function.push_back('_'); inst.function += cc; return true; } static bool TryDecodeFMOVcc(Instruction &inst, uint32_t bits) { union { uint32_t flat; struct { uint32_t rs2:5; uint32_t opf_low:6; uint32_t opf_cc:3; uint32_t cond:4; uint32_t _1:1; uint32_t op3:6; uint32_t rd:5; uint32_t op:2; } __attribute__((packed)); } __attribute__((packed)) enc = {bits}; static_assert(sizeof(enc) == 4); const auto cc = kFCCRName[enc.opf_cc]; if (cc.empty()) { return false; // Reserved. } inst.category = Instruction::kCategoryNormal; inst.function.reserve(12); auto access_size = kAddressSize; switch(enc.opf_low) { case 0b0001: access_size = 32; inst.function.insert(0, "FMOVS"); break; case 0b0010: access_size = 64; inst.function.insert(0, "FMOVD"); break; case 0b0011: access_size = 128; inst.function.insert(0, "FMOVQ"); break; default: return false; } AddFpuRegOp(inst, enc.rs2, access_size, Operand::kActionRead); AddFpuRegOp(inst, enc.rd, access_size, Operand::kActionWrite); if (enc.opf_cc < 0b100) { inst.function += kFCondName[enc.cond]; } else { inst.function += kCondName[enc.cond]; } inst.function.push_back('_'); inst.function += cc; return true; } static bool TryDecodeFMOVr(Instruction &inst, uint32_t bits) { union { uint32_t flat; struct { uint32_t rs2:5; uint32_t opf_low:5; uint32_t rcond:3; uint32_t _1:1; uint32_t rs1:5; uint32_t op3:6; uint32_t rd:5; uint32_t op:2; } __attribute__((packed)); } __attribute__((packed)) enc = {bits}; static_assert(sizeof(enc) == 4); if ((enc.rcond == 0b000) || (enc.rcond == 0b100)) { return false; // Reserved. } inst.category = Instruction::kCategoryNormal; inst.function.reserve(9); auto access_size = kAddressSize; switch(enc.opf_low) { case 0b0001: access_size = 32; inst.function.insert(0, "FMOVRS"); break; case 0b0010: access_size = 64; inst.function.insert(0, "FMOVRD"); break; case 0b0011: access_size = 128; inst.function.insert(0, "FMOVRQ"); break; default: return false; } AddIntRegop(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddFpuRegOp(inst, enc.rs2, access_size, Operand::kActionRead); AddFpuRegOp(inst, enc.rd, access_size, Operand::kActionWrite); inst.function += kRCondName[enc.rcond]; return true; } static bool TryDecodeFMOV(Instruction &inst, uint32_t bits) { union { uint32_t flat; struct { uint32_t rs2:5; uint32_t opf_low:6; uint32_t opf_cc:3; uint32_t cond:4; uint32_t _1:1; uint32_t op3:6; uint32_t rd:5; uint32_t op:2; } __attribute__((packed)); } __attribute__((packed)) enc = {bits}; static_assert(sizeof(enc) == 4); if ((enc.opf_low == 0b0001) || (enc.opf_low == 0b0010) || (enc.opf_low == 0b0011)) { return TryDecodeFMOVcc(inst, bits); } return TryDecodeFMOVr(inst, bits); } static bool TryDecodeFCMP_FMOV(Instruction &inst, uint32_t bits) { Format3c enc = {bits}; auto shifted_opf = enc.opf >> 3; if (shifted_opf == 0b001010) { return TryDecodeFCMP(inst, bits); } return TryDecodeFMOV(inst, bits); } static bool TryDecodeOpf_rs1_op_rs2_rd( Instruction &inst, uint32_t bits, uint32_t rs1_size, uint32_t rs2_size, uint32_t rd_size, const char *iform) { Format3b enc = {bits}; inst.function = iform; inst.category = Instruction::kCategoryNormal; if (rs1_size) { AddFpuRegOp(inst, enc.rs1, rs1_size, Operand::kActionRead); } if (rs2_size) { AddFpuRegOp(inst, enc.rs2, rs2_size, Operand::kActionRead); } if (rd_size) { AddFpuRegOp(inst, enc.rd, rd_size, Operand::kActionWrite); } return true; } static bool TryDecodeIMPDEP1(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "IMPDEP1"; inst.category = Instruction::kCategoryNormal; AddImmop(inst, enc.opf, kAddressSize32, false); return true; } static bool TryDecodeIMPDEP2(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "IMPDEP2"; inst.category = Instruction::kCategoryNormal; AddImmop(inst, enc.opf, kAddressSize32, false); return true; } static bool TryDecodeBMASK(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "BMASK"; inst.category = Instruction::kCategoryNormal; AddIntRegop(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeBSHUFFLE(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "BSHUFFLE"; inst.category = Instruction::kCategoryNormal; AddFpuRegOp(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddFpuRegOp(inst, enc.rs2, kAddressSize, Operand::kActionRead); AddFpuRegOp(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } #define SZERO 0 #define SWORD 32 #define DWORD 64 #define QWORD 128 #define DEFINE_FUNCTION(name, rs1_size, rs2_size, rd_size) \ static bool TryDecode ## name(Instruction &inst, uint32_t bits) { \ return TryDecodeOpf_rs1_op_rs2_rd(inst, bits, rs1_size, rs2_size, rd_size, #name); \ } DEFINE_FUNCTION(FABSS, SZERO, SWORD, SWORD) DEFINE_FUNCTION(FABSD, SZERO, DWORD, DWORD) DEFINE_FUNCTION(FABSQ, SZERO, QWORD, QWORD) DEFINE_FUNCTION(FADDS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FADDD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FADDQ, QWORD, QWORD, QWORD) DEFINE_FUNCTION(FSUBS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FSUBD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FSUBQ, QWORD, QWORD, QWORD) DEFINE_FUNCTION(FDIVS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FDIVD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FDIVQ, QWORD, QWORD, QWORD) DEFINE_FUNCTION(FHADDS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FHADDD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FMOVS, SZERO, SWORD, SWORD) DEFINE_FUNCTION(FMOVD, SZERO, DWORD, DWORD) DEFINE_FUNCTION(FMOVQ, SZERO, QWORD, QWORD) DEFINE_FUNCTION(FMULS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FMULD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FMULQ, QWORD, QWORD, QWORD) DEFINE_FUNCTION(FSMULD, SWORD, SWORD, DWORD) DEFINE_FUNCTION(FDMULQ, DWORD, DWORD, QWORD) DEFINE_FUNCTION(FXTOS, SZERO, DWORD, SWORD) DEFINE_FUNCTION(FXTOD, SZERO, DWORD, DWORD) DEFINE_FUNCTION(FXTOQ, SZERO, DWORD, QWORD) DEFINE_FUNCTION(FITOS, SZERO, SWORD, SWORD) DEFINE_FUNCTION(FITOD, SZERO, SWORD, DWORD) DEFINE_FUNCTION(FITOQ, SZERO, SWORD, QWORD) DEFINE_FUNCTION(FSTOX, SZERO, SWORD, DWORD) DEFINE_FUNCTION(FDTOX, SZERO, DWORD, DWORD) DEFINE_FUNCTION(FQTOX, SZERO, QWORD, DWORD) DEFINE_FUNCTION(FSTOI, SZERO, SWORD, SWORD) DEFINE_FUNCTION(FDTOI, SZERO, DWORD, SWORD) DEFINE_FUNCTION(FQTOI, SZERO, QWORD, SWORD) DEFINE_FUNCTION(FNEGS, SZERO, SWORD, SWORD) DEFINE_FUNCTION(FNEGD, SZERO, DWORD, SWORD) DEFINE_FUNCTION(FNEGQ, SZERO, QWORD, SWORD) DEFINE_FUNCTION(FSQRTS, SZERO, SWORD, SWORD) DEFINE_FUNCTION(FSQRTD, SZERO, DWORD, SWORD) DEFINE_FUNCTION(FSQRTQ, SZERO, QWORD, SWORD) DEFINE_FUNCTION(FSTOD, SZERO, SWORD, DWORD) DEFINE_FUNCTION(FSTOQ, SZERO, SWORD, QWORD) DEFINE_FUNCTION(FDTOS, SZERO, DWORD, SWORD) DEFINE_FUNCTION(FDTOQ, SZERO, DWORD, QWORD) DEFINE_FUNCTION(FQTOS, SZERO, QWORD, SWORD) DEFINE_FUNCTION(FQTOD, SZERO, QWORD, DWORD) static bool (*const kop10_op352Level[1u << 8])(Instruction &, uint32_t) = { [0b00000000] = nullptr, [0b00000001] = TryDecodeFMOVS, [0b00000010] = TryDecodeFMOVD, [0b00000011] = TryDecodeFMOVQ, [0b00000100] = nullptr, [0b00000101] = TryDecodeFNEGS, [0b00000110] = TryDecodeFNEGD, [0b00000111] = TryDecodeFNEGQ, [0b00001000] = nullptr, [0b00001001] = TryDecodeFABSS, [0b00001010] = TryDecodeFABSD, [0b00001011] = TryDecodeFABSQ, [0b00001100] = nullptr, [0b00001101] = nullptr, [0b00001110] = nullptr, [0b00001111] = nullptr, [0b00010000] = nullptr, [0b00010001] = nullptr, [0b00010010] = nullptr, [0b00010011] = nullptr, [0b00010100] = nullptr, [0b00010101] = nullptr, [0b00010110] = nullptr, [0b00010111] = nullptr, [0b00011000] = nullptr, [0b00011001] = TryDecodeBMASK, [0b00011010] = nullptr, [0b00011011] = nullptr, [0b00011100] = nullptr, [0b00011101] = nullptr, [0b00011110] = nullptr, [0b00011111] = nullptr, [0b00100000] = nullptr, [0b00100001] = nullptr, [0b00100010] = nullptr, [0b00100011] = nullptr, [0b00100100] = nullptr, [0b00100101] = nullptr, [0b00100110] = nullptr, [0b00100111] = nullptr, [0b00101000] = nullptr, [0b00101001] = TryDecodeFSQRTS, [0b00101010] = TryDecodeFSQRTD, [0b00101011] = TryDecodeFSQRTQ, [0b00101100] = nullptr, [0b00101101] = nullptr, [0b00101110] = nullptr, [0b00101111] = nullptr, [0b00110000] = nullptr, [0b00110001] = nullptr, [0b00110010] = nullptr, [0b00110011] = nullptr, [0b00110100] = nullptr, [0b00110101] = nullptr, [0b00110110] = nullptr, [0b00110111] = nullptr, [0b00111000] = nullptr, [0b00111001] = nullptr, [0b00111010] = nullptr, [0b00111011] = nullptr, [0b00111100] = nullptr, [0b00111101] = nullptr, [0b00111110] = nullptr, [0b00111111] = nullptr, [0b01000000] = nullptr, [0b01000001] = TryDecodeFADDS, [0b01000010] = TryDecodeFADDD, [0b01000011] = TryDecodeFADDQ, [0b01000100] = nullptr, [0b01000101] = TryDecodeFSUBS, [0b01000110] = TryDecodeFSUBD, [0b01000111] = TryDecodeFSUBQ, [0b01001000] = nullptr, [0b01001001] = TryDecodeFMULS, [0b01001010] = TryDecodeFMULD, [0b01001011] = TryDecodeFMULQ, [0b01001100] = nullptr, [0b01001101] = TryDecodeFDIVS, [0b01001110] = TryDecodeFDIVD, [0b01001111] = TryDecodeFDIVQ, [0b01010000] = nullptr, [0b01010001] = nullptr, [0b01010010] = nullptr, [0b01010011] = nullptr, [0b01010100] = nullptr, [0b01010101] = nullptr, [0b01010110] = nullptr, [0b01010111] = nullptr, [0b01011000] = nullptr, [0b01011001] = nullptr, [0b01011010] = nullptr, [0b01011011] = nullptr, [0b01011100] = nullptr, [0b01011101] = nullptr, [0b01011110] = nullptr, [0b01011111] = nullptr, [0b01100000] = nullptr, [0b01100001] = TryDecodeFHADDS, [0b01100010] = TryDecodeFHADDD, [0b01100011] = nullptr, [0b01100100] = nullptr, [0b01100101] = nullptr, [0b01100110] = nullptr, [0b01100111] = nullptr, [0b01101000] = nullptr, [0b01101001] = TryDecodeFSMULD, [0b01101010] = nullptr, [0b01101011] = nullptr, [0b01101100] = nullptr, [0b01101101] = nullptr, [0b01101110] = TryDecodeFDMULQ, [0b01101111] = nullptr, [0b01110000] = nullptr, [0b01110001] = nullptr, [0b01110010] = nullptr, [0b01110011] = nullptr, [0b01110100] = nullptr, [0b01110101] = nullptr, [0b01110110] = nullptr, [0b01110111] = nullptr, [0b01111000] = nullptr, [0b01111001] = nullptr, [0b01111010] = nullptr, [0b01111011] = nullptr, [0b01111100] = nullptr, [0b01111101] = nullptr, [0b01111110] = nullptr, [0b01111111] = nullptr, [0b10000000] = nullptr, [0b10000001] = TryDecodeFSTOX, [0b10000010] = TryDecodeFDTOX, [0b10000011] = TryDecodeFQTOX, [0b10000100] = TryDecodeFXTOS, [0b10000101] = nullptr, [0b10000110] = nullptr, [0b10000111] = nullptr, [0b10001000] = TryDecodeFXTOD, [0b10001001] = nullptr, [0b10001010] = nullptr, [0b10001011] = nullptr, [0b10001100] = TryDecodeFXTOQ, [0b10001101] = nullptr, [0b10001110] = nullptr, [0b10001111] = nullptr, [0b10010000] = nullptr, [0b10010001] = nullptr, [0b10010010] = nullptr, [0b10010011] = nullptr, [0b10010100] = nullptr, [0b10010101] = nullptr, [0b10010110] = nullptr, [0b10010111] = nullptr, [0b10011000] = nullptr, [0b10011001] = nullptr, [0b10011010] = nullptr, [0b10011011] = nullptr, [0b10011100] = nullptr, [0b10011101] = nullptr, [0b10011110] = nullptr, [0b10011111] = nullptr, [0b10100000] = nullptr, [0b10100001] = nullptr, [0b10100010] = nullptr, [0b10100011] = nullptr, [0b10100100] = nullptr, [0b10100101] = nullptr, [0b10100110] = nullptr, [0b10100111] = nullptr, [0b10101000] = nullptr, [0b10101001] = nullptr, [0b10101010] = nullptr, [0b10101011] = nullptr, [0b10101100] = nullptr, [0b10101101] = nullptr, [0b10101110] = nullptr, [0b10101111] = nullptr, [0b10110000] = nullptr, [0b10110001] = nullptr, [0b10110010] = nullptr, [0b10110011] = nullptr, [0b10110100] = nullptr, [0b10110101] = nullptr, [0b10110110] = nullptr, [0b10110111] = nullptr, [0b10111000] = nullptr, [0b10111001] = nullptr, [0b10111010] = nullptr, [0b10111011] = nullptr, [0b10111100] = nullptr, [0b10111101] = nullptr, [0b10111110] = nullptr, [0b10111111] = nullptr, [0b11000000] = nullptr, [0b11000001] = nullptr, [0b11000010] = nullptr, [0b11000011] = nullptr, [0b11000100] = TryDecodeFITOS, [0b11000101] = nullptr, [0b11000110] = TryDecodeFDTOS, [0b11000111] = TryDecodeFQTOS, [0b11001000] = TryDecodeFITOD, [0b11001001] = TryDecodeFSTOD, [0b11001010] = nullptr, [0b11001011] = TryDecodeFQTOD, [0b11001100] = TryDecodeFITOQ, [0b11001101] = TryDecodeFSTOQ, [0b11001110] = TryDecodeFDTOQ, [0b11001111] = nullptr, [0b11010000] = nullptr, [0b11010001] = TryDecodeFSTOI, [0b11010010] = TryDecodeFDTOI, [0b11010011] = TryDecodeFQTOI, [0b11010100] = nullptr, [0b11010101] = nullptr, [0b11010110] = nullptr, [0b11010111] = nullptr, [0b11011000] = nullptr, [0b11011001] = nullptr, [0b11011010] = nullptr, [0b11011011] = nullptr, [0b11011100] = nullptr, [0b11011101] = nullptr, [0b11011110] = nullptr, [0b11011111] = nullptr, [0b11100000] = nullptr, [0b11100001] = nullptr, [0b11100010] = nullptr, [0b11100011] = nullptr, [0b11100100] = nullptr, [0b11100101] = nullptr, [0b11100110] = nullptr, [0b11100111] = nullptr, [0b11101000] = nullptr, [0b11101001] = nullptr, [0b11101010] = nullptr, [0b11101011] = nullptr, [0b11101100] = nullptr, [0b11101101] = nullptr, [0b11101110] = nullptr, [0b11101111] = nullptr, [0b11110000] = nullptr, [0b11110001] = nullptr, [0b11110010] = nullptr, [0b11110011] = nullptr, [0b11110100] = nullptr, [0b11110101] = nullptr, [0b11110110] = nullptr, [0b11110111] = nullptr, [0b11111000] = nullptr, [0b11111001] = nullptr, [0b11111010] = nullptr, [0b11111011] = nullptr, [0b11111100] = nullptr, [0b11111101] = nullptr, [0b11111110] = nullptr, [0b11111111] = nullptr, }; static bool TryDecodeOpf52(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; auto func = kop10_op352Level[enc.opf]; if (!func) { LOG(ERROR) << "Decoding IMPDEP1 with OP=10 op3=110100 opf=" << std::bitset<8>(enc.opf) << " at "<< std::hex << inst.pc << std::dec; return TryDecodeIMPDEP1(inst, bits); } return func(inst, bits); } static bool TryDecodeEDGE8cc (Instruction &inst, uint32_t bits) { Format3b enc = {bits}; inst.function = "EDGE8cc"; inst.category = Instruction::kCategoryNormal; AddIntRegop(inst, enc.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc.rd, kAddressSize, Operand::kActionWrite); return true; } DEFINE_FUNCTION(FORD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FORS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FNORD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FNORS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FANDD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FANDS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FNANDD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FNANDS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FXORD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FXORS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FXNORD, DWORD, DWORD, DWORD) DEFINE_FUNCTION(FXNORS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FZEROS, SZERO, SZERO, SWORD) DEFINE_FUNCTION(FZEROD, SZERO, SZERO, DWORD) DEFINE_FUNCTION(FONES, SZERO, SZERO, SWORD) DEFINE_FUNCTION(FONED, SZERO, SZERO, DWORD) DEFINE_FUNCTION(FNADDS, SWORD, SWORD, SWORD) DEFINE_FUNCTION(FNADDD, DWORD, DWORD, DWORD) static bool (*const kop10_op354Level[1u << 8])(Instruction &, uint32_t) = { [0b00000000] = TryDecodeEDGE8cc, [0b00000001] = nullptr, [0b00000010] = nullptr, [0b00000011] = nullptr, [0b00000100] = nullptr, [0b00000101] = nullptr, [0b00000110] = nullptr, [0b00000111] = nullptr, [0b00001000] = nullptr, [0b00001001] = nullptr, [0b00001010] = nullptr, [0b00001011] = nullptr, [0b00001100] = nullptr, [0b00001101] = nullptr, [0b00001110] = nullptr, [0b00001111] = nullptr, [0b00010000] = nullptr, [0b00010001] = nullptr, [0b00010010] = nullptr, [0b00010011] = nullptr, [0b00010100] = nullptr, [0b00010101] = nullptr, [0b00010110] = nullptr, [0b00010111] = nullptr, [0b00011000] = TryDecodeALIGNADDRESS, [0b00011001] = nullptr, [0b00011010] = TryDecodeALIGNADDRESS_LITTLE, [0b00011011] = nullptr, [0b00011100] = nullptr, [0b00011101] = nullptr, [0b00011110] = nullptr, [0b00011111] = nullptr, [0b00100000] = nullptr, [0b00100001] = nullptr, [0b00100010] = nullptr, [0b00100011] = nullptr, [0b00100100] = nullptr, [0b00100101] = nullptr, [0b00100110] = nullptr, [0b00100111] = nullptr, [0b00101000] = nullptr, [0b00101001] = nullptr, [0b00101010] = nullptr, [0b00101011] = nullptr, [0b00101100] = nullptr, [0b00101101] = nullptr, [0b00101110] = nullptr, [0b00101111] = nullptr, [0b00110000] = nullptr, [0b00110001] = nullptr, [0b00110010] = nullptr, [0b00110011] = nullptr, [0b00110100] = nullptr, [0b00110101] = nullptr, [0b00110110] = nullptr, [0b00110111] = nullptr, [0b00111000] = nullptr, [0b00111001] = nullptr, [0b00111010] = nullptr, [0b00111011] = nullptr, [0b00111100] = nullptr, [0b00111101] = nullptr, [0b00111110] = nullptr, [0b00111111] = nullptr, [0b01000000] = nullptr, [0b01000001] = nullptr, [0b01000010] = nullptr, [0b01000011] = nullptr, [0b01000100] = nullptr, [0b01000101] = nullptr, [0b01000110] = nullptr, [0b01000111] = nullptr, [0b01001000] = TryDecodeFALIGNDATA, [0b01001001] = nullptr, [0b01001010] = nullptr, [0b01001011] = nullptr, [0b01001100] = TryDecodeBSHUFFLE, [0b01001101] = nullptr, [0b01001110] = nullptr, [0b01001111] = nullptr, [0b01010000] = nullptr, [0b01010001] = TryDecodeFNADDS, [0b01010010] = TryDecodeFNADDD, [0b01010011] = nullptr, [0b01010100] = nullptr, [0b01010101] = nullptr, [0b01010110] = nullptr, [0b01010111] = nullptr, [0b01011000] = nullptr, [0b01011001] = nullptr, [0b01011010] = nullptr, [0b01011011] = nullptr, [0b01011100] = nullptr, [0b01011101] = nullptr, [0b01011110] = nullptr, [0b01011111] = nullptr, [0b01100000] = TryDecodeFZEROD, [0b01100001] = TryDecodeFZEROS, [0b01100010] = TryDecodeFNORD, [0b01100011] = nullptr, [0b01100100] = nullptr, [0b01100101] = nullptr, [0b01100110] = nullptr, [0b01100111] = TryDecodeFNORS, [0b01101000] = nullptr, [0b01101001] = nullptr, [0b01101010] = nullptr, [0b01101011] = nullptr, [0b01101100] = TryDecodeFXORS, [0b01101101] = TryDecodeFXORD, [0b01101110] = TryDecodeFNANDD, [0b01101111] = TryDecodeFNANDS, [0b01110000] = TryDecodeFANDD, [0b01110001] = TryDecodeFANDS, [0b01110010] = TryDecodeFXNORD, [0b01110011] = TryDecodeFXNORS, [0b01110100] = nullptr, [0b01110101] = nullptr, [0b01110110] = nullptr, [0b01110111] = nullptr, [0b01111000] = nullptr, [0b01111001] = nullptr, [0b01111010] = nullptr, [0b01111011] = nullptr, [0b01111100] = TryDecodeFORD, [0b01111101] = TryDecodeFORS, [0b01111110] = TryDecodeFONED, [0b01111111] = TryDecodeFONES, [0b10000000] = nullptr, [0b10000001] = nullptr, [0b10000010] = nullptr, [0b10000011] = nullptr, [0b10000100] = nullptr, [0b10000101] = nullptr, [0b10000110] = nullptr, [0b10000111] = nullptr, [0b10001000] = nullptr, [0b10001001] = nullptr, [0b10001010] = nullptr, [0b10001011] = nullptr, [0b10001100] = nullptr, [0b10001101] = nullptr, [0b10001110] = nullptr, [0b10001111] = nullptr, [0b10010000] = nullptr, [0b10010001] = nullptr, [0b10010010] = nullptr, [0b10010011] = nullptr, [0b10010100] = nullptr, [0b10010101] = nullptr, [0b10010110] = nullptr, [0b10010111] = nullptr, [0b10011000] = nullptr, [0b10011001] = nullptr, [0b10011010] = nullptr, [0b10011011] = nullptr, [0b10011100] = nullptr, [0b10011101] = nullptr, [0b10011110] = nullptr, [0b10011111] = nullptr, [0b10100000] = nullptr, [0b10100001] = nullptr, [0b10100010] = nullptr, [0b10100011] = nullptr, [0b10100100] = nullptr, [0b10100101] = nullptr, [0b10100110] = nullptr, [0b10100111] = nullptr, [0b10101000] = nullptr, [0b10101001] = nullptr, [0b10101010] = nullptr, [0b10101011] = nullptr, [0b10101100] = nullptr, [0b10101101] = nullptr, [0b10101110] = nullptr, [0b10101111] = nullptr, [0b10110000] = nullptr, [0b10110001] = nullptr, [0b10110010] = nullptr, [0b10110011] = nullptr, [0b10110100] = nullptr, [0b10110101] = nullptr, [0b10110110] = nullptr, [0b10110111] = nullptr, [0b10111000] = nullptr, [0b10111001] = nullptr, [0b10111010] = nullptr, [0b10111011] = nullptr, [0b10111100] = nullptr, [0b10111101] = nullptr, [0b10111110] = nullptr, [0b10111111] = nullptr, [0b11000000] = nullptr, [0b11000001] = nullptr, [0b11000010] = nullptr, [0b11000011] = nullptr, [0b11000100] = nullptr, [0b11000101] = nullptr, [0b11000110] = nullptr, [0b11000111] = nullptr, [0b11001000] = nullptr, [0b11001001] = nullptr, [0b11001010] = nullptr, [0b11001011] = nullptr, [0b11001100] = nullptr, [0b11001101] = nullptr, [0b11001110] = nullptr, [0b11001111] = nullptr, [0b11010000] = nullptr, [0b11010001] = nullptr, [0b11010010] = nullptr, [0b11010011] = nullptr, [0b11010100] = nullptr, [0b11010101] = nullptr, [0b11010110] = nullptr, [0b11010111] = nullptr, [0b11011000] = nullptr, [0b11011001] = nullptr, [0b11011010] = nullptr, [0b11011011] = nullptr, [0b11011100] = nullptr, [0b11011101] = nullptr, [0b11011110] = nullptr, [0b11011111] = nullptr, [0b11100000] = nullptr, [0b11100001] = nullptr, [0b11100010] = nullptr, [0b11100011] = nullptr, [0b11100100] = nullptr, [0b11100101] = nullptr, [0b11100110] = nullptr, [0b11100111] = nullptr, [0b11101000] = nullptr, [0b11101001] = nullptr, [0b11101010] = nullptr, [0b11101011] = nullptr, [0b11101100] = nullptr, [0b11101101] = nullptr, [0b11101110] = nullptr, [0b11101111] = nullptr, [0b11110000] = nullptr, [0b11110001] = nullptr, [0b11110010] = nullptr, [0b11110011] = nullptr, [0b11110100] = nullptr, [0b11110101] = nullptr, [0b11110110] = nullptr, [0b11110111] = nullptr, [0b11111000] = nullptr, [0b11111001] = nullptr, [0b11111010] = nullptr, [0b11111011] = nullptr, [0b11111100] = nullptr, [0b11111101] = nullptr, [0b11111110] = nullptr, [0b11111111] = nullptr, }; static bool TryDecodeOpf54(Instruction &inst, uint32_t bits) { Format3b enc = {bits}; auto func = kop10_op354Level[enc.opf]; if (!func) { LOG(ERROR) << "Decoding IMPDEP1 with OP=10 op3=110110 opf=" << std::bitset<8>(enc.opf) << " at "<< std::hex << inst.pc << std::dec; return TryDecodeIMPDEP1(inst, bits); } return func(inst, bits); } #define DEFINE_TryDecode(ins) \ static bool TryDecode ## ins(Instruction &inst, uint32_t bits) { \ return TryDecode_rs1_simm32_op_rs2_rd(inst, bits, #ins); \ } // Logical Operations DEFINE_TryDecode(AND) DEFINE_TryDecode(ANDcc) DEFINE_TryDecode(ANDN) DEFINE_TryDecode(ANDNcc) DEFINE_TryDecode(OR) DEFINE_TryDecode(ORcc) DEFINE_TryDecode(ORN) DEFINE_TryDecode(ORNcc) DEFINE_TryDecode(XOR) DEFINE_TryDecode(XORcc) DEFINE_TryDecode(XNOR) DEFINE_TryDecode(XNORcc) // Binary Operations DEFINE_TryDecode(ADD) DEFINE_TryDecode(ADDC) DEFINE_TryDecode(ADDcc) DEFINE_TryDecode(ADDCcc) DEFINE_TryDecode(SUB) DEFINE_TryDecode(SUBC) DEFINE_TryDecode(SUBcc) DEFINE_TryDecode(SUBCcc) DEFINE_TryDecode(UMUL) DEFINE_TryDecode(SMUL) DEFINE_TryDecode(MULX) DEFINE_TryDecode(UMULcc) DEFINE_TryDecode(SMULcc) DEFINE_TryDecode(UDIV) DEFINE_TryDecode(SDIV) DEFINE_TryDecode(UDIVX) DEFINE_TryDecode(SDIVX) DEFINE_TryDecode(UDIVcc) DEFINE_TryDecode(SDIVcc) #undef DEFINE_TryDecode #define DEFINE_TryDecode(ins) \ static bool TryDecode ## ins(Instruction &inst, uint32_t bits) { \ if (!TryDecode_rs1_simm32_op_rs2_rd(inst, bits, #ins)) { \ return false; \ } \ inst.category = Instruction::kCategoryConditionalAsyncHyperCall; \ return true; \ } DEFINE_TryDecode(TADDcc) DEFINE_TryDecode(TSUBcc) DEFINE_TryDecode(TADDccTV) DEFINE_TryDecode(TSUBccTV) #undef DEFINE_TryDecode static bool TryDecodeSWAP(Instruction &inst, uint32_t bits) { inst.is_atomic_read_modify_write = true; return TryDecode_rs1_simm32_op_rs2_rd(inst, bits, "SWAP"); } static bool TryDecode_Shift(Instruction &inst, uint32_t bits, const char *iform_name, unsigned rs1_size=32) { Format3ai0 enc_i0 = {bits}; Format3ai0 enc_i1 = {bits}; AddIntRegop(inst, enc_i0.rs1, rs1_size, Operand::kActionRead); if (enc_i1.i) { /* if (enc_i1.asi) { LOG(ERROR) << "TryDecode_Shift asi is null"; return false; // Reserved bits; must be zero. }*/ AddImmop(inst, enc_i1.rs2 /* shcnt */, kAddressSize32, false); // Embed the masking of the shift in the operand. } else if (enc_i0.rs2) { inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeShiftRegister; op.action = Operand::kActionRead; op.size = kAddressSize32; op.shift_reg.reg.name = kReadIntRegName[enc_i0.rs2]; op.shift_reg.reg.size = kAddressSize32; op.shift_reg.shift_op = Operand::ShiftRegister::kShiftLeftWithZeroes; op.shift_reg.extend_op = Operand::ShiftRegister::kExtendUnsigned; op.shift_reg.shift_size = 0; op.shift_reg.extract_size = 5; // Register `%g0` is `rs2`. } else { AddImmop(inst, 0 /* shcnt */, kAddressSize32, false); } AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); inst.function = iform_name; inst.category = Instruction::kCategoryNormal; return true; } static bool TryDecode_ShiftX(Instruction &inst, uint32_t bits, const char *iform_name) { Format3ei0 enc_i0 = {bits}; Format3ei2 enc_i2 = {bits}; AddIntRegop(inst, enc_i0.rs1, kAddressSize, Operand::kActionRead); if (enc_i2.i) { AddImmop(inst, enc_i2.shcnt64 /* shcnt */, kAddressSize, false); // Embed the masking of the shift in the operand. } else if (enc_i0.rs2) { inst.operands.emplace_back(); auto &op = inst.operands.back(); op.type = Operand::kTypeShiftRegister; op.action = Operand::kActionRead; op.size = kAddressSize; op.shift_reg.reg.name = kReadIntRegName[enc_i0.rs2]; op.shift_reg.reg.size = kAddressSize; op.shift_reg.shift_op = Operand::ShiftRegister::kShiftLeftWithZeroes; op.shift_reg.extend_op = Operand::ShiftRegister::kExtendUnsigned; op.shift_reg.shift_size = 0; op.shift_reg.extract_size = 6; // Register `%g0` is `rs2`. } else { AddImmop(inst, 0 /* shcnt */, kAddressSize, false); } AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); inst.function = iform_name; inst.category = Instruction::kCategoryNormal; return true; } static bool TryDecodeSLL(Instruction &inst, uint32_t bits) { Format3ei0 enc = {bits}; if (enc.x == 1) { return TryDecode_ShiftX(inst, bits, "SLLX"); } else { return TryDecode_Shift(inst, bits, "SLL", 64); } } static bool TryDecodeSRL(Instruction &inst, uint32_t bits) { Format3ei0 enc = {bits}; if (enc.x == 1) { return TryDecode_ShiftX(inst, bits, "SRLX"); } else { return TryDecode_Shift(inst, bits, "SRL"); } } static bool TryDecodeSRA(Instruction &inst, uint32_t bits) { Format3ei0 enc = {bits}; if (enc.x == 1) { return TryDecode_ShiftX(inst, bits, "SRAX"); } else { return TryDecode_Shift(inst, bits, "SRA"); } } enum class RegClass { kInt, kFP }; static bool TryDecode_Load( Instruction &inst, uint32_t bits, const char *iform, unsigned mem_size, unsigned reg_size, RegClass rclass=RegClass::kInt, bool has_asi=false) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.function = iform; inst.category = Instruction::kCategoryNormal; // ASI register is added as one of the operand if (has_asi) { if (enc_i1.i) { AddDestRegop(inst, "ASI_REG", 8); } else { AddImmop(inst, enc_i0.asi, 8, false); } } if (enc_i1.i) { AddBasePlusOffsetMemop( inst, Operand::kActionRead, mem_size, enc_i0.rs1, 0, enc_i1.simm13); } else { AddBasePlusOffsetMemop( inst, Operand::kActionRead, mem_size, enc_i0.rs1, enc_i0.rs2, 0); } if (RegClass::kInt == rclass) { AddIntRegop(inst, enc_i0.rd, reg_size, Operand::kActionWrite); } else if (!AddFpuRegOp(inst, enc_i0.rd, reg_size, Operand::kActionWrite)) { return false; } return true; } static bool TryDecode_Store( Instruction &inst, uint32_t bits, const char *iform, unsigned reg_size, unsigned mem_size, RegClass rclass=RegClass::kInt, bool has_asi=false) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.function = iform; inst.category = Instruction::kCategoryNormal; // ASI register is added as one of the operand if (has_asi) { if (enc_i1.i) { AddDestRegop(inst, "ASI_REG", 8); } else { AddImmop(inst, enc_i0.asi, 8, false); } } if (RegClass::kInt == rclass) { AddIntRegop(inst, enc_i0.rd, reg_size, Operand::kActionRead); } else if (!AddFpuRegOp(inst, enc_i0.rd, reg_size, Operand::kActionRead)) { return false; } if (enc_i1.i) { AddBasePlusOffsetMemop( inst, Operand::kActionWrite, mem_size, enc_i0.rs1, 0, enc_i1.simm13); } else { AddBasePlusOffsetMemop( inst, Operand::kActionWrite, mem_size, enc_i0.rs1, enc_i0.rs2, 0); } return true; } static bool TryDecodeLDSB(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDSB", 8, kAddressSize); } static bool TryDecodeLDSH(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDSH", 16, kAddressSize); } static bool TryDecodeLDSW(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDSW", 32, kAddressSize); } static bool TryDecodeLDUB(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDUB", 8, kAddressSize); } static bool TryDecodeLDUH(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDUH", 16, kAddressSize); } static bool TryDecodeLDUW(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDUW", 32, kAddressSize); } static bool TryDecodeLDX(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDX", 64, 64); } static bool TryDecodeLDF(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDF", 32, 32, RegClass::kFP); } static bool TryDecodeLDDF(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDDF", 64, 64, RegClass::kFP); } static bool TryDecodeLDQF(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDQF", 128, 128, RegClass::kFP); } static bool TryDecodeLDSBA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDSBA", 8, kAddressSize, RegClass::kInt, true); } static bool TryDecodeLDSHA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDSHA", 16, kAddressSize, RegClass::kInt, true); } static bool TryDecodeLDSWA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDSWA", 32, kAddressSize, RegClass::kInt, true); } static bool TryDecodeLDUBA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDUBA", 8, kAddressSize, RegClass::kInt, true); } static bool TryDecodeLDUHA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDUHA", 16, kAddressSize, RegClass::kInt, true); } static bool TryDecodeLDUWA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDUWA", 32, kAddressSize, RegClass::kInt, true); } static bool TryDecodeLDXA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDXA", 64, 64, RegClass::kInt, true); } static bool TryDecodeLDFA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDFA", 32, 32, RegClass::kFP, true); } static bool TryDecodeLDDFA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDDFA", 64, 64, RegClass::kFP, true); } static bool TryDecodeLDQFA(Instruction &inst, uint32_t bits) { return TryDecode_Load(inst, bits, "LDQFA", 128, 128, RegClass::kFP, true); } static bool TryDecodeLDSTUB(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.function = "LDSTUB"; inst.category = Instruction::kCategoryNormal; inst.is_atomic_read_modify_write = true; // if i != 0 if (enc_i1.i) { AddBasePlusOffsetMemop( inst, Operand::kActionWrite, 8, enc_i0.rs1, 0, enc_i1.simm13); } else { AddBasePlusOffsetMemop( inst, Operand::kActionWrite, 8, enc_i0.rs1, 0, enc_i0.rs2); } AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeLDSTUBA(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.function = "LDSTUBA"; inst.category = Instruction::kCategoryNormal; inst.is_atomic_read_modify_write = true; // if i != 0 if (enc_i1.i) { AddDestRegop(inst, "ASI_REG", 8); AddBasePlusOffsetMemop( inst, Operand::kActionWrite, 8, enc_i0.rs1, 0, enc_i1.simm13); } else { AddImmop(inst, enc_i0.asi, 8, false); AddBasePlusOffsetMemop( inst, Operand::kActionWrite, 8, enc_i0.rs1, 0, enc_i0.rs2); } AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeLDFSR(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; if (enc_i1.i) { AddBasePlusOffsetMemop( inst, Operand::kActionRead, kAddressSize32, enc_i0.rs1, 0, enc_i1.simm13); } else { AddBasePlusOffsetMemop( inst, Operand::kActionRead, kAddressSize32, enc_i0.rs1, enc_i0.rs2, 0); } inst.category = Instruction::kCategoryNormal; switch(enc_i0.rd) { case 0: inst.function = "LDFSR"; break; case 1: inst.function = "LDXFSR"; break; case 3: inst.function = "LDXEFSR"; break; default: return false; } return true; } static bool TryDecodeSTB(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STB", kAddressSize, 8); } static bool TryDecodeSTH(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STH", kAddressSize, 16); } static bool TryDecodeSTW(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STW", kAddressSize, 32); } static bool TryDecodeSTX(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STX", 64, 64); } static bool TryDecodeSTBA(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STBA", kAddressSize, 8, RegClass::kInt, true); } static bool TryDecodeSTHA(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STHA", kAddressSize, 16, RegClass::kInt, true); } static bool TryDecodeSTWA(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STWA", kAddressSize, 32, RegClass::kInt, true); } static bool TryDecodeSTXA(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STXA", 64, 64, RegClass::kInt, true); } static bool TryDecodeSTF(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STF", 32, 32, RegClass::kFP); } static bool TryDecodeSTDF(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STDF", 64, 64, RegClass::kFP); } static bool TryDecodeSTQF(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STQF", 128, 128, RegClass::kFP); } static bool TryDecodeSTFA(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STFA", 32, 32, RegClass::kFP, true); } static bool TryDecodeSTDFA(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STDFA", 64, 64, RegClass::kFP, true); } static bool TryDecodeSTQFA(Instruction &inst, uint32_t bits) { return TryDecode_Store(inst, bits, "STQFA", 128, 128, RegClass::kFP, true); } static bool TryDecodeSTFSR(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; if (enc_i1.i) { AddBasePlusOffsetMemop( inst, Operand::kActionWrite, kAddressSize32, enc_i0.rs1, 0, enc_i1.simm13); } else { AddBasePlusOffsetMemop( inst, Operand::kActionWrite, kAddressSize32, enc_i0.rs1, enc_i0.rs2, 0); } inst.category = Instruction::kCategoryNormal; switch(enc_i0.rd) { case 0: inst.function = "STFSR"; break; case 1: inst.function = "STXFSR"; break; case 3: inst.function = "STXEFSR"; break; default: return false; } return true; } static bool TryDecodeMEMBAR_RDasr(Instruction &inst, uint32_t bits) { Format3f enc = {bits}; if ((enc.bits != 0b01111) && (enc.i != 1)) { return TryDecodeRDasr(inst, bits); } inst.function = "MEMBAR"; inst.category = Instruction::kCategoryNormal; AddImmop(inst, enc.mmask /* mmask */, kAddressSize32, false); AddImmop(inst, enc.cmask /* cmask */, kAddressSize32, false); return true; } static bool TryDecode_rs1_imm_asi_op_rs2_rd( Instruction &inst, uint32_t bits, const char *iform) { Format3ai0 enc_i0 = {bits}; inst.function = iform; inst.category = Instruction::kCategoryNormal; AddIntRegop(inst, enc_i0.rs1, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc_i0.rs2, kAddressSize, Operand::kActionRead); AddIntRegop(inst, enc_i0.rd, kAddressSize, Operand::kActionWrite); return true; } static bool TryDecodeCASA(Instruction &inst, uint32_t bits) { inst.is_atomic_read_modify_write = true; return TryDecode_rs1_imm_asi_op_rs2_rd(inst, bits, "CASA"); } static bool TryDecodeCASXA(Instruction &inst, uint32_t bits) { inst.is_atomic_read_modify_write = true; return TryDecode_rs1_imm_asi_op_rs2_rd(inst, bits, "CASA"); } static bool TryDecodeFLUSHW(Instruction &inst, uint32_t bits) { inst.function = "FLUSHW"; inst.category = Instruction::kCategoryNormal; return true; } static bool TryDecodeFLUSH(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; inst.function = "FLUSH"; inst.category = Instruction::kCategoryNormal; if (enc_i0.i == 0) { AddBasePlusOffsetMemop( inst, Operand::kActionRead, kAddressSize, enc_i0.rs1, enc_i0.rs2, 0); } return true; } static bool TryDecodePREFETCH(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.function = "PREFETCH"; inst.category = Instruction::kCategoryNormal; if (enc_i0.i == 0) { AddBasePlusOffsetMemop( inst, Operand::kActionRead, kAddressSize, enc_i0.rs1, enc_i0.rs2, 0); } else { AddBasePlusOffsetMemop( inst, Operand::kActionRead, kAddressSize32, enc_i0.rs1, 0, enc_i1.simm13); } AddImmop(inst, enc_i0.rd /* fcn */, kAddressSize32, false); return true; } static bool TryDecodePREFETCHA(Instruction &inst, uint32_t bits) { Format3ai0 enc_i0 = {bits}; Format3ai1 enc_i1 = {bits}; inst.function = "PREFETCHA"; inst.category = Instruction::kCategoryNormal; if (enc_i1.i) { AddDestRegop(inst, "ASI_REG", 8); AddBasePlusOffsetMemop( inst, Operand::kActionRead, kAddressSize32, enc_i0.rs1, 0, enc_i1.simm13); } else { AddImmop(inst, enc_i0.asi, 8, false); AddBasePlusOffsetMemop( inst, Operand::kActionRead, kAddressSize, enc_i0.rs1, enc_i0.rs2, 0); } AddImmop(inst, enc_i0.rd /* fcn */, kAddressSize32, false); return true; } static bool (*const kop00_op2Level[1u << 3])(Instruction &, uint32_t) = { [0b000] = TryDecodeUNIMP, [0b001] = TryDecodeBPcc, [0b010] = TryDecodeBcc, [0b011] = TryDecodeBPr, [0b100] = TryDecodeSETHI, [0b101] = TryDecodeFBPcc, [0b110] = TryDecodeFBcc, [0b111] = nullptr, }; static bool (*const kop10_op3Level[1U << 6])(Instruction &, uint32_t) = { [0b000000] = TryDecodeADD, [0b000001] = TryDecodeAND, [0b000010] = TryDecodeOR, [0b000011] = TryDecodeXOR, [0b000100] = TryDecodeSUB, [0b000101] = TryDecodeANDN, [0b000110] = TryDecodeORN, [0b000111] = TryDecodeXNOR, [0b001000] = TryDecodeADDC, [0b001001] = TryDecodeMULX, [0b001010] = TryDecodeUMUL, [0b001011] = TryDecodeSMUL, [0b001100] = TryDecodeSUBC, [0b001101] = TryDecodeUDIVX, [0b001110] = TryDecodeUDIV, [0b001111] = TryDecodeSDIV, [0b010000] = TryDecodeADDcc, [0b010001] = TryDecodeANDcc, [0b010010] = TryDecodeORcc, [0b010011] = TryDecodeXORcc, [0b010100] = TryDecodeSUBcc, [0b010101] = TryDecodeANDNcc, [0b010110] = TryDecodeORNcc, [0b010111] = TryDecodeXNORcc, [0b011000] = TryDecodeADDCcc, [0b011001] = nullptr, [0b011010] = TryDecodeUMULcc, [0b011011] = TryDecodeSMULcc, [0b011100] = TryDecodeSUBCcc, [0b011101] = nullptr, [0b011110] = TryDecodeUDIVcc, [0b011111] = TryDecodeSDIVcc, [0b100000] = TryDecodeTADDcc, [0b100001] = TryDecodeTSUBcc, [0b100010] = TryDecodeTADDccTV, [0b100011] = TryDecodeTSUBccTV, [0b100100] = nullptr, [0b100101] = TryDecodeSLL, [0b100110] = TryDecodeSRL, [0b100111] = TryDecodeSRA, [0b101000] = TryDecodeMEMBAR_RDasr, [0b101001] = nullptr, [0b101010] = TryDecodeRDPr, [0b101011] = TryDecodeFLUSHW, [0b101100] = TryDecodeMOVcc, [0b101101] = TryDecodeSDIVX, [0b101110] = nullptr, [0b101111] = TryDecodeMOVr, [0b110000] = TryDecodeWRasr, [0b110001] = nullptr, [0b110010] = nullptr, [0b110011] = nullptr, [0b110100] = TryDecodeOpf52, [0b110101] = TryDecodeFCMP_FMOV, [0b110110] = TryDecodeOpf54, [0b110111] = TryDecodeIMPDEP2, [0b111000] = TryDecodeJMPL, [0b111001] = TryDecodeRETURN, [0b111010] = TryDecodeTcc, [0b111011] = TryDecodeFLUSH, [0b111100] = TryDecodeSave, [0b111101] = TryDecodeRestore, [0b111110] = nullptr, [0b111111] = nullptr, }; static bool (*const kop11_op3Level[1u << 6])(Instruction &, uint32_t) = { [0b000000] = TryDecodeLDUW, [0b000001] = TryDecodeLDUB, [0b000010] = TryDecodeLDUH, [0b000011] = nullptr, [0b000100] = TryDecodeSTW, [0b000101] = TryDecodeSTB, [0b000110] = TryDecodeSTH, [0b000111] = nullptr, [0b001000] = TryDecodeLDSW, [0b001001] = TryDecodeLDSB, [0b001010] = TryDecodeLDSH, [0b001011] = TryDecodeLDX, [0b001100] = nullptr, [0b001101] = TryDecodeLDSTUB, [0b001110] = TryDecodeSTX, [0b001111] = TryDecodeSWAP, [0b010000] = TryDecodeLDUWA, [0b010001] = TryDecodeLDUBA, [0b010010] = TryDecodeLDUHA, [0b010011] = nullptr, [0b010100] = TryDecodeSTWA, [0b010101] = TryDecodeSTBA, [0b010110] = TryDecodeSTHA, [0b010111] = nullptr, [0b011000] = TryDecodeLDSWA, [0b011001] = TryDecodeLDSBA, [0b011010] = TryDecodeLDSHA, [0b011011] = TryDecodeLDXA, [0b011100] = nullptr, [0b011101] = TryDecodeLDSTUBA, [0b011110] = TryDecodeSTXA, [0b011111] = nullptr, [0b100000] = TryDecodeLDF, [0b100001] = TryDecodeLDFSR, [0b100010] = TryDecodeLDQF, [0b100011] = TryDecodeLDDF, [0b100100] = TryDecodeSTF, [0b100101] = TryDecodeSTFSR, [0b100110] = TryDecodeSTQF, [0b100111] = TryDecodeSTDF, [0b101000] = nullptr, [0b101001] = nullptr, [0b101010] = nullptr, [0b101011] = nullptr, [0b101100] = nullptr, [0b101101] = TryDecodePREFETCH, [0b101110] = nullptr, [0b101111] = nullptr, [0b110000] = TryDecodeLDFA, [0b110001] = nullptr, [0b110010] = TryDecodeLDQFA, [0b110011] = TryDecodeLDDFA, [0b110100] = TryDecodeSTFA, [0b110101] = nullptr, [0b110110] = TryDecodeSTQFA, [0b110111] = TryDecodeSTDFA, [0b111000] = nullptr, [0b111001] = nullptr, [0b111010] = nullptr, [0b111011] = nullptr, [0b111100] = TryDecodeCASA, [0b111101] = TryDecodePREFETCHA, [0b111110] = TryDecodeCASXA, [0b111111] = nullptr, }; // SETHI, Branches, and ILLTRAP static bool TryDecode_op00(Instruction &inst, uint32_t bits) { auto index = (bits >> 22u) & 0x7u; auto func = kop00_op2Level[index]; if (!func) { LOG(ERROR) << "OP=00 op2=" << std::bitset<3>(index); return false; } return func(inst, bits); } // It's a PC-relative CALL instruction. static bool TryDecode_op01(Instruction &inst, uint32_t bits) { return TryDecodeCALL(inst, bits); } static bool TryDecode_op10(Instruction &inst, uint32_t bits) { auto index = (bits >> 19u) & 0x3Fu; auto func = kop10_op3Level[index]; if (!func) { LOG(ERROR) << "OP=10 op3=" << std::bitset<6>(index); return false; } return func(inst, bits); } static bool TryDecode_op11(Instruction &inst, uint32_t bits) { auto index = (bits >> 19u) & 0x3Fu; auto func = kop11_op3Level[index]; if (!func) { LOG(ERROR) << "OP=11 op3=" << std::bitset<6>(index); return false; } return func(inst, bits); } static bool (*const kopLevel[])(Instruction &, uint32_t) = { TryDecode_op00, TryDecode_op01, TryDecode_op10, TryDecode_op11 }; static uint32_t BytesToBits(const uint8_t *bytes) { uint32_t bits = 0; bits = (bits << 8) | static_cast<uint32_t>(bytes[0]); bits = (bits << 8) | static_cast<uint32_t>(bytes[1]); bits = (bits << 8) | static_cast<uint32_t>(bytes[2]); bits = (bits << 8) | static_cast<uint32_t>(bytes[3]); return bits; } } bool TryDecode(Instruction &inst) { const auto num_bytes = inst.bytes.size(); if (num_bytes == 4) { const auto bytes = reinterpret_cast<const uint8_t *>(inst.bytes.data()); const auto bits = BytesToBits(bytes); return kopLevel[bits >> 30u](inst, bits); // Pseudo-operations, e.g. SET=SETHI+OR. } else if (num_bytes == 8) { if (inst.in_delay_slot) { LOG(WARNING) << "Decoding 8-byte pseudo-op at " << std::hex << inst.pc << std::dec << " in delay slot; ignoring second four bytes"; inst.bytes.resize(4); inst.next_pc = inst.pc + 4; return TryDecode(inst); } const auto bytes = reinterpret_cast<const uint8_t *>(inst.bytes.data()); const auto bits1 = BytesToBits(bytes); const auto bits2 = BytesToBits(&(bytes[4])); // op=00, op2=0b100 const auto bits1_op = bits1 >> 30u; const auto bits1_op2 = (bits1 >> 22u) & 0x7u; bool ret = false; if (bits1_op == 0b00 && bits1_op2 == 0b100) { // SETHI. const auto bits2_op = bits2 >> 30u; const auto bits2_op3 = (bits2 >> 19u) & 0x3Fu; if (bits2_op == 0b10 && bits2_op3 == 0b000010) { // OR. ret = TryDecodeSET_SETHI_OR(inst, bits1, bits2); } else if (bits2_op == 0b10 && bits2_op3 == 0b000000) { // ADD ret = TryDecodeSET_SETHI_ADD(inst, bits1, bits2); } } if (!ret) { inst.bytes.resize(4); inst.next_pc = inst.pc + 4; ret = TryDecode(inst); LOG_IF(ERROR, !ret) << "Unsupported 8-byte instruction: " << inst.Serialize(); } return ret; } else { return false; } } } // namespace sparc64 } // namespace remill
28.920096
88
0.668603
[ "vector" ]
f542182754be72d39d1630bcf8c4911d093465b0
5,682
cc
C++
src/media/audio/lib/clock/utils.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
src/media/audio/lib/clock/utils.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
src/media/audio/lib/clock/utils.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 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 "src/media/audio/lib/clock/utils.h" #include <cmath> #include "src/lib/syslog/cpp/logger.h" namespace media::audio { zx_status_t DuplicateClock(const zx::clock& original_clock, zx::clock* dupe_clock) { FX_DCHECK(dupe_clock) << "Null ptr passed to DuplicateClock"; constexpr auto rights = ZX_RIGHT_DUPLICATE | ZX_RIGHT_TRANSFER | ZX_RIGHT_READ; return original_clock.duplicate(rights, dupe_clock); } zx_status_t GetAndDisplayClockDetails(const zx::clock& ref_clock) { if (!ref_clock.is_valid()) { FX_LOGS(INFO) << "Clock is invalid"; return ZX_OK; } zx_clock_details_v1_t clock_details; zx_status_t status = ref_clock.get_details(&clock_details); if (status != ZX_OK) { FX_PLOGS(ERROR, status) << "Error calling zx::clock::get_details"; return status; } DisplayClockDetails(clock_details); return ZX_OK; } void DisplayClockDetails(const zx_clock_details_v1_t& clock_details) { FX_LOGS(INFO) << "******************************************"; FX_LOGS(INFO) << "Clock details -"; FX_LOGS(INFO) << " options:\t\t\t\t0x" << std::hex << clock_details.options; FX_LOGS(INFO) << " backstop_time:\t\t\t" << clock_details.backstop_time; FX_LOGS(INFO) << " query_ticks:\t\t\t" << clock_details.query_ticks; FX_LOGS(INFO) << " last_value_update_ticks:\t\t" << clock_details.last_value_update_ticks; FX_LOGS(INFO) << " last_rate_adjust_update_ticks:\t" << clock_details.last_rate_adjust_update_ticks; FX_LOGS(INFO) << " generation_counter:\t\t" << clock_details.generation_counter; FX_LOGS(INFO) << " mono_to_synthetic -"; FX_LOGS(INFO) << " reference_offset:\t\t" << clock_details.mono_to_synthetic.reference_offset; FX_LOGS(INFO) << " synthetic_offset:\t\t" << clock_details.mono_to_synthetic.synthetic_offset; FX_LOGS(INFO) << " rate -"; FX_LOGS(INFO) << " synthetic_ticks:\t\t" << clock_details.mono_to_synthetic.rate.synthetic_ticks; FX_LOGS(INFO) << " reference_ticks:\t\t" << clock_details.mono_to_synthetic.rate.reference_ticks; FX_LOGS(INFO) << "******************************************"; } fit::result<ClockSnapshot, zx_status_t> SnapshotClock(const zx::clock& ref_clock) { ClockSnapshot snapshot; zx_clock_details_v1_t clock_details; zx_status_t status = ref_clock.get_details(&clock_details); if (status != ZX_OK) { return fit::error(status); } snapshot.timeline_transform = TimelineFunction(clock_details.mono_to_synthetic.synthetic_offset, clock_details.mono_to_synthetic.reference_offset, clock_details.mono_to_synthetic.rate.synthetic_ticks, clock_details.mono_to_synthetic.rate.reference_ticks); snapshot.generation = clock_details.generation_counter; return fit::ok(snapshot); } // Naming is confusing here. zx::clock transforms/structs call the underlying baseline clock (ticks // or monotonic: we use monotonic) their "reference" clock. Unfortunately, in media terminology a // "reference clock" could be any continuous monotonically increasing clock -- including not only // the local system monotonic, but also custom clocks maintained outside the kernel (which zx::clock // calls "synthetic" clocks). // // Thus in these util functions that convert between clocks, a conversion that we usually call "from // monotonic to reference" is (in zx::clock terms) a conversion "from reference to synthetic", where // the baseline reference here is the monotonic clock. fit::result<zx::time, zx_status_t> ReferenceTimeFromMonotonicTime(const zx::clock& ref_clock, zx::time mono_time) { zx_clock_details_v1_t clock_details; zx_status_t status = ref_clock.get_details(&clock_details); if (status != ZX_OK) { return fit::error(status); } return fit::ok(zx::time( affine::Transform::Apply(clock_details.mono_to_synthetic.reference_offset, clock_details.mono_to_synthetic.synthetic_offset, affine::Ratio(clock_details.mono_to_synthetic.rate.synthetic_ticks, clock_details.mono_to_synthetic.rate.reference_ticks), mono_time.get()))); } fit::result<zx::time, zx_status_t> MonotonicTimeFromReferenceTime(const zx::clock& ref_clock, zx::time ref_time) { zx_clock_details_v1_t clock_details; zx_status_t status = ref_clock.get_details(&clock_details); if (status != ZX_OK) { return fit::error(status); } return fit::ok(zx::time(affine::Transform::ApplyInverse( clock_details.mono_to_synthetic.reference_offset, clock_details.mono_to_synthetic.synthetic_offset, affine::Ratio(clock_details.mono_to_synthetic.rate.synthetic_ticks, clock_details.mono_to_synthetic.rate.reference_ticks), ref_time.get()))); } affine::Transform ToAffineTransform(TimelineFunction& tl_function) { return affine::Transform( tl_function.reference_time(), tl_function.subject_time(), affine::Ratio(tl_function.subject_delta(), tl_function.reference_delta())); } TimelineFunction ToTimelineFunction(affine::Transform affine_trans) { return TimelineFunction(affine_trans.b_offset(), affine_trans.a_offset(), affine_trans.numerator(), affine_trans.denominator()); } } // namespace media::audio
42.402985
100
0.689546
[ "transform" ]
f5427a64214d2654619da4b70742a61011d78fb9
2,645
cpp
C++
Engine/Engine/MouseInput.cpp
knnth3/GameEngine
0434b224da9c8389ee79779cc20a5932eed61b46
[ "MIT" ]
null
null
null
Engine/Engine/MouseInput.cpp
knnth3/GameEngine
0434b224da9c8389ee79779cc20a5932eed61b46
[ "MIT" ]
null
null
null
Engine/Engine/MouseInput.cpp
knnth3/GameEngine
0434b224da9c8389ee79779cc20a5932eed61b46
[ "MIT" ]
null
null
null
#include "MouseInput.h" #include <glm\gtx\transform.hpp> using namespace Engine; glm::vec2 Engine::MouseInput::GetPositon()const { return m_position; } glm::vec3 Engine::MouseInput::Get3DPosition() { glm::vec3 position; if (m_camera) { std::lock_guard<std::mutex> lock(m_mouse_lock); glm::vec3 origin = m_camera->GetPosition(); glm::vec3 mousePosition = GetWorldSpaceCoords(); glm::vec3 planeNormal = glm::vec3(0, 1, 0); float farDistance = m_camera->GetFarPlane() / 2; float DotPt1 = glm::dot(origin, planeNormal); float DotPt2 = glm::dot(mousePosition, planeNormal); float distanceToPlane = 0.0f - (DotPt1 / DotPt2); glm::vec3 mouse3Dposition = origin + (mousePosition * distanceToPlane); position = mouse3Dposition; } return position; } glm::vec3 Engine::MouseInput::Get3DPosition_2() { glm::vec3 position; if (m_camera) { std::lock_guard<std::mutex> lock(m_mouse_lock); glm::vec3 cameraPos = m_camera->GetPosition(); glm::vec3 mousePos = GetWorldSpaceCoords(); float t = -cameraPos.y / mousePos.y; glm::vec3 mousePosition = cameraPos + (mousePos * t); mousePosition.y = 0.0f; position = mousePosition; } return position; } void Engine::MouseInput::AttatchCamera(std::shared_ptr<Engine::Camera>& camera) { std::lock_guard<std::mutex> lock(m_mouse_lock); m_camera = camera; } void Engine::MouseInput::SetPosition(float x, float y) { std::lock_guard<std::mutex> lock(m_mouse_lock); m_position.x = x; m_position.y = y; } glm::vec2 Engine::MouseInput::GetTranslatedCoords() { glm::vec2 mousePosition; if (m_camera) { auto mousePos = GetPositon(); mousePosition.x = (2.0f * mousePos.x) / m_camera->GetWindowWidth() - 1.0f; mousePosition.y = 1.0f - (2.0f * mousePos.y) / m_camera->GetWindowHeight(); } return mousePosition; } glm::vec4 Engine::MouseInput::GetEyeSpaceCoords(glm::vec4 position) { glm::vec4 EyeSpaceCoords; if (m_camera) { EyeSpaceCoords = glm::inverse(m_camera->Get3DProjectionMatrix()) * position; EyeSpaceCoords = glm::vec4(EyeSpaceCoords.x, EyeSpaceCoords.y, -1.0f, 0.0f); } return EyeSpaceCoords; } glm::vec3 Engine::MouseInput::GetWorldSpaceCoords() { glm::vec3 worldCoords; if (m_camera) { //Eye space glm::vec2 mousePos = GetPositon(); glm::vec2 normalized = GetTranslatedCoords(); glm::vec4 clipCoords = glm::vec4(normalized, -1.0f, 1.0f); glm::vec4 eyeCoords = GetEyeSpaceCoords(clipCoords); //World space glm::vec4 mouseCoords = glm::inverse(m_camera->GetViewMatrix()) * eyeCoords; worldCoords = glm::vec3(mouseCoords.x, mouseCoords.y, mouseCoords.z); worldCoords = glm::normalize(worldCoords); } return worldCoords; }
26.45
79
0.714934
[ "transform" ]
f548c8b190844663b1dcaec0498ec94339c68219
4,259
cpp
C++
clients/gtest/orgxr_ungxr_gtest.cpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
38
2019-09-11T19:38:53.000Z
2022-03-21T07:08:59.000Z
clients/gtest/orgxr_ungxr_gtest.cpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
208
2018-06-07T21:31:54.000Z
2022-03-31T20:12:10.000Z
clients/gtest/orgxr_ungxr_gtest.cpp
rkamd/rocSOLVER
de338c6cfc78e9e00be141d11529b8faeaba911f
[ "BSD-2-Clause" ]
38
2018-06-05T22:29:48.000Z
2022-03-31T07:30:47.000Z
/* ************************************************************************ * Copyright (c) 2020-2021 Advanced Micro Devices, Inc. * * ************************************************************************ */ #include "testing_orgxr_ungxr.hpp" using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; typedef std::tuple<vector<int>, vector<int>> orgqr_tuple; // each m_size_range vector is a {M, lda} // each n_size_range vector is a {N, K} // case when m = 0 and n = 0 will also execute the bad arguments test // (null handle, null pointers and invalid values) // for checkin_lapack tests const vector<vector<int>> m_size_range = { // quick return {0, 1}, // always invalid {-1, 1}, {20, 5}, // invalid for case * {50, 50}, // normal (valid) samples {70, 100}, {130, 130}}; const vector<vector<int>> n_size_range = { // quick return {0, 1}, // always invalid {-1, 1}, {1, -1}, {10, 20}, // invalid for case * {55, 55}, // normal (valid) samples {10, 0}, {20, 20}, {35, 25}}; // for daily_lapack tests const vector<vector<int>> large_m_size_range = {{400, 410}, {640, 640}, {1000, 1024}, {2000, 2000}}; const vector<vector<int>> large_n_size_range = {{164, 162}, {198, 140}, {130, 130}, {220, 220}, {400, 200}}; Arguments orgqr_setup_arguments(orgqr_tuple tup) { vector<int> m_size = std::get<0>(tup); vector<int> n_size = std::get<1>(tup); Arguments arg; arg.set<rocblas_int>("m", m_size[0]); arg.set<rocblas_int>("lda", m_size[1]); arg.set<rocblas_int>("n", n_size[0]); arg.set<rocblas_int>("k", n_size[1]); arg.timing = 0; return arg; } template <bool BLOCKED> class ORGXR_UNGXR : public ::TestWithParam<orgqr_tuple> { protected: ORGXR_UNGXR() {} virtual void SetUp() {} virtual void TearDown() {} template <typename T> void run_tests() { Arguments arg = orgqr_setup_arguments(GetParam()); if(arg.peek<rocblas_int>("m") == 0 && arg.peek<rocblas_int>("n") == 0) testing_orgxr_ungxr_bad_arg<T, BLOCKED>(); testing_orgxr_ungxr<T, BLOCKED>(arg); } }; class ORG2R : public ORGXR_UNGXR<false> { }; class UNG2R : public ORGXR_UNGXR<false> { }; class ORGQR : public ORGXR_UNGXR<true> { }; class UNGQR : public ORGXR_UNGXR<true> { }; // non-batch tests TEST_P(ORG2R, __float) { run_tests<float>(); } TEST_P(ORG2R, __double) { run_tests<double>(); } TEST_P(UNG2R, __float_complex) { run_tests<rocblas_float_complex>(); } TEST_P(UNG2R, __double_complex) { run_tests<rocblas_double_complex>(); } TEST_P(ORGQR, __float) { run_tests<float>(); } TEST_P(ORGQR, __double) { run_tests<double>(); } TEST_P(UNGQR, __float_complex) { run_tests<rocblas_float_complex>(); } TEST_P(UNGQR, __double_complex) { run_tests<rocblas_double_complex>(); } INSTANTIATE_TEST_SUITE_P(daily_lapack, ORG2R, Combine(ValuesIn(large_m_size_range), ValuesIn(large_n_size_range))); INSTANTIATE_TEST_SUITE_P(checkin_lapack, ORG2R, Combine(ValuesIn(m_size_range), ValuesIn(n_size_range))); INSTANTIATE_TEST_SUITE_P(daily_lapack, UNG2R, Combine(ValuesIn(large_m_size_range), ValuesIn(large_n_size_range))); INSTANTIATE_TEST_SUITE_P(checkin_lapack, UNG2R, Combine(ValuesIn(m_size_range), ValuesIn(n_size_range))); INSTANTIATE_TEST_SUITE_P(daily_lapack, ORGQR, Combine(ValuesIn(large_m_size_range), ValuesIn(large_n_size_range))); INSTANTIATE_TEST_SUITE_P(checkin_lapack, ORGQR, Combine(ValuesIn(m_size_range), ValuesIn(n_size_range))); INSTANTIATE_TEST_SUITE_P(daily_lapack, UNGQR, Combine(ValuesIn(large_m_size_range), ValuesIn(large_n_size_range))); INSTANTIATE_TEST_SUITE_P(checkin_lapack, UNGQR, Combine(ValuesIn(m_size_range), ValuesIn(n_size_range)));
23.273224
100
0.596149
[ "vector" ]
f548f30d1097ccf01ae45e1aa640b80fe82f5c09
5,532
cpp
C++
Gears/Util/UIUtils.cpp
gaybro8777/GTAVManualTransmission
b3bafedf3dbcbdb83e8e7febb87ca61e0c2b5dd6
[ "Zlib" ]
144
2016-02-01T01:22:24.000Z
2022-03-29T09:13:12.000Z
Gears/Util/UIUtils.cpp
gaybro8777/GTAVManualTransmission
b3bafedf3dbcbdb83e8e7febb87ca61e0c2b5dd6
[ "Zlib" ]
86
2016-02-27T14:20:31.000Z
2022-03-30T08:10:47.000Z
Gears/Util/UIUtils.cpp
gaybro8777/GTAVManualTransmission
b3bafedf3dbcbdb83e8e7febb87ca61e0c2b5dd6
[ "Zlib" ]
39
2016-02-07T07:57:54.000Z
2022-03-30T12:41:02.000Z
#include "UIUtils.h" #include "inc/natives.h" #include "inc/enums.h" #include "fmt/format.h" #include <algorithm> #include "../Constants.h" #include "../ScriptSettings.hpp" extern ScriptSettings g_settings; namespace { const size_t maxStringLength = 99; int notificationHandle = 0; } void showNotification(const std::string& message, int* prevNotification) { if (prevNotification != nullptr && *prevNotification != 0) { HUD::THEFEED_REMOVE_ITEM(*prevNotification); } HUD::BEGIN_TEXT_COMMAND_THEFEED_POST("STRING"); HUD::ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME(message.c_str()); int id = HUD::END_TEXT_COMMAND_THEFEED_POST_TICKER(false, false); if (prevNotification != nullptr) { *prevNotification = id; } } float UI::GetStringWidth(const std::string& text, float scale, int font) { HUD::_BEGIN_TEXT_COMMAND_GET_WIDTH("STRING"); HUD::ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME(text.c_str()); HUD::SET_TEXT_FONT(font); HUD::SET_TEXT_SCALE(scale, scale); return HUD::_END_TEXT_COMMAND_GET_WIDTH(true); } void UI::Notify(int level, const std::string& message) { Notify(level, message, true); } void UI::Notify(int level, const std::string& message, bool removePrevious) { if (level < g_settings.HUD.NotifyLevel) return; int* notifHandleAddr = nullptr; if (removePrevious) { notifHandleAddr = &notificationHandle; } showNotification(fmt::format("{}\n{}", Constants::NotificationPrefix, message), notifHandleAddr); } void UI::ShowText(float x, float y, float scale, const std::string &text, int font, const Util::ColorI &rgba, bool outline) { HUD::SET_TEXT_FONT(font); HUD::SET_TEXT_SCALE(scale, scale); HUD::SET_TEXT_COLOUR(rgba.R, rgba.G, rgba.B, rgba.A); HUD::SET_TEXT_WRAP(0.0, 1.0); HUD::SET_TEXT_CENTRE(0); if (outline) HUD::SET_TEXT_OUTLINE(); HUD::BEGIN_TEXT_COMMAND_DISPLAY_TEXT("STRING"); HUD::ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME(text.c_str()); HUD::END_TEXT_COMMAND_DISPLAY_TEXT(x, y, 0); } void UI::ShowText3D(Vector3 location, const std::vector<std::string> &textLines, const Util::ColorI& backgroundColor, const Util::ColorI& fontColor) { float height = 0.0125f; GRAPHICS::SET_DRAW_ORIGIN(location.x, location.y, location.z, 0); int i = 0; float szX = 0.060f; for (const auto& line : textLines) { ShowText(0, 0 + height * static_cast<float>(i), 0.2f, line, 0, fontColor, true); float currWidth = UI::GetStringWidth(line, 0.2f, 0); if (currWidth > szX) { szX = currWidth; } i++; } float szY = (height * static_cast<float>(i)) + 0.02f; GRAPHICS::DRAW_RECT(0.027f, (height * static_cast<float>(i)) / 2.0f, szX, szY, backgroundColor.R, backgroundColor.G, backgroundColor.B, backgroundColor.A, 0); GRAPHICS::CLEAR_DRAW_ORIGIN(); } void UI::ShowText3DColors(Vector3 location, const std::vector<std::pair<std::string, Util::ColorI>> &textLines, const Util::ColorI& backgroundColor) { float height = 0.0125f; GRAPHICS::SET_DRAW_ORIGIN(location.x, location.y, location.z, 0); int i = 0; float szX = 0.060f; for (const auto& line : textLines) { float currWidth = UI::GetStringWidth(line.first, 0.2f, 0); if (currWidth > szX) { szX = currWidth; } } for (const auto& line : textLines) { ShowText(0.0f, 0.0f + height * static_cast<float>(i), 0.2f, line.first, 0, line.second, true); i++; } float szY = (height * static_cast<float>(i)) + 0.01f; GRAPHICS::DRAW_RECT(szX * 0.5f, (height * static_cast<float>(i)) / 2.0f, szX + 0.01f, szY, backgroundColor.R, backgroundColor.G, backgroundColor.B, backgroundColor.A, 0); GRAPHICS::CLEAR_DRAW_ORIGIN(); } void UI::ShowSubtitle(const std::string &message, int duration) { HUD::BEGIN_TEXT_COMMAND_PRINT("CELL_EMAIL_BCON"); for (size_t i = 0; i < message.size(); i += maxStringLength) { size_t npos = std::min(maxStringLength, static_cast<int>(message.size()) - i); HUD::ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME(message.substr(i, npos).c_str()); } HUD::END_TEXT_COMMAND_PRINT(duration, 1); } void UI::ShowHelpText(const std::string& message) { HUD::BEGIN_TEXT_COMMAND_DISPLAY_HELP("CELL_EMAIL_BCON"); for (size_t i = 0; i < message.size(); i += maxStringLength) { size_t npos = std::min(maxStringLength, static_cast<int>(message.size()) - i); HUD::ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME(message.substr(i, npos).c_str()); } HUD::END_TEXT_COMMAND_DISPLAY_HELP(0, false, false, -1); } void UI::DrawSphere(Vector3 p, float scale, const Util::ColorI& c) { GRAPHICS::DRAW_MARKER(eMarkerType::MarkerTypeDebugSphere, p.x, p.y, p.z, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, scale, scale, scale, c.R, c.G, c.B, c.A, false, false, 2, false, nullptr, nullptr, false); } void UI::DrawBar(float x, float y, float width, float height, Util::ColorI fg, Util::ColorI bg, float value) { float bgpaddingx = 0.00f; float bgpaddingy = 0.01f; // background GRAPHICS::DRAW_RECT(x, y, width + bgpaddingx, height + bgpaddingy, bg.R, bg.G, bg.B, bg.A, 0); // rpm bar GRAPHICS::DRAW_RECT(x - width * 0.5f + value * width * 0.5f, y, width * value, height, fg.R, fg.G, fg.B, fg.A, 0); }
35.012658
118
0.647505
[ "vector" ]
f54bb73f8089288a1ab22344b1adfd4704f3b918
8,338
cpp
C++
pwiz/data/msdata/MSDataMerger.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz/data/msdata/MSDataMerger.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz/data/msdata/MSDataMerger.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // $Id: MSDataMerger.cpp 2908 2011-08-05 16:41:41Z chambm $ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2010 Vanderbilt University - Nashville, TN 37232 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #define PWIZ_SOURCE #include "MSDataMerger.hpp" #include "pwiz/utility/misc/Std.hpp" #include "pwiz/utility/misc/DateTime.hpp" #include "Diff.hpp" #include "References.hpp" using boost::shared_ptr; using namespace pwiz::util; namespace pwiz { namespace msdata { namespace { void mergeParamContainers(ParamContainer& target, const ParamContainer& source) { Diff<ParamContainer> diff(target, source); if (diff) { const ParamContainer& source_minus_target = diff.b_a; target.cvParams.insert(target.cvParams.end(), source_minus_target.cvParams.begin(), source_minus_target.cvParams.end()); target.userParams.insert(target.userParams.end(), source_minus_target.userParams.begin(), source_minus_target.userParams.end()); target.paramGroupPtrs.insert(target.paramGroupPtrs.end(), source_minus_target.paramGroupPtrs.begin(), source_minus_target.paramGroupPtrs.end()); } } class SpectrumListMerger : public SpectrumList { struct IndexEntry : public SpectrumIdentity { SpectrumListPtr spectrumListPtr; SourceFilePtr sourceFilePtr; size_t originalIndex; }; const MSData& msd_; vector<MSDataPtr> inputMSDataPtrs_; vector<IndexEntry> index_; map<string, IndexList> idToIndexes_; public: SpectrumListMerger(const MSData& msd, const vector<MSDataPtr>& inputs) : msd_(msd), inputMSDataPtrs_(inputs) { BOOST_FOREACH(const MSDataPtr& input, inputs) for (size_t i=0; i < input->run.spectrumListPtr->size(); ++i) { SpectrumPtr s = input->run.spectrumListPtr->spectrum(i); Spectrum& oldIdentity = *s; idToIndexes_[oldIdentity.id].push_back(index_.size()); IndexEntry ie; ie.id = oldIdentity.id; ie.index = index_.size(); ie.originalIndex = i; ie.spectrumListPtr = input->run.spectrumListPtr; // because of the high chance of duplicate ids, sourceFilePtrs are always explicit SourceFilePtr oldSourceFilePtr = oldIdentity.sourceFilePtr.get() ? oldIdentity.sourceFilePtr : input->run.defaultSourceFilePtr; if (oldSourceFilePtr.get()) ie.sourceFilePtr = SourceFilePtr(new SourceFile(input->run.id + "_" + oldSourceFilePtr->id)); index_.push_back(ie); } } virtual size_t size() const {return index_.size();} virtual const SpectrumIdentity& spectrumIdentity(size_t index) const { if (index >= size()) throw runtime_error("[SpectrumListMerger::spectrumIdentity()] Bad index: " + lexical_cast<string>(index)); return index_[index]; } virtual size_t find(const string& id) const { map<string, IndexList>::const_iterator itr = idToIndexes_.find(id); if (itr == idToIndexes_.end()) return size(); return itr->second[0]; // TODO: address duplicate ids when sourceFilePtr is disregarded... } virtual SpectrumPtr spectrum(size_t index, bool getBinaryData) const { if (index >= size()) throw runtime_error("[SpectrumListMerger::spectrum()] Bad index: " + lexical_cast<string>(index)); const IndexEntry& ie = index_[index]; SpectrumPtr result = ie.spectrumListPtr->spectrum(ie.originalIndex, getBinaryData); result->index = ie.index; // because of the high chance of duplicate ids, sourceFilePtrs are always explicit result->sourceFilePtr = ie.sourceFilePtr; // resolve references into MSData::*Ptrs that may be invalidated after merging References::resolve(*result, msd_); return result; } }; } // namespace PWIZ_API_DECL MSDataMerger::MSDataMerger(const vector<MSDataPtr>& inputs) : inputMSDataPtrs_(inputs) { // MSData::id and Run::id are set to the longest common prefix of all inputs' Run::ids, // or if there is no common prefix, to a concatenation of all inputs' Run::ids vector<string> runIds; // Run::startTimeStamp is set to the earliest timestamp vector<blt::local_date_time> runTimestamps; BOOST_FOREACH(const MSDataPtr& input, inputs) { const MSData& msd = *input; // merge fileDescription/sourceFilePtrs (prepend each source file with its source run id) BOOST_FOREACH(const SourceFilePtr& sourceFilePtr, msd.fileDescription.sourceFilePtrs) { this->fileDescription.sourceFilePtrs.push_back(SourceFilePtr(new SourceFile(*sourceFilePtr))); SourceFile& sf = *this->fileDescription.sourceFilePtrs.back(); sf.id = msd.run.id + "_" + sf.id; } runIds.push_back(msd.run.id); if (!msd.run.startTimeStamp.empty()) runTimestamps.push_back(decode_xml_datetime(msd.run.startTimeStamp)); DiffConfig config; config.ignoreSpectra = config.ignoreChromatograms = true; Diff<MSData, msdata::DiffConfig> diff(*this, msd, config); // merge cvs this->cvs.insert(this->cvs.end(), diff.b_a.cvs.begin(), diff.b_a.cvs.end()); // merge fileDescription/fileContent mergeParamContainers(this->fileDescription.fileContent, diff.b_a.fileDescription.fileContent); // merge fileDescription/contacts this->fileDescription.contacts.insert(this->fileDescription.contacts.end(), diff.b_a.fileDescription.contacts.begin(), diff.b_a.fileDescription.contacts.end()); // merge file-level shared *Ptrs this->paramGroupPtrs.insert(this->paramGroupPtrs.end(), diff.b_a.paramGroupPtrs.begin(), diff.b_a.paramGroupPtrs.end()); this->samplePtrs.insert(this->samplePtrs.end(), diff.b_a.samplePtrs.begin(), diff.b_a.samplePtrs.end()); this->softwarePtrs.insert(this->softwarePtrs.end(), diff.b_a.softwarePtrs.begin(), diff.b_a.softwarePtrs.end()); this->instrumentConfigurationPtrs.insert(this->instrumentConfigurationPtrs.end(), diff.b_a.instrumentConfigurationPtrs.begin(), diff.b_a.instrumentConfigurationPtrs.end()); this->dataProcessingPtrs.insert(this->dataProcessingPtrs.end(), diff.b_a.dataProcessingPtrs.begin(), diff.b_a.dataProcessingPtrs.end()); // merge run? } string lcp = pwiz::util::longestCommonPrefix(runIds); // trim typical separator characters from the end of the LCP bal::trim_right_if(lcp, bal::is_any_of(" _-.")); if (lcp.empty()) this->id = this->run.id = "merged-spectra"; else this->id = this->run.id = lcp; if (!runTimestamps.empty()) this->run.startTimeStamp = encode_xml_datetime(*std::min_element(runTimestamps.begin(), runTimestamps.end())); this->run.spectrumListPtr = SpectrumListPtr(new SpectrumListMerger(*this, inputMSDataPtrs_)); } } // namespace msdata } // namespace pwiz
37.390135
153
0.622931
[ "vector" ]
f54ce1d6e6cee6dec31b5c2fb4c503eccd24be56
66,736
cpp
C++
source/exhumed/src/object.cpp
Talon1024/Raze
d92f56f36f246f12ea4012b3f9d5eb6c4abe0070
[ "RSA-MD" ]
2
2020-03-26T10:11:17.000Z
2021-01-19T08:16:48.000Z
source/exhumed/src/object.cpp
bisk89/Raze
1a2663f7ac84d4e4f472e0796b937447ee6fab6b
[ "RSA-MD" ]
null
null
null
source/exhumed/src/object.cpp
bisk89/Raze
1a2663f7ac84d4e4f472e0796b937447ee6fab6b
[ "RSA-MD" ]
null
null
null
//------------------------------------------------------------------------- /* Copyright (C) 2010-2019 EDuke32 developers and contributors Copyright (C) 2019 sirlemonhead, Nuke.YKT This file is part of PCExhumed. PCExhumed is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- #include "ns.h" #include "engine.h" #include "object.h" #include "exhumed.h" #include "move.h" #include "random.h" #include "view.h" #include "sound.h" #include "init.h" #include "runlist.h" #include "names.h" #include "sequence.h" #include "lighting.h" #include "anims.h" #include "items.h" #include "player.h" #include "trigdat.h" #include "bullet.h" #include <string.h> #include <assert.h> BEGIN_PS_NS #define kMaxBobs 200 #define kMaxDrips 50 #define kMaxMoveSects 50 #define kMaxObjects 128 #define kMaxWallFace 4096 #define kMaxSlideData 128 #define kMaxPoints 1024 #define kMaxTraps 40 #define kMaxTrails 20 #define kMaxTrailPoints 100 static short ObjectSeq[] = { 46, -1, 72, -1 }; static short ObjectStatnum[] = { kStatExplodeTrigger, kStatExplodeTarget, 98, kStatDestructibleSprite }; struct Trail { short field_0; short field_2; short field_4; short pad; }; struct TrailPoint { int x; int y; }; struct Bob { short nSector; char field_2; char field_3; int z; }; struct Drip { short nSprite; short field_2; }; // 56 bytes struct Elev { short field_0; short nChannel; short nSector; int field_6; int field_A; short nCountZOffsets; // count of items in zOffsets short nCurZOffset; int zOffsets[8]; // different Z offsets short field_32; short nSprite; short field_36; }; // 16 bytes struct MoveSect { short nSector; short nTrail; short nTrailPoint; short field_6; short field_8; // nSector? int field_10; short field_14; // nChannel? }; struct Object { short field_0; short nHealth; short field_4; short nSprite; short field_8; short field_10; short field_12; }; struct wallFace { short nChannel; short nWall; short field_4; short field_6[8]; }; // TODO - rename struct slideData2 { short nChannel; short field_2; short field_4; short field_6; short field_8; uint8_t field_A[6]; // pad? }; struct slideData { int field_0; int field_4; int field_8; int field_C; int x1; int y1; int x2; int y2; int field_20; int field_24; int field_28; int field_2C; int field_30; int field_34; int field_38; int field_3C; }; struct Point { short field_0; short field_2; short field_4; short field_6; short field_8; short field_A; short field_C; short field_E; }; struct Trap { short field_0; short nSprite; short nType; short field_6; short field_8; short field_A; short field_C; short field_E; }; Trap sTrap[kMaxTraps]; Bob sBob[kMaxBobs]; Trail sTrail[kMaxTrails]; TrailPoint sTrailPoint[kMaxTrailPoints]; Elev Elevator[kMaxElevs]; Object ObjectList[kMaxObjects]; MoveSect sMoveSect[kMaxMoveSects]; slideData SlideData[kMaxSlideData]; short sMoveDir[kMaxMoveSects]; wallFace WallFace[kMaxWallFace]; slideData2 SlideData2[kMaxSlideData]; Point PointList[kMaxPoints]; short nTrapInterval[kMaxTraps]; short sBobID[kMaxBobs]; short PointCount; short PointFree[kMaxPoints]; short SlideCount = 0; short SlideFree[kMaxSlides]; char nTrailPointVal[kMaxTrailPoints]; short nTrailPointPrev[kMaxTrailPoints]; short nTrailPointNext[kMaxTrailPoints]; Drip sDrip[kMaxDrips]; short ElevCount = -1; short WallFaceCount = -1; int lFinaleStart; short nTrailPoints; short nEnergyBlocks; short nMoveSects; short nFinaleStage; short nTrails; short nTraps; short nFinaleSpr; short ObjectCount; short nDrips; short nBobs = 0; short nDronePitch = 0; short nSmokeSparks = 0; // done void InitObjects() { ObjectCount = 0; nTraps = 0; nDrips = 0; nBobs = 0; nTrails = 0; nTrailPoints = 0; nMoveSects = 0; memset(sTrail, -1, sizeof(sTrail)); nEnergyBlocks = 0; nDronePitch = 0; nFinaleStage = 0; lFinaleStart = 0; nSmokeSparks = 0; } // done void InitElev() { ElevCount = kMaxElevs; } // done int BuildWallSprite(int nSector) { int nWall = sector[nSector].wallptr; int x = wall[nWall].x; int y = wall[nWall].y; int x2 = wall[nWall + 1].x; int y2 = wall[nWall + 1].y; int nSprite = insertsprite(nSector, 401); sprite[nSprite].x = (x + x2) / 2; sprite[nSprite].y = (y + y2) / 2; sprite[nSprite].z = (sector[nSector].floorz + sector[nSector].ceilingz) / 2; sprite[nSprite].cstat = 0x8000; return nSprite; } // done short FindWallSprites(short nSector) { int var_24 = 0x7FFFFFFF; int ecx = 0x7FFFFFFF; int nWall = sector[nSector].wallptr; int nWallCount = sector[nSector].wallnum; int esi = 0x80000002; int edi = 0x80000002; int i; for (i = 0; i < nWallCount; i++) { if (wall[nWall].x < var_24) { var_24 = wall[nWall].x; } if (esi < wall[nWall].x) { esi = wall[nWall].x; } if (ecx > wall[nWall].y) { ecx = wall[nWall].y; } if (edi < wall[nWall].y) { edi = wall[nWall].y; } nWall++; } ecx -= 5; esi += 5; edi += 5; var_24 -= 5; int nSprite = -1; for (i = 0; i < kMaxSprites; i++) { if (sprite[i].lotag == 0) { if ((sprite[i].cstat & 0x50) == 80) { int var_28 = sprite[i].x; int ebx = sprite[i].y; if ((var_28 >= var_24) && (esi >= var_28) && (ebx >= ecx) && (ebx <= edi)) { sprite[i].owner = nSprite; nSprite = i; } } } } if (nSprite < 0) { nSprite = insertsprite(nSector, 401); sprite[nSprite].x = (var_24 + esi) / 2; sprite[nSprite].y = (ecx + edi) / 2; sprite[nSprite].z = sector[nSector].floorz; sprite[nSprite].cstat = 0x8000; sprite[nSprite].owner = -1; sprite[nSprite].lotag = 0; sprite[nSprite].hitag = 0; } return nSprite; } int BuildElevF(int nChannel, int nSector, int nWallSprite, int arg_4, int arg_5, int nCount, ...) { assert(ElevCount > 0); if (ElevCount <= 0) { return -1; } ElevCount--; Elevator[ElevCount].field_0 = 2; Elevator[ElevCount].field_6 = arg_4; Elevator[ElevCount].field_32 = -1; Elevator[ElevCount].field_A = arg_5; Elevator[ElevCount].nChannel = nChannel; Elevator[ElevCount].nSector = nSector; Elevator[ElevCount].nCountZOffsets = 0; Elevator[ElevCount].nCurZOffset = 0; Elevator[ElevCount].field_36 = 0; if (nWallSprite < 0) { nWallSprite = BuildWallSprite(nSector); } Elevator[ElevCount].nSprite = nWallSprite; va_list zlist; va_start(zlist, nCount); while (1) { if (Elevator[ElevCount].nCountZOffsets >= nCount) { return ElevCount; } int nVal = Elevator[ElevCount].nCountZOffsets; Elevator[ElevCount].nCountZOffsets++; Elevator[ElevCount].zOffsets[nVal] = va_arg(zlist, int); } va_end(zlist); return ElevCount; } int BuildElevC(int arg1, int nChannel, int nSector, int nWallSprite, int arg5, int arg6, int nCount, ...) { int edi = arg5; assert(ElevCount > 0); if (ElevCount <= 0) { return -1; } ElevCount--; Elevator[ElevCount].field_0 = arg1; if (arg1 & 4) { edi = arg5 / 2; } Elevator[ElevCount].field_6 = edi; Elevator[ElevCount].nCountZOffsets = 0; Elevator[ElevCount].field_36 = 0; Elevator[ElevCount].nCurZOffset = 0; Elevator[ElevCount].field_A = arg6; Elevator[ElevCount].field_32 = -1; Elevator[ElevCount].nChannel = nChannel; Elevator[ElevCount].nSector = nSector; if (nWallSprite < 0) { nWallSprite = BuildWallSprite(nSector); } Elevator[ElevCount].nSprite = nWallSprite; va_list zlist; va_start(zlist, nCount); while (1) { if (Elevator[ElevCount].nCountZOffsets >= nCount) { return ElevCount; } int nVal = Elevator[ElevCount].nCountZOffsets; Elevator[ElevCount].nCountZOffsets++; Elevator[ElevCount].zOffsets[nVal] = va_arg(zlist, int); } va_end(zlist); return ElevCount; } // TODO - tidy me up // RENAME param A - not always Z // Confirmed 100% correct with original .exe int LongSeek(int *pZVal, int a2, int a3, int a4) { int v4; // edx@1 int v5; // ebx@2 v4 = a2 - *pZVal; if (v4 < 0) { v5 = -a3; if (v5 > v4) v4 = v5; (*pZVal) += v4; } if (v4 > 0) { if (a4 < v4) v4 = a4; (*pZVal) += v4; } return v4; } // done int CheckSectorSprites(short nSector, int nVal) { int b = 0; if (nVal) { short nSprite = headspritesect[nSector]; int nZDiff = sector[nSector].floorz - sector[nSector].ceilingz; while (nSprite != -1) { if ((sprite[nSprite].cstat & 0x101) && (nZDiff < GetSpriteHeight(nSprite))) { if (nVal != 1) { return 1; } b = 1; runlist_DamageEnemy(nSprite, -1, 5); if (sprite[nSprite].statnum == 100 && PlayerList[GetPlayerFromSprite(nSprite)].nHealth <= 0) { PlayFXAtXYZ(StaticSound[kSoundJonFDie], sprite[nSprite].x, sprite[nSprite].y, sprite[nSprite].z, sprite[nSprite].sectnum | 0x4000); } } nSprite = nextspritesect[nSprite]; } } else { for (int i = headspritesect[nSector]; i != -1; i = nextspritesect[i]) { if (sprite[i].cstat & 0x101) { return 1; } } b = 0; } return b; } // done void MoveSectorSprites(int nSector, int z) { int nSprite = headspritesect[nSector]; while (nSprite != -1) { if (sprite[nSprite].statnum != 200) { sprite[nSprite].z += z; } nSprite = nextspritesect[nSprite]; } } void StartElevSound(short nSprite, int nVal) { short nSound; if (nVal & 2) { nSound = nElevSound; } else { nSound = nStoneSound; } D3PlayFX(StaticSound[nSound], nSprite); } void FuncElev(int a, int UNUSED(b), int nRun) { short nElev = RunData[nRun].nVal; assert(nElev >= 0 && nElev < kMaxElevs); short nChannel = Elevator[nElev].nChannel; short var_18 = Elevator[nElev].field_0; assert(nChannel >= 0 && nChannel < kMaxChannels); int nMessage = a & 0x7F0000; if (nMessage < 0x10000) { return; } // int var_24 = var_18 & 0x10; // floor based? switch (nMessage) { default: { return; } case 0x10000: { // short ax = var_18 & 8; short dx = sRunChannels[nChannel].c; int edi = 999; // FIXME CHECKME - this isn't default set to anything in the ASM that I can see - if ax is 0 and var_24 is 0, this will never be set to a known value otherwise! if (var_18 & 0x8) { if (dx) { edi = 1; } else { edi = 0; } } else { // loc_20D48: if (var_18 & 0x10) // was var_24 { if (Elevator[nElev].field_32 < 0) { Elevator[nElev].field_32 = runlist_AddRunRec(NewRun, RunData[nRun].nMoves); StartElevSound(Elevator[nElev].nSprite, var_18); edi = 1; } } else { if (dx < 0) { edi = 0; } else { if (dx == Elevator[nElev].nCurZOffset || dx >= Elevator[nElev].nCountZOffsets) { Elevator[nElev].field_36 = dx; edi = 1; } else { Elevator[nElev].nCurZOffset = sRunChannels[nChannel].c; edi = 1; } } } } assert(edi != 999); // loc_20DF9: if (edi) { if (Elevator[nElev].field_32 < 0) { Elevator[nElev].field_32 = runlist_AddRunRec(NewRun, RunData[nRun].nMoves); StartElevSound(Elevator[nElev].nSprite, var_18); } } else { //loc_20E4E: if (Elevator[nElev].field_32 >= 0) { runlist_SubRunRec(Elevator[nElev].field_32); Elevator[nElev].field_32 = -1; } } return; } case 0x20000: { short nSector = Elevator[nElev].nSector; short di = Elevator[nElev].nSprite; int ebp = 0; // initialise to *something* if (var_18 & 0x2) { int nZOffset = Elevator[nElev].nCurZOffset; int nZVal = Elevator[nElev].zOffsets[nZOffset]; short nSectorB = nSector; int nVal = LongSeek((int*)&sector[nSector].floorz, nZVal, Elevator[nElev].field_6, Elevator[nElev].field_A); ebp = nVal; if (!nVal) { if (var_18 & 0x10) { Elevator[nElev].nCurZOffset ^= 1; StartElevSound(di, var_18); } else { StopSpriteSound(di); runlist_SubRunRec(nRun); Elevator[nElev].field_32 = -1; runlist_ReadyChannel(nChannel); D3PlayFX(StaticSound[nStopSound], Elevator[nElev].nSprite); } } else { assert(nSector == nSectorB); MoveSectorSprites(nSector, nVal); if (nVal < 0 && CheckSectorSprites(nSector, 2)) { runlist_ChangeChannel(nChannel, sRunChannels[nChannel].c == 0); return; } } } else { // loc_20FC3: int ceilZ = sector[nSector].ceilingz; sectortype *var_28 = &sector[nSector]; int nZOffset = Elevator[nElev].nCurZOffset; int zVal = Elevator[nElev].zOffsets[nZOffset]; int nVal = LongSeek(&ceilZ, zVal, Elevator[nElev].field_6, Elevator[nElev].field_A); ebp = nVal; if (!nVal) { if (var_18 & 0x10) { Elevator[nElev].nCurZOffset ^= 1; StartElevSound(Elevator[nElev].nSprite, var_18); } else { runlist_SubRunRec(nRun); Elevator[nElev].field_32 = -1; StopSpriteSound(Elevator[nElev].nSprite); D3PlayFX(StaticSound[nStopSound], Elevator[nElev].nSprite); runlist_ReadyChannel(nChannel); } return; } else if (nVal > 0) { if (ceilZ == zVal) { if (var_18 & 0x4) { SetQuake(di, 30); } PlayFXAtXYZ(StaticSound[kSound26], sprite[di].x, sprite[di].y, sprite[di].z, sprite[di].sectnum); } if (var_18 & 0x4) { if (CheckSectorSprites(nSector, 1)) { return; } } else { if (CheckSectorSprites(nSector, 0)) { runlist_ChangeChannel(nChannel, sRunChannels[nChannel].c == 0); return; } } } var_28->ceilingz = ceilZ; } // maybe this doesn't go here? while (di != -1) { sprite[di].z += ebp; di = sprite[di].owner; } return; } } } // done void InitWallFace() { WallFaceCount = kMaxWallFace; } int BuildWallFace(short nChannel, short nWall, int nCount, ...) { if (WallFaceCount <= 0) { I_Error("Too many wall faces!\n"); } WallFaceCount--; WallFace[WallFaceCount].field_4 = 0; WallFace[WallFaceCount].nWall = nWall; WallFace[WallFaceCount].nChannel = nChannel; if (nCount > 8) { nCount = 8; } va_list piclist; va_start(piclist, nCount); while (WallFace[WallFaceCount].field_4 < nCount) { int i = WallFace[WallFaceCount].field_4; WallFace[WallFaceCount].field_4++; WallFace[WallFaceCount].field_6[i] = (short)va_arg(piclist, int); } va_end(piclist); return WallFaceCount | 0x70000; } void FuncWallFace(int a, int UNUSED(b), int nRun) { int nWallFace = RunData[nRun].nVal; assert(nWallFace >= 0 && nWallFace < kMaxWallFace); short nChannel = WallFace[nWallFace].nChannel; if ((a & 0x7F0000) != 0x10000) return; short si = sRunChannels[nChannel].c; if ((si <= WallFace[nWallFace].field_4) && (si >= 0)) { wall[WallFace[nWallFace].nWall].picnum = WallFace[nWallFace].field_6[si]; } } // done void InitPoint() { PointCount = 0; for (int i = 0; i < kMaxPoints; i++) { PointFree[i] = i; } } // done int GrabPoint() { return PointFree[PointCount++]; } // done void InitSlide() { SlideCount = kMaxSlides; for (int i = 0; i < kMaxSlides; i++) { SlideFree[i] = i; } } int IdentifySector(int nVal) { for (int i = 0; i < numsectors; i++) { for (int j = 0; ; j++) { if (j < sector[i].wallnum) { int nWall = sector[i].wallptr; if (nWall + j == nVal) return i; } else { break; } } } return -1; } int BuildSlide(int nChannel, int nStartWall, int ebx, int ecx, int nWall2, int nWall3, int nWall4) { if (SlideCount <= 0) { I_Error("Too many slides!\n"); return -1; } SlideCount--; int nSlide = SlideCount; short nSector = IdentifySector(nStartWall); SlideData2[nSlide].field_4 = -1; SlideData2[nSlide].nChannel = nChannel; SlideData2[nSlide].field_2 = -1; int nPoint = GrabPoint(); SlideData2[nSlide].field_2 = nPoint; PointList[nPoint].field_E = -1; PointList[nPoint].field_0 = nSector; short startwall = sector[nSector].wallptr; short endwall = startwall + sector[nSector].wallnum; for (int nWall = startwall; nWall < endwall; nWall++) { short ax = SlideData2[nSlide].field_2; if (ax >= 0) { while (ax >= 0) { if (wall[nWall].nextsector == PointList[ax].field_0) { break; } ax = PointList[ax].field_E; } } else { if (wall[nWall].nextsector >= 0) { nPoint = GrabPoint(); PointList[nPoint].field_E = SlideData2[nSlide].field_2; PointList[nPoint].field_0 = wall[nWall].nextsector; SlideData2[nSlide].field_2 = nPoint; } } } SlideData[nSlide].field_0 = nStartWall; SlideData[nSlide].field_4 = ebx; SlideData[nSlide].field_8 = nWall2; SlideData[nSlide].field_C = nWall3; SlideData[nSlide].x1 = wall[nStartWall].x; SlideData[nSlide].y1 = wall[nStartWall].y; SlideData[nSlide].x2 = wall[nWall2].x; SlideData[nSlide].y2 = wall[nWall2].y; SlideData[nSlide].field_20 = wall[ebx].x; SlideData[nSlide].field_24 = wall[ebx].y; SlideData[nSlide].field_28 = wall[nWall3].x; SlideData[nSlide].field_2C = wall[nWall3].y; SlideData[nSlide].field_30 = wall[ecx].x; SlideData[nSlide].field_34 = wall[ecx].y; SlideData[nSlide].field_38 = wall[nWall4].x; SlideData[nSlide].field_3C = wall[nWall4].y; int nSprite = insertsprite(nSector, 899); SlideData2[nSlide].field_6 = nSprite; sprite[nSprite].cstat = 0x8000; sprite[nSprite].x = wall[nStartWall].x; sprite[nSprite].y = wall[nStartWall].y; sprite[nSprite].z = sector[nSector].floorz; SlideData2[nSlide].field_8 = 0; return nSlide | 0x80000; } void FuncSlide(int a, int UNUSED(b), int nRun) { int nSlide = RunData[nRun].nVal; assert(nSlide >= 0 && nSlide < kMaxSlides); short nChannel = SlideData2[nSlide].nChannel; int nMessage = a & 0x7F0000; int ebp = 0; short cx = sRunChannels[nChannel].c; switch (nMessage) { case 0x10000: { if (SlideData2[nSlide].field_4 >= 0) { runlist_SubRunRec(SlideData2[nSlide].field_4); SlideData2[nSlide].field_4 = -1; } if (sRunChannels[nChannel].c && sRunChannels[nChannel].c != 1) { return; } SlideData2[nSlide].field_4 = runlist_AddRunRec(NewRun, RunData[nRun].nMoves); if (SlideData2[nSlide].field_8 != sRunChannels[nChannel].c) { D3PlayFX(StaticSound[kSound23], SlideData2[nSlide].field_6); SlideData2[nSlide].field_8 = sRunChannels[nChannel].c; } return; } case 0x20000: { int clipmask = ebp + 1; // RENAME if (cx == 1) { short nWall = SlideData[nSlide].field_4; int x = wall[nWall].x; int y = wall[nWall].y; int nSeekA = LongSeek(&x, SlideData[nSlide].field_30, 20, 20); int var_34 = nSeekA; int var_20 = nSeekA; int nSeekB = LongSeek(&y, SlideData[nSlide].field_34, 20, 20); int var_2C = nSeekB; int var_24 = nSeekB; dragpoint(SlideData[nSlide].field_4, x, y, 0); movesprite(SlideData2[nSlide].field_6, var_34 << 14, var_2C << 14, 0, 0, 0, CLIPMASK1); if (var_34 == 0) { if (var_2C == 0) { ebp = clipmask; } } nWall = SlideData[nSlide].field_0; y = wall[nWall].y + var_24; x = wall[nWall].x + var_20; dragpoint(SlideData[nSlide].field_0, x, y, 0); nWall = SlideData[nSlide].field_C; x = wall[nWall].x; y = wall[nWall].y; int nSeekC = LongSeek(&x, SlideData[nSlide].field_38, 20, 20); int var_30 = nSeekC; var_20 = nSeekC; int nSeekD = LongSeek(&y, SlideData[nSlide].field_3C, 20, 20); int edi = nSeekD; var_24 = nSeekD; dragpoint(SlideData[nSlide].field_C, x, y, 0); if (var_30 == 0 && edi == 0) { ebp++; } nWall = SlideData[nSlide].field_8; x = wall[nWall].x + var_20; y = wall[nWall].y + var_24; dragpoint(SlideData[nSlide].field_8, x, y, 0); } else if (cx == 0) // right branch { short nWall = SlideData[nSlide].field_0; int x = wall[nWall].x; int y = wall[nWall].y; int nSeekA = LongSeek(&x, SlideData[nSlide].x1, 20, 20); int edi = nSeekA; int var_1C = nSeekA; int nSeekB = LongSeek(&y, SlideData[nSlide].y1, 20, 20); int ecx = nSeekB; int var_28 = nSeekB; dragpoint(SlideData[nSlide].field_0, x, y, 0); if (edi == 0 && ecx == 0) { ebp = clipmask; } nWall = SlideData[nSlide].field_4; y = wall[nWall].y + var_28; x = wall[nWall].x + var_1C; dragpoint(SlideData[nSlide].field_4, x, y, 0); nWall = SlideData[nSlide].field_8; x = wall[nWall].x; y = wall[nWall].y; int nSeekC = LongSeek(&x, SlideData[nSlide].x2, 20, 20); edi = nSeekC; var_1C = nSeekC; int nSeekD = LongSeek(&y, SlideData[nSlide].y2, 20, 20); ecx = nSeekD; var_28 = nSeekD; dragpoint(SlideData[nSlide].field_8, x, y, 0); if (edi == 0 && ecx == 0) { ebp++; } nWall = SlideData[nSlide].field_C; y = wall[nWall].y + var_28; x = wall[nWall].x + var_1C; dragpoint(SlideData[nSlide].field_C, x, y, 0); } // loc_21A51: if (ebp >= 2) { runlist_SubRunRec(SlideData2[nSlide].field_4); SlideData2[nSlide].field_4 = -1; D3PlayFX(StaticSound[nStopSound], SlideData2[nSlide].field_6); runlist_ReadyChannel(nChannel); } return; } } } int BuildTrap(int nSprite, int edx, int ebx, int ecx) { int var_14 = edx; int var_18 = ebx; int var_10 = ecx; if (nTraps >= kMaxTraps) { I_Error("Too many traps!\n"); } short nTrap = nTraps; nTraps++; changespritestat(nSprite, 0); sprite[nSprite].cstat = 0x8000; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = 0; sprite[nSprite].extra = -1; sprite[nSprite].lotag = runlist_HeadRun() + 1; sprite[nSprite].hitag = runlist_AddRunRec(NewRun, nTrap | 0x1F0000); sprite[nSprite].owner = runlist_AddRunRec(sprite[nSprite].lotag - 1, nTrap | 0x1F0000); // GrabTimeSlot(3); sTrap[nTrap].nSprite = nSprite; sTrap[nTrap].nType = (var_14 == 0) + 14; sTrap[nTrap].field_0 = -1; nTrapInterval[nTrap] = 64 - (2 * var_10); if (nTrapInterval[nTrap] < 5) { nTrapInterval[nTrap] = 5; } sTrap[nTrap].field_C = 0; sTrap[nTrap].field_A = 0; if (var_18 == -1) { return nTrap | 0x1F0000; } sTrap[nTrap].field_6 = -1; sTrap[nTrap].field_8 = -1; short nSector = sprite[nSprite].sectnum; short nWall = sector[nSector].wallptr; int i = 0; while (1) { if (sector[nSector].wallnum >= i) { return nTrap | 0x1F0000; } if (var_18 == wall[nWall].hitag) { if (sTrap[nTrap].field_6 != -1) { sTrap[nTrap].field_8 = nWall; sTrap[nTrap].field_C = wall[nWall].picnum; return nTrap | 0x1F0000; } else { sTrap[nTrap].field_6 = nWall; sTrap[nTrap].field_A = wall[nWall].picnum; } } ecx++; nWall++; } } void FuncTrap(int a, int UNUSED(b), int nRun) { short nTrap = RunData[nRun].nVal; short nSprite = sTrap[nTrap].nSprite; int nMessage = a & 0x7F0000; switch (nMessage) { case 0x10000: { short nChannel = a & 0x3FFF; if (sRunChannels[nChannel].c > 0) { sTrap[nTrap].field_0 = 12; } else { sTrap[nTrap].field_0 = -1; } return; } case 0x20000: { if (sTrap[nTrap].field_0 >= 0) { sTrap[nTrap].field_0--; if (sTrap[nTrap].field_0 > 10) { return; } short nType = sTrap[nTrap].nType; if (sTrap[nTrap].field_0 == 0) { sTrap[nTrap].field_0 = nTrapInterval[nTrap]; if (nType == 14) { short nWall = sTrap[nTrap].field_6; if (nWall > -1) { wall[nWall].picnum = sTrap[nTrap].field_A; } nWall = sTrap[nTrap].field_8; if (nWall > -1) { wall[nWall].picnum = sTrap[nTrap].field_C; } } } else { // loc_21D92: if (sTrap[nTrap].field_0 != 5) { return; } int nBullet = BuildBullet(nSprite, nType, 0, 0, 0, sprite[nSprite].ang, 0, 1); if (nBullet > -1) { short nBulletSprite = nBullet & 0xFFFF; // isolate the sprite index (disregard top 16 bits) assert(nBulletSprite >= 0); if (nType == 15) { sprite[nBulletSprite].ang = (sprite[nBulletSprite].ang - 512) & kAngleMask; D3PlayFX(StaticSound[kSound32], nSprite); } else { sprite[nBulletSprite].clipdist = 50; short nWall = sTrap[nTrap].field_6; if (nWall > -1) { wall[nWall].picnum = sTrap[nTrap].field_A + 1; } nWall = sTrap[nTrap].field_8; if (nWall > -1) { wall[nWall].picnum = sTrap[nTrap].field_C + 1; } D3PlayFX(StaticSound[kSound36], nSprite); } } } } return; } case 0x30000: case 0x90000: case 0x80000: case 0xA0000: return; default: DebugOut("unknown msg %d for trap\n", a & 0x7F0000); return; } } int BuildArrow(int nSprite, int nVal) { return BuildTrap(nSprite, 0, -1, nVal); } int BuildFireBall(int nSprite, int a, int b) { return BuildTrap(nSprite, 1, a, b); } int BuildSpark(int nSprite, int nVal) { int var_14 = insertsprite(sprite[nSprite].sectnum, 0); if (var_14 < 0) { return -1; } assert(var_14 < kMaxSprites); sprite[var_14].x = sprite[nSprite].x; sprite[var_14].y = sprite[nSprite].y; sprite[var_14].cstat = 0; sprite[var_14].shade = -127; sprite[var_14].pal = 1; sprite[var_14].xoffset = 0; sprite[var_14].yoffset = 0; sprite[var_14].xrepeat = 50; sprite[var_14].yrepeat = 50; if (nVal >= 2) { sprite[var_14].picnum = kEnergy2; nSmokeSparks++; if (nVal == 3) { sprite[var_14].xrepeat = 120; sprite[var_14].yrepeat = 120; } else { sprite[var_14].xrepeat = sprite[nSprite].xrepeat + 15; sprite[var_14].yrepeat = sprite[nSprite].xrepeat + 15; } } else { int nAngle = (sprite[nSprite].ang + 256) - RandomSize(9); if (nVal) { sprite[var_14].xvel = Cos(nAngle) >> 5; sprite[var_14].yvel = Sin(nAngle) >> 5; } else { sprite[var_14].xvel = Cos(nAngle) >> 6; sprite[var_14].yvel = Sin(nAngle) >> 6; } sprite[var_14].zvel = -(RandomSize(4) << 7); sprite[var_14].picnum = kTile985 + nVal; } sprite[var_14].z = sprite[nSprite].z; sprite[var_14].lotag = runlist_HeadRun() + 1; sprite[var_14].clipdist = 1; sprite[var_14].hitag = 0; // GrabTimeSlot(3); sprite[var_14].extra = -1; sprite[var_14].owner = runlist_AddRunRec(sprite[var_14].lotag - 1, var_14 | 0x260000); sprite[var_14].hitag = runlist_AddRunRec(NewRun, var_14 | 0x260000); return var_14; } void FuncSpark(int a, int UNUSED(b), int nRun) { int nSprite = RunData[nRun].nVal; assert(nSprite >= 0 && nSprite < kMaxSprites); int nMessage = a & 0x7F0000; if (nMessage != 0x20000) { return; } sprite[nSprite].shade += 3; sprite[nSprite].xrepeat -= 2; if (sprite[nSprite].xrepeat >= 4 && sprite[nSprite].shade <= 100) { sprite[nSprite].yrepeat -= 2; // calling BuildSpark() with 2nd parameter as '1' will set kTile986 if (sprite[nSprite].picnum == kTile986 && (sprite[nSprite].xrepeat & 2)) { BuildSpark(nSprite, 2); } if (sprite[nSprite].picnum >= kTile3000) { return; } sprite[nSprite].zvel += 128; int nMov = movesprite(nSprite, sprite[nSprite].xvel << 12, sprite[nSprite].yvel << 12, sprite[nSprite].zvel, 2560, -2560, CLIPMASK1); if (!nMov) { return; } if (sprite[nSprite].zvel <= 0) { return; } } sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = 0; if (sprite[nSprite].picnum > kTile3000) { nSmokeSparks--; } runlist_DoSubRunRec(sprite[nSprite].owner); runlist_FreeRun(sprite[nSprite].lotag - 1); runlist_SubRunRec(sprite[nSprite].hitag); mydeletesprite(nSprite); } void DimLights() { static short word_96786 = 0; word_96786 = word_96786 == 0; if (word_96786 == 0) return; for (int i = 0; i < numsectors; i++) { if (sector[i].ceilingshade < 100) sector[i].ceilingshade++; if (sector[i].floorshade < 100) sector[i].floorshade++; short startwall = sector[i].wallptr; short endwall = startwall + sector[i].wallnum; for (int nWall = startwall; nWall < endwall; nWall++) { if (wall[nWall].shade < 100) wall[nWall].shade++; } } } void DoFinale() { static int dword_96788 = 0; static int dword_1542FC = 0; if (!lFinaleStart) return; dword_96788++; if (dword_96788 < 90) { if (!(dword_96788 & 2)) { int nAng = RandomSize(11); sprite[nFinaleSpr].ang = nAng; BuildSpark(nFinaleSpr, 1); } if (!RandomSize(2)) { PlayFX2(StaticSound[kSound78] | 0x2000, nFinaleSpr); for (int i = 0; i < nTotalPlayers; i++) { nQuake[i] = 1280; } } } else { DimLights(); if (nDronePitch <= -2400) { if (nFinaleStage < 2) { if (nFinaleStage == 1) { StopLocalSound(); PlayLocalSound(StaticSound[kSound76], 0); dword_1542FC = (int)totalclock + 120; nFinaleStage++; } } else if (nFinaleStage <= 2) { if ((int)totalclock >= dword_1542FC) { PlayLocalSound(StaticSound[kSound77], 0); nFinaleStage++; dword_1542FC = (int)totalclock + 360; } } else if (nFinaleStage == 3 && (int)totalclock >= dword_1542FC) { FinishLevel(); } } else { nDronePitch -= 128; BendAmbientSound(); nFinaleStage = 1; } } } int BuildEnergyBlock(short nSector) { short startwall = sector[nSector].wallptr; short nWalls = sector[nSector].wallnum; int x = 0; int y = 0; for (int i = 0; i < nWalls; i++) { x += wall[startwall + i].x; y += wall[startwall + i].y; wall[startwall + i].picnum = kClockSymbol16; wall[startwall + i].pal = 0; wall[startwall + i].shade = 50; } int xAvg = x / nWalls; int yAvg = y / nWalls; int nSprite = insertsprite(nSector, 406); short nextsector = wall[startwall].nextsector; sprite[nSprite].x = xAvg; sprite[nSprite].y = yAvg; sector[nSector].extra = nSprite; // GrabTimeSlot(3); sprite[nSprite].z = sector[nextsector].floorz; // CHECKME - name of this variable? int nRepeat = (sprite[nSprite].z - sector[nSector].floorz) >> 8; if (nRepeat > 255) { nRepeat = 255; } sprite[nSprite].xrepeat = nRepeat; sprite[nSprite].cstat = 0x8000; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = 0; sprite[nSprite].extra = -1; sprite[nSprite].lotag = runlist_HeadRun() + 1; sprite[nSprite].hitag = 0; sprite[nSprite].owner = runlist_AddRunRec(sprite[nSprite].lotag - 1, nSprite | 0x250000); nEnergyBlocks++; return nSprite | 0x250000; } // TODO - tidy void KillCreatures() { signed int v0; signed int v1; int i; v0 = 99; v1 = 99; while (1) { if (v0 != 100) { for (i = headspritestat[v1]; i != -1; i = nextspritestat[i]) { runlist_DamageEnemy(i, -1, 1600); } } ++v0; ++v1; if (v0 > 107) { return; } } } void ExplodeEnergyBlock(int nSprite) { short nSector = sprite[nSprite].sectnum; short startwall = sector[nSector].wallptr; short nWalls = sector[nSector].wallnum; int i; for (i = 0; i < nWalls; i++) { short nextwall = wall[startwall + i].nextwall; if (wall[nextwall].pal >= 4) { wall[nextwall].pal = 7; } else { wall[nextwall].pal = 0; } wall[nextwall].shade = 50; } if (sector[nSector].floorpal >= 4) { sector[nSector].floorpal = 7; } else { sector[nSector].floorpal = 0; } sector[nSector].floorshade = 50; sector[nSector].extra = -1; sector[nSector].floorz = sprite[nSprite].z; sprite[nSprite].z = (sprite[nSprite].z + sector[nSector].floorz) / 2; BuildSpark(nSprite, 3); sprite[nSprite].cstat = 0; sprite[nSprite].xrepeat = 100; PlayFX2(StaticSound[kSound78], nSprite); sprite[nSprite].xrepeat = 0; nEnergyTowers--; for (i = 0; i < 20; i++) { sprite[nSprite].ang = RandomSize(11); BuildSpark(nSprite, 1); // shoot out blue orbs } TintPalette(64, 64, 64); if (nEnergyTowers == 1) { runlist_ChangeChannel(nEnergyChan, nEnergyTowers); StatusMessage(1000, "TAKE OUT THE CONTROL CENTER!"); } else if (nEnergyTowers != 0) { StatusMessage(500, "%d TOWERS REMAINING", nEnergyTowers); } else { nFinaleSpr = nSprite; lFinaleStart = (int)totalclock; if (!lFinaleStart) { lFinaleStart = lFinaleStart + 1; } for (i = 0; i < numsectors; i++) { if (sector[i].ceilingpal == 1) { sector[i].ceilingpal = 0; } if (sector[i].floorpal == 1) { sector[i].floorpal = 0; } short startwall = sector[i].wallptr; short endwall = startwall + sector[i].wallnum; for (int nWall = startwall; nWall < endwall; nWall++) { if (wall[nWall].pal == 1) { wall[nWall].pal = 0; } } } KillCreatures(); } changespritestat(nSprite, 0); } void FuncEnergyBlock(int a, int nDamage, int nRun) { short nSprite = RunData[nRun].nVal; int nMessage = a & 0x7F0000; switch (nMessage) { case 0x20000: case 0x30000: case 0x90000: { return; } case 0xA0000: { short nSector = sprite[nSprite].sectnum; if (sector[nSector].extra == -1) { return; } int nFloorZ = sector[nSector].floorz; sector[nSector].floorz = sprite[nSprite].z; sprite[nSprite].z -= 256; nDamage = runlist_CheckRadialDamage(nSprite); // restore previous values sector[nSector].floorz = nFloorZ; sprite[nSprite].z += 256; if (nDamage <= 0) { return; } // fall through to case 0x80000 fallthrough__; } case 0x80000: { nDamage >>= 2; if (nDamage <= 0) { return; } if (nDamage < sprite[nSprite].xrepeat) { sprite[nSprite].xrepeat -= nDamage; int nSprite2 = insertsprite(lasthitsect, 0); sprite[nSprite2].ang = a & 0xFFFF; sprite[nSprite2].x = lasthitx; sprite[nSprite2].y = lasthity; sprite[nSprite2].z = lasthitz; BuildSpark(nSprite2, 0); // shoot out blue orb when damaged mydeletesprite(nSprite2); } else { sprite[nSprite].xrepeat = 0; // using xrepeat to store health ExplodeEnergyBlock(nSprite); } return; } } } int BuildObject(short nSprite, int nOjectType, int nHitag) { if (ObjectCount >= kMaxObjects) { I_Error("Too many objects!\n"); } short nObject = ObjectCount; ObjectCount++; changespritestat(nSprite, ObjectStatnum[nOjectType]); // 0x7FFD to ensure set as blocking ('B' and 'H') sprite and also disable translucency and set not invisible sprite[nSprite].cstat = (sprite[nSprite].cstat | 0x101) & 0x7FFD; sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = 0; sprite[nSprite].extra = -1; sprite[nSprite].lotag = runlist_HeadRun() + 1; sprite[nSprite].hitag = 0; sprite[nSprite].owner = runlist_AddRunRec(sprite[nSprite].lotag - 1, nObject | 0x170000); // GrabTimeSlot(3); if (sprite[nSprite].statnum == kStatDestructibleSprite) { ObjectList[nObject].nHealth = 4; } else { ObjectList[nObject].nHealth = 120; } ObjectList[nObject].nSprite = nSprite; ObjectList[nObject].field_4 = runlist_AddRunRec(NewRun, nObject | 0x170000); short nSeq = ObjectSeq[nOjectType]; if (nSeq > -1) { ObjectList[nObject].field_8 = SeqOffsets[nSeq]; if (!nOjectType) // if not Explosion Trigger (e.g. Exploding Fire Cauldron) { ObjectList[nObject].field_0 = RandomSize(4) % (SeqSize[ObjectList[nObject].field_8] - 1); } int nSprite2 = insertsprite(sprite[nSprite].sectnum, 0); ObjectList[nObject].field_10 = nSprite2; sprite[nSprite2].cstat = 0x8000; sprite[nSprite2].x = sprite[nSprite].x; sprite[nSprite2].y = sprite[nSprite].y; sprite[nSprite2].z = sprite[nSprite].z; } else { ObjectList[nObject].field_0 = 0; ObjectList[nObject].field_8 = -1; if (sprite[nSprite].statnum == kStatDestructibleSprite) { ObjectList[nObject].field_10 = -1; } else { ObjectList[nObject].field_10 = -nHitag; } } return nObject | 0x170000; } // in-game destructable wall mounted screen void ExplodeScreen(short nSprite) { sprite[nSprite].z -= GetSpriteHeight(nSprite) / 2; for (int i = 0; i < 30; i++) { BuildSpark(nSprite, 0); // shoot out blue orbs } sprite[nSprite].cstat = 0x8000; PlayFX2(StaticSound[kSound78], nSprite); } void FuncObject(int a, int b, int nRun) { short nObject = RunData[nRun].nVal; short nSprite = ObjectList[nObject].nSprite; short nStat = sprite[nSprite].statnum; short bx = ObjectList[nObject].field_8; int nMessage = a & 0x7F0000; switch (nMessage) { default: { DebugOut("unknown msg %d for Object\n", a & 0x7F0000); return; } case 0x30000: return; case 0x80000: { if (nStat >= 150 || ObjectList[nObject].nHealth <= 0) { return; } if (nStat == 98) { D3PlayFX((StaticSound[kSound47] | 0x2000) | (RandomSize(2) << 9), nSprite); return; } ObjectList[nObject].nHealth -= (short)b; if (ObjectList[nObject].nHealth > 0) { return; } if (nStat == kStatDestructibleSprite) { ExplodeScreen(nSprite); } else { ObjectList[nObject].nHealth = -(RandomSize(3) + 1); } return; } case 0x90000: { if (bx > -1) { seq_PlotSequence(a & 0xFFFF, bx, ObjectList[nObject].field_0, 1); } return; } case 0xA0000: { if (ObjectList[nObject].nHealth > 0 && sprite[nSprite].cstat & 0x101 && (nStat != kStatExplodeTarget || sprite[nRadialSpr].statnum == 201 || (nRadialBullet != 3 && nRadialBullet > -1) || sprite[nRadialSpr].statnum == kStatExplodeTrigger)) { int nDamage = runlist_CheckRadialDamage(nSprite); if (nDamage <= 0) { return; } if (sprite[nSprite].statnum != kStatAnubisDrum) { ObjectList[nObject].nHealth -= nDamage; } if (sprite[nSprite].statnum == kStatExplodeTarget) { sprite[nSprite].xvel = 0; sprite[nSprite].yvel = 0; sprite[nSprite].zvel = 0; } else if (sprite[nSprite].statnum != kStatAnubisDrum) { sprite[nSprite].xvel >>= 1; sprite[nSprite].yvel >>= 1; sprite[nSprite].zvel >>= 1; } if (ObjectList[nObject].nHealth > 0) { return; } if (sprite[nSprite].statnum == kStatExplodeTarget) { ObjectList[nObject].nHealth = -1; short ax = ObjectList[nObject].field_10; if (ax < 0 || ObjectList[ax].nHealth <= 0) { return; } ObjectList[ax].nHealth = -1; } else if (sprite[nSprite].statnum == kStatDestructibleSprite) { ObjectList[nObject].nHealth = 0; ExplodeScreen(nSprite); } else { ObjectList[nObject].nHealth = -(RandomSize(4) + 1); } } return; } case 0x20000: { if (nStat == 97 || (!(sprite[nSprite].cstat & 0x101))) { return; } if (nStat != kStatExplodeTarget) { Gravity(nSprite); } // do animation if (bx != -1) { ObjectList[nObject].field_0++; if (ObjectList[nObject].field_0 >= SeqSize[bx]) { ObjectList[nObject].field_0 = 0; } sprite[nSprite].picnum = seq_GetSeqPicnum2(bx, ObjectList[nObject].field_0); } if (ObjectList[nObject].nHealth >= 0) { goto FUNCOBJECT_GOTO; } ObjectList[nObject].nHealth++; if (ObjectList[nObject].nHealth) { FUNCOBJECT_GOTO: if (nStat != kStatExplodeTarget) { int nMov = movesprite(nSprite, sprite[nSprite].xvel << 6, sprite[nSprite].yvel << 6, sprite[nSprite].zvel, 0, 0, CLIPMASK0); if (sprite[nSprite].statnum == kStatExplodeTrigger) { sprite[nSprite].pal = 1; } if (nMov & 0x20000) { sprite[nSprite].xvel -= sprite[nSprite].xvel >> 3; sprite[nSprite].yvel -= sprite[nSprite].yvel >> 3; } if (((nMov & 0xC000) > 0x8000) && ((nMov & 0xC000) == 0xC000)) { sprite[nSprite].yvel = 0; sprite[nSprite].xvel = 0; } } return; } else { int var_18; // red branch if ((nStat == kStatExplodeTarget) || (sprite[nSprite].z < sector[sprite[nSprite].sectnum].floorz)) { var_18 = 36; } else { var_18 = 34; } AddFlash(sprite[nSprite].sectnum, sprite[nSprite].x, sprite[nSprite].y, sprite[nSprite].z, 128); BuildAnim(-1, var_18, 0, sprite[nSprite].x, sprite[nSprite].y, sector[sprite[nSprite].sectnum].floorz, sprite[nSprite].sectnum, 240, 4); // int edi = nSprite | 0x4000; if (nStat == kStatExplodeTrigger) { for (int i = 4; i < 8; i++) { BuildCreatureChunk(nSprite | 0x4000, seq_GetSeqPicnum(kSeqFirePot, (i >> 2) + 1, 0)); } runlist_RadialDamageEnemy(nSprite, 200, 20); } else if (nStat == kStatExplodeTarget) { for (int i = 0; i < 8; i++) { BuildCreatureChunk(nSprite | 0x4000, seq_GetSeqPicnum(kSeqFirePot, (i >> 1) + 3, 0)); } } if (levelnum <= 20 || nStat != kStatExplodeTrigger) { runlist_SubRunRec(sprite[nSprite].owner); runlist_SubRunRec(ObjectList[nObject].field_4); mydeletesprite(nSprite); return; } else { StartRegenerate(nSprite); ObjectList[nObject].nHealth = 120; sprite[nSprite].x = sprite[ObjectList[nObject].field_10].x; sprite[nSprite].y = sprite[ObjectList[nObject].field_10].y; sprite[nSprite].z = sprite[ObjectList[nObject].field_10].z; mychangespritesect(nSprite, sprite[ObjectList[nObject].field_10].sectnum); return; } } } } } void BuildDrip(int nSprite) { if (nDrips >= kMaxDrips) { I_Error("Too many drips!\n"); } sDrip[nDrips].nSprite = nSprite; sDrip[nDrips].field_2 = RandomSize(8) + 90; nDrips++; sprite[nSprite].cstat = 0x8000u; } void DoDrips() { int i; for (i = 0; i < nDrips; i++) { sDrip[i].field_2--; if (sDrip[i].field_2 <= 0) { short nSprite = sDrip[i].nSprite; short nSeqOffset = SeqOffsets[kSeqDrips]; if (!(SectFlag[sprite[nSprite].sectnum] & kSectLava)) { nSeqOffset++; } seq_MoveSequence(nSprite, nSeqOffset, RandomSize(2) % SeqSize[nSeqOffset]); sDrip[i].field_2 = RandomSize(8) + 90; } } for (i = 0; i < nBobs; i++) { sBob[i].field_2 += 4; int edx = Sin(sBob[i].field_2 << 3) >> 4; short nSector = sBob[i].nSector; if (sBob[i].field_3) { sector[nSector].ceilingz = edx + sBob[i].z; } else { int nFloorZ = sector[nSector].floorz; sector[nSector].floorz = edx + sBob[i].z; MoveSectorSprites(nSector, sector[nSector].floorz - nFloorZ); } } } void SnapBobs(short nSectorA, short nSectorB) { int ecx = -1; int ebx = ecx; // int var_14 = nSector; // int edi = edx; for (int i = 0; i < nBobs; i++) { int esi = sBob[i].nSector; if (esi != nSectorA) { if (nSectorB != esi) continue; esi = ebx; ecx = i; } else { esi = ecx; ebx = i; } if (esi != -1) { break; } } if (ecx <= -1) { return; } if (ebx <= -1) { return; } sBob[ecx].field_2 = sBob[ebx].field_2; } void AddSectorBob(int nSector, int nHitag, int bx) { if (nBobs >= kMaxBobs) { I_Error("Too many bobs!\n"); } sBob[nBobs].field_3 = bx; int z; if (bx == 0) { z = sector[nSector].floorz; } else { z = sector[nSector].ceilingz; } sBob[nBobs].z = z; sBob[nBobs].field_2 = nHitag << 4; sBobID[nBobs] = nHitag; sBob[nBobs].nSector = nSector; SectFlag[nSector] |= 0x0010; nBobs++; } // Confirmed 100% correct with original .exe int FindTrail(int nVal) { for (int i = 0; i < nTrails; i++) { if (sTrail[i].field_2 == nVal) return i; } sTrail[nTrails].field_2 = nVal; sTrail[nTrails].field_0 = -1; return nTrails++; } // ok ? void ProcessTrailSprite(int nSprite, int nLotag, int nHitag) { if (nTrailPoints >= 100) { I_Error("Too many trail point sprites (900-949)... increase MAX_TRAILPOINTS\n"); } short nPoint = nTrailPoints; nTrailPoints++; sTrailPoint[nPoint].x = sprite[nSprite].x; sTrailPoint[nPoint].y = sprite[nSprite].y; int nTrail = FindTrail(nHitag); int var_14 = nLotag - 900; nTrailPointVal[nPoint] = var_14; int field0 = sTrail[nTrail].field_0; if (field0 == -1) { sTrail[nTrail].field_0 = nPoint; sTrail[nTrail].field_4 = nPoint; nTrailPointNext[nPoint] = -1; nTrailPointPrev[nPoint] = -1; } else { int ecx = -1; while (field0 != -1) { if (nTrailPointVal[field0] > var_14) { nTrailPointPrev[nPoint] = nTrailPointPrev[field0]; nTrailPointPrev[field0] = nPoint; nTrailPointNext[nPoint] = field0; if (field0 == sTrail[nTrail].field_0) { sTrail[nTrail].field_0 = nPoint; } break; } ecx = field0; field0 = nTrailPointNext[field0]; } if (field0 == -1) { nTrailPointNext[ecx] = nPoint; nTrailPointPrev[nPoint] = ecx; nTrailPointNext[nPoint] = -1; sTrail[nTrail].field_4 = nPoint; } } mydeletesprite(nSprite); } // ok? void AddMovingSector(int nSector, int edx, int ebx, int ecx) { if (nMoveSects >= kMaxMoveSects) { I_Error("Too many moving sectors\n"); } CreatePushBlock(nSector); short nTrail = FindTrail(ebx); sMoveDir[nMoveSects] = 1; MoveSect *pMoveSect = &sMoveSect[nMoveSects]; nMoveSects++; pMoveSect->nTrail = nTrail; pMoveSect->nTrailPoint = -1; pMoveSect->field_8 = -1; pMoveSect->field_6 = ecx; pMoveSect->field_10 = (edx / 1000) + 1; pMoveSect->nSector = nSector; if (ecx & 8) { pMoveSect->field_14 = runlist_AllocChannel(ebx % 1000); } else { pMoveSect->field_14 = -1; } sector[nSector].floorstat |= 0x40; } void DoMovingSects() { for (int i = 0; i < nMoveSects; i++) { if (sMoveSect[i].nSector == -1) { continue; } if (sMoveSect[i].field_14 != -1 && !sRunChannels[sMoveSect[i].field_14].c) { continue; } short nSector = sMoveSect[i].nSector; short nBlock = sector[nSector].extra; BlockInfo *pBlockInfo = &sBlockInfo[nBlock]; if (sMoveSect[i].nTrailPoint == -1) { if (sMoveSect[i].field_6 & 0x20) { runlist_ChangeChannel(sMoveSect[i].field_14, 0); } short ax; if (sMoveSect[i].field_6 & 0x10) { sMoveDir[i] = -sMoveDir[i]; if (sMoveDir[i] > 0) { ax = sTrail[sMoveSect[i].nTrail].field_0; } else { ax = sTrail[sMoveSect[i].nTrail].field_4; } } else { ax = sTrail[sMoveSect[i].nTrail].field_0; } sMoveSect[i].nTrailPoint = ax; } short nTrail = sMoveSect[i].nTrailPoint; // TrailPoint *pTrail = &sTrailPoint[nTrail]; // loc_23872: int nAngle = GetMyAngle(sTrailPoint[nTrail].x - pBlockInfo->x, sTrailPoint[nTrail].y - pBlockInfo->y); int nXVel = (Sin(nAngle + 512) << 4) * sMoveSect[i].field_10; int nYVel = (Sin(nAngle) << 4) * sMoveSect[i].field_10; int ebx = (sTrailPoint[nTrail].x - pBlockInfo->x) << 14; int eax = nXVel; if (eax < 0) { eax = -eax; } int edx = eax; eax = ebx; int ecx = (sTrailPoint[nTrail].y - pBlockInfo->y) << 14; if (eax < 0) { eax = -eax; } // loc_238EC: if (edx <= eax) { eax = nYVel; if (eax < 0) { eax = -eax; } edx = eax; eax = ecx; if (eax < 0) { eax = -eax; } if (edx > eax) { // loc_23908: nYVel = ecx; nXVel = ebx; if (sMoveDir[i] > 0) { sMoveSect[i].nTrailPoint = nTrailPointNext[sMoveSect[i].nTrailPoint]; } else { sMoveSect[i].nTrailPoint = nTrailPointPrev[sMoveSect[i].nTrailPoint]; } } } else { // repeat of code from loc_23908 nYVel = ecx; nXVel = ebx; if (sMoveDir[i] > 0) { sMoveSect[i].nTrailPoint = nTrailPointNext[sMoveSect[i].nTrailPoint]; } else { sMoveSect[i].nTrailPoint = nTrailPointPrev[sMoveSect[i].nTrailPoint]; } } // loc_2393A: if (sMoveSect[i].field_8 != -1) { MoveSector(sMoveSect[i].field_8, -1, &nXVel, &nYVel); } int var_2C = nXVel; int var_30 = nYVel; MoveSector(nSector, -1, &nXVel, &nYVel); if (nXVel != var_2C || nYVel != var_30) { MoveSector(sMoveSect[i].field_8, -1, &var_2C, &var_30); MoveSector(sMoveSect[i].field_8, -1, &nXVel, &nYVel); } } } void PostProcess() { int i, j; for (i = 0; i < nMoveSects; i++) { int nTrail = sMoveSect[i].nTrail; sMoveSect[i].nTrailPoint = sTrail[nTrail].field_0; if (sMoveSect[i].field_6 & 0x40) { runlist_ChangeChannel(sMoveSect[i].field_14, 1); } short nSector = sMoveSect[i].nSector; if (SectFlag[nSector] & kSectUnderwater) { sector[nSector].ceilingstat |= 0x40; sector[nSector].floorstat &= 0xBFFF; for (j = 0; j < nMoveSects; j++) { if (j != i && sMoveSect[i].nTrail == sMoveSect[j].nTrail) { sMoveSect[j].field_8 = sMoveSect[i].nSector; SnapSectors(sMoveSect[j].nSector, sMoveSect[i].nSector, 0); sMoveSect[i].nSector = -1; } } } } for (i = 0; i < nBobs; i++) { if (sBob[i].field_3 == 0) { int bobID = sBobID[i]; for (j = 0; j < nBobs; j++) { if (j != i) { if (sBob[i].field_3 != 0 && sBobID[j] == bobID) { SnapSectors(i, j, 0); } } } } } if (levelnew != kMap20) { // esi is i for (i = 0; i < numsectors; i++) { int var_20 = 30000; if (SectSpeed[i] && SectDepth[i] && !(SectFlag[i] & kSectLava)) { SectSoundSect[i] = i; SectSound[i] = StaticSound[kSound43]; } else { // ebp and ecx are j for (j = 0; j < numsectors; j++) { // loc_23CA6: if (i != j && SectSpeed[j] && !(SectFlag[i] & kSectLava)) { int xVal = wall[sector[i].wallptr].x - wall[sector[j].wallptr].x; if (xVal < 0) { xVal = -xVal; } int yVal = wall[sector[i].wallptr].x - wall[sector[j].wallptr].x; if (yVal < 0) { yVal = -yVal; } if (xVal < 15000 && yVal < 15000 && (xVal + yVal < var_20)) { var_20 = xVal + yVal; SectSoundSect[i] = j; SectSound[i] = StaticSound[kSound43]; } } } } } } else // nMap == kMap20) { // int var_24 = 0; int ebp = 0; for (i = 0; i < numsectors; i++) { SectSoundSect[i] = i; SectSound[i] = StaticSound[kSound62]; int startwall = sector[ebp].wallptr; int endwall = sector[ebp].wallptr + sector[ebp].wallnum; int nWall = startwall; while (nWall < endwall) { if (wall[nWall].picnum == kTile3603) { wall[nWall].pal = 1; int nSprite = insertsprite(i, 407); sprite[nSprite].cstat = 0x8000; } nWall++; } } for (i = 0; i < kMaxSprites; i++) { if (sprite[i].statnum < kMaxStatus && sprite[i].picnum == kTile3603) { changespritestat(i, 407); sprite[i].pal = 1; } } } // esi is i for (i = 0; i < ObjectCount; i++) { int nObjectSprite = ObjectList[i].nSprite; if (sprite[nObjectSprite].statnum == kStatExplodeTarget) { if (!ObjectList[i].field_10) { ObjectList[i].field_10 = -1; } else { int edi = ObjectList[i].field_10; ObjectList[i].field_10 = -1; // ecx, ebx is j for (j = 0; j < ObjectCount; j++) { if (i != j && sprite[ObjectList[j].nSprite].statnum == kStatExplodeTarget && edi == ObjectList[j].field_10) { ObjectList[i].field_10 = j; ObjectList[j].field_10 = i; } } } } } } static SavegameHelper sgh("objects", SA(sTrap), SA(sBob), SA(sTrail), SA(sTrailPoint), SA(Elevator), SA(ObjectList), SA(sMoveSect), SA(SlideData), SA(sMoveDir), SA(WallFace), SA(SlideData2), SA(PointList), SA(nTrapInterval), SA(sBobID), SA(PointFree), SA(SlideFree), SA(nTrailPointVal), SA(nTrailPointPrev), SA(nTrailPointNext), SA(sDrip), SV(PointCount), SV(SlideCount), SV(ElevCount), SV(WallFaceCount), SV(lFinaleStart), SV(nTrailPoints), SV(nEnergyBlocks), SV(nMoveSects), SV(nFinaleStage), SV(nTrails), SV(nTraps), SV(nFinaleSpr), SV(ObjectCount), SV(nDrips), SV(nBobs), SV(nDronePitch), SV(nSmokeSparks), nullptr); END_PS_NS
24.562385
187
0.484087
[ "object" ]
f551729ea6417aea30e49459075d0ccdfd05332f
94,133
cpp
C++
D3MkEntityTree/Structure.cpp
kenjiuno/D3MkEntityTree
7df5492858c1786a1586fa06d25c89b581d8d3ff
[ "IJG" ]
null
null
null
D3MkEntityTree/Structure.cpp
kenjiuno/D3MkEntityTree
7df5492858c1786a1586fa06d25c89b581d8d3ff
[ "IJG" ]
null
null
null
D3MkEntityTree/Structure.cpp
kenjiuno/D3MkEntityTree
7df5492858c1786a1586fa06d25c89b581d8d3ff
[ "IJG" ]
null
null
null
// +-------------------------------------------------- // | // | Structure.cpp // | // | D3MkEntityTree : Copyright (c) 2004, 2005, kentaro-k.21 // | #include "StdAfx.h" #include "Structure.h" #include "OSP.h" #include "OutDeb.h" #include "Sol.h" #include "resource.h" #pragma comment(lib, "vfw32") #ifdef _DEBUG #define new DEBUG_NEW #endif #define HTML_HEADER_1 \ "<?xml version=\"1.0\" encoding=\"windows-1250\"?>\n" \ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" \ "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" \ "<head>\n" \ "<meta name=\"GENERATOR\" content=\"D3MkEntityTree\" />\n" \ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1250\" />\n" \ "</head>\n" \ "<body>\n" \ "" using namespace OSP; // -> // -> // -> // -> // ? // -> // -> // -> // -> namespace { void _InheritMap(map<CString, CString> &m0, const map<CString, CString> &m1) { map<CString, CString>::const_iterator iterPos = m1.begin(), iterEnd = m1.end(); for (; iterPos != iterEnd; iterPos++) { if (m0.find(iterPos->first) == m0.end()) { m0.insert(*iterPos); } } } }; // -> // -> // -> // -> // CSparseDef // -> // -> // -> // -> bool CSparseDef::Parse() { if (!Next()) return false; try { while (SkipAlWsComment()) { CString strToken; ForceReadTexto(strToken); CString strKey = strToken; strToken.MakeLower(); CString strName; SkipWs(); if (false); else if (strToken == "entitydef") { Parse_entityDef(); } else if (strToken == "model") { Parse_model(); } else if (strToken == "sound") { Parse_sound(); } else if (strToken == "export") { Parse_export(); } else if (strToken == "mapdef") { Parse_mapDef(); } else if (strToken == "skin") { Parse_skin(); } else if (strToken == "table") { Parse_table(); } else if (strToken == "material") { ForceReadTexto(strName); Parse_material(strName); } else if (strToken == "particle") { Parse_any(); } else if (strToken == "fx") { Parse_any(); } else if (strToken == "articulatedfigure") { Parse_any(); } else if (strToken == "pda") { Parse_any(); } else if (strToken == "video") { Parse_any(); } else if (strToken == "audio") { Parse_any(); } else if (strToken == "email") { Parse_any(); } else if (Q4() && strToken == "guide") { Parse_guide(); } else if (Q4() && strToken == "camera") { Parse_camera(); } else { Parse_material(strKey); } } return true; } catch (Error) { return false; } } bool CSparseDef::ReadText1(CString &strText, bool fQuotedCondOk) { if (fQuotedCondOk) { if (Cur() == '\"') { ReadTextQuoted(strText); return true; } } strText.Empty(); while (!IsEnd()) { int a = Cur(); if (!isalnum(a) && a != '_') break; strText += (char)a; Next(); } return strText.GetLength() != 0; } void CSparseDef::Parse_entityDef() { SkipAlWsComment(); CDoom3entityDef entityDef; if (!ReadText1(entityDef.strName)) KillMe(); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; SkipAlWsComment(); ReadTexto(strKey); SkipAlWsComment(); ReadTextTokens(strValue); // DO NOT overwrite entityDef.m.insert(make_pair(strKey, strValue)); entityDef.o.push_back(strKey); } wk.entityDefMap[entityDef.strName] = entityDef; } void CSparseDef::Parse_model() { SkipAlWsComment(); CDoom3model model; if (!ReadText1(model.strName)) KillMe(); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strToken; if (!ReadText1(strToken, true)) KillMe(); SkipWs(); if (false); else if (strToken == "mesh" || strToken == "skin" || strToken == "inherit") { CString strValue; if (!ReadTexto(strValue)) KillMe(); model.m[strToken] = strValue; } else if (strToken == "offset") { ReadTextBracketInside(model.strOffset); } else if (strToken == "channel") { CString channel, channelValue; if (!ReadText1(channel)) KillMe(); SkipWs(); ReadTextBracketInside(channelValue); model.channels[channel] = channelValue; } else if (strToken == "anim") { CString anim, animValue; if (!ReadTexto(anim)) KillMe(); while (true) { CString anim1; SkipWs(); if (!ReadTexto(anim1)) // q4 KillMe(); if (animValue.IsEmpty()) animValue = anim1; SkipWs(); if (IsMatch(',')) continue; break; }; SkipAlWsComment(); if (Cur() == '{') { Force1(SkipMidBracketContext()); } #if 0 if (IsMatch('{')) { while (!IsMatchFinally('}')) { SkipMidBracketContext(); SkipTokensUntilMidBracket(); #if 1 SkipAlWsComment(); CString strValue; if (!ReadTexto(strValue)) KillMe(); #else SkipAlWsComment(); CString frame, frameNo; if (!ReadText1(frame)) KillMe(); if (frame == "frame") { SkipWs(); if (!ReadText3(frameNo)) KillMe(); CString co, coValue; SkipWs(); if (!ReadText2(co)) KillMe(); SkipWs(); ReadText2(coValue, true); } else if (frame == "ai_no_turn") { } else if (frame == "anim_turn") { } else if (frame == "prevent_idle_override") { } else if (frame == "random_cycle_start") { } else { KillMe(); } #endif } } #endif model.anims[anim] = animValue; } } wk.modelMap[model.strName] = model; } bool CSparseDef::ReadText2(CString &strText, bool fQuotedCondOk) { if (fQuotedCondOk) { if (Cur() == '\"') { ReadTextQuoted(strText); return true; } } strText.Empty(); while (!IsEnd()) { int a = Cur(); if (!isalnum(a) && a != '_' && a != '/' && a != '.' && a != ':' && a != '\\') break; strText += (char)a; Next(); } return strText.GetLength() != 0; } void CSparseDef::ReadTextBracketInside(CString &strText) { strText.Empty(); ForceMatch('('); while (!IsMatchFinally(')', false)) { strText += (char)Cur(); Next(); } } bool CSparseDef::ReadText3(CString &strText) { strText.Empty(); while (!IsEnd()) { int a = Cur(); if (!isdigit(a) && a != '-' && a != '.') // FIXME: Ahh break; strText += (char)a; Next(); } return strText.GetLength() != 0; } void CSparseDef::Parse_sound() { SkipAlWsComment(); CString strName; if (!ReadText1(strName)) KillMe(); ForceMatch('{'); CString strKw, strValue; while (!IsMatchFinally('}')) { CString strKey, strValue; SkipAlWsComment(); if (!ReadText2(strKey)) KillMe(); SkipWs(); if (false); else if (strKey == "minDistance") { if (!ReadText3(strValue)) KillMe(); } else if (strKey == "maxDistance") { if (!ReadText3(strValue)) KillMe(); } else if (strKey == "volume") { if (!ReadText3(strValue)) KillMe(); } else if (strKey == "no_dups") { } else { } } } void CSparseDef::Parse_export() { SkipAlWsComment(); CString strName; if (!ReadText1(strName)) KillMe(); Force1(SkipMidBracketContext()); #if 0 ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey; if (!ReadText1(strKey)) KillMe(); if (false); else if (strKey == "options" || strKey == "anim" || strKey == "mesh" || strKey == "addoptions" || strKey == "camera") { CString strValue; while (true) { SkipWs(); if (IsLineBReak()) break; if (!ReadText4(strValue)) KillMe(); } } } #endif } bool CSparseDef::ReadText4(CString &strText) { strText.Empty(); while (!IsEnd()) { int a = Cur(); if (!isalnum(a) && a != '_' && a != '/' && a != '.' && a != '-') break; strText += (char)a; Next(); } return strText.GetLength() != 0; } void CSparseDef::Parse_mapDef() { SkipAlWsComment(); CString strName; if (!ReadTexto(strName)) KillMe(); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; SkipAlWsComment(); ReadTexto(strKey); SkipAlWsComment(); ReadTexto(strValue); } } void CSparseDef::Parse_any() { SkipAlWsComment(); CString strName; if (!ReadTexto(strName)) KillMe(); CString strValue; ForceMatch('{'); while (!IsMatchFinally('}')) { if (IsMatch('{')) { while (!IsMatchFinally('}')) { if (!ReadTexto(strValue)) KillMe(); } } else { if (!ReadTexto(strValue)) KillMe(); } } } void CSparseDef::Parse_skin() { SkipAlWsComment(); CDoom3skin skin; if (!ReadTexto(skin.strName)) KillMe(); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; SkipAlWsComment(); if (!ReadTexto(strKey)) KillMe(); SkipWs(); if (!ReadTexto(strValue)) { strValue = strKey; strKey = "model"; } if (false); else if (strKey == "model" || strKey == "_default") { skin.m[strKey] = strValue; } else { skin.materialArray.push_back(make_pair(strKey, strValue)); } } } void CSparseDef::Parse_material(CString strName) { strName.Replace('\\', '/'); CDoom3material mtr; mtr.strName = strName; ForceMatch('{'); while (!IsMatchFinally('}')) { if (IsMatch('{')) { Parse_indent(mtr.v); continue; } CString strKey, strValue; SkipAlWsComment(); if (!ReadTexto(strKey)) KillMe(); strKey.MakeLower(); SkipWs(); if (false); else if (false || strKey == "diffusemap" || strKey == "specularmap" || strKey == "bumpmap" ||(Q4() && strKey == "downsize") ) { CDoom3materialIndent v; Parse_map(v.tex); if (false); else if (strKey == "diffusemap") v.bf1 = bfDiffuseMap; else if (strKey == "specularmap") v.bf1 = bfSpecularMap; else if (strKey == "bumpmap") v.bf1 = bfBumpMap; else if (strKey == "downsize") v.bf1 = bfDownSize; mtr.v.push_back(v); } else if (false ) { } else { mtr.m[strKey]; SkipTokensUntilLf(); } } wk.materialMap[mtr.strName] = mtr; } void CSparseDef::Parse_indent(CDoom3materialIndentArray &v) { CDoom3materialIndent mi; while (!IsMatchFinally('}')) { CString strKey, strValue; SkipAlWsComment(); if (!ReadTexto(strKey)) KillMe(); strKey.MakeLower(); SkipWs(); if (false); else if (false || strKey == "alphatest" || strKey == "if" ) { CSparseExpr e(GetLeader()); SymList syms; if (!e.Parse(syms)) KillMe(); CExprBinder r(syms); if (r.Parse()) { if (false); else if (strKey == "alphatest") mi.soAlphaTest = r.so; else if (strKey == "if") mi.soIf = r.so; } else { printf(""); } } else if (false || strKey == "scale" || strKey == "translate" || strKey == "rotate" // || strKey == "centerscale" // || strKey == "rgb" // || strKey == "red" // || strKey == "green" // || strKey == "blue" ) { CSparseExpr e(GetLeader()); SymList syms; if (!e.Parse(syms)) KillMe(); CExprBinder r(syms); if (r.Parse()) { if (false); else if (strKey == "scale") mi.so_scale = r.so; else if (strKey == "translate") mi.so_translate = r.so; else if (strKey == "rotate") mi.so_rotate = r.so; } else { printf(""); } } else if (false || strKey == "map" ) { Parse_map(mi.tex); } else if (strKey == "blend") { if (!ReadTexto(strValue)) KillMe(); strValue.MakeLower(); if (false); else if (mi.Parse_blendf1(strValue, mi.bf1)) { printf(""); } else if (mi.Parse_blendf2(strValue, mi.bf1)) { ForceMatch(','); SkipWs(); if (!ReadTexto(strValue)) KillMe(); strValue.MakeLower(); if (!mi.Parse_blendf2(strValue, mi.bf2)) KillMe(); printf(""); } else KillMe(); } else { SkipTokensUntilLf(); } } v.push_back(mi); } void CSparseDef::Parse_table() { CString strKey; if (!ReadTexto(strKey)) KillMe(); ForceMatch('{'); SkipAlWsComment(); CDoom3table t; CString strValue; while (ReadTexto(strValue)) { if (false); else if (strValue == "clamp") t.fClamp = true; else if (strValue == "snap") t.fSnap = true; else break; SkipAlWsComment(); } int iLv = 0; if (IsMatch('{')) iLv++; if (!IsMatchFinally('}')) { for (; ; ) { SkipAlWsComment(); float x; if (ReadDecimalo(strValue)) { Force1(ParseFloat(strValue, x)); t.vec.push_back(x); } if (IsMatchFinally('}')) break; ForceMatch(','); } } if (iLv != 0) { ForceMatch('}'); } t.m = (int)t.vec.size(); wk.tableMap[strKey] = t; } void CSparseDef::Parse_map(CDoom3materialTexo &tex) { CSparseMapExpr e(GetLeader(), tex); Force1(e.Parse()); } void CSparseDef::Parse_camera() { CString strAlias; SkipWs(); ForceReadTexto(strAlias); Force1(SkipMidBracketContext()); } void CSparseDef::Parse_guide() { CString strAlias; SkipWs(); ForceReadTexto(strAlias); CString strFunc; SkipWs(); ForceReadTexto(strFunc); ForceMatch('('); while (true) { SkipAlWsComment(); CString strParm; ForceReadTexto(strParm); if (IsMatch(')')) break; ForceMatch(','); } } // -> // -> // -> // -> // CDoom3Workpad // -> // -> // -> // -> void CDoom3Workpad::CompleteInherit(CDoom3entityDef &entityDef) { CString strName = entityDef.strName; while (true) { { InheritMap::iterator iterPos = inheritMap.find(strName), iterEnd = inheritMap.end(); if (iterPos == iterEnd) break; strName = iterPos->second; } { CDoom3entityDefMap::iterator iterPos = entityDefMap.find(strName), iterEnd = entityDefMap.end(); if (iterPos == iterEnd) break; CDoom3entityDef &r = iterPos->second; _InheritMap(entityDef.m, r.m); entityDef.o.insert(entityDef.o.end(), r.o.begin(), r.o.end()); } }; } void CDoom3Workpad::CompleteInherit(CDoom3model &model) { CString strName = model.strName; while (true) { { InheritMap::iterator iterPos = inheritModelMap.find(strName), iterEnd = inheritModelMap.end(); if (iterPos == iterEnd) break; strName = iterPos->second; } { CDoom3modelMap::iterator iterPos = modelMap.find(strName), iterEnd = modelMap.end(); if (iterPos == iterEnd) break; CDoom3model &r = iterPos->second; _InheritMap(model.m, r.m); _InheritMap(model.anims, r.anims); _InheritMap(model.channels, r.channels); } } } // -> // -> // -> // -> // CSparseBase // -> // -> // -> // -> bool CSparseBase::SkipWs() { while (!IsEnd()) { int a = Cur(); if (a == ' ' || a == '\t' || a == 11) { Next(); continue; } return true; } return false; } bool CSparseBase::IsWs() { switch (Cur()) { case ' ': case '\t': case '\r': case '\n': case 11: case 0: return true; } return false; } bool CSparseBase::IsLineBReak() { switch (Cur()) { case '\r': case '\n': return true; } return false; } bool CSparseBase::IsSPC() { switch (Cur()) { case ' ': case '\t': return true; } return false; } bool CSparseBase::IsInlineComment() { if (!IsMatch('/', false)) return false; if (IsMatch('/', false)) { if (Next()) { while (true) { if (IsLineBReak()) break; if (!Next()) break; }; } return true; } if (IsMatch('*', false)) { if (!Next()) KillMe(); while (!IsEnd()) { if (IsMatch('*', false)) { if (IsMatch('/', false)) { return true; } } else { Next(); } continue; } KillMe(); } return true; } void CSparseBase::ReadTextQuoted(CString &strText) { strText.Empty(); ForceMatch('\"'); while (!IsMatchFinally('\"', false)) { strText += (char)Cur(); Next(); } } void CSparseBase::ForceMatch(char c, bool fSkipAlWs) { if (fSkipAlWs) SkipAlWsComment(); if (IsEnd() || Cur() != c) KillMe(); Next(); } bool CSparseBase::IsMatch(char c, bool fSkipAlWs) { if (fSkipAlWs) SkipAlWsComment(); if (IsEnd() || Cur() != c) return false; Next(); return true; } bool CSparseBase::IsMatchFinally(char c, bool fSkipAlWs) { if (fSkipAlWs) SkipAlWsComment(); if (IsEnd()) KillMe(); if (Cur() != c) return false; Next(); return true; } bool CSparseBase::SkipAlWsComment() { while (!IsEnd()) { if (IsWs()) { Next(); continue; } if (IsInlineComment()) { continue; } return true; } return false; } bool CSparseBase::ReadTexto(CString &strText) { if (Cur() == '\"') { ReadTextQuoted(strText); return true; } strText.Empty(); while (!IsEnd()) { int a = Cur(); if (isspace(a) || a == '{' || a == '}' || a == ',' || a == '(' || a == ')') break; strText += (char)a; Next(); } return strText.GetLength() != 0; } bool CSparseBase::ReadDecimalo(CString &strText) { strText.Empty(); while (!IsEnd()) { int a = Cur(); if (!(a == '-') && !('0' <= a && a <= '9') && !(a == '.')) break; strText += (char)a; Next(); } { int a = Cur(); if (a == 'f' || a == 'F') // q4 Next(); } return strText.GetLength() != 0; } bool CSparseBase::SkipMidBracketContext() { if (IsMatch('{')) { if (!SkipTokensUntilMidBracket()) KillMe(); while (!IsMatchFinally('}')) { if (!SkipTokensUntilMidBracket()) KillMe(); int a = Cur(); if (a == '{') { if (!SkipMidBracketContext()) KillMe(); } } return true; } return false; } bool CSparseBase::SkipTokensUntilMidBracket() { while (!IsEnd()) { int a = Cur(); if (a == '{' || a == '}') return true; Next(); } return false; } void CSparseBase::SkipTokensUntilLf() { while (true) { int a = Cur(); if (IsLineBReak() || a == '{' || a == '}') break; if (!Next()) break; } } void CSparseBase::ReadInlineTexto(CString &strText) { strText.Empty(); while (!IsLineBReak()) { int a = Cur(); if (a == '{' || a == '}') { break; } else if (a == '/') { if (Next()) { int a = Cur(); if (false); else if (a == '/') { while (Next() && !IsLineBReak()); break; } else if (a == '*') { while (true) { if (!Next()) KillMe(); { int a = Cur(); if (a != '*') continue; } if (!Next()) KillMe(); { int a = Cur(); if (a != '/') continue; } Next(); break; } break; } } } strText += (char)a; if (!Next()) { break; } } } void CSparseBase::ForceReadTexto(CString &strText) { if (!ReadTexto(strText)) KillMe(); } bool CSparseBase::ReadTextTokens(CString &strText) { CString str; strText.Empty(); ReadTexto(str); strText += str; for (; ; ) { if (!SkipWs() || Cur() != '\\') break; Next(); if (!SkipAlWsComment()) break; if (IsWs()) break; ReadTexto(str); strText += str; } return true; } // -> // -> // -> // -> // CSparseMD5Mesh // -> // -> // -> // -> bool CSparseMD5Mesh::Parse() { if (!Next()) return false; if (mesh.basejointAvail) { mesh.basejoint.m.RotationQuaternion(My3DMath::Quatern().Identify(mesh.basejoint.q)); } iCurMesh = 0; try { while (SkipAlWsComment()) { CString strKey, strValue; int nValue; if (!ReadTexto(strKey)) KillMe(); strKey.MakeLower(); SkipWs(); if (false); else if (strKey == "md5version") { if (!ReadTexto(strValue)) KillMe(); if (strValue != "10") KillMe(); } else if (strKey == "commandline") { if (!ReadTexto(strValue)) KillMe(); } else if (strKey == "numjoints") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); mesh.joints.resize(nValue); } else if (strKey == "nummeshes") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); mesh.meshes.resize(nValue); } else if (strKey == "joints") { Parse_joints(); } else if (strKey == "mesh") { Parse_mesh(); } else { KillMe(); } } return true; } catch (Error) { return false; } } void CSparseMD5Mesh::Parse_joints() { ForceMatch('{'); int iIndex = 0; while (!IsMatchFinally('}')) { if (mesh.joints.size() <= (UINT)iIndex) KillMe(); CMD5MeshJoint &j = mesh.joints[iIndex]; CString strValue; if (!ReadTexto(j.strName)) KillMe(); SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, j.iJointRef) || (j.iJointRef != -1 && mesh.joints.size() < (UINT)j.iJointRef)) KillMe(); ReadVtx3(j.ok.o); ReadVtx3(j.ok.q); j.ok.m.RotationQuaternion(My3DMath::Quatern().Identify(j.ok.q)); if (mesh.basejointAvail) { j.ok.o += mesh.basejoint.o; // j.ok.m *= mesh.basejoint.m; } iIndex++; } } void CSparseMD5Mesh::ReadVtx3(My3DMath::Vtx3 &v) { ForceMatch('('); CString str[3]; SkipWs(); if (!ReadTexto(str[0]) || !ParseFloat(str[0], v.x)) KillMe(); SkipWs(); if (!ReadTexto(str[1]) || !ParseFloat(str[1], v.y)) KillMe(); SkipWs(); if (!ReadTexto(str[2]) || !ParseFloat(str[2], v.z)) KillMe(); ForceMatch(')'); } void CSparseMD5Mesh::ReadVtx2(My3DMath::Vtx2 &v) { ForceMatch('('); CString str[2]; SkipWs(); if (!ReadTexto(str[0]) || !ParseFloat(str[0], v.x)) KillMe(); SkipWs(); if (!ReadTexto(str[1]) || !ParseFloat(str[1], v.y)) KillMe(); ForceMatch(')'); } void CSparseMD5Mesh::Parse_mesh() { if (mesh.meshes.size() <= (UINT)iCurMesh) KillMe(); CMD5MeshMesh &meshmesh = mesh.meshes[iCurMesh]; ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; int nValue; if (!ReadTexto(strKey)) KillMe(); SkipWs(); if (false); else if (strKey == "shader") { if (!ReadTexto(strValue)) KillMe(); meshmesh.m[strKey] = strValue; } else if (strKey == "numverts") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); meshmesh.verts.resize(nValue); } else if (strKey == "vert") { int iElem; if (!ReadTexto(strValue) || !ParseInt(strValue, iElem)) KillMe(); if (meshmesh.verts.size() <= (UINT)iElem) KillMe(); CMD5MeshMeshVert &vert = meshmesh.verts[iElem]; SkipWs(); ReadVtx2(vert.o); SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, vert.iWeight)) KillMe(); SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, vert.nWeights)) KillMe(); } else if (strKey == "numtris") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); meshmesh.tris.resize(nValue); } else if (strKey == "tri") { int iElem; if (!ReadTexto(strValue) || !ParseInt(strValue, iElem)) KillMe(); if (meshmesh.tris.size() <= (UINT)iElem) KillMe(); CMD5MeshMeshTri &tri = meshmesh.tris[iElem]; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, tri.v[0])) KillMe(); SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, tri.v[1])) KillMe(); SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, tri.v[2])) KillMe(); } else if (strKey == "numweights") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); meshmesh.weights.resize(nValue); } else if (strKey == "weight") { int iElem; if (!ReadTexto(strValue) || !ParseInt(strValue, iElem)) KillMe(); if (meshmesh.weights.size() <= (UINT)iElem) KillMe(); CMD5MeshMeshWeight &weight = meshmesh.weights[iElem]; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, weight.iJoint)) KillMe(); SkipWs(); if (!ReadTexto(strValue) || !ParseFloat(strValue, weight.nMass)) KillMe(); ReadVtx3(weight.o); } else { KillMe(); } } iCurMesh++; } // -> // -> // -> // -> // CHtmlMkThumb2 // -> // -> // -> // -> void CHtmlMkThumb2::MkHead(bool fHead) { if (fHead) { fprintf(f, HTML_HEADER_1 ); fprintf(f, "<table>\n" ); } else { if (iCol != -1) { fprintf(f, "</tr>\n" ); iCol = -1; } fprintf(f, "</table>\n" ); fprintf(f, "</body>\n" "</html>\n" ); } iTable = 0; } void CHtmlMkThumb2::MkTableHead(bool fHead, LPCTSTR pszName) { if (fHead) { if (pszName != NULL) { fprintf(f, "<tr>\n" "<td colspan=\"4\"><h1>%s</h1></td>\n" "</tr>\n" , (LPCSTR)pszName ); iCol = -1; } } else { if (iCol < 0) { } else { fprintf(f, "</tr>\n" ); iCol = -1; } } } void CHtmlMkThumb2::AddThumb(CString strName, CString strHref, CString strHrefThere) { if (iCol < 0) { fprintf(f, "<tr>\n" ); iCol = 0; } if (iCol == 4) { iCol = 0; fprintf(f, "</tr>\n" "<tr>\n" ); } fprintf(f, "<td>\n" "<p align=\"center\">\n" "<img src=\"%s\" width=\"120\" height=\"90\" />\n" "<br />\n" "<a href=\"%s\">%s</a>\n" "</p>\n" "</td>\n" , (LPCSTR)strHref , (LPCSTR)strHrefThere , (LPCSTR)strName ); iCol++; } // -> // -> // -> // -> // CSparseSkin // -> // -> // -> // -> bool CSparseSkin::Parse() { if (!Next()) return false; try { while (SkipAlWsComment()) { CString strToken; ReadTexto(strToken); strToken.MakeLower(); if (false); else if (strToken == "skin") { Parse_skin(); } else { KillMe(); } } return true; } catch (Error) { return false; } } void CSparseSkin::Parse_skin() { SkipAlWsComment(); CDoom3skin skin; if (!ReadTexto(skin.strName)) KillMe(); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; SkipAlWsComment(); if (!ReadTexto(strKey)) KillMe(); SkipWs(); if (!ReadTexto(strValue)) { strValue = strKey; strKey = "model"; } if (false); else if (strKey == "model" || strKey == "_default") { skin.m[strKey] = strValue; } else { skin.materialArray.push_back(make_pair(strKey, strValue)); } } } // -> // -> // -> // -> // CMD5MeshMesh // -> // -> // -> // -> void CMD5MeshMesh::InterpolateVertex(MD5MeshJointArray &j, UINT iVert, My3DMath::Vtx3 &v) { CMD5MeshMeshVert &vert = verts.at(iVert); UINT i = 0 +vert.iWeight; UINT m = i +vert.nWeights; BYTE x = 0; My3DMath::Vtx3 v0; v0.Empty(); for (; i < m; i++, x++) { CMD5MeshMeshWeight &weight = weights.at(i); CMD5MeshJoint &j0 = j.at(weight.iJoint); My3DMath::Vtx3 v1; v1 = (weight.o * j0.ok.m + j0.ok.o).Mult(weight.nMass); v0 += v1; } v = v0; } // -> // -> // -> // -> // CSparseMD5Anim // -> // -> // -> // -> bool CSparseMD5Anim::Parse() { if (!Next()) return false; try { while (SkipAlWsComment()) { CString strKey, strValue; int nValue; if (!ReadTexto(strKey)) KillMe(); strKey.MakeLower(); SkipWs(); if (false); else if (strKey == "md5version") { if (!ReadTexto(strValue)) KillMe(); if (strValue != "10") KillMe(); } else if (strKey == "commandline") { if (!ReadTexto(strValue)) KillMe(); } else if (strKey == "numframes") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); anim.frames.resize(nValue); } else if (strKey == "numjoints") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); anim.joints.resize(nValue); anim.baseframe.resize(nValue); } else if (strKey == "framerate") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); anim.nFrameRate = nValue; } else if (strKey == "numanimatedcomponents") { if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); anim.nAnimatedComp = nValue; } else if (strKey == "hierarchy") { Parse_hierarchy(); } else if (strKey == "bounds") { Parse_bounds(); } else if (strKey == "baseframe") { Parse_baseframe(); } else if (strKey == "frame") { Parse_frame(); } else { KillMe(); } } return true; } catch (Error) { return false; } } void CSparseMD5Anim::Parse_hierarchy() { SkipAlWsComment(); UINT iIndex = 0; // # bounds: frame count // # baseframe: joint count ForceMatch('{'); while (!IsMatchFinally('}')) { if (anim.joints.size() <= iIndex) KillMe(); CString strKey; if (!ReadTexto(strKey)) KillMe(); CString str1, str2, str3; int iJointRef, nFlags, iVarIndex; SkipWs(); if (!ReadTexto(str1) || !ParseInt(str1, iJointRef)) KillMe(); SkipWs(); if (!ReadTexto(str2) || !ParseInt(str2, nFlags)) KillMe(); SkipWs(); if (!ReadTexto(str3) || !ParseInt(str3, iVarIndex)) KillMe(); CMD5AnimJoint &j = anim.joints.at(iIndex); j.strName = strKey; j.iJointRef = iJointRef; j.nFlags = nFlags; j.iVarIndex = iVarIndex; iIndex++; } } void CSparseMD5Anim::Parse_bounds() { SkipAlWsComment(); UINT iIndex = 0; My3DMath::Vtx3 v; ForceMatch('{'); while (!IsMatchFinally('}')) { ReadVtx3(v); ReadVtx3(v); iIndex++; } } void CSparseMD5Anim::ReadVtx3(My3DMath::Vtx3 &v) { ForceMatch('('); CString str[3]; SkipWs(); if (!ReadTexto(str[0]) || !ParseFloat(str[0], v.x)) KillMe(); SkipWs(); if (!ReadTexto(str[1]) || !ParseFloat(str[1], v.y)) KillMe(); SkipWs(); if (!ReadTexto(str[2]) || !ParseFloat(str[2], v.z)) KillMe(); ForceMatch(')'); } void CSparseMD5Anim::Parse_baseframe() { SkipAlWsComment(); UINT iIndex = 0; ForceMatch('{'); while (!IsMatchFinally('}')) { if (anim.baseframe.size() <= iIndex || anim.joints.size() <= iIndex) KillMe(); CMD5AnimFramePatch &frm = anim.baseframe.at(iIndex); ReadVtx3(frm.o); ReadVtx3(frm.q); iIndex++; } } void CSparseMD5Anim::Parse_frame() { SkipAlWsComment(); CString strValue; int iFrame; if (!ReadTexto(strValue) || !ParseInt(strValue, iFrame)) KillMe(); if (anim.frames.size() <= 0U+iFrame) KillMe(); ForceMatch('{'); UINT i; // 0x01 Tx // 0x02 Ty // 0x04 Tz // 0x08 Qx // 0x10 Qy // 0x20 Qz MD5AnimFramePatchArray &frmvec = anim.frames.at(iFrame); frmvec = anim.baseframe; for (i = 0; i < anim.joints.size(); i++) { CMD5AnimJoint &j = anim.joints.at(i); CMD5AnimFramePatch &frm = frmvec.at(i); for (int x = 0; x < 6; x++) { if (j.nFlags & (1 << x)) { SkipAlWsComment(); float f; if (!ReadTexto(strValue) || !ParseFloat(strValue, f)) KillMe(); switch (x) { case 0: frm.o.x = f; break; case 1: frm.o.y = f; break; case 2: frm.o.z = f; break; case 3: frm.q.x = f; break; case 4: frm.q.y = f; break; case 5: frm.q.z = f; break; } } } frm.m.RotationQuaternion(My3DMath::Quatern().Identify(frm.q)); if (j.iJointRef == 0 && anim.basejointAvail && 0U+iFrame < anim.basejoint.size()) { CMD5AnimFramePatch &frmref = anim.basejoint.at(iFrame); frm.o = frm.o * frmref.m + frmref.o; frm.m = frm.m * frmref.m; } else if (!(j.iJointRef < 0)) { CMD5AnimFramePatch &frmref = frmvec.at(j.iJointRef); frm.o = frm.o * frmref.m + frmref.o; frm.m = frm.m * frmref.m; } printf(""); } ForceMatch('}'); } // -> // -> // -> // -> // CAviMk // -> // -> // -> // -> bool CAviMk::Create(CString strAvi, int nFrameRate, CSize size) { Close(); cv.cbSize = sizeof(cv); cv.dwFlags = ICMF_COMPVARS_VALID; if (cv.hic == NULL) { cv.hic = ICOpen( cv.fccType = ICTYPE_VIDEO, cv.fccHandler = MAKEFOURCC('i','v','5','0'), ICMODE_COMPRESS ); } if (cv.hic == NULL) { cv.hic = ICOpen( cv.fccType = ICTYPE_VIDEO, cv.fccHandler = MAKEFOURCC('i','v','4','1'), ICMODE_COMPRESS ); } if (cv.hic == NULL) { cv.hic = ICOpen( cv.fccType = ICTYPE_VIDEO, cv.fccHandler = MAKEFOURCC('i','v','3','2'), ICMODE_COMPRESS ); } if (cv.hic == NULL) { cv.hic = ICOpen( cv.fccType = ICTYPE_VIDEO, cv.fccHandler = MAKEFOURCC('c','v','i','d'), ICMODE_COMPRESS ); } if (cv.hic == NULL) { cv.fccType = ICTYPE_VIDEO; cv.fccHandler = comptypeDIB; } if (cv.hic != NULL) { DWORD dwICValue = 0; cv.lDataRate = 1024*32; cv.lQ = __max(-1, __min(2000, (int)ICGetDefaultQuality(cv.hic))); cv.lKey = ICGetDefaultKeyFrameRate(cv.hic); DWORD nData = ICGetStateSize(cv.hic); void *pData = GlobalAlloc(GPTR, nData); if (ICGetState(cv.hic, pData, nData) != 0) { cv.lpState = pData; cv.cbState = nData; } } fUseComp = (cv.hic != NULL); fCont = false; HRESULT hr; try { CLSID clsid = CLSID_AVIFile; hr = AVIFileOpen( &pAvif, strAvif = strAvi, 0 |OF_CREATE |OF_SHARE_DENY_WRITE |OF_READWRITE, &clsid ); if (FAILED(hr)) { fprintf(ff.f, "ERR! AVIFileOpen hr=0x%08lX\n", (ULONG)hr); throw hr; } AVISTREAMINFO avis; ZeroMemory(&avis, sizeof(avis)); avis.fccType = streamtypeVIDEO; avis.fccHandler = ICTYPE_VIDEO; avis.dwScale = 1; avis.dwRate = nFrameRate; avis.dwQuality = -1; SetRect(&avis.rcFrame, 0, 0, size.cx, size.cy); _tcscpy(avis.szName, "Vid"); hr = AVIFileCreateStream( pAvif, &pAvisVid, &avis ); if (FAILED(hr)) { fprintf(ff.f, "ERR! AVIFileCreateStream hr=0x%08lX\n", (ULONG)hr); throw hr; } BITMAPINFOHEADER &bih = bi.bmiHeader; ZeroMemory(&bi, sizeof(bi)); bih.biSize = sizeof(bih); bih.biWidth = size.cx; bih.biHeight = size.cy; bih.biPlanes = 1; bih.biBitCount = 24; bih.biCompression = BI_RGB; bih.biSizeImage = nSizeImage = 3 * size.cx * size.cy; if (fUseComp) { if (!ICSeqCompressFrameStart(&cv, &bi)) { fprintf(ff.f, "ERR! ICSeqCompressFrameStart hr=0x%08lX\n", (ULONG)hr); throw hr = E_FAIL; } fCont = true; } iCurFrame = 0; return true; } catch (HRESULT) { } return false; } void CAviMk::Close(bool fOk) { if (cv.hic) { if (fCont) { ICSeqCompressFrameEnd(&cv); } ICCompressorFree(&cv); } fCont = false; ZeroMemory(&cv, sizeof(cv)); pAvisVid = NULL; pAvif = NULL; if (!fOk && !strAvif.IsEmpty()) VERIFY(DeleteFile(strAvif)); strAvif = ""; } bool CAviMk::AddFrame(void *pvData) { HRESULT hr; if (iCurFrame == 0) { void *pHeader = &bi; int nHeader = sizeof(BITMAPINFOHEADER); if (fUseComp) { pHeader = cv.lpbiOut; nHeader = cv.lpbiOut->bmiHeader.biSize; } hr = AVIStreamSetFormat( pAvisVid, iCurFrame, pHeader, nHeader ); if (FAILED(hr)) { fprintf(ff.f, "ERR! AVIStreamSetFormat hr=0x%08lX\n", (ULONG)hr); return false; } } if (fUseComp) { BOOL fKey = false; LONG nRawData = 0; LPVOID pRawData = ICSeqCompressFrame( &cv, 0, pvData, &fKey, &nRawData ); if (pRawData == NULL) { fprintf(ff.f, "ERR! ICSeqCompressFrame\n", (ULONG)hr); return false; } LONG nSampWritten = 0; LONG nBytesWritten = 0; hr = AVIStreamWrite( pAvisVid, iCurFrame, 1, pRawData, nRawData, 0, &nSampWritten, &nBytesWritten ); if (FAILED(hr)) { fprintf(ff.f, "ERR! AVIStreamWrite hr=0x%08lX\n", (ULONG)hr); return false; } } else { LONG nSampWritten = 0; LONG nBytesWritten = 0; hr = AVIStreamWrite( pAvisVid, iCurFrame, 1, pvData, nSizeImage, 0, &nSampWritten, &nBytesWritten ); if (FAILED(hr)) { fprintf(ff.f, "ERR! AVIStreamWrite hr=0x%08lX\n", (ULONG)hr); return false; } } iCurFrame++; return true; } // -> // -> // -> // -> // CSparseExpr // -> // -> // -> // -> bool CSparseExpr::ParseToken() { if (IsLineBReak()) return false; if (!SkipWs()) return false; sym.strName.Empty(); int a = Cur(); if (false); else if (a == '.' || ('0' <= a && a <= '9')) { Parse_decimal(); return true; } else if (a == '[') { Next(); sym.sym = sym.symIndexo; return true; } else if (a == ']') { Next(); sym.sym = sym.symIndexc; return true; } else if (a == '(') { Next(); sym.sym = sym.symBracketo; return true; } else if (a == ')') { Next(); sym.sym = sym.symBracketc; return true; } else if (a == '+') { Next(); sym.sym = sym.symAdd; return true; } else if (a == '*') { Next(); sym.sym = sym.symMul; return true; } else if (a == '-') { Next(); sym.sym = sym.symSub; return true; } else if (a == '/') { if (Next()) { int a = Cur(); if (a == '/') { while (Next() && !IsLineBReak()); return false; } if (a == '*') { KillMe(); } } sym.sym = sym.symDiv; return true; } else if (a == '%') { Next(); sym.sym = sym.symMod; return true; } else if (a == '<') { if (Next()) { int a = Cur(); if (a == '=') { Next(); sym.sym = sym.symOpLEqual; return true; } } sym.sym = sym.symOpLess; return true; } else if (a == '>') { if (Next()) { int a = Cur(); if (a == '=') { Next(); sym.sym = sym.symOpGEqual; return true; } } sym.sym = sym.symOpGreater; return true; } else if (a == ',') { Next(); sym.sym = sym.symComma; return true; } else if (a == '=') { if (Next()) { int a = Cur(); if (a == '=') { Next(); sym.sym = sym.symOpEqual; return true; } } KillMe(); } else if (a == '!') { if (Next()) { int a = Cur(); if (a == '=') { Next(); sym.sym = sym.symOpNotEqual; return true; } } KillMe(); } else if (a == '&') { if (Next()) { int a = Cur(); if (a == '&') { Next(); sym.sym = sym.symOpLAnd; return true; } } KillMe(); } else if (a == '|') { if (Next()) { int a = Cur(); if (a == '|') { Next(); sym.sym = sym.symOpLOr; return true; } } KillMe(); } else if (Is_Name(a)) { Parse_name(); return true; } return false; } bool CSparseExpr::Parse(SymList &syms) { // if (!Next()) return false; try { syms.clear(); while (ParseToken()) { syms.push_back(sym); } return true; } catch (Error) { return false; } } void CSparseExpr::Parse_decimal() { while (true) { int a = Cur(); if ('0' <= a && a <= '9') { if (!Next()) break; continue; } break; } int a = Cur(); if (a == '.') { Next(); } while (true) { int a = Cur(); if ('0' <= a && a <= '9') { if (!Next()) break; continue; } break; } sym.sym = sym.symDecimal; } bool CSparseExpr::Next(bool fAccum) { if (fAccum) sym.strName += (char)Cur(); return CSparseBase::Next(); } void CSparseExpr::Parse_name() { while (!IsEnd()) { int a = Cur(); if (Is_Name(a)) { if (!Next()) break; continue; } if (a == '\"') { if (!Next(false)) KillMe(); while (true) { int a = Cur(); if (a == '\"') break; if (!Next()) KillMe(); } Next(false); } break; } sym.sym = sym.symName; } // -> // -> // -> // -> // CExprBinder // -> // -> // -> // -> bool CExprBinder::Parse() { iterPos = syms.begin(); iterEnd = syms.end(); sa = &so.var; try { while (!IsEnd()) { Parse_1(CSym::symComma, true); sa->back()->symo = CSymo::symoNo; } return true; } catch (Error) { return false; } } void CExprBinder::Parse_1(CSym::Sym symEnd, bool fRoot) { sa->push_back(new CSymo()); for (; ; ) { Parse_value(); if (IsEnd()) { if (symEnd != CSym::symNo && !fRoot) KillMe(); break; } if (Cur().sym == symEnd) { Next(); break; } Parse_op2(); } EndSymo(); } void CExprBinder::Parse_op1() { switch (Cur().sym) { case CSym::symAdd: AddSymo_ops(CSymo::symoAdd1); break; case CSym::symSub: AddSymo_ops(CSymo::symoSub1); break; default: return; } if (!Next()) { KillMe(); } } void CExprBinder::Parse_op2() { switch (Cur().sym) { case CSym::symAdd: AddSymo_ops(CSymo::symoAdd2); break; case CSym::symSub: AddSymo_ops(CSymo::symoSub2); break; case CSym::symMul: AddSymo_ops(CSymo::symoMul2); break; case CSym::symDiv: AddSymo_ops(CSymo::symoDiv2); break; case CSym::symMod: AddSymo_ops(CSymo::symoMod2); break; case CSym::symOpLess: AddSymo_ops(CSymo::symoOpLess); break; case CSym::symOpLEqual: AddSymo_ops(CSymo::symoOpLEqual); break; case CSym::symOpGreater: AddSymo_ops(CSymo::symoOpGreater); break; case CSym::symOpGEqual: AddSymo_ops(CSymo::symoOpGEqual); break; case CSym::symOpEqual: AddSymo_ops(CSymo::symoOpEqual); break; case CSym::symOpNotEqual: AddSymo_ops(CSymo::symoOpNotEqual); break; case CSym::symOpLAnd: AddSymo_ops(CSymo::symoOpLAnd); break; case CSym::symOpLOr: AddSymo_ops(CSymo::symoOpLOr); break; default: KillMe(); } if (!Next()) { KillMe(); } } void CExprBinder::Parse_value() { Parse_op1(); switch (Cur().sym) { case CSym::symDecimal: { AddSymo_var(CSymo::symoDecimal); Next(); return; } case CSym::symName: { CSym sym = Cur(); if (!Next()) KillMe(); if (Cur().sym == CSym::symIndexo) { if (!Next()) KillMe(); Parse_1(CSym::symIndexc); AddSymo_indexo(sym); } else { AddSymo_var(CSymo::symoName, sym); } return; } case CSym::symBracketo: { if (!Next()) KillMe(); Parse_1(CSym::symBracketc); AddSymo_bracketo(); return; } default: { KillMe(); } } } void CExprBinder::Printo() { Printo(so.var, 0); } void CExprBinder::Printo(SymoArray &sa, int f) { if (sa.size() == 0) return; CString str(' ', f); CString str1(' ', f+1); printf(str); puts("{"); UINT i; for (i = 0; i < sa.size(); i++) { CSymo *sa1 = sa.at(i); printf(str1); printf("%s, '%s'\n" , (LPCSTR)sa1->GetOpName() , (LPCSTR)sa1->strName ); Printo(sa1->var, f +1); } printf(str); puts("}"); } void CExprBinder::Close() { } // -> // -> // -> // -> // CEvalExpr // -> // -> // -> // -> void CEvalExpr::eval(SymoArray &sa) { UINT i; for (i = 0; i < sa.size(); i++) { CSymo *so = sa[i]; switch (so->symo) { case CSymo::symoDecimal: { vals.push_back(strtod(so->strName, NULL)); break; } case CSymo::symoName: { double r = evalNameo.EvalNameo(so->strName); vals.push_back(0); break; } case CSymo::symoIndexo: { CEvalExpr ee(evalNameo); if (ee.EvalIndexo(*so) && ee.vals.size() == 1) { double r = ee.vals[0]; r = evalTable.EvalTable(so->strName, (float)r); vals.push_back(r); } else { vals.push_back(0); } break; } case CSymo::symoAdd2: case CSymo::symoMul2: case CSymo::symoSub2: case CSymo::symoDiv2: case CSymo::symoMod2: case CSymo::symoOpEqual: case CSymo::symoOpLess: case CSymo::symoOpLEqual: case CSymo::symoOpGreater: case CSymo::symoOpGEqual: case CSymo::symoOpNotEqual: case CSymo::symoOpLAnd: case CSymo::symoOpLOr: { if (vals.size() < 2) KillMe(); double v2 = vals.back(); vals.pop_back(); double v1 = vals.back(); vals.pop_back(); double r; if (false); else if (so->symo == CSymo::symoAdd2) r = EvalOp::Add2(v1, v2); else if (so->symo == CSymo::symoMul2) r = EvalOp::Mul2(v1, v2); else if (so->symo == CSymo::symoSub2) r = EvalOp::Sub2(v1, v2); else if (so->symo == CSymo::symoDiv2) r = EvalOp::Div2(v1, v2); else if (so->symo == CSymo::symoMod2) r = EvalOp::Mod2(v1, v2); else if (so->symo == CSymo::symoOpEqual) r = EvalOp::OpEqual(v1, v2); else if (so->symo == CSymo::symoOpLess) r = EvalOp::OpLess(v1, v2); else if (so->symo == CSymo::symoOpLEqual) r = EvalOp::OpLEqual(v1, v2); else if (so->symo == CSymo::symoOpGreater) r = EvalOp::OpGreater(v1, v2); else if (so->symo == CSymo::symoOpGEqual) r = EvalOp::OpGEqual(v1, v2); else if (so->symo == CSymo::symoOpNotEqual) r = EvalOp::OpNotEqual(v1, v2); else if (so->symo == CSymo::symoOpLAnd) r = EvalOp::OpLAnd(v1, v2); else if (so->symo == CSymo::symoOpLOr) r = EvalOp::OpLOr(v1, v2); vals.push_back(r); break; } case CSymo::symoAdd1: case CSymo::symoSub1: { if (vals.size() < 1) KillMe(); double v1 = vals.back(); vals.pop_back(); double r; if (false); else if (so->symo == CSymo::symoAdd1) r = EvalOp::Add1(v1); else if (so->symo == CSymo::symoSub1) r = EvalOp::Sub1(v1); vals.push_back(r); break; } default: { KillMe(); } } } } bool CEvalExpr::Eval(SymoArray &sa) { try { eval(sa); return true; } catch (Error) { return false; } } bool CEvalExpr::Eval(CSymo &so, UINT iIdx) { if (so.var.size() <= iIdx) return false; if (so.var[iIdx]->var.size() == 0) return false; return Eval(so.var[iIdx]->var); } bool CEvalExpr::EvalIndexo(CSymo &so) { if (so.var.size() == 0) return false; return Eval(so.var); } // -> // -> // -> // -> // CSparseLWO2 // -> // -> // -> // -> bool CSparseLWO2::Parse() { try { Parse_1(); return true; } catch (Error) { return false; } } void CSparseLWO2::Parse_1() { //TRACE0("Parse_1\n"); Sure4r(*(DWORD *)"FORM"); Skip(4); Sure4r(*(DWORD *)"LWO2"); while (!IsEnd()) { DWORD x, v; Read4r(x); Read4(v); if (0) { char c[5]; *(DWORD *)c = x; c[4] = 0; TRACE1(" %s\n", c); } CSparseLWO2 mv(mesh); mv.pData = pData +iData; mv.iData = 0; mv.nData = v; mv.fLE = fLE; // if (false); else if (x == *(DWORD *)"TAGS") { mesh.at0.clear(); CString strName; while (!mv.IsEnd()) { mv.ReadName(strName); mesh.at0.push_back(strName); } } else if (x == *(DWORD *)"PNTS") { mesh.av.clear(); mesh.av.reserve(v / 12); while (!mv.IsEnd()) { CLWO2MeshVertex v; mv.ReadVtx3(v.v); mesh.av.push_back(v); } } else if (x == *(DWORD *)"PTAG") { DWORD x; mv.Read4r(x); if (x == *(DWORD *)"SURF") { while (!mv.IsEnd()) { DWORD poly; WORD texture; mv.ReadX(poly); mv.Read2(texture); if (mesh.at0.size() <= texture) KillMe(); if (mesh.ap.size() <= poly) KillMe(); mesh.ap[poly].texture = texture; } } } else if (x == *(DWORD *)"POLS") { mv.Sure4r(*(DWORD *)"FACE"); mesh.ap.clear(); mesh.ap.reserve((v - 4) / (2 * 2)); while (!mv.IsEnd()) { WORD x; mv.Read2(x); x &= 1023; CLWO2MeshPoly mp; UINT i; for (i = 0; i < x; i++) { DWORD vert; mv.ReadX(vert); CLWO2MeshPolyMap mpm; mpm.v = mpm.vt0 = vert; mp.verts.push_back(mpm); } mesh.ap.push_back(mp); } } else if (x == *(DWORD *)"VMAP") { DWORD x; mv.Read4r(x); if (x == *(DWORD *)"TXUV") { mv.Sure2(2); mv.ReadName(); DWORD vert = 0; while (!mv.IsEnd()) { mv.ReadX(vert); if (mesh.av.size() <= vert) KillMe(); CLWO2MeshVertex &v = mesh.av[vert]; mv.ReadVtx2(v.vt0); } } } else if (x == *(DWORD *)"VMAD") { DWORD x; mv.Read4r(x); if (x == *(DWORD *)"TXUV") { mv.Sure2(2); mv.ReadName(); DWORD vert = 0, poly = 0; while (!mv.IsEnd()) { mv.ReadX(vert); if (mesh.av.size() <= vert) KillMe(); mv.ReadX(poly); if (mesh.ap.size() <= poly) KillMe(); CLWO2MeshVertex mvm; UINT vt0New = mesh.av.size(); mv.ReadVtx2(mvm.vt0); mesh.av.push_back(mvm); CLWO2MeshPoly &mp = mesh.ap[poly]; UINT t; for (t = 0; t < mp.verts.size(); t++) { if (mp.verts[t].vt0 == vert) { mp.verts[t].vt0 = vt0New; } } } } } // Skip(v + (v & 1)); } } // -> // -> // -> // -> // CSparseASE // -> // -> // -> // -> bool CSparseASE::Parse() { try { Parse_1(); return true; } catch (Error) { return false; } } void CSparseASE::Parse_1() { if (!Next()) KillMe(); while (SkipAlWsComment()) { CString str; ReadLeadTexto(str); SkipWs(); CString strValue; if (false); else if (str == "3DSMAX_ASCIIEXPORT") { ForceReadTexto(strValue); if (strValue != "200") KillMe(); } else if (str == "GEOMOBJECT") { Parse_GEOMOBJECT(); } else if (str == "MATERIAL_LIST") { Parse_MATERIAL_LIST(); } else { SkipAny(); } } } void CSparseASE::Parse_GEOMOBJECT() { mesh.mza.push_back(CAseMeshGEOM()); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; ReadLeadTexto(strKey); SkipWs(); if (false); else if (strKey == "MESH") { Parse_MESH(); } else { SkipAny(); } } } void CSparseASE::Parse_MESH() { CAseMeshGEOM &mz = mesh.mza.back(); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; ReadLeadTexto(strKey); SkipWs(); int nValue; if (false); else if (strKey == "MESH_NUMVERTEX") { ForceReadTexto(strValue); if (!ParseInt(strValue, nValue)) KillMe(); mz.mva.resize(nValue); } else if (strKey == "MESH_NUMFACES") { ForceReadTexto(strValue); if (!ParseInt(strValue, nValue)) KillMe(); mz.mfa.resize(nValue); } else if (strKey == "MESH_VERTEX_LIST") { CString strKey2; ForceMatch('{'); while (!IsMatchFinally('}')) { SkipAlWsComment(); ReadLeadTexto(strKey2); if (strKey2 != "MESH_VERTEX") KillMe(); int iIdx; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, iIdx) || mz.mva.size() <= 0U +iIdx) KillMe(); CAseMeshVertex &mv = mz.mva[iIdx]; SkipWs(); if (!ReadTexto(strValue) || !ParseFloat(strValue, mv.v.x)) KillMe(); SkipWs(); if (!ReadTexto(strValue) || !ParseFloat(strValue, mv.v.y)) KillMe(); SkipWs(); if (!ReadTexto(strValue) || !ParseFloat(strValue, mv.v.z)) KillMe(); } } else if (strKey == "MESH_FACE_LIST") { CString strKey2; ForceMatch('{'); while (!IsMatchFinally('}')) { SkipAlWsComment(); ReadLeadTexto(strKey2); if (strKey2 != "MESH_FACE") KillMe(); int iIdx; SkipWs(); if (!ReadNameo(strValue) || !ParseInt(strValue, iIdx) || mz.mfa.size() <= 0U +iIdx) KillMe(); CAseMeshFace &mf = mz.mfa[iIdx]; ForceMatch(':'); while (true) { SkipWs(); if (!ReadNameo(strKey2)) break; ForceMatch(':'); if (false || strKey2 == "A" || strKey2 == "B" || strKey2 == "C" || strKey2 == "AB" || strKey2 == "BC" || strKey2 == "CA" ) { SkipWs(); if (!ReadNameo(strValue) || !ParseInt(strValue, nValue)) KillMe(); if (false); else if (strKey2 == "A") mf.v[0] = nValue; else if (strKey2 == "B") mf.v[1] = nValue; else if (strKey2 == "C") mf.v[2] = nValue; } else { KillMe(); } } SkipWs(); while (!IsLineBReak()) { SkipWs(); ReadLeadTexto(strKey2); if (false || strKey2 == "MESH_SMOOTHING" || strKey2 == "MESH_MTLID" ) { SkipWs(); ReadNameo(strValue); int nValue2; if (strKey2 == "MESH_MTLID" && ParseInt(strValue, nValue2) && 0U +nValue2 < mesh.mma.size()) { mf.tex0 = nValue2; } SkipWs(); while (IsMatch(',', false)) { SkipWs(); ReadNameo(strValue); SkipWs(); } } else { KillMe(); } } } } else if (strKey == "MESH_NUMTVERTEX") { ForceReadTexto(strValue); if (!ParseInt(strValue, nValue)) KillMe(); mz.mtva.resize(nValue); } else if (strKey == "MESH_TVERTLIST") { CString strKey2; ForceMatch('{'); while (!IsMatchFinally('}')) { SkipAlWsComment(); ReadLeadTexto(strKey2); if (strKey2 != "MESH_TVERT") KillMe(); int iIdx; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, iIdx) || mz.mtva.size() <= 0U +iIdx) KillMe(); CAseMeshTVert &mtv = mz.mtva[iIdx]; float fValue; SkipWs(); if (!ReadTexto(strValue) || !ParseFloat(strValue, fValue)) KillMe(); mtv.vt0.x = fValue; SkipWs(); if (!ReadTexto(strValue) || !ParseFloat(strValue, fValue)) KillMe(); mtv.vt0.y = fValue; SkipWs(); if (!ReadTexto(strValue) || !ParseFloat(strValue, fValue)) KillMe(); printf(""); } } else if (strKey == "MESH_NUMTVFACES") { ForceReadTexto(strValue); if (!ParseInt(strValue, nValue)) KillMe(); ASSERT(mz.mfa.size() == nValue); } else if (strKey == "MESH_TFACELIST") { CString strKey2; ForceMatch('{'); while (!IsMatchFinally('}')) { SkipAlWsComment(); ReadLeadTexto(strKey2); if (strKey2 != "MESH_TFACE") KillMe(); int iIdx; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, iIdx) || mz.mfa.size() <= 0U +iIdx) KillMe(); CAseMeshFace &mf = mz.mfa[iIdx]; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); mf.tf[0] = nValue; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); mf.tf[1] = nValue; SkipWs(); if (!ReadTexto(strValue) || !ParseInt(strValue, nValue)) KillMe(); mf.tf[2] = nValue; } } else { SkipAny(); } }; } void CSparseASE::Parse_MATERIAL_LIST() { ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; ReadLeadTexto(strKey); SkipWs(); int nValue; if (false); else if (strKey == "MATERIAL_COUNT") { ForceReadTexto(strValue); if (!ParseInt(strValue, nValue)) KillMe(); mesh.mma.resize(nValue); } else if (strKey == "MATERIAL") { int iMaterial; ForceReadTexto(strValue); if (!ParseInt(strValue, iMaterial)) KillMe(); if (mesh.mma.size() <= 0U +iMaterial) KillMe(); ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; ReadLeadTexto(strKey); SkipWs(); if (false); else if (strKey == "MAP_DIFFUSE") { ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; ReadLeadTexto(strKey); SkipWs(); if (false); else if (strKey == "BITMAP") { CString strTex; ForceReadTexto(strTex); mesh.mma[iMaterial].strTex = strTex; } else { SkipAny(); } } } else { SkipAny(); } } } else { SkipAny(); } }; } bool CSparseASE::ReadNameo(CString &strText) { strText.Empty(); while (!IsEnd()) { int a = Cur(); if (!isalnum(a) && a != '_') break; strText += (char)a; Next(); } return strText.GetLength() != 0; } void CSparseASE::SkipAny(int nLv) { CString str; for (; ; ) { if (!SkipWs()) { if (nLv == 0) break; if (!Next()) KillMe(); continue; } if (IsLineBReak()) { if (nLv == 0) break; if (!Next()) KillMe(); continue; } int a = Cur(); if (a == '{') { if (!Next()) KillMe(); SkipAny(nLv +1); continue; } if (a == '}') { if (nLv == 0) KillMe(); if (!Next()) KillMe(); break; } if (a == '*') { ReadLeadTexto(str); continue; } if (!ReadTexto(str)) { KillMe(); } } } namespace MSHPP { // -> // -> // -> // -> // CHHKMk // -> // -> // -> // -> void CHHKMk::MkHeader(bool fHeader) { if (fHeader) { fprintf(f, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\" \"\">" "<HTML>" "<BODY>" "<OBJECT type=\"text/site properties\">" "<param name=\"ImageType\" value=\"Folder\" />" "</OBJECT>" "<UL>\n" ); } else { fprintf(f, "</UL>" "</BODY>" "</HTML>\n" ); } } void CHHKMk::StartKw(LPCSTR pszDispName) { fprintf(f, "<LI>" "<OBJECT type=\"text/sitemap\">" "<param name=\"Name\" value=\"%s\" />\n" , pszDispName ); } void CHHKMk::WriteKwHref(LPCSTR pszDispAlt, LPCSTR pszHref) { fprintf(f, "<param name=\"Name\" value=\"%s\" />" "<param name=\"Local\" value=\"%s\" />\n" , pszDispAlt , pszHref ); } void CHHKMk::EndKw() { fprintf(f, "</OBJECT>" "</LI>\n" ); } // -> // -> // -> // -> // CHHCMk // -> // -> // -> // -> void CHHCMk::MkHeader(bool fHeader) { if (fHeader) { fprintf(f, "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\" \"\">" "<HTML>" "<BODY>" "<OBJECT type=\"text/site properties\">" "<param name=\"ImageType\" value=\"Folder\" />\n" "</OBJECT>" "<UL>\n" ); } else { fprintf(f, "</UL>" "</BODY>" "</HTML>\n" ); } } void CHHCMk::StartDir(LPCSTR pszDispName, LPCSTR pszHref) { fprintf(f, "<LI>" "<OBJECT type=\"text/sitemap\">" "<param name=\"Name\" value=\"%s\" />" "<param name=\"%s\" value=\"%s\" />\n" "</OBJECT>" "</LI>" "<UL>\n" , pszDispName ,(pszHref != NULL) ? "Local" : "_Local_" , pszHref ); } void CHHCMk::WriteItem(LPCSTR pszDispName, LPCSTR pszHref) { fprintf(f, "<LI>" "<OBJECT type=\"text/sitemap\">" "<param name=\"Name\" value=\"%s\" />" "<param name=\"Local\" value=\"%s\" />\n" "</OBJECT>" "</LI>\n" , pszDispName , pszHref ); } void CHHCMk::EndDir() { fprintf(f, "</UL>\n" ); } // -> // -> // -> // -> // CHHPMk // -> // -> // -> // -> bool CHHPMk::Mk(LPCSTR pszFiles) { SizeBuff sb; if (!Sol::ExtractResource(MAKEINTRESOURCE(rhw.gethhpres()), "DATA", sb)) return false; SetEnvironmentVariable("FILES_HERE", "\r\n"); // SetEnvironmentVariable("FILES_HERE", pszFiles); DWORD r1 = ExpandEnvironmentStrings((LPSTR)sb.GetData(), NULL, 0); if (r1 == 0) return false; SizeBuff sbNew(r1); DWORD r2 = ExpandEnvironmentStrings((LPSTR)sb.GetData(), (LPSTR)sbNew.GetData(), sbNew.GetSize()); if (r2 == 0) return false; if (fwrite(sbNew.GetData(), r2 -1, 1, f) != 1) return false; return true; } // -> // -> // -> // -> // CHHKTemplate // -> // -> // -> // -> bool CHHKTemplate::Commit(CHHKMk &mk) { KwMMap::iterator iterPos = kmm.begin(), iterEnd = kmm.end(); for (; iterPos != iterEnd; ) { KwMMap::iterator iterHi = kmm.upper_bound(iterPos->first); mk.StartKw(iterPos->first); for (; iterPos != iterHi; iterPos++) { mk.WriteKwHref(iterPos->first, iterPos->second); } mk.EndKw(); } return true; } // -> // -> // -> // -> // CHHCTemplate // -> // -> // -> // -> bool CHHCTemplate::Commit(CHHCMk &mk) { mk.WriteItem("index.html", "index.html"); if (km_entityDef.size() != 0) { mk.StartDir("entityDef", NULL); { KwMMap::iterator iterPos = km_entityDef.begin(), iterEnd = km_entityDef.end(); for (; iterPos != iterEnd; iterPos++) { mk.WriteItem(iterPos->first, iterPos->second); } } mk.EndDir(); } // KwMMap::iterator // iterPos = km_entityDef.begin(), // iterEnd = km_entityDef.end(); // for (; iterPos != iterEnd; ) { // KwMMap::iterator // iterHi = km_entityDef.upper_bound(iterPos->first); // mk.StartDir(iterPos->first, NULL); // for (; iterPos != iterHi; iterPos++) { // mk.WriteItem(iterPos->first, iterPos->second); // } // mk.EndDir(); // } if (km_Mapobject.size() != 0) { mk.StartDir("Mapobject", NULL); { KwMMap::iterator iterPos = km_Mapobject.begin(), iterEnd = km_Mapobject.end(); for (; iterPos != iterEnd; iterPos++) { mk.WriteItem(iterPos->first, iterPos->second); } } mk.EndDir(); } return true; } // -> // -> // -> // -> // CHHPTemplate // -> // -> // -> // -> bool CHHPTemplate::Commit(CHHPMk &mk) { CString str; FileList::iterator iterPos = files.begin(), iterEnd = files.end(); for (; iterPos != iterEnd; iterPos++) { str += *iterPos + "\r\n"; } if (!mk.Mk(str)) return false; return true; } }; // namespace MSHPP // -> // -> // -> // -> // CMaterialStats // -> // -> // -> // -> void CMaterialStats::Run() { DataMap m; FILE *f = fopen(OSP_JoinPath(OSP_GetDir(OSP_GetModuleFileName(NULL)), "MatUsed.txt"), "wt"); { CDoom3materialMap::const_iterator iterPos = wk.materialMap.begin(), iterEnd = wk.materialMap.end(); for (; iterPos != iterEnd; iterPos++) { const CDoom3materialIndentArray &mia = iterPos->second.v; DataArray v(mia.size()); UINT i; for (i = 0; i < mia.size(); i++) { Data &r = v[i]; const CDoom3materialIndent &mi = mia[i]; r.bf1 = mi.bf1; r.bf2 = mi.bf2; } m[v].cx++; m[v].names.push_back(iterPos->first); } } DataRMMap rmm; { DataMap::iterator iterPos = m.begin(), iterEnd = m.end(); for (; iterPos != iterEnd; iterPos++) rmm.insert(make_pair(iterPos->second, iterPos->first)); } if (f) { fprintf(f, "<table cellpadding=\"5\" cellspacing=\"1\">\n" "<tr><th>1</th><th>2</th><th>3</th></tr>\n" ); DataRMMap::iterator iterPos = rmm.begin(), iterEnd = rmm.end(); for (; iterPos != iterEnd; iterPos++) { fprintf(f, "<tr><td valign=\"top\">\n" ); DataArray &v = iterPos->second; UINT i; for (i = 0; i < v.size(); i++) { fprintf(f, (v[i].bf2 == bfNo) ? "%s" : "%s,%s" , GetBlendfName(v[i].bf1) , GetBlendfName(v[i].bf2) ); if (i +1 != v.size()) fprintf(f, "<br>"); } fprintf(f, "</td>\n" ); MaterialDistributionRMMap mrmm; list<CString>::const_iterator iter2Pos = iterPos->first.names.begin(), iter2End = iterPos->first.names.end(); for (; iter2Pos != iter2End; iter2Pos++) { MaterialDistributionMMap::const_iterator iter3Pos = mm.find(*iter2Pos), iter3End = mm.end(); if (iter3Pos == iter3End) { mrmm.insert(make_pair(0, *iter2Pos)); } else { mrmm.insert(make_pair(iter3Pos->second, iter3Pos->first)); } } fprintf(f, "<td valign=\"top\">\n" ); { UINT x = 0, cx = mrmm.size(); MaterialDistributionRMMap::iterator iter4Pos = mrmm.begin(), iter4End = mrmm.end(); for (; iter4Pos != iter4End && x < 10; iter4Pos++, x++) { fprintf(f, "%s%s\n" , (x != 0) ? "<br>" : "" , (LPCSTR)iter4Pos->second ); } } fprintf(f, "</td>\n" ); fprintf(f, "<td valign=\"top\">%d</td>\n" , 0U +iterPos->first.cx ); } fprintf(f, "</table>\n" ); } if (f) fclose(f); } // -> // -> // -> // -> // CSparseV2Map // -> // -> // -> // -> bool CSparseV2Map::Parse() { if (!Next()) return false; try { Parse_1(); return true; } catch (Error) { return false; } } void CSparseV2Map::Parse_1() { CString strKey, strValue, strTex, strBind; ForceReadTexto(strKey); SkipWs(); ForceReadTexto(strValue); if (strKey != "Version") KillMe(); if (strValue == "2") { iVer = 2; } else if (fq4 && strValue == "3") { iVer = 3; } else { KillMe(); } StrSet_t ss; while (SkipAlWsComment()) { CV2MapEntity &entity = *(mesh.ea.insert(mesh.ea.end(), CV2MapEntity())); ForceMatch('{'); while (!IsMatchFinally('}')) { SkipAlWsComment(); if (ReadTexto(strKey)) { SkipWs(); ForceReadTexto(strValue); strKey.MakeLower(); entity.m[*(ss.insert(strKey).first)] = *(ss.insert(strValue).first); } else { ForceMatch('{'); SkipAlWsComment(); ForceReadTexto(strKey); if (false); else if (strKey == "brushDef3") { V2MapBrushArray_t &va = entity.va; va.push_back(CV2MapBrush()); CV2MapBrush &vv = va.back(); ForceMatch('{'); while (!IsMatchFinally('}')) { vv.pa.push_back(CV2MapPlane()); CV2MapPlane &vp = vv.pa.back(); ForceMatch('('); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.v.x))); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.v.y))); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.v.z))); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.fr))); ForceMatch(')'); ForceMatch('('); ForceMatch('('); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.m32[0][0]))); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.m32[0][1]))); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.m32[0][2]))); ForceMatch(')'); ForceMatch('('); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.m32[1][0]))); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.m32[1][1]))); SkipWs(); Force1((ForceReadTexto(strValue), ParseFloat(strValue, vp.m32[1][2]))); ForceMatch(')'); ForceMatch(')'); SkipWs(); ForceReadTexto(strValue); vp.strTex = *(ss.insert(strValue).first); if (iVer == 2) { SkipWs(); ForceReadTexto(strValue); SkipWs(); ForceReadTexto(strValue); SkipWs(); ForceReadTexto(strValue); } if (fStat) mm[strTex]++; } } else if (strKey == "patchDef3") { V2MapPatchDef3Array_t &p3a = entity.p3a; p3a.push_back(CV2MapPatchDef3()); CV2MapPatchDef3 &p3 = p3a.back(); p3.fIs3 = true; int cx; int cy; ForceMatch('{'); SkipAlWsComment(); ForceReadTexto(strTex); ForceMatch('('); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, cy)); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, cx)); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[0])); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[1])); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[2])); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[3])); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[4])); ForceMatch(')'); Force1(cx > 0 && cy > 0); p3.cx = cx; p3.cy = cy; p3.ca.resize(cx*cy); p3.strTex = strTex; ForceMatch('('); for (int y = 0; y < cy; y++) { ForceMatch('('); for (int x = 0; x < cx; x++) { CV2MapPatchDef3Coord &p3c = p3.ca[x +cx*y]; ForceMatch('('); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.v.x)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.v.y)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.v.z)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.tv.x)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.tv.y)); ForceMatch(')'); } ForceMatch(')'); } ForceMatch(')'); ForceMatch('}'); if (fStat) mm[strTex]++; } else if (strKey == "patchDef2") { V2MapPatchDef3Array_t &p3a = entity.p3a; p3a.push_back(CV2MapPatchDef3()); CV2MapPatchDef3 &p3 = p3a.back(); p3.fIs3 = false; p3.t[3] = p3.t[4] = 0; int cx; int cy; ForceMatch('{'); SkipAlWsComment(); ForceReadTexto(strTex); ForceMatch('('); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, cy)); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, cx)); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[0])); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[1])); SkipWs(); ForceReadTexto(strValue); Force1(ParseInt(strValue, p3.t[2])); ForceMatch(')'); Force1(cx > 0 && cy > 0); p3.cx = cx; p3.cy = cy; p3.ca.resize(cx*cy); p3.strTex = strTex; ForceMatch('('); for (int y = 0; y < cy; y++) { ForceMatch('('); for (int x = 0; x < cx; x++) { CV2MapPatchDef3Coord &p3c = p3.ca[x +cx*y]; ForceMatch('('); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.v.x)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.v.y)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.v.z)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.tv.x)); SkipWs(); ForceReadTexto(strValue); Force1(ParseFloat(strValue, p3c.tv.y)); ForceMatch(')'); } ForceMatch(')'); } ForceMatch(')'); ForceMatch('}'); if (fStat) mm[strTex]++; } else { KillMe(); } ForceMatch('}'); } } entity.o.Empty(); entity.rotation.Identity(); entity.fHasBind = false; if (Sol::GetValue(entity.m, "name", strValue) && strValue.GetLength() > 0) { entity.strName = strValue; mesh.em[strValue] = &entity; if (Sol::GetValue(entity.m, "bind", strBind) && strBind.GetLength() > 0) { entity.fHasBind = true; mesh.vrmm.insert(make_pair(strBind, strValue)); mesh.vs.insert(strBind); } } if (Sol::GetValue(entity.m, "origin", strValue)) { if (3 != sscanf(strValue, "%f %f %f", &entity.o.x, &entity.o.y, &entity.o.z)) { entity.o.Empty(); } } float fAngle; if (Sol::GetValue(entity.m, "angle", strValue) && ParseFloat(strValue, fAngle)) { entity.rotation.RotateZ(entity.rotation, (180.f + fAngle) /180.f *3.14f); } if (Sol::GetValue(entity.m, "rotation", strValue)) { if (9 != sscanf(strValue, "%f %f %f %f %f %f %f %f %f" , &entity.rotation._11 , &entity.rotation._12 , &entity.rotation._13 , &entity.rotation._21 , &entity.rotation._22 , &entity.rotation._23 , &entity.rotation._31 , &entity.rotation._32 , &entity.rotation._33 ) ) { entity.rotation.Identity(); } else { // My3DMath::Mtx m; // m.RotateZ(m, 180); // entity.rotation = entity.rotation * m; } } } printf(""); } namespace NfMD5 { // -> // -> // -> // -> // ParseMD5Mesh_t // -> // -> // -> // -> bool ParseMD5Mesh_t::Parse() { if (!Next()) return false; iCurMesh = 0; try { while (SkipAlWsComment()) { CString strKey, strValue; int nValue; if (!ReadTexto(strKey)) KillMe(); strKey.MakeLower(); SkipWs(); if (false); else if (strKey == "md5version") { Force1((ForceReadTexto(strValue), strValue == "10")); } else if (strKey == "commandline") { Force1((ForceReadTexto(strValue), true)); } else if (strKey == "numjoints") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); mesh.aJ.resize(nValue); } else if (strKey == "nummeshes") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); mesh.aM.resize(nValue); } else if (strKey == "joints") { Parse_joints(); } else if (strKey == "mesh") { Parse_mesh(); } else { KillMe(); } } return true; } catch (Error) { return false; } } void ParseMD5Mesh_t::Parse_joints() { ForceMatch('{'); int iIndex = 0; while (!IsMatchFinally('}')) { if (mesh.aJ.size() <= (UINT)iIndex) KillMe(); MD5MeshJoint_t &j = mesh.aJ[iIndex]; CString strValue; ForceReadTexto(j.strName); SkipWs(); Force1((ForceReadTexto(strValue), ParseInt(strValue, j.iJ) && (j.iJ == -1 || (UINT)j.iJ < mesh.aJ.size()))); My3DMath::Vtx3 q; ReadVtx3(j.o); ReadVtx3(q); j.q.Identify(q); j.pRefJ = (j.iJ < 0) ? NULL : &mesh.aJ.at(j.iJ) ; iIndex++; } } void ParseMD5Mesh_t::ReadVtx3(My3DMath::Vtx3 &v) { ForceMatch('('); CString str[3]; SkipWs(); if (!ReadTexto(str[0]) || !ParseFloat(str[0], v.x)) KillMe(); SkipWs(); if (!ReadTexto(str[1]) || !ParseFloat(str[1], v.y)) KillMe(); SkipWs(); if (!ReadTexto(str[2]) || !ParseFloat(str[2], v.z)) KillMe(); ForceMatch(')'); } void ParseMD5Mesh_t::ReadVtx2(My3DMath::Vtx2 &v) { ForceMatch('('); CString str[2]; SkipWs(); if (!ReadTexto(str[0]) || !ParseFloat(str[0], v.x)) KillMe(); SkipWs(); if (!ReadTexto(str[1]) || !ParseFloat(str[1], v.y)) KillMe(); ForceMatch(')'); } void ParseMD5Mesh_t::Parse_mesh() { if (mesh.aM.size() <= (UINT)iCurMesh) KillMe(); MD5MeshModel_t &mm = mesh.aM[iCurMesh]; ForceMatch('{'); while (!IsMatchFinally('}')) { CString strKey, strValue; int nValue; ForceReadTexto(strKey); SkipWs(); if (false); else if (strKey == "shader") { ForceReadTexto(mm.strShader); } else if (strKey == "numverts") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); mm.aV.resize(nValue); } else if (strKey == "vert") { int iElem; Force1((ForceReadTexto(strValue), ParseInt(strValue, iElem))); Force1((UINT)iElem < mm.aV.size()); MD5MeshVert_t &mv = mm.aV[iElem]; SkipWs(); ReadVtx2(mv.o); SkipWs(); Force1(ReadTexto(strValue) && ParseInt(strValue, mv.iW)); SkipWs(); Force1(ReadTexto(strValue) && ParseInt(strValue, mv.nW)); } else if (strKey == "numtris") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); mm.aT.resize(nValue); } else if (strKey == "tri") { int iElem; Force1((ForceReadTexto(strValue), ParseInt(strValue, iElem))); Force1((UINT)iElem < mm.aT.size()); MD5MeshTri_t &mt = mm.aT[iElem]; SkipWs(); Force1(ReadTexto(strValue) && ParseInt(strValue, mt.iV[0])); SkipWs(); Force1(ReadTexto(strValue) && ParseInt(strValue, mt.iV[1])); SkipWs(); Force1(ReadTexto(strValue) && ParseInt(strValue, mt.iV[2])); Force1((UINT)mt.iV[0] < mm.aV.size()); Force1((UINT)mt.iV[1] < mm.aV.size()); Force1((UINT)mt.iV[2] < mm.aV.size()); mt.pV[0] = &mm.aV.at(mt.iV[0]); mt.pV[1] = &mm.aV.at(mt.iV[1]); mt.pV[2] = &mm.aV.at(mt.iV[2]); } else if (strKey == "numweights") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); mm.aW.resize(nValue); } else if (strKey == "weight") { int iElem; Force1((ForceReadTexto(strValue), ParseInt(strValue, iElem))); Force1((UINT)iElem < mm.aW.size()); MD5MeshWeight_t &mw = mm.aW[iElem]; SkipWs(); Force1(ReadTexto(strValue) && ParseInt(strValue, mw.iJ)); SkipWs(); Force1(ReadTexto(strValue) && ParseFloat(strValue, mw.nMass)); ReadVtx3(mw.o); Force1((UINT)mw.iJ < mesh.aJ.size()); mw.pJ = &mesh.aJ.at(mw.iJ); } else { KillMe(); } } { size_t i; for (i = 0; i < mm.aV.size(); i++) { MD5MeshVert_t &mv = mm.aV[i]; Force1((UINT)(mv.iW + mv.nW) <= mm.aW.size()); size_t x, cx = (size_t)mv.nW; mv.ppW.resize(cx); for (x = 0; x < cx; x++) mv.ppW.at(x) = &mm.aW.at(mv.iW + x); } } iCurMesh++; } // -> // -> // -> // -> // ParseMD5Anim_t // -> // -> // -> // -> bool ParseMD5Anim_t::Parse() { if (!Next()) return false; try { while (SkipAlWsComment()) { CString strKey, strValue; int nValue; ForceReadTexto(strKey); strKey.MakeLower(); SkipWs(); if (false); else if (strKey == "md5version") { Force1((ForceReadTexto(strValue), strValue == "10")); } else if (strKey == "commandline") { Force1((ForceReadTexto(strValue), true)); } else if (strKey == "numframes") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); anim.framea.resize(nValue); anim.bounda.resize(nValue); } else if (strKey == "numjoints") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); anim.jointa.resize(nValue); anim.baseframe.resize(nValue); } else if (strKey == "framerate") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); anim.nFrameRate = nValue; } else if (strKey == "numanimatedcomponents") { Force1((ForceReadTexto(strValue), ParseInt(strValue, nValue))); anim.nAnimatedComp = nValue; } else if (strKey == "hierarchy") { Parse_hierarchy(); } else if (strKey == "bounds") { Parse_bounds(); } else if (strKey == "baseframe") { Parse_baseframe(); } else if (strKey == "frame") { Parse_frame(); } else { KillMe(); } } return true; } catch (Error) { return false; } } void ParseMD5Anim_t::Parse_hierarchy() { SkipAlWsComment(); UINT iIndex = 0; // # bounds: frame count // # baseframe: joint count ForceMatch('{'); while (!IsMatchFinally('}')) { Force1(iIndex < anim.jointa.size()); CString strKey; ForceReadTexto(strKey); CString str1, str2, str3; int iJointRef, nFlags, iVarIndex; SkipWs(); Force1((ForceReadTexto(str1), ParseInt(str1, iJointRef))); SkipWs(); Force1((ForceReadTexto(str1), ParseInt(str1, nFlags))); SkipWs(); Force1((ForceReadTexto(str1), ParseInt(str1, iVarIndex))); Force1(iJointRef < 0 || ((UINT)iJointRef < anim.jointa.size())); MD5AnimJoint_t &j = anim.jointa.at(iIndex); j.strName = strKey; j.iRefJ = iJointRef; j.f6 = nFlags; j.pRefJ = (iJointRef < 0) ? NULL : &anim.jointa.at(iJointRef) ; iIndex++; } } void ParseMD5Anim_t::Parse_bounds() { SkipAlWsComment(); UINT iIndex = 0; My3DMath::Vtx3 v; ForceMatch('{'); while (!IsMatchFinally('}')) { Force1(iIndex < anim.bounda.size()); MD5AnimBound_t &r = anim.bounda[iIndex]; ReadVtx3(r.vmin); ReadVtx3(r.vmax); iIndex++; } } void ParseMD5Anim_t::ReadVtx3(My3DMath::Vtx3 &v) { ForceMatch('('); CString str[3]; SkipWs(); if (!ReadTexto(str[0]) || !ParseFloat(str[0], v.x)) KillMe(); SkipWs(); if (!ReadTexto(str[1]) || !ParseFloat(str[1], v.y)) KillMe(); SkipWs(); if (!ReadTexto(str[2]) || !ParseFloat(str[2], v.z)) KillMe(); ForceMatch(')'); } void ParseMD5Anim_t::Parse_baseframe() { SkipAlWsComment(); UINT iIndex = 0; ForceMatch('{'); while (!IsMatchFinally('}')) { Force1(iIndex < anim.baseframe.size() && iIndex < anim.jointa.size()); MD5AnimPatch_t &e = anim.baseframe.at(iIndex); My3DMath::Vtx3 q; ReadVtx3(e.o); ReadVtx3(e.p); iIndex++; } } void ParseMD5Anim_t::Parse_frame() { SkipAlWsComment(); CString strValue; int iFrame; Force1((ForceReadTexto(strValue), ParseInt(strValue, iFrame))); Force1((UINT)iFrame < anim.framea.size()); ForceMatch('{'); UINT i; // 0x01 Tx // 0x02 Ty // 0x04 Tz // 0x08 Qx // 0x10 Qy // 0x20 Qz MD5AnimFrame_t &f = anim.framea.at(iFrame); f = anim.baseframe; for (i = 0; i < anim.jointa.size(); i++) { MD5AnimJoint_t &j = anim.jointa.at(i); MD5AnimPatch_t &e = f.at(i); for (int x = 0; x < 6; x++) { if (j.f6 & (1 << x)) { SkipAlWsComment(); float f; Force1((ForceReadTexto(strValue), ParseFloat(strValue, f))); switch (x) { case 0: e.o.x = f; break; case 1: e.o.y = f; break; case 2: e.o.z = f; break; case 3: e.p.x = f; break; case 4: e.p.y = f; break; case 5: e.p.z = f; break; } } } e.q.Identify(e.p); } ForceMatch('}'); } }; // -> // -> // -> // -> // CSparseMapExpr // -> // -> // -> // -> bool CSparseMapExpr::Parse() { try { mt.iFirst = Parse_map(); return true; } catch (Error) { return false; } } size_t CSparseMapExpr::Parse_map() { SkipAlWsComment(); CString strName; ForceReadTexto(strName); CString strKey = strName; strName.MakeLower(); CDoom3materialTexoMap m1; CString strValue; if (false); else if (strName == "addnormals") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(','); m1.x1 = Parse_map(); ForceMatch(')'); m1.tt = texAn; } else if (strName == "heightmap") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(','); SkipAlWsComment(); Force1(ReadTexto(strValue) && ParseFloat(strValue, m1.v0)); ForceMatch(')'); m1.tt = texHm; } else if (strName == "makealpha") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(')'); m1.tt = texMa; } else if (strName == "makeintensity") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(')'); m1.tt = texMi; } else if (strName == "smoothnormals") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(')'); m1.tt = texSn; } else if (strName == "add") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(','); m1.x1 = Parse_map(); ForceMatch(')'); m1.tt = texAx; } else if (strName == "scale") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(','); SkipAlWsComment(); Force1(ReadTexto(strValue) && ParseFloat(strValue, m1.v0)); ForceMatch(','); SkipAlWsComment(); Force1(ReadTexto(strValue) && ParseFloat(strValue, m1.v1)); ForceMatch(','); SkipAlWsComment(); Force1(ReadTexto(strValue) && ParseFloat(strValue, m1.v2)); ForceMatch(','); SkipAlWsComment(); Force1(ReadTexto(strValue) && ParseFloat(strValue, m1.v3)); ForceMatch(')'); m1.tt = texSx; } else if (strName == "invertalpha") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(')'); m1.tt = texIa; } else if (strName == "downsize") { ForceMatch('('); m1.x0 = Parse_map(); ForceMatch(','); SkipAlWsComment(); Force1(ReadTexto(strValue) && ParseFloat(strValue, m1.v1)); ForceMatch(')'); m1.tt = texDs; } else { m1.tt = texFlat; m1.strName = strKey; } size_t r = mt.size(); mt.push_back(m1); return r; } // -> // -> // -> // -> // CSparseTarga // -> // -> // -> // -> bool CSparseTarga::Parse() { // http://www.openspc2.org/format/TGA/ #pragma pack(push, 1) struct Header { BYTE x1; BYTE fColorMapped; BYTE iFormat; WORD x2; WORD x3; BYTE x4; WORD x5; WORD x6; WORD cx; WORD cy; BYTE nBitCount; BYTE x7; }; #pragma pack(pop) Header v; if (!SurelyReadBytes(&v, sizeof(v))) return false; if (v.fColorMapped != 0 || v.x2 != 0 || v.x3 != 0 || (v.x7 & 0xD0) != 0) return false; if (false); else if (v.iFormat == 2 && v.nBitCount == 24 && (v.x4 == 0 || v.x4 == 24)); else if (v.iFormat == 2 && v.nBitCount == 32 && (v.x4 == 0 || v.x4 == 32)); else if (v.iFormat == 3 && v.nBitCount == 8 && (v.x4 == 0 || v.x4 == 8 )); else if (v.iFormat == 10 && v.nBitCount == 24 && (v.x4 == 0 || v.x4 == 24)); else if (v.iFormat == 10 && v.nBitCount == 32 && (v.x4 == 0 || v.x4 == 32)); else { return false; } bool fUpdown = ((v.x7 & 0x20) ? true : false); bool fRLE = (v.iFormat == 10); if (!rIma.Create(v.cx, v.cy, v.nBitCount)) return false; if (!SurelySkipBytes(v.x1)) return false; if (!fRLE) { for (UINT y = 0; y < v.cy; y++) { BYTE *pData = rIma.GetVert(fUpdown ? (y) : (v.cy -y -1) ); if (!SurelyReadBytes(pData, rIma.nPitch)) return false; } } else { CDoom3ImaPix iw(rIma, fUpdown); UINT iPix = 0, nPix = v.cy * v.cx; BYTE x1 = v.nBitCount / 8; char aPix[4]; for (; iPix < nPix; ) { BYTE x; if (!ReadByte(x)) return false; BYTE cx = (x & 0x7F) + 1; if (x & 0x80) { if (!SurelyReadBytes(aPix, x1)) return false; if (!iw.WritePix(aPix, cx)) return false; } else { for (BYTE i = 0; i < cx; i++) { if (!SurelyReadBytes(aPix, x1)) return false; if (!iw.WritePix(aPix, 1)) return false; } } iPix += cx; } } return true; } // -> // -> // -> // -> // CDoom3FlatIma // -> // -> // -> // -> const CDoom3FlatIma &CDoom3FlatIma::operator =(const CDoom3FlatIma &s) { fv = s.fv; if (fv.GetData() == NULL) { cx = 0; cy = 0; nBitCount = 0; nPitch = 0; nDataLen = 0; } else { cx = s.cx; cy = s.cy; nBitCount = s.nBitCount; nPitch = s.nPitch; nDataLen = s.nDataLen; } pData = fv.GetData(); return s; } bool CDoom3FlatIma::Create(const CDoom3FlatIma &s) { return Create(s.cx, s.cy, s.nBitCount); } bool CDoom3FlatIma::Create(UINT cx, UINT cy, WORD nBitCount) { for (; ; ) { if (nBitCount != 8 && nBitCount != 24 && nBitCount != 32) break; this->nPitch = nBitCount * cx / 8; this->nDataLen = this->nPitch * cy; if (!fv.Alloc(this->nDataLen)) break; this->pData = (BYTE *)fv.GetData(); this->cx = cx; this->cy = cy; this->nBitCount = nBitCount; return true; } Close(); return false; } void CDoom3FlatIma::Close() { cx = cy = 0; nBitCount = nPitch = 0; pData = NULL; fv.Free(); } BYTE *CDoom3FlatIma::GetVert(UINT y) { return fv.GetData() + nPitch * y; } namespace MaterialTexo { // -> // -> // -> // -> // TexoEval // -> // -> // -> // -> bool TexoEval::Eval(CDoom3FlatIma &rIma) { try { if (mt.empty()) return false; if (!eval(mt.iFirst, rIma)) return false; return true; } catch (Error) { return false; } } bool TexoEval::eval(size_t i, CDoom3FlatIma &rIma) { CDoom3materialTexoMap &mtm = mt[i]; CDoom3FlatIma aIma0, aIma1; switch (mtm.tt) { case texFlat: { if (!rTex.LoadIma(mtm.strName, rIma)) return false; return true; } case texMa: { if (!eval(mtm.x0, aIma0)) return false; switch (aIma0.nBitCount) { case 8: { rIma = aIma0; return true; } case 24: { UINT x, y, cx = aIma0.cx, cy = aIma0.cy; if (!rIma.Create(aIma0.cx, aIma0.cy, 8)) return false; for (y = 0; y < cy; y++) { BYTE *pVertSrc = aIma0.GetVert(y); BYTE *pVertDst = rIma.GetVert(y); for (x = 0; x < cx; x++, pVertDst++, pVertSrc += 3) { *pVertDst = (0U +pVertSrc[0] +pVertSrc[1] +pVertSrc[2]) / 3; } } return true; } case 32: { UINT x, y, cx = aIma0.cx, cy = aIma0.cy; if (!rIma.Create(aIma0.cx, aIma0.cy, 8)) return false; for (y = 0; y < cy; y++) { BYTE *pVertSrc = aIma0.GetVert(y); BYTE *pVertDst = rIma.GetVert(y); for (x = 0; x < cx; x++, pVertDst++, pVertSrc += 4) { *pVertDst = (0U +pVertSrc[0] +pVertSrc[1] +pVertSrc[2] +pVertSrc[3]) / 4; } } return true; } default: { ASSERT(false); return false; } } } case texAn: case texHm: case texMi: case texSn: case texAx: case texSx: case texIa: { if (!eval(mtm.x0, rIma)) return false; return true; } default: { return false; } } } }; // -> // -> // -> // -> // CDoom3table // -> // -> // -> // -> float CDoom3table::Eval(float x) { if (fSnap) { // snap int i = int(x * m + 0.5f); if (fClamp) { // clamp if (i < 0) i = 0; if (m <=i) i = m -1; } else { // repeat i = ((i % m) + m) % m; } return vec[i]; } else { // linear interpolation (lerp?) int x1 = int(x * m ); int x2 = int(x * m +1); float f = x * m -x1; x1 = (x1 + m) % m; x2 = (x2 + m) % m; float r = 0 + vec[x1] * (1.0f -f) + vec[x2] * ( f) ; return r; } } // -> // -> // -> // -> // CEaseWriter // -> // -> // -> // -> bool CEaseWriter::Write() { if (f == NULL) return false; fprintf(f, "%u\n", 0U +mesh.meshes.size()); size_t i; for (i = 0; i < mesh.meshes.size(); i++) { CMD5MeshMesh &mm = mesh.meshes[i]; size_t x; fprintf(f, "%u\n", 0U +mm.verts.size()); for (x = 0; x < mm.verts.size(); x++) { CMD5MeshMeshVert &v0 = mm.verts[x]; fprintf(f, "%f,%f", v0.o.x, v0.o.y); My3DMath::Vtx3 v3; mm.InterpolateVertex(mesh.joints, x, v3); fprintf(f, ",%f,%f,%f\n", v3.x, v3.y, v3.z); } fprintf(f, "%u\n", 0U +mm.tris.size()); for (x = 0; x < mm.tris.size(); x++) { CMD5MeshMeshTri &v0 = mm.tris[x]; fprintf(f, "%u,%u,%u\n", v0.v[0], v0.v[1], v0.v[2]); } } return true; } // -> // -> // -> // -> // CV2MapDeck // -> // -> // -> // -> void CV2MapDeck::SearchDep(CString strName, StrSet_t &ss) const { if (ss.find(strName) != ss.end()) return; ss.insert(strName); V2MapBindRMMap_t::const_iterator iterPos = vrmm.lower_bound(strName), iterEnd = vrmm.upper_bound(strName); for (; iterPos != iterEnd; iterPos++) { SearchDep(iterPos->second, ss); } } CV2MapEntity *CV2MapDeck::FindEntity(CString strName) const { V2MapEntityPtrMap_t::const_iterator iterPos = em.find(strName), iterEnd = em.end(); if (iterPos != iterEnd) return iterPos->second; return NULL; } // -> // -> // -> // -> // CV2MapWriter // -> // -> // -> // -> bool CV2MapWriter::MkHeader() { fprintf(f, "Version 2\n" ); iEntity = 0; return true; } bool CV2MapWriter::MkEntityHeader() { fprintf(f, "// entity %u\n" "{\n" , iEntity ); iEntity++; iPrimitive = 0; return true; } bool CV2MapWriter::MkEntityFooter() { fprintf(f, "}\n" ); return true; } bool CV2MapWriter::MkEntity(CV2MapEntity &entity) { VarMap::iterator iterPos = entity.m.begin(), iterEnd = entity.m.end(); for (; iterPos != iterEnd; iterPos++) { fprintf(f, "\"%s\" \"%s\"\n" , (LPCSTR)iterPos->first , (LPCSTR)iterPos->second ); } if (entity.va.size() != 0) { size_t i; for (i = 0; i < entity.va.size(); i++) { fprintf(f, "// primitive %u\n" "{\n" " brushDef3\n" " {\n" , iPrimitive ); iPrimitive++; CV2MapBrush &v = entity.va[i]; size_t x; for (x = 0; x < v.pa.size(); x++) { CV2MapPlane &vp = v.pa[x]; fprintf(f, " ( %s %s %s %s ) ( ( %s %s %s ) ( %s %s %s ) ) \"%s\" 0 0 0\n" , (LPCSTR)Sol::f2s(vp.v.x) , (LPCSTR)Sol::f2s(vp.v.y) , (LPCSTR)Sol::f2s(vp.v.z) , (LPCSTR)Sol::f2s(vp.fr) , (LPCSTR)Sol::f2s(vp.m32[0][0]) , (LPCSTR)Sol::f2s(vp.m32[0][1]) , (LPCSTR)Sol::f2s(vp.m32[0][2]) , (LPCSTR)Sol::f2s(vp.m32[1][0]) , (LPCSTR)Sol::f2s(vp.m32[1][1]) , (LPCSTR)Sol::f2s(vp.m32[1][2]) , (LPCSTR)vp.strTex ); } fprintf(f, " }\n" "}\n" ); } for (i = 0; i < entity.p3a.size(); i++) { CV2MapPatchDef3 &p3 = entity.p3a[i]; fprintf(f, "// primitive %u\n" "{\n" " patchDef3\n" " {\n" " \"%s\"\n" " ( %d %d %d %d %d %d %d )\n" " (\n" , iPrimitive , (LPCSTR)p3.strTex , p3.cy , p3.cx , p3.t[0] , p3.t[1] , p3.t[2] , p3.t[3] , p3.t[4] ); iPrimitive++; size_t x, y, cx = p3.cx, cy = p3.cy; for (y = 0; y < cy; y++) { fprintf(f, " (" ); for (x = 0; x < cx; x++) { CV2MapPatchDef3Coord &p3c = p3.ca[x +cx*y]; My3DMath::Vtx3 v = p3c.v + patchDef_forceo; fprintf(f, " ( %s %s %s %s %s )" , (LPCSTR)Sol::f2s(v.x) , (LPCSTR)Sol::f2s(v.y) , (LPCSTR)Sol::f2s(v.z) , (LPCSTR)Sol::f2s(p3c.tv.x) , (LPCSTR)Sol::f2s(p3c.tv.y) ); } fprintf(f, " )\n" ); } fprintf(f, " )\n" " }\n" "}\n" ); } } return true; } // -> // -> // -> // -> // CHwsMan // -> // -> // -> // -> UINT CHwsMan::getindexres() { return IDR_HTML_INDEX; } UINT CHwsMan::gethhpres() { return IDR_DATA_D3HHP; } // -> // -> // -> // -> // CHwsManq4 // -> // -> // -> // -> UINT CHwsManq4::getindexres() { return IDR_HTML_INDEX_Q4; } UINT CHwsManq4::gethhpres() { return IDR_DATA_Q4HHP; }
19.842538
129
0.52906
[ "mesh", "object", "model" ]
f5546af7801c38cc708a443864d3d5e0c4c2f57a
52,334
cc
C++
google/cloud/storage/tests/object_integration_test.cc
AVaksman/google-cloud-cpp
86ccde498987e240024f6e850f3b53eafff383b5
[ "Apache-2.0" ]
null
null
null
google/cloud/storage/tests/object_integration_test.cc
AVaksman/google-cloud-cpp
86ccde498987e240024f6e850f3b53eafff383b5
[ "Apache-2.0" ]
null
null
null
google/cloud/storage/tests/object_integration_test.cc
AVaksman/google-cloud-cpp
86ccde498987e240024f6e850f3b53eafff383b5
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 "google/cloud/log.h" #include "google/cloud/storage/client.h" #include "google/cloud/storage/testing/storage_integration_test.h" #include "google/cloud/testing_util/capture_log_lines_backend.h" #include "google/cloud/testing_util/init_google_mock.h" #include <gmock/gmock.h> #include <regex> namespace google { namespace cloud { namespace storage { inline namespace STORAGE_CLIENT_NS { namespace { using google::cloud::storage::testing::CountMatchingEntities; using google::cloud::storage::testing::TestPermanentFailure; using ::testing::HasSubstr; /// Store the project and instance captured from the command-line arguments. class ObjectTestEnvironment : public ::testing::Environment { public: ObjectTestEnvironment(std::string project, std::string instance) { project_id_ = std::move(project); bucket_name_ = std::move(instance); } static std::string const& project_id() { return project_id_; } static std::string const& bucket_name() { return bucket_name_; } private: static std::string project_id_; static std::string bucket_name_; }; std::string ObjectTestEnvironment::project_id_; std::string ObjectTestEnvironment::bucket_name_; class ObjectIntegrationTest : public google::cloud::storage::testing::StorageIntegrationTest { protected: std::string MakeEntityName() { // We always use the viewers for the project because it is known to exist. return "project-viewers-" + ObjectTestEnvironment::project_id(); } }; /// @test Verify the Object CRUD (Create, Get, Update, Delete, List) operations. TEST_F(ObjectIntegrationTest, BasicCRUD) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto objects = client.ListObjects(bucket_name); std::vector<ObjectMetadata> initial_list(objects.begin(), objects.end()); auto name_counter = [](std::string const& name, std::vector<ObjectMetadata> const& list) { return std::count_if( list.begin(), list.end(), [name](ObjectMetadata const& m) { return m.name() == name; }); }; auto object_name = MakeRandomObjectName(); ASSERT_EQ(0, name_counter(object_name, initial_list)) << "Test aborted. The object <" << object_name << "> already exists." << "This is unexpected as the test generates a random object name."; // Create the object, but only if it does not exist already. ObjectMetadata insert_meta = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), Projection("full")); objects = client.ListObjects(bucket_name); std::vector<ObjectMetadata> current_list(objects.begin(), objects.end()); EXPECT_EQ(1U, name_counter(object_name, current_list)); ObjectMetadata get_meta = client.GetObjectMetadata( bucket_name, object_name, Generation(insert_meta.generation()), Projection("full")); EXPECT_EQ(get_meta, insert_meta); ObjectMetadata update = get_meta; update.mutable_acl().emplace_back( ObjectAccessControl().set_role("READER").set_entity( "allAuthenticatedUsers")); update.set_cache_control("no-cache") .set_content_disposition("inline") .set_content_encoding("identity") .set_content_language("en") .set_content_type("plain/text"); update.mutable_metadata().emplace("updated", "true"); ObjectMetadata updated_meta = client.UpdateObject(bucket_name, object_name, update, Projection("full")); // Because some of the ACL values are not predictable we convert the values we // care about to strings and compare that. { auto acl_to_string_vector = [](std::vector<ObjectAccessControl> const& acl) { std::vector<std::string> v; std::transform(acl.begin(), acl.end(), std::back_inserter(v), [](ObjectAccessControl const& x) { return x.entity() + " = " + x.role(); }); return v; }; auto expected = acl_to_string_vector(update.acl()); auto actual = acl_to_string_vector(updated_meta.acl()); EXPECT_THAT(expected, ::testing::UnorderedElementsAreArray(actual)); } EXPECT_EQ(update.cache_control(), updated_meta.cache_control()) << updated_meta; EXPECT_EQ(update.content_disposition(), updated_meta.content_disposition()) << updated_meta; EXPECT_EQ(update.content_encoding(), updated_meta.content_encoding()) << updated_meta; EXPECT_EQ(update.content_language(), updated_meta.content_language()) << updated_meta; EXPECT_EQ(update.content_type(), updated_meta.content_type()) << updated_meta; EXPECT_EQ(update.metadata(), updated_meta.metadata()) << updated_meta; ObjectMetadata desired_patch = updated_meta; desired_patch.set_content_language("en"); desired_patch.mutable_metadata().erase("updated"); desired_patch.mutable_metadata().emplace("patched", "true"); ObjectMetadata patched_meta = client.PatchObject(bucket_name, object_name, updated_meta, desired_patch); EXPECT_EQ(desired_patch.metadata(), patched_meta.metadata()) << patched_meta; EXPECT_EQ(desired_patch.content_language(), patched_meta.content_language()) << patched_meta; client.DeleteObject(bucket_name, object_name); objects = client.ListObjects(bucket_name); current_list.assign(objects.begin(), objects.end()); EXPECT_EQ(0U, name_counter(object_name, current_list)); } TEST_F(ObjectIntegrationTest, FullPatch) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. ObjectMetadata original = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), Projection("full")); ObjectMetadata desired = original; desired.mutable_acl().push_back(ObjectAccessControl() .set_entity("allAuthenticatedUsers") .set_role("READER")); if (original.cache_control() != "no-cache") { desired.set_cache_control("no-cache"); } else { desired.set_cache_control(""); } if (original.content_disposition() != "inline") { desired.set_content_disposition("inline"); } else { desired.set_content_disposition("attachment; filename=test.txt"); } if (original.content_encoding() != "identity") { desired.set_content_encoding("identity"); } else { desired.set_content_encoding(""); } // Use 'en' and 'fr' as test languages because they are known to be supported. // The server rejects private tags such as 'x-pig-latin'. if (original.content_language() != "en") { desired.set_content_language("en"); } else { desired.set_content_language("fr"); } if (original.content_type() != "application/octet-stream") { desired.set_content_type("application/octet-stream"); } else { desired.set_content_type("application/text"); } // We want to create a diff that modifies the metadata, so either erase or // insert a value for `test-label` depending on the initial state. if (original.has_metadata("test-label")) { desired.mutable_metadata().erase("test-label"); } else { desired.mutable_metadata().emplace("test-label", "test-value"); } ObjectMetadata patched = client.PatchObject(bucket_name, object_name, original, desired); // acl() - cannot compare for equality because many fields are updated with // unknown values (entity_id, etag, etc) EXPECT_EQ(1U, std::count_if(patched.acl().begin(), patched.acl().end(), [](ObjectAccessControl const& x) { return x.entity() == "allAuthenticatedUsers"; })); EXPECT_EQ(desired.cache_control(), patched.cache_control()); EXPECT_EQ(desired.content_disposition(), patched.content_disposition()); EXPECT_EQ(desired.content_encoding(), patched.content_encoding()); EXPECT_EQ(desired.content_language(), patched.content_language()); EXPECT_EQ(desired.content_type(), patched.content_type()); EXPECT_EQ(desired.metadata(), patched.metadata()); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, ListObjectsVersions) { auto bucket_name = ObjectTestEnvironment::bucket_name(); Client client; // This test requires the bucket to be configured with versioning. The buckets // used by the CI build are already configured with versioning enabled. The // bucket created in the testbench also has versioning. Regardless, check here // first to produce a better error message if there is a configuration // problem. auto bucket_meta = client.GetBucketMetadata(bucket_name); ASSERT_TRUE(bucket_meta.versioning().has_value()); ASSERT_TRUE(bucket_meta.versioning().value().enabled); auto create_object_with_3_versions = [&client, &bucket_name, this] { auto object_name = MakeRandomObjectName(); auto meta = client.InsertObject(bucket_name, object_name, "contents for the first revision", storage::IfGenerationMatch(0)); client.InsertObject(bucket_name, object_name, "contents for the second revision"); client.InsertObject(bucket_name, object_name, "contents for the final revision"); return meta.name(); }; std::vector<std::string> expected(4); std::generate_n(expected.begin(), expected.size(), create_object_with_3_versions); ListObjectsReader reader = client.ListObjects(bucket_name, Versions(true)); std::vector<std::string> actual; for (auto it = reader.begin(); it != reader.end(); ++it) { auto const& meta = *it; EXPECT_EQ(bucket_name, meta.bucket()); actual.push_back(meta.name()); } auto produce_joined_list = [&actual] { std::string joined; for (auto const& x : actual) { joined += " "; joined += x; joined += "\n"; } return joined; }; // There may be a lot of other objects in the bucket, so we want to verify // that any objects we created are found there, but cannot expect a perfect // match. for (auto const& name : expected) { EXPECT_EQ(3, std::count(actual.begin(), actual.end(), name)) << "Expected to find 3 copies of " << name << " in the object list:\n" << produce_joined_list(); } } TEST_F(ObjectIntegrationTest, BasicReadWrite) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); std::string expected = LoremIpsum(); // Create the object, but only if it does not exist already. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, expected, IfGenerationMatch(0)); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); // Create a iostream to read the object back. auto stream = client.ReadObject(bucket_name, object_name); std::string actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, EncryptedReadWrite) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); std::string expected = LoremIpsum(); EncryptionKeyData key = MakeEncryptionKeyData(); // Create the object, but only if it does not exist already. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, expected, IfGenerationMatch(0), EncryptionKey(key)); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); ASSERT_TRUE(meta.has_customer_encryption()); EXPECT_EQ("AES256", meta.customer_encryption().encryption_algorithm); EXPECT_EQ(key.sha256, meta.customer_encryption().key_sha256); // Create a iostream to read the object back. auto stream = client.ReadObject(bucket_name, object_name, EncryptionKey(key)); std::string actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, ReadNotFound) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create a iostream to read the object back. auto stream = client.ReadObject(bucket_name, object_name); EXPECT_TRUE(stream.eof()); EXPECT_FALSE(stream.IsOpen()); } TEST_F(ObjectIntegrationTest, Copy) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto source_object_name = MakeRandomObjectName(); auto destination_object_name = MakeRandomObjectName(); std::string expected = LoremIpsum(); ObjectMetadata source_meta = client.InsertObject( bucket_name, source_object_name, expected, IfGenerationMatch(0)); EXPECT_EQ(source_object_name, source_meta.name()); EXPECT_EQ(bucket_name, source_meta.bucket()); ObjectMetadata meta = client.CopyObject( bucket_name, source_object_name, bucket_name, destination_object_name, WithObjectMetadata(ObjectMetadata().set_content_type("text/plain"))); EXPECT_EQ(destination_object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); EXPECT_EQ("text/plain", meta.content_type()); auto stream = client.ReadObject(bucket_name, destination_object_name); std::string actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); client.DeleteObject(bucket_name, destination_object_name); client.DeleteObject(bucket_name, source_object_name); } TEST_F(ObjectIntegrationTest, StreamingWrite) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0)); // We will construct the expected response while streaming the data up. std::ostringstream expected; WriteRandomLines(os, expected); ObjectMetadata meta = os.Close(); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); auto expected_str = expected.str(); ASSERT_EQ(expected_str.size(), meta.size()); // Create a iostream to read the object back. auto stream = client.ReadObject(bucket_name, object_name); std::string actual(std::istreambuf_iterator<char>{stream}, {}); ASSERT_FALSE(actual.empty()); EXPECT_EQ(expected_str.size(), actual.size()) << " meta=" << meta; EXPECT_EQ(expected_str, actual); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, StreamingWriteAutoClose) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // We will construct the expected response while streaming the data up. std::string expected = "A short string to test\n"; { // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0)); os << expected; } // Create a iostream to read the object back. auto stream = client.ReadObject(bucket_name, object_name); std::string actual(std::istreambuf_iterator<char>{stream}, {}); ASSERT_FALSE(actual.empty()); EXPECT_EQ(expected, actual); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, XmlStreamingWrite) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0), Fields("")); // We will construct the expected response while streaming the data up. std::ostringstream expected; WriteRandomLines(os, expected); ObjectMetadata meta = os.Close(); // When asking for an empty list of fields we should not expect any values: EXPECT_TRUE(meta.bucket().empty()); EXPECT_TRUE(meta.name().empty()); // Create a iostream to read the object back. auto stream = client.ReadObject(bucket_name, object_name); std::string actual(std::istreambuf_iterator<char>{stream}, {}); ASSERT_FALSE(actual.empty()); auto expected_str = expected.str(); EXPECT_EQ(expected_str.size(), actual.size()) << " meta=" << meta; EXPECT_EQ(expected_str, actual); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, XmlReadWrite) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); std::string expected = LoremIpsum(); // Create the object, but only if it does not exist already. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, expected, IfGenerationMatch(0), Fields("")); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); // Create a iostream to read the object back. auto stream = client.ReadObject(bucket_name, object_name); std::string actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, AccessControlCRUD) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. (void)client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); auto entity_name = MakeEntityName(); std::vector<ObjectAccessControl> initial_acl = client.ListObjectAcl(bucket_name, object_name); auto name_counter = [](std::string const& name, std::vector<ObjectAccessControl> const& list) { auto name_matcher = [](std::string const& name) { return [name](ObjectAccessControl const& m) { return m.entity() == name; }; }; return std::count_if(list.begin(), list.end(), name_matcher(name)); }; ASSERT_EQ(0, name_counter(entity_name, initial_acl)) << "Test aborted. The entity <" << entity_name << "> already exists." << "This is unexpected as the test generates a random object name."; ObjectAccessControl result = client.CreateObjectAcl(bucket_name, object_name, entity_name, "OWNER"); EXPECT_EQ("OWNER", result.role()); auto current_acl = client.ListObjectAcl(bucket_name, object_name); // Search using the entity name returned by the request, because we use // 'project-editors-<project_id>' this different than the original entity // name, the server "translates" the project id to a project number. EXPECT_EQ(1, name_counter(result.entity(), current_acl)); auto get_result = client.GetObjectAcl(bucket_name, object_name, entity_name); EXPECT_EQ(get_result, result); ObjectAccessControl new_acl = get_result; new_acl.set_role("READER"); auto updated_result = client.UpdateObjectAcl(bucket_name, object_name, new_acl); EXPECT_EQ(updated_result.role(), "READER"); get_result = client.GetObjectAcl(bucket_name, object_name, entity_name); EXPECT_EQ(get_result, updated_result); new_acl = get_result; new_acl.set_role("OWNER"); get_result = client.PatchObjectAcl(bucket_name, object_name, entity_name, get_result, new_acl, IfMatchEtag(get_result.etag())); EXPECT_EQ(get_result.role(), new_acl.role()); // Remove an entity and verify it is no longer in the ACL. client.DeleteObjectAcl(bucket_name, object_name, entity_name); current_acl = client.ListObjectAcl(bucket_name, object_name); EXPECT_EQ(0, name_counter(result.entity(), current_acl)); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, WriteWithContentType) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // We will construct the expected response while streaming the data up. std::ostringstream expected; // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0), ContentType("text/plain")); os << LoremIpsum(); ObjectMetadata meta = os.Close(); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); EXPECT_EQ("text/plain", meta.content_type()); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, CopyPredefinedAclAuthenticatedRead) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto copy_name = MakeRandomObjectName(); ObjectMetadata original = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); ObjectMetadata meta = client.CopyObject( bucket_name, object_name, bucket_name, copy_name, IfGenerationMatch(0), DestinationPredefinedAcl::AuthenticatedRead(), Projection::Full()); EXPECT_LT(0, CountMatchingEntities(meta.acl(), ObjectAccessControl() .set_entity("allAuthenticatedUsers") .set_role("READER"))) << meta; client.DeleteObject(bucket_name, copy_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, CopyPredefinedAclBucketOwnerFullControl) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto copy_name = MakeRandomObjectName(); BucketMetadata bucket = client.GetBucketMetadata(bucket_name, Projection::Full()); ASSERT_TRUE(bucket.has_owner()); std::string owner = bucket.owner().entity; ObjectMetadata original = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); ObjectMetadata meta = client.CopyObject( bucket_name, object_name, bucket_name, copy_name, IfGenerationMatch(0), DestinationPredefinedAcl::BucketOwnerFullControl(), Projection::Full()); EXPECT_LT(0, CountMatchingEntities( meta.acl(), ObjectAccessControl().set_entity(owner).set_role("OWNER"))) << meta; client.DeleteObject(bucket_name, copy_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, CopyPredefinedAclBucketOwnerRead) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto copy_name = MakeRandomObjectName(); BucketMetadata bucket = client.GetBucketMetadata(bucket_name, Projection::Full()); ASSERT_TRUE(bucket.has_owner()); std::string owner = bucket.owner().entity; ObjectMetadata original = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); ObjectMetadata meta = client.CopyObject( bucket_name, object_name, bucket_name, copy_name, IfGenerationMatch(0), DestinationPredefinedAcl::BucketOwnerRead(), Projection::Full()); EXPECT_LT(0, CountMatchingEntities( meta.acl(), ObjectAccessControl().set_entity(owner).set_role("READER"))) << meta; client.DeleteObject(bucket_name, copy_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, CopyPredefinedAclPrivate) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto copy_name = MakeRandomObjectName(); ObjectMetadata original = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); ObjectMetadata meta = client.CopyObject( bucket_name, object_name, bucket_name, copy_name, IfGenerationMatch(0), DestinationPredefinedAcl::Private(), Projection::Full()); ASSERT_TRUE(meta.has_owner()); EXPECT_LT( 0, CountMatchingEntities(meta.acl(), ObjectAccessControl() .set_entity(meta.owner().entity) .set_role("OWNER"))) << meta; client.DeleteObject(bucket_name, copy_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, CopyPredefinedAclProjectPrivate) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto copy_name = MakeRandomObjectName(); ObjectMetadata original = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); ObjectMetadata meta = client.CopyObject( bucket_name, object_name, bucket_name, copy_name, IfGenerationMatch(0), DestinationPredefinedAcl::ProjectPrivate(), Projection::Full()); ASSERT_TRUE(meta.has_owner()); EXPECT_LT( 0, CountMatchingEntities(meta.acl(), ObjectAccessControl() .set_entity(meta.owner().entity) .set_role("OWNER"))) << meta; client.DeleteObject(bucket_name, copy_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, CopyPredefinedAclPublicRead) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto copy_name = MakeRandomObjectName(); ObjectMetadata original = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); ObjectMetadata meta = client.CopyObject( bucket_name, object_name, bucket_name, copy_name, IfGenerationMatch(0), DestinationPredefinedAcl::PublicRead(), Projection::Full()); EXPECT_LT( 0, CountMatchingEntities( meta.acl(), ObjectAccessControl().set_entity("allUsers").set_role("READER"))) << meta; client.DeleteObject(bucket_name, copy_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, ComposeSimple) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); // Compose new of object using previously created object auto composed_object_name = MakeRandomObjectName(); std::vector<ComposeSourceObject> source_objects = {{object_name}, {object_name}}; ObjectMetadata composed_meta = client.ComposeObject( bucket_name, source_objects, composed_object_name, WithObjectMetadata(ObjectMetadata().set_content_type("plain/text"))); EXPECT_EQ(meta.size() * 2, composed_meta.size()); client.DeleteObject(bucket_name, composed_object_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, ComposedUsingEncryptedObject) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); std::string content = LoremIpsum(); EncryptionKeyData key = MakeEncryptionKeyData(); // Create the object, but only if it does not exist already. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, content, IfGenerationMatch(0), EncryptionKey(key)); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); ASSERT_TRUE(meta.has_customer_encryption()); EXPECT_EQ("AES256", meta.customer_encryption().encryption_algorithm); EXPECT_EQ(key.sha256, meta.customer_encryption().key_sha256); // Compose new of object using previously created object auto composed_object_name = MakeRandomObjectName(); std::vector<ComposeSourceObject> source_objects = {{object_name}, {object_name}}; ObjectMetadata composed_meta = client.ComposeObject( bucket_name, source_objects, composed_object_name, EncryptionKey(key)); EXPECT_EQ(meta.size() * 2, composed_meta.size()); client.DeleteObject(bucket_name, composed_object_name); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, RewriteSimple) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto source_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. ObjectMetadata source_meta = client.InsertObject( bucket_name, source_name, LoremIpsum(), IfGenerationMatch(0)); EXPECT_EQ(source_name, source_meta.name()); EXPECT_EQ(bucket_name, source_meta.bucket()); // Rewrite object into a new object. auto object_name = MakeRandomObjectName(); ObjectMetadata rewritten_meta = client.RewriteObjectBlocking( bucket_name, source_name, bucket_name, object_name); EXPECT_EQ(bucket_name, rewritten_meta.bucket()); EXPECT_EQ(object_name, rewritten_meta.name()); client.DeleteObject(bucket_name, object_name); client.DeleteObject(bucket_name, source_name); } TEST_F(ObjectIntegrationTest, RewriteEncrypted) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto source_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. EncryptionKeyData source_key = MakeEncryptionKeyData(); ObjectMetadata source_meta = client.InsertObject(bucket_name, source_name, LoremIpsum(), IfGenerationMatch(0), EncryptionKey(source_key)); EXPECT_EQ(source_name, source_meta.name()); EXPECT_EQ(bucket_name, source_meta.bucket()); // Compose new of object using previously created object auto object_name = MakeRandomObjectName(); EncryptionKeyData dest_key = MakeEncryptionKeyData(); ObjectRewriter rewriter = client.RewriteObject( bucket_name, source_name, bucket_name, object_name, SourceEncryptionKey(source_key), EncryptionKey(dest_key)); ObjectMetadata rewritten_meta = rewriter.Result(); EXPECT_EQ(bucket_name, rewritten_meta.bucket()); EXPECT_EQ(object_name, rewritten_meta.name()); client.DeleteObject(bucket_name, object_name); client.DeleteObject(bucket_name, source_name); } TEST_F(ObjectIntegrationTest, RewriteLarge) { // The testbench always requires multiple iterations to copy this object. Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto source_name = MakeRandomObjectName(); std::string large_text; long const lines = 8 * 1024 * 1024 / 128; for (long i = 0; i != lines; ++i) { auto line = google::cloud::internal::Sample(generator_, 127, "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "012456789"); large_text += line + "\n"; } ObjectMetadata source_meta = client.InsertObject( bucket_name, source_name, large_text, IfGenerationMatch(0)); EXPECT_EQ(source_name, source_meta.name()); EXPECT_EQ(bucket_name, source_meta.bucket()); // Rewrite object into a new object. auto object_name = MakeRandomObjectName(); ObjectRewriter writer = client.RewriteObject(bucket_name, source_name, bucket_name, object_name); ObjectMetadata rewritten_meta = writer.ResultWithProgressCallback([](RewriteProgress const& p) { EXPECT_TRUE((p.total_bytes_rewritten < p.object_size) xor p.done) << "p.done=" << p.done << ", p.object_size=" << p.object_size << ", p.total_bytes_rewritten=" << p.total_bytes_rewritten; }); EXPECT_EQ(bucket_name, rewritten_meta.bucket()); EXPECT_EQ(object_name, rewritten_meta.name()); client.DeleteObject(bucket_name, object_name); client.DeleteObject(bucket_name, source_name); } /// @test Verify that MD5 hashes are computed by default. TEST_F(ObjectIntegrationTest, DefaultMD5HashXML) { Client client(ClientOptions() .set_enable_raw_client_tracing(true) .set_enable_http_tracing(true)); auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto backend = std::make_shared<testing_util::CaptureLogLinesBackend>(); auto id = LogSink::Instance().AddBackend(backend); ObjectMetadata insert_meta = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), Fields("")); LogSink::Instance().RemoveBackend(id); auto count = std::count_if(backend->log_lines.begin(), backend->log_lines.end(), [](std::string const& line) { return line.rfind("x-goog-hash: md5=", 0) == 0; }); EXPECT_EQ(1, count); client.DeleteObject(bucket_name, object_name); } /// @test Verify that MD5 hashes are computed by default. TEST_F(ObjectIntegrationTest, DefaultMD5HashJSON) { Client client(ClientOptions() .set_enable_raw_client_tracing(true) .set_enable_http_tracing(true)); auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto backend = std::make_shared<testing_util::CaptureLogLinesBackend>(); auto id = LogSink::Instance().AddBackend(backend); ObjectMetadata insert_meta = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0)); LogSink::Instance().RemoveBackend(id); auto count = std::count_if( backend->log_lines.begin(), backend->log_lines.end(), [](std::string const& line) { // This is a big indirect, we detect if the upload changed to // multipart/related, and if so, we assume the hash value is being used. // Unfortunately I (@coryan) cannot think of a way to examine the upload // contents. return line.rfind("content-type: multipart/related; boundary=", 0) == 0; }); EXPECT_EQ(1, count); if (insert_meta.has_metadata("x_testbench_upload")) { // When running against the testbench, we have some more information to // verify the right upload type and contents were sent. EXPECT_EQ("multipart", insert_meta.metadata("x_testbench_upload")); ASSERT_TRUE(insert_meta.has_metadata("x_testbench_md5")); auto expected_md5 = ComputeMD5Hash(LoremIpsum()); EXPECT_EQ(expected_md5, insert_meta.metadata("x_testbench_md5")); } client.DeleteObject(bucket_name, object_name); } /// @test Verify that `DisableMD5Hash` actually disables the header. TEST_F(ObjectIntegrationTest, DisableMD5HashXML) { Client client(ClientOptions() .set_enable_raw_client_tracing(true) .set_enable_http_tracing(true)); auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto backend = std::make_shared<testing_util::CaptureLogLinesBackend>(); auto id = LogSink::Instance().AddBackend(backend); ObjectMetadata insert_meta = client.InsertObject( bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), DisableMD5Hash(true), Fields("")); LogSink::Instance().RemoveBackend(id); auto count = std::count_if(backend->log_lines.begin(), backend->log_lines.end(), [](std::string const& line) { return line.rfind("x-goog-hash: md5=", 0) == 0; }); EXPECT_EQ(0U, count); client.DeleteObject(bucket_name, object_name); } /// @test Verify that `DisableMD5Hash` actually disables the payload. TEST_F(ObjectIntegrationTest, DisableMD5HashJSON) { Client client(ClientOptions() .set_enable_raw_client_tracing(true) .set_enable_http_tracing(true)); auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto backend = std::make_shared<testing_util::CaptureLogLinesBackend>(); auto id = LogSink::Instance().AddBackend(backend); ObjectMetadata insert_meta = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), DisableMD5Hash(true)); LogSink::Instance().RemoveBackend(id); auto count = std::count_if( backend->log_lines.begin(), backend->log_lines.end(), [](std::string const& line) { // This is a big indirect, we detect if the upload changed to // multipart/related, and if so, we assume the hash value is being used. // Unfortunately I (@coryan) cannot think of a way to examine the upload // contents. return line.rfind("content-type: multipart/related; boundary=", 0) == 0; }); EXPECT_EQ(0, count); if (insert_meta.has_metadata("x_testbench_upload")) { // When running against the testbench, we have some more information to // verify the right upload type and contents were sent. EXPECT_EQ("simple", insert_meta.metadata("x_testbench_upload")); ASSERT_FALSE(insert_meta.has_metadata("x_testbench_md5")); } client.DeleteObject(bucket_name, object_name); } /// @test Verify that MD5 hashes are computed by default on downloads. TEST_F(ObjectIntegrationTest, DefaultMD5StreamingReadXML) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create an object and a stream to read it back. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), Projection::Full()); auto stream = client.ReadObject(bucket_name, object_name); std::string actual(std::istreambuf_iterator<char>{stream}, {}); ASSERT_FALSE(stream.IsOpen()); ASSERT_FALSE(actual.empty()); EXPECT_EQ(stream.received_hash(), stream.computed_hash()); EXPECT_THAT(stream.received_hash(), HasSubstr(meta.md5_hash())); client.DeleteObject(bucket_name, object_name); } /// @test Verify that MD5 hashes are computed by default on downloads. TEST_F(ObjectIntegrationTest, DefaultMD5StreamingReadJSON) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create an object and a stream to read it back. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), Projection::Full()); auto stream = client.ReadObject(bucket_name, object_name, IfMetagenerationNotMatch(0)); std::string actual(std::istreambuf_iterator<char>{stream}, {}); ASSERT_FALSE(stream.IsOpen()); ASSERT_FALSE(actual.empty()); EXPECT_EQ(stream.received_hash(), stream.computed_hash()); EXPECT_THAT(stream.received_hash(), HasSubstr(meta.md5_hash())); client.DeleteObject(bucket_name, object_name); } /// @test Verify that hashes and checksums can be disabled on downloads. TEST_F(ObjectIntegrationTest, DisableHashesStreamingReadXML) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create an object and a stream to read it back. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), Projection::Full()); auto stream = client.ReadObject(bucket_name, object_name, DisableMD5Hash(true), DisableCrc32cChecksum(true)); std::string actual(std::istreambuf_iterator<char>{stream}, {}); ASSERT_FALSE(stream.IsOpen()); ASSERT_FALSE(actual.empty()); EXPECT_TRUE(stream.computed_hash().empty()); EXPECT_TRUE(stream.received_hash().empty()); client.DeleteObject(bucket_name, object_name); } /// @test Verify that hashes and checksums can be disabled on downloads. TEST_F(ObjectIntegrationTest, DisableHashesStreamingReadJSON) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create an object and a stream to read it back. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, LoremIpsum(), IfGenerationMatch(0), Projection::Full()); auto stream = client.ReadObject( bucket_name, object_name, DisableMD5Hash(true), DisableCrc32cChecksum(true), IfMetagenerationNotMatch(0)); std::string actual(std::istreambuf_iterator<char>{stream}, {}); ASSERT_FALSE(stream.IsOpen()); ASSERT_FALSE(actual.empty()); EXPECT_TRUE(stream.computed_hash().empty()); EXPECT_TRUE(stream.received_hash().empty()); client.DeleteObject(bucket_name, object_name); } /// @test Verify that MD5 hashes are computed by default on uploads. TEST_F(ObjectIntegrationTest, DefaultMD5StreamingWriteXML) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0), Fields("")); // We will construct the expected response while streaming the data up. std::ostringstream expected; WriteRandomLines(os, expected); auto expected_md5hash = ComputeMD5Hash(expected.str()); ObjectMetadata meta = os.Close(); EXPECT_EQ(os.received_hash(), os.computed_hash()); EXPECT_THAT(os.received_hash(), HasSubstr(expected_md5hash)); client.DeleteObject(bucket_name, object_name); } /// @test Verify that MD5 hashes are computed by default on uploads. TEST_F(ObjectIntegrationTest, DefaultMD5StreamingWriteJSON) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0)); // We will construct the expected response while streaming the data up. std::ostringstream expected; WriteRandomLines(os, expected); auto expected_md5hash = ComputeMD5Hash(expected.str()); ObjectMetadata meta = os.Close(); EXPECT_EQ(os.received_hash(), os.computed_hash()); EXPECT_THAT(os.received_hash(), HasSubstr(expected_md5hash)); client.DeleteObject(bucket_name, object_name); } /// @test Verify that hashes and checksums can be disabled in uploads. TEST_F(ObjectIntegrationTest, DisableHashesStreamingWriteXML) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0), Fields(""), DisableMD5Hash(true), DisableCrc32cChecksum(true)); // We will construct the expected response while streaming the data up. std::ostringstream expected; WriteRandomLines(os, expected); ObjectMetadata meta = os.Close(); EXPECT_TRUE(os.received_hash().empty()); EXPECT_TRUE(os.computed_hash().empty()); client.DeleteObject(bucket_name, object_name); } /// @test Verify that hashes and checksums can be disabled in uploads. TEST_F(ObjectIntegrationTest, DisableHashesStreamingWriteJSON) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // Create the object, but only if it does not exist already. auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0), DisableMD5Hash(true), DisableCrc32cChecksum(true)); // We will construct the expected response while streaming the data up. std::ostringstream expected; WriteRandomLines(os, expected); ObjectMetadata meta = os.Close(); EXPECT_TRUE(os.received_hash().empty()); EXPECT_TRUE(os.computed_hash().empty()); client.DeleteObject(bucket_name, object_name); } TEST_F(ObjectIntegrationTest, CopyFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto source_object_name = MakeRandomObjectName(); auto destination_object_name = MakeRandomObjectName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.CopyObject(bucket_name, source_object_name, bucket_name, destination_object_name); }); } TEST_F(ObjectIntegrationTest, GetObjectMetadataFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // This operation should fail because the source object does not exist. TestPermanentFailure( [&] { client.GetObjectMetadata(bucket_name, object_name); }); } TEST_F(ObjectIntegrationTest, StreamingWriteFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); std::string expected = LoremIpsum(); // Create the object, but only if it does not exist already. ObjectMetadata meta = client.InsertObject(bucket_name, object_name, expected, IfGenerationMatch(0)); EXPECT_EQ(object_name, meta.name()); EXPECT_EQ(bucket_name, meta.bucket()); auto os = client.WriteObject(bucket_name, object_name, IfGenerationMatch(0)); os << "Test message\n"; // This operation should fail because the object already exists. #if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS EXPECT_THROW(try { os.Close(); } catch (std::runtime_error const& ex) { EXPECT_THAT(ex.what(), HasSubstr("[412]")); throw; }, std::runtime_error); #else EXPECT_DEATH_IF_SUPPORTED(os.Close(), "exceptions are disabled"); #endif // GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS } TEST_F(ObjectIntegrationTest, ListObjectsFailure) { auto bucket_name = MakeRandomBucketName(); Client client; ListObjectsReader reader = client.ListObjects(bucket_name, Versions(true)); // This operation should fail because the bucket does not exist. TestPermanentFailure([&] { std::vector<ObjectMetadata> actual; actual.assign(reader.begin(), reader.end()); }); } TEST_F(ObjectIntegrationTest, DeleteObjectFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.DeleteObject(bucket_name, object_name); }); } TEST_F(ObjectIntegrationTest, UpdateObjectFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // This operation should fail because the source object does not exist. TestPermanentFailure( [&] { client.UpdateObject(bucket_name, object_name, ObjectMetadata()); }); } TEST_F(ObjectIntegrationTest, PatchObjectFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.PatchObject(bucket_name, object_name, ObjectMetadataPatchBuilder()); }); } TEST_F(ObjectIntegrationTest, ComposeFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto composed_object_name = MakeRandomObjectName(); std::vector<ComposeSourceObject> source_objects = {{object_name}, {object_name}}; // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.ComposeObject(bucket_name, source_objects, composed_object_name); }); } TEST_F(ObjectIntegrationTest, RewriteFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto source_object_name = MakeRandomObjectName(); auto destination_object_name = MakeRandomObjectName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.RewriteObjectBlocking(bucket_name, source_object_name, bucket_name, destination_object_name); }); } TEST_F(ObjectIntegrationTest, ListAccessControlFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.ListObjectAcl(bucket_name, object_name); }); } TEST_F(ObjectIntegrationTest, CreateAccessControlFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto entity_name = MakeEntityName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.CreateObjectAcl(bucket_name, object_name, entity_name, "READER"); }); } TEST_F(ObjectIntegrationTest, GetAccessControlFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto entity_name = MakeEntityName(); // This operation should fail because the source object does not exist. TestPermanentFailure( [&] { client.GetObjectAcl(bucket_name, object_name, entity_name); }); } TEST_F(ObjectIntegrationTest, UpdateAccessControlFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto entity_name = MakeEntityName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.UpdateObjectAcl( bucket_name, object_name, ObjectAccessControl().set_entity(entity_name).set_role("READER")); }); } TEST_F(ObjectIntegrationTest, PatchAccessControlFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto entity_name = MakeEntityName(); // This operation should fail because the source object does not exist. TestPermanentFailure([&] { client.PatchObjectAcl( bucket_name, object_name, entity_name, ObjectAccessControl(), ObjectAccessControl().set_entity(entity_name).set_role("READER")); }); } TEST_F(ObjectIntegrationTest, DeleteAccessControlFailure) { Client client; auto bucket_name = ObjectTestEnvironment::bucket_name(); auto object_name = MakeRandomObjectName(); auto entity_name = MakeEntityName(); // This operation should fail because the source object does not exist. TestPermanentFailure( [&] { client.DeleteObjectAcl(bucket_name, object_name, entity_name); }); } } // anonymous namespace } // namespace STORAGE_CLIENT_NS } // namespace storage } // namespace cloud } // namespace google int main(int argc, char* argv[]) { google::cloud::testing_util::InitGoogleMock(argc, argv); // Make sure the arguments are valid. if (argc != 3) { std::string const cmd = argv[0]; auto last_slash = std::string(argv[0]).find_last_of('/'); std::cerr << "Usage: " << cmd.substr(last_slash + 1) << " <project-id> <bucket-name>" << std::endl; return 1; } std::string const project_id = argv[1]; std::string const bucket_name = argv[2]; (void)::testing::AddGlobalTestEnvironment( new google::cloud::storage::ObjectTestEnvironment(project_id, bucket_name)); return RUN_ALL_TESTS(); }
38.967982
80
0.714086
[ "object", "vector", "transform" ]
f556b2776e06238b677ef08da0e9f964408a6eba
8,252
cc
C++
src/test/common/test_bloom_filter.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
4
2020-04-08T03:42:02.000Z
2020-10-01T20:34:48.000Z
src/test/common/test_bloom_filter.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
93
2020-03-26T14:29:14.000Z
2020-11-12T05:54:55.000Z
src/test/common/test_bloom_filter.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
23
2020-03-24T10:28:44.000Z
2020-09-24T09:42:19.000Z
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2013 Inktank <info@inktank.com> * * LGPL2.1 (see COPYING-LGPL2.1) or later */ #include <iostream> #include <gtest/gtest.h> #include "include/stringify.h" #include "common/bloom_filter.hpp" TEST(BloomFilter, Basic) { bloom_filter bf(10, .1, 1); bf.insert("foo"); bf.insert("bar"); ASSERT_TRUE(bf.contains("foo")); ASSERT_TRUE(bf.contains("bar")); ASSERT_EQ(2U, bf.element_count()); } TEST(BloomFilter, Empty) { bloom_filter bf; for (int i=0; i<100; ++i) { ASSERT_FALSE(bf.contains(i)); ASSERT_FALSE(bf.contains(stringify(i))); } } TEST(BloomFilter, Sweep) { std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); std::cout << "# max\tfpp\tactual\tsize\tB/insert" << std::endl; for (int ex = 3; ex < 12; ex += 2) { for (float fpp = .001; fpp < .5; fpp *= 4.0) { int max = 2 << ex; bloom_filter bf(max, fpp, 1); bf.insert("foo"); bf.insert("bar"); ASSERT_TRUE(bf.contains("foo")); ASSERT_TRUE(bf.contains("bar")); for (int n = 0; n < max; n++) bf.insert("ok" + stringify(n)); int test = max * 100; int hit = 0; for (int n = 0; n < test; n++) if (bf.contains("asdf" + stringify(n))) hit++; ASSERT_TRUE(bf.contains("foo")); ASSERT_TRUE(bf.contains("bar")); double actual = (double)hit / (double)test; bufferlist bl; encode(bf, bl); double byte_per_insert = (double)bl.length() / (double)max; std::cout << max << "\t" << fpp << "\t" << actual << "\t" << bl.length() << "\t" << byte_per_insert << std::endl; ASSERT_TRUE(actual < fpp * 10); } } } TEST(BloomFilter, SweepInt) { std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); std::cout << "# max\tfpp\tactual\tsize\tB/insert\tdensity\tapprox_element_count" << std::endl; for (int ex = 3; ex < 12; ex += 2) { for (float fpp = .001; fpp < .5; fpp *= 4.0) { int max = 2 << ex; bloom_filter bf(max, fpp, 1); bf.insert("foo"); bf.insert("bar"); ASSERT_TRUE(123); ASSERT_TRUE(456); for (int n = 0; n < max; n++) bf.insert(n); int test = max * 100; int hit = 0; for (int n = 0; n < test; n++) if (bf.contains(100000 + n)) hit++; ASSERT_TRUE(123); ASSERT_TRUE(456); double actual = (double)hit / (double)test; bufferlist bl; encode(bf, bl); double byte_per_insert = (double)bl.length() / (double)max; std::cout << max << "\t" << fpp << "\t" << actual << "\t" << bl.length() << "\t" << byte_per_insert << "\t" << bf.density() << "\t" << bf.approx_unique_element_count() << std::endl; ASSERT_TRUE(actual < fpp * 10); ASSERT_TRUE(actual > fpp / 10); ASSERT_TRUE(bf.density() > 0.40); ASSERT_TRUE(bf.density() < 0.60); } } } TEST(BloomFilter, CompressibleSweep) { std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); std::cout << "# max\tins\test ins\tafter\ttgtfpp\tactual\tsize\tb/elem\n"; float fpp = .01; int max = 1024; for (int div = 1; div < 10; div++) { compressible_bloom_filter bf(max, fpp, 1); int t = max/div; for (int n = 0; n < t; n++) bf.insert(n); unsigned est = bf.approx_unique_element_count(); if (div > 1) bf.compress(1.0 / div); for (int n = 0; n < t; n++) ASSERT_TRUE(bf.contains(n)); int test = max * 100; int hit = 0; for (int n = 0; n < test; n++) if (bf.contains(100000 + n)) hit++; double actual = (double)hit / (double)test; bufferlist bl; encode(bf, bl); double byte_per_insert = (double)bl.length() / (double)max; unsigned est_after = bf.approx_unique_element_count(); std::cout << max << "\t" << t << "\t" << est << "\t" << est_after << "\t" << fpp << "\t" << actual << "\t" << bl.length() << "\t" << byte_per_insert << std::endl; ASSERT_TRUE(actual < fpp * 2.0); ASSERT_TRUE(actual > fpp / 2.0); ASSERT_TRUE(est_after < est * 2); ASSERT_TRUE(est_after > est / 2); } } TEST(BloomFilter, BinSweep) { std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(5); int total_max = 16384; float total_fpp = .01; std::cout << "total_inserts " << total_max << " target-fpp " << total_fpp << std::endl; for (int bins = 1; bins < 16; ++bins) { int max = total_max / bins; float fpp = total_fpp / bins;//pow(total_fpp, bins); std::vector<std::unique_ptr<bloom_filter>> ls; bufferlist bl; for (int i=0; i<bins; i++) { ls.push_back(std::make_unique<bloom_filter>(max, fpp, i)); for (int j=0; j<max; j++) { ls.back()->insert(10000 * (i+1) + j); } encode(*ls.front(), bl); } int hit = 0; int test = max * 100; for (int i=0; i<test; ++i) { for (std::vector<std::unique_ptr<bloom_filter>>::iterator j = ls.begin(); j != ls.end(); ++j) { if ((*j)->contains(i * 732)) { // note: sequential i does not work here; the intenral int hash is weak!! hit++; break; } } } double actual = (double)hit / (double)test; std::cout << "bins " << bins << " bin-max " << max << " bin-fpp " << fpp << " actual-fpp " << actual << " total-size " << bl.length() << std::endl; } } // disable these tests; doing dual insertions in consecutive filters // appears to be equivalent to doing a single insertion in a bloom // filter that is twice as big. #if 0 // test the fpp over a sequence of bloom filters, each with unique // items inserted into it. // // we expect: actual_fpp = num_filters * per_filter_fpp TEST(BloomFilter, Sequence) { int max = 1024; double fpp = .01; for (int seq = 2; seq <= 128; seq *= 2) { std::vector<bloom_filter*> ls; for (int i=0; i<seq; i++) { ls.push_back(new bloom_filter(max*2, fpp, i)); for (int j=0; j<max; j++) { ls.back()->insert("ok" + stringify(j) + "_" + stringify(i)); if (ls.size() > 1) ls[ls.size() - 2]->insert("ok" + stringify(j) + "_" + stringify(i)); } } int hit = 0; int test = max * 100; for (int i=0; i<test; ++i) { for (std::vector<bloom_filter*>::iterator j = ls.begin(); j != ls.end(); ++j) { if ((*j)->contains("bad" + stringify(i))) { hit++; break; } } } double actual = (double)hit / (double)test; std::cout << "seq " << seq << " max " << max << " fpp " << fpp << " actual " << actual << std::endl; } } // test the ffp over a sequence of bloom filters, where actual values // are always inserted into a consecutive pair of filters. in order // to have a false positive, we need to falsely match two consecutive // filters. // // we expect: actual_fpp = num_filters * per_filter_fpp^2 TEST(BloomFilter, SequenceDouble) { int max = 1024; double fpp = .01; for (int seq = 2; seq <= 128; seq *= 2) { std::vector<bloom_filter*> ls; for (int i=0; i<seq; i++) { ls.push_back(new bloom_filter(max*2, fpp, i)); for (int j=0; j<max; j++) { ls.back()->insert("ok" + stringify(j) + "_" + stringify(i)); if (ls.size() > 1) ls[ls.size() - 2]->insert("ok" + stringify(j) + "_" + stringify(i)); } } int hit = 0; int test = max * 100; int run = 0; for (int i=0; i<test; ++i) { for (std::vector<bloom_filter*>::iterator j = ls.begin(); j != ls.end(); ++j) { if ((*j)->contains("bad" + stringify(i))) { run++; if (run >= 2) { hit++; break; } } else { run = 0; } } } double actual = (double)hit / (double)test; std::cout << "seq " << seq << " max " << max << " fpp " << fpp << " actual " << actual << " expected " << (fpp*fpp*(double)seq) << std::endl; } } #endif TEST(BloomFilter, Assignement) { bloom_filter bf1(10, .1, 1), bf2; bf1.insert("foo"); bf2 = bf1; bf1.insert("bar"); ASSERT_TRUE(bf2.contains("foo")); ASSERT_FALSE(bf2.contains("bar")); ASSERT_EQ(2U, bf1.element_count()); ASSERT_EQ(1U, bf2.element_count()); }
26.96732
119
0.562288
[ "vector" ]
f556d20b11dd643f83ae227e4fdc80514a0f0aad
4,146
cpp
C++
source/PyMaterialX/PyMaterialXRender/PyMesh.cpp
alister-chowdhury/MaterialX
ec83067eb6ca694cbc5c68394762ee15b041f71b
[ "BSD-3-Clause" ]
8
2019-05-18T10:56:25.000Z
2022-03-08T21:00:24.000Z
source/PyMaterialX/PyMaterialXRender/PyMesh.cpp
alister-chowdhury/MaterialX
ec83067eb6ca694cbc5c68394762ee15b041f71b
[ "BSD-3-Clause" ]
null
null
null
source/PyMaterialX/PyMaterialXRender/PyMesh.cpp
alister-chowdhury/MaterialX
ec83067eb6ca694cbc5c68394762ee15b041f71b
[ "BSD-3-Clause" ]
1
2020-02-24T02:16:19.000Z
2020-02-24T02:16:19.000Z
// // TM & (c) 2019 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <PyMaterialX/PyMaterialX.h> #include <MaterialXRender/Mesh.h> namespace py = pybind11; namespace mx = MaterialX; void bindPyMesh(py::module& mod) { py::class_<mx::MeshStream, mx::MeshStreamPtr>(mod, "MeshStream") .def_readonly_static("POSITION_ATTRIBUTE", &mx::MeshStream::POSITION_ATTRIBUTE) .def_readonly_static("NORMAL_ATTRIBUTE", &mx::MeshStream::NORMAL_ATTRIBUTE) .def_readonly_static("TEXCOORD_ATTRIBUTE", &mx::MeshStream::TEXCOORD_ATTRIBUTE) .def_readonly_static("TANGENT_ATTRIBUTE", &mx::MeshStream::TANGENT_ATTRIBUTE) .def_readonly_static("BITANGENT_ATTRIBUTE", &mx::MeshStream::BITANGENT_ATTRIBUTE) .def_readonly_static("COLOR_ATTRIBUTE", &mx::MeshStream::COLOR_ATTRIBUTE) .def_readonly_static("GEOMETRY_PROPERTY_ATTRIBUTE", &mx::MeshStream::GEOMETRY_PROPERTY_ATTRIBUTE) .def_readonly_static("STRIDE_2D", &mx::MeshStream::STRIDE_2D) .def_readonly_static("STRIDE_3D", &mx::MeshStream::STRIDE_3D) .def_readonly_static("DEFAULT_STRIDE", &mx::MeshStream::DEFAULT_STRIDE) .def_static("create", &mx::MeshStream::create) .def(py::init<const std::string&, const std::string&, unsigned int>()) .def("resize", &mx::MeshStream::resize) .def("getName", &mx::MeshStream::getName) .def("getType", &mx::MeshStream::getType) .def("getIndex", &mx::MeshStream::getIndex) .def("getData", static_cast<mx::MeshFloatBuffer& (mx::MeshStream::*)()>(&mx::MeshStream::getData), py::return_value_policy::reference) .def("getStride", &mx::MeshStream::getStride) .def("setStride", &mx::MeshStream::setStride) .def("getSize", &mx::MeshStream::getSize) .def("transform", &mx::MeshStream::transform); py::class_<mx::MeshPartition, mx::MeshPartitionPtr>(mod, "MeshPartition") .def_static("create", &mx::MeshPartition::create) .def(py::init<>()) .def("resize", &mx::MeshPartition::resize) .def("getIdentifier", &mx::MeshPartition::getIdentifier) .def("setIdentifier", &mx::MeshPartition::setIdentifier) .def("getIndices", static_cast<mx::MeshIndexBuffer& (mx::MeshPartition::*)()>(&mx::MeshPartition::getIndices), py::return_value_policy::reference) .def("getFaceCount", &mx::MeshPartition::getFaceCount) .def("setFaceCount", &mx::MeshPartition::setFaceCount); py::class_<mx::Mesh, mx::MeshPtr>(mod, "Mesh") .def_static("create", &mx::Mesh::create) .def(py::init<const std::string&>()) .def("getIdentifier", &mx::Mesh::getIdentifier) .def("setSourceUri", &mx::Mesh::setSourceUri) .def("hasSourceUri", &mx::Mesh::hasSourceUri) .def("getSourceUri", &mx::Mesh::getSourceUri) .def("getStream", static_cast<mx::MeshStreamPtr (mx::Mesh::*)(const std::string&) const>(&mx::Mesh::getStream)) .def("getStream", static_cast<mx::MeshStreamPtr (mx::Mesh::*)(const std::string&, unsigned int) const> (&mx::Mesh::getStream)) .def("addStream", &mx::Mesh::addStream) .def("setVertexCount", &mx::Mesh::setVertexCount) .def("getVertexCount", &mx::Mesh::getVertexCount) .def("setMinimumBounds", &mx::Mesh::setMinimumBounds) .def("getMinimumBounds", &mx::Mesh::getMinimumBounds) .def("setMaximumBounds", &mx::Mesh::setMaximumBounds) .def("getMaximumBounds", &mx::Mesh::getMaximumBounds) .def("setSphereCenter", &mx::Mesh::setSphereCenter) .def("getSphereCenter", &mx::Mesh::getSphereCenter) .def("setSphereRadius", &mx::Mesh::setSphereRadius) .def("getSphereRadius", &mx::Mesh::getSphereRadius) .def("getPartitionCount", &mx::Mesh::getPartitionCount) .def("addPartition", &mx::Mesh::addPartition) .def("getPartition", &mx::Mesh::getPartition) .def("generateTangents", &mx::Mesh::generateTangents) .def("mergePartitions", &mx::Mesh::mergePartitions) .def("splitByUdims", &mx::Mesh::splitByUdims); }
55.28
154
0.666425
[ "mesh", "transform" ]
f55a6ba05225b969bb175298b78e8a2c3890b1a4
11,587
cpp
C++
test/wave_equation_adjointness.cpp
thiesgerken/wavepi
5af37946dcc1910ad1cccdc76d2e2f546eeafec4
[ "BSD-3-Clause" ]
null
null
null
test/wave_equation_adjointness.cpp
thiesgerken/wavepi
5af37946dcc1910ad1cccdc76d2e2f546eeafec4
[ "BSD-3-Clause" ]
null
null
null
test/wave_equation_adjointness.cpp
thiesgerken/wavepi
5af37946dcc1910ad1cccdc76d2e2f546eeafec4
[ "BSD-3-Clause" ]
null
null
null
/* * adjointness.cpp * * Created on: 22.07.2017 * Author: thies */ #include <base/ConstantMesh.h> #include <base/DiscretizedFunction.h> #include <base/SpaceTimeMesh.h> #include <base/Util.h> #include <deal.II/base/exceptions.h> #include <deal.II/base/function.h> #include <deal.II/base/logstream.h> #include <deal.II/base/numbers.h> #include <deal.II/base/point.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/fe/fe_q.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/grid/tria.h> #include <forward/L2RightHandSide.h> #include <forward/VectorRightHandSide.h> #include <forward/WaveEquation.h> #include <forward/WaveEquationAdjoint.h> #include <forward/WaveEquationBase.h> #include <gtest/gtest.h> #include <norms/H1L2.h> #include <norms/L2L2.h> #include <stddef.h> #include <fstream> #include <iostream> #include <memory> #include <vector> namespace { using namespace dealii; using namespace wavepi::forward; using namespace wavepi::base; using namespace wavepi; /***** NOTE: This module is used for automatic figure generation and should therefore only be changed together with the thesis! *****/ template <int dim> class TestF : public LightFunction<dim> { public: virtual ~TestF() = default; virtual double evaluate(const Point<dim> &p, const double t) const { // if (p.norm() < 0.5) return std::sin(t * 2 * numbers::PI); // else // return 0.0; } }; template <int dim> class TestG : public LightFunction<dim> { public: virtual ~TestG() = default; virtual double evaluate(const Point<dim> &p, const double t) const { Point<dim> pc = Point<dim>::unit_vector(0); pc *= 0.5; return t * std::sin(p.distance(pc) * 2 * numbers::PI); } }; template <int dim> class TestH : public LightFunction<dim> { public: virtual ~TestH() = default; virtual double evaluate(const Point<dim> &p, const double t) const { return p.norm() * t; } }; template <int dim> class TestC : public LightFunction<dim> { public: virtual ~TestC() = default; virtual double evaluate(const Point<dim> &p, const double t) const { return p[0] * cos(t) + 1.5; } }; template <int dim> class TestRho : public LightFunction<dim> { public: virtual ~TestRho() = default; virtual double evaluate(const Point<dim> &p, const double t) const { return p.norm() + sin(t) + 1.5; } }; template <int dim> class TestNu : public LightFunction<dim> { public: virtual ~TestNu() = default; virtual double evaluate(const Point<dim> &p, const double t) const { // if (t > 1.0) return 0.0; return std::abs(p[1]) * sin(t); } }; template <int dim> class TestQ : public LightFunction<dim> { public: virtual ~TestQ() = default; virtual double evaluate(const Point<dim> &p, const double t) const { return p.norm() < 0.5 ? std::sin(t / 2 * 2 * numbers::PI) : 0.0; } static const Point<dim> q_position; }; template <int dim> void run_wave_adjoint_test(int fe_order, int quad_order, int refines, int n_steps, typename WaveEquationBase<dim>::L2AdjointSolver adjoint_solver, bool trivial, double tol, std::shared_ptr<std::ofstream> log = nullptr) { AssertThrow(adjoint_solver == WaveEquationBase<dim>::WaveEquationAdjoint || adjoint_solver == WaveEquationBase<dim>::WaveEquationBackwards, ExcInternalError()); auto triangulation = std::make_shared<Triangulation<dim>>(); GridGenerator::hyper_cube(*triangulation, -1, 1); Util::set_all_boundary_ids(*triangulation, 0); triangulation->refine_global(refines); double t_start = 0.0, t_end = 2.0, dt = t_end / (n_steps - 1); std::vector<double> times; for (size_t i = 0; t_start + i * dt <= t_end; i++) times.push_back(t_start + i * dt); std::shared_ptr<SpaceTimeMesh<dim>> mesh = std::make_shared<ConstantMesh<dim>>(times, FE_Q<dim>(fe_order), QGauss<dim>(quad_order), triangulation); deallog << std::endl << "---------- n_dofs / timestep: " << mesh->get_dof_handler(0)->n_dofs(); deallog << ", n_steps: " << times.size() << " ----------" << std::endl; WaveEquation<dim> wave_eq(mesh); if (!trivial) { wave_eq.set_param_rho(std::make_shared<TestRho<dim>>()); wave_eq.set_param_c(std::make_shared<TestC<dim>>()); wave_eq.set_param_q(std::make_shared<TestQ<dim>>()); wave_eq.set_param_nu(std::make_shared<TestNu<dim>>()); } WaveEquationAdjoint<dim> wave_eq_adj(wave_eq); bool use_adj = adjoint_solver == WaveEquationBase<dim>::WaveEquationAdjoint; double err_avg = 0.0; double err_simple; for (size_t i = 0; i < 1 + 10; i++) { std::shared_ptr<DiscretizedFunction<dim>> f, g; if (i == 0) { TestF<dim> f_cont; f = std::make_shared<DiscretizedFunction<dim>>(mesh, f_cont); TestG<dim> g_cont; g = std::make_shared<DiscretizedFunction<dim>>(mesh, g_cont); } else { f = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh)); g = std::make_shared<DiscretizedFunction<dim>>(DiscretizedFunction<dim>::noise(mesh)); if (n_steps > 7) { // make f and g a slightly smoother, random noise might be a too harsh f->set_norm(std::make_shared<norms::H1L2<dim>>(0.1)); f->dot_transform_inverse(); g->set_norm(std::make_shared<norms::H1L2<dim>>(0.1)); g->dot_transform_inverse(); } } f->set_norm(std::make_shared<norms::L2L2<dim>>()); *f *= 1.0 / f->norm(); g->set_norm(std::make_shared<norms::L2L2<dim>>()); *g *= 1.0 / g->norm(); DiscretizedFunction<dim> sol_f = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(f), WaveEquation<dim>::Forward); sol_f.throw_away_derivative(); sol_f.set_norm(std::make_shared<norms::L2L2<dim>>()); EXPECT_GT(sol_f.norm(), 0.0); auto g_time_mass = std::make_shared<DiscretizedFunction<dim>>(*g); g_time_mass->set_norm(std::make_shared<norms::L2L2<dim>>()); DiscretizedFunction<dim> adj_g(mesh); if (use_adj) { // if L2RightHandSide would be used, we would also need a call to solve_mass g_time_mass->dot_transform(); adj_g = wave_eq_adj.run(std::make_shared<VectorRightHandSide<dim>>(g_time_mass)); // wave_eq_adj does everything except the multiplication with the mass matrix (to allow for optimization) adj_g.set_norm(std::make_shared<norms::L2L2<dim>>()); adj_g.dot_mult_mass_and_transform_inverse(); } else { // dot_transforms not needed here, wave_eq backwards should be the L^2([0,T], L^2)-Adjoint adj_g = wave_eq.run(std::make_shared<L2RightHandSide<dim>>(g_time_mass), WaveEquation<dim>::Backward); adj_g.throw_away_derivative(); adj_g.set_norm(std::make_shared<norms::L2L2<dim>>()); } EXPECT_GT(adj_g.norm(), 0.0); double dot_solf_g = sol_f * (*g); double dot_f_adjg = (*f) * adj_g; double fg_err = std::abs(dot_solf_g - dot_f_adjg) / (std::abs(dot_solf_g) + 1e-300); if (i == 0) { // deallog << "simple f,g: " << std::scientific << "(Lf, g) = " << dot_solf_g << ", (f, L*g) = " << dot_f_adjg // << std::endl; err_simple = fg_err; deallog << std::scientific << " relative error for simple f,g = " << fg_err << std::endl; } else err_avg = ((i - 1) * err_avg + fg_err) / i; // deallog << std::scientific << "(Lf, g) = " << dot_solf_g << ", (f, L*g) = " << dot_f_adjg // << ", rel. error = " << fg_err << std::endl; // EXPECT_LT(zz_err, tol); } deallog << std::scientific << "average relative error for random f,g = " << err_avg << std::endl; double h = dealii::GridTools::maximal_cell_diameter(*mesh->get_triangulation(0)); if (log) *log << std::scientific << mesh->length() << " " << dt << " " << refines << " " << h << " " << err_avg << std::endl; EXPECT_LT(err_simple, tol); EXPECT_LT(err_avg, tol); } } // namespace // TEST(WaveEquationAdjointness, Adjoint1DFE1) { // for (int i = 3; i < 10; i++) // run_wave_adjoint_test<1>(1, 5, 6, 1 << i, WaveEquationBase<1>::WaveEquationAdjoint, false, 1e-4); // } // TEST(WaveEquationAdjointness, Adjoint1DFE2) { // for (int i = 3; i < 10; i++) // run_wave_adjoint_test<1>(2, 5, 4, 1 << i, WaveEquationBase<1>::WaveEquationAdjoint, false, 1e-4); // } TEST(WaveEquationAdjointness, Backwards2DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_Backwards2DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 10; i++) run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationBackwards, false, 1e+2, f); } TEST(WaveEquationAdjointness, BackwardsTrivial2DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_BackwardsTrivial2DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 10; i++) run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationBackwards, true, 1e+2, f); } TEST(WaveEquationAdjointness, Adjoint2DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_Adjoint2DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 10; i++) run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationAdjoint, false, 1e-4, f); } TEST(WaveEquationAdjointness, AdjointTrivial2DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_AdjointTrivial2DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 10; i++) run_wave_adjoint_test<2>(1, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationAdjoint, true, 1e-4, f); } // TEST(WaveEquationAdjointness, Adjoint2DFE2) { // auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_Adjoint2DFE2.dat", std::ios_base::trunc); // ASSERT_TRUE(*f) << "could not open file for output"; // for (int i = 3; i < 10; i++) // run_wave_adjoint_test<2>(2, 5, 5, 1 << i, WaveEquationBase<2>::WaveEquationAdjoint, false, 1e-4, f); // } TEST(WaveEquationAdjointness, Adjoint3DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_Adjoint3DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 9; i++) run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationAdjoint, false, 1e-4, f); } TEST(WaveEquationAdjointness, Backwards3DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_Backwards3DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 9; i++) run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationBackwards, false, 1e+2, f); } TEST(WaveEquationAdjointness, AdjointTrivial3DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_AdjointTrivial3DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 9; i++) run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationAdjoint, true, 1e-4, f); } TEST(WaveEquationAdjointness, BackwardsTrivial3DFE1) { auto f = std::make_shared<std::ofstream>("./WaveEquationAdjointness_BackwardsTrivial3DFE1.dat", std::ios_base::trunc); ASSERT_TRUE(*f) << "could not open file for output"; for (int i = 3; i < 9; i++) run_wave_adjoint_test<3>(1, 5, 3, 1 << i, WaveEquationBase<3>::WaveEquationBackwards, true, 1e+2, f); }
35.873065
120
0.662639
[ "mesh", "vector" ]
f55c7d13f1349bdecafabfb0a2e7baf83454b32b
4,716
cpp
C++
internal/core/unittest/test_reduce.cpp
AropJoe/milvus
132b3c2248c50e96a4edde56aefb43659a270837
[ "Apache-2.0" ]
2
2021-09-05T15:00:49.000Z
2022-01-05T06:42:23.000Z
internal/core/unittest/test_reduce.cpp
AropJoe/milvus
132b3c2248c50e96a4edde56aefb43659a270837
[ "Apache-2.0" ]
38
2021-11-22T11:15:27.000Z
2022-03-30T08:14:12.000Z
internal/core/unittest/test_reduce.cpp
Bennu-Li/milvus
35612881e33ce19a7407628769f6b51a7518bfe9
[ "Apache-2.0" ]
3
2021-11-17T09:21:42.000Z
2021-11-22T11:54:09.000Z
// Copyright (C) 2019-2020 Zilliz. 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 <gtest/gtest.h> #include <queue> #include <random> #include <vector> #include "query/SubSearchResult.h" using namespace milvus; using namespace milvus::query; TEST(Reduce, SubQueryResult) { int64_t num_queries = 512; int64_t topk = 32; int64_t iteration = 50; int64_t round_decimal = 3; constexpr int64_t limit = 100000000L; auto metric_type = MetricType::METRIC_L2; using queue_type = std::priority_queue<int64_t>; std::vector<queue_type> ref_results(num_queries); for (auto& ref_result : ref_results) { for (int i = 0; i < topk; ++i) { ref_result.push(limit); } } std::default_random_engine e(42); SubSearchResult final_result(num_queries, topk, metric_type, round_decimal); for (int i = 0; i < iteration; ++i) { std::vector<int64_t> ids; std::vector<float> distances; for (int n = 0; n < num_queries; ++n) { for (int k = 0; k < topk; ++k) { auto gen_x = e() % limit; ref_results[n].push(gen_x); ref_results[n].pop(); ids.push_back(gen_x); distances.push_back(gen_x); } std::sort(ids.begin() + n * topk, ids.begin() + n * topk + topk); std::sort(distances.begin() + n * topk, distances.begin() + n * topk + topk); } SubSearchResult sub_result(num_queries, topk, metric_type, round_decimal); sub_result.mutable_distances() = distances; sub_result.mutable_ids() = ids; final_result.merge(sub_result); } for (int n = 0; n < num_queries; ++n) { ASSERT_EQ(ref_results[n].size(), topk); for (int k = 0; k < topk; ++k) { auto ref_x = ref_results[n].top(); ref_results[n].pop(); auto index = n * topk + topk - 1 - k; auto id = final_result.get_ids()[index]; auto distance = final_result.get_distances()[index]; ASSERT_EQ(id, ref_x); ASSERT_EQ(distance, ref_x); } } } TEST(Reduce, SubSearchResultDesc) { int64_t num_queries = 512; int64_t topk = 32; int64_t iteration = 50; int64_t round_decimal = 3; constexpr int64_t limit = 100000000L; constexpr int64_t init_value = 0; auto metric_type = MetricType::METRIC_INNER_PRODUCT; using queue_type = std::priority_queue<int64_t, std::vector<int64_t>, std::greater<int64_t>>; std::vector<queue_type> ref_results(num_queries); for (auto& ref_result : ref_results) { for (int i = 0; i < topk; ++i) { ref_result.push(init_value); } } std::default_random_engine e(42); SubSearchResult final_result(num_queries, topk, metric_type, round_decimal); for (int i = 0; i < iteration; ++i) { std::vector<int64_t> ids; std::vector<float> distances; for (int n = 0; n < num_queries; ++n) { for (int k = 0; k < topk; ++k) { auto gen_x = e() % limit; ref_results[n].push(gen_x); ref_results[n].pop(); ids.push_back(gen_x); distances.push_back(gen_x); } std::sort(ids.begin() + n * topk, ids.begin() + n * topk + topk, std::greater<int64_t>()); std::sort(distances.begin() + n * topk, distances.begin() + n * topk + topk, std::greater<float>()); } SubSearchResult sub_result(num_queries, topk, metric_type, round_decimal); sub_result.mutable_distances() = distances; sub_result.mutable_ids() = ids; final_result.merge(sub_result); } for (int n = 0; n < num_queries; ++n) { ASSERT_EQ(ref_results[n].size(), topk); for (int k = 0; k < topk; ++k) { auto ref_x = ref_results[n].top(); ref_results[n].pop(); auto index = n * topk + topk - 1 - k; auto id = final_result.get_ids()[index]; auto distance = final_result.get_distances()[index]; ASSERT_EQ(id, ref_x); ASSERT_EQ(distance, ref_x); } } }
38.341463
113
0.594784
[ "vector" ]
f55d8ca230f19e21018a2b16a7879f0fc55f899f
13,942
cc
C++
omaha/net/network_request_unittest.cc
theroguekiller1/tablet-a
5f5207f1cb936f380368f623f2128749a289c777
[ "Apache-2.0" ]
2
2019-09-06T20:53:41.000Z
2021-03-09T08:41:24.000Z
omaha/net/network_request_unittest.cc
theroguekiller1/tablet-a
5f5207f1cb936f380368f623f2128749a289c777
[ "Apache-2.0" ]
1
2018-12-19T12:23:39.000Z
2018-12-19T12:23:39.000Z
omaha/net/network_request_unittest.cc
theroguekiller1/tablet-a
5f5207f1cb936f380368f623f2128749a289c777
[ "Apache-2.0" ]
1
2017-10-19T13:06:16.000Z
2017-10-19T13:06:16.000Z
// Copyright 2007-2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== #include <windows.h> #include <winhttp.h> #include <vector> #include "base/scoped_ptr.h" #include "base/basictypes.h" #include "omaha/base/browser_utils.h" #include "omaha/base/constants.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/queue_timer.h" #include "omaha/base/scope_guard.h" #include "omaha/base/scoped_any.h" #include "omaha/base/scoped_ptr_address.h" #include "omaha/base/time.h" #include "omaha/base/utils.h" #include "omaha/base/vista_utils.h" #include "omaha/net/bits_request.h" #include "omaha/net/cup_ecdsa_request.h" #include "omaha/net/network_config.h" #include "omaha/net/network_request.h" #include "omaha/net/simple_request.h" #include "omaha/testing/unit_test.h" namespace omaha { class NetworkRequestTest : public testing::Test, public NetworkRequestCallback { protected: NetworkRequestTest() {} static void SetUpTestCase() { // Initialize the detection chain: GoogleProxy, FireFox if it is the // default browser, and IE. NetworkConfig* network_config = NULL; EXPECT_HRESULT_SUCCEEDED( NetworkConfigManager::Instance().GetUserNetworkConfig(&network_config)); network_config->Clear(); network_config->Add(new UpdateDevProxyDetector); BrowserType browser_type(BROWSER_UNKNOWN); GetDefaultBrowserType(&browser_type); if (browser_type == BROWSER_FIREFOX) { network_config->Add(new FirefoxProxyDetector); } network_config->Add(new IEWPADProxyDetector); network_config->Add(new IEPACProxyDetector); network_config->Add(new IENamedProxyDetector); network_config->Add(new DefaultProxyDetector); vista::GetLoggedOnUserToken(&token_); } static void TearDownTestCase() { if (token_) { ::CloseHandle(token_); } NetworkConfig* network_config = NULL; EXPECT_HRESULT_SUCCEEDED( NetworkConfigManager::Instance().GetUserNetworkConfig(&network_config)); network_config->Clear(); } virtual void SetUp() { NetworkConfig* network_config = NULL; EXPECT_HRESULT_SUCCEEDED( NetworkConfigManager::Instance().GetUserNetworkConfig(&network_config)); network_request_.reset(new NetworkRequest(network_config->session())); network_request_->set_retry_delay_jitter(0); } virtual void TearDown() {} virtual void OnProgress(int bytes, int bytes_total, int, const TCHAR*) { UNREFERENCED_PARAMETER(bytes); UNREFERENCED_PARAMETER(bytes_total); NET_LOG(L3, (_T("[downloading %d of %d]"), bytes, bytes_total)); } virtual void OnRequestBegin() { NET_LOG(L3, (_T("[download starts]"))); } virtual void OnRequestRetryScheduled(time64 next_retry_time) { UNREFERENCED_PARAMETER(next_retry_time); time64 now = GetCurrent100NSTime(); ASSERT1(next_retry_time > now); NET_LOG(L3, (_T("\n[Download will retry in %d seconds]\n"), CeilingDivide(next_retry_time - now, kSecsTo100ns))); } static void CancelCallback(QueueTimer* queue_timer) { ASSERT_TRUE(queue_timer); ASSERT_TRUE(queue_timer->ctx()); void* ctx = queue_timer->ctx(); NetworkRequestTest* test = static_cast<NetworkRequestTest*>(ctx); const TCHAR* msg = _T("CancelCallback"); ASSERT_HRESULT_SUCCEEDED(test->network_request_->Cancel()); } // http get. void HttpGetHelper() { std::vector<uint8> response; CString url = _T("http://www.google.com/robots.txt"); network_request_->set_num_retries(2); EXPECT_HRESULT_SUCCEEDED(network_request_->Get(url, &response)); int http_status = network_request_->http_status_code(); EXPECT_TRUE(http_status == HTTP_STATUS_OK || http_status == HTTP_STATUS_PARTIAL_CONTENT); } // https get. void HttpsGetHelper() { std::vector<uint8> response; CString url = _T("https://www.google.com/robots.txt"); network_request_->set_num_retries(2); EXPECT_HRESULT_SUCCEEDED(network_request_->Get(url, &response)); int http_status = network_request_->http_status_code(); EXPECT_TRUE(http_status == HTTP_STATUS_OK || http_status == HTTP_STATUS_PARTIAL_CONTENT); } // http post. void HttpPostHelper() { std::vector<uint8> response; CString url = _T("http://tools.google.com/service/update2"); // Post a buffer. const uint8 request[] = "<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" testsource=\"dev\"/>"; // NOLINT network_request_->set_num_retries(2); EXPECT_HRESULT_SUCCEEDED(network_request_->Post(url, request, arraysize(request) - 1, &response)); int http_status = network_request_->http_status_code(); EXPECT_TRUE(http_status == HTTP_STATUS_OK || http_status == HTTP_STATUS_PARTIAL_CONTENT); // Post an UTF8 string. CStringA utf8_request(reinterpret_cast<const char*>(request)); EXPECT_HRESULT_SUCCEEDED(network_request_->PostUtf8String(url, utf8_request, &response)); http_status = network_request_->http_status_code(); EXPECT_TRUE(http_status == HTTP_STATUS_OK || http_status == HTTP_STATUS_PARTIAL_CONTENT); // Post a Unicode string. CString unicode_request(reinterpret_cast<const char*>(request)); EXPECT_HRESULT_SUCCEEDED(network_request_->PostString(url, unicode_request, &response)); http_status = network_request_->http_status_code(); EXPECT_TRUE(http_status == HTTP_STATUS_OK || http_status == HTTP_STATUS_PARTIAL_CONTENT); } // Download http file. void DownloadHelper() { CString url = _T("http://dl.google.com/update2/UpdateData.bin"); CString temp_file = GetTempFilename(_T("tmp")); ASSERT_FALSE(temp_file.IsEmpty()); network_request_->set_num_retries(2); network_request_->set_low_priority(true); network_request_->set_callback(this); EXPECT_HRESULT_SUCCEEDED(network_request_->DownloadFile(url, temp_file)); EXPECT_TRUE(::DeleteFile(temp_file)); int http_status = network_request_->http_status_code(); EXPECT_TRUE(http_status == HTTP_STATUS_OK || http_status == HTTP_STATUS_PARTIAL_CONTENT); } void MultipleRequestsHelper() { std::vector<uint8> response; CString url = _T("http://tools.google.com/service/update2"); const uint8 request[] = "<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" testsource=\"dev\"/>"; // NOLINT for (size_t i = 0; i != 3; ++i) { EXPECT_HRESULT_SUCCEEDED(network_request_->Post(url, request, arraysize(request) - 1, &response)); int http_status = network_request_->http_status_code(); EXPECT_TRUE(http_status == HTTP_STATUS_OK || http_status == HTTP_STATUS_PARTIAL_CONTENT); } } void PostRequestHelper() { std::vector<uint8> response; CString url = _T("http://tools.google.com/service/update2"); CString request = _T("<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" testsource=\"dev\"/>"); // NOLINT EXPECT_HRESULT_SUCCEEDED(network_request_->PostString(url, request, &response)); } void PostRequestNegativeTestHelper() { std::vector<uint8> response; CString url = _T("http://no_such_host.google.com/service/update2"); CString request = _T("<o:gupdate xmlns:o=\"http://www.google.com/update2/request\" testsource=\"dev\"/>"); // NOLINT EXPECT_HRESULT_FAILED(network_request_->PostString(url, request, &response)); } void RetriesNegativeTestHelper() { // Try a direct connection to a non-existent host and keep retrying until // the retries are used up. Urlmon request is using IE's settings. // Therefore, it is possible a proxy is used. In this case, the http // response is '503 Service Unavailable'. ProxyConfig config; network_request_->set_proxy_configuration(&config); network_request_->set_num_retries(2); network_request_->set_time_between_retries(10); // 10 miliseconds. std::vector<uint8> response; CString url = _T("http://nohost/nofile"); // One request plus 2 retries after 10 and 20 miliseconds respectively. HRESULT hr = network_request_->Get(url, &response); EXPECT_TRUE(hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_NAME_NOT_RESOLVED) || hr == INET_E_RESOURCE_NOT_FOUND || hr == HRESULTFromHttpStatusCode(503)); } void CancelTest_GetHelper() { HANDLE timer_queue = ::CreateTimerQueue(); ASSERT_TRUE(timer_queue); ON_SCOPE_EXIT(::DeleteTimerQueueEx, timer_queue, INVALID_HANDLE_VALUE); QueueTimer queue_timer(timer_queue, &NetworkRequestTest::CancelCallback, this); ASSERT_HRESULT_SUCCEEDED(queue_timer.Start(200, 0, WT_EXECUTEONLYONCE)); // Try a direct connection to a non-existent host and keep retrying until // canceled by the timer. ProxyConfig config; network_request_->set_proxy_configuration(&config); network_request_->set_num_retries(10); network_request_->set_time_between_retries(10); // 10 miliseconds. std::vector<uint8> response; CString url = _T("http://nohost/nofile"); EXPECT_EQ(GOOPDATE_E_CANCELLED, network_request_->Get(url, &response)); EXPECT_EQ(GOOPDATE_E_CANCELLED, network_request_->Get(url, &response)); } scoped_ptr<NetworkRequest> network_request_; static HANDLE token_; }; HANDLE NetworkRequestTest::token_ = NULL; // http get. TEST_F(NetworkRequestTest, HttpGet) { network_request_->AddHttpRequest(new SimpleRequest); HttpGetHelper(); } // https get. TEST_F(NetworkRequestTest, HttpsGet) { network_request_->AddHttpRequest(new SimpleRequest); HttpsGetHelper(); } // http post. TEST_F(NetworkRequestTest, HttpPost) { network_request_->AddHttpRequest(new CupEcdsaRequest(new SimpleRequest)); network_request_->AddHttpRequest(new SimpleRequest); HttpPostHelper(); } // Download http file. TEST_F(NetworkRequestTest, Download) { BitsRequest* bits_request(new BitsRequest); // Bits specific settings. // // Hardcode for now the min value, just to see how it works. // TODO(omaha): expose properties to NetworkRequest. bits_request->set_minimum_retry_delay(60); bits_request->set_no_progress_timeout(5); network_request_->AddHttpRequest(bits_request); network_request_->AddHttpRequest(new SimpleRequest); DownloadHelper(); } TEST_F(NetworkRequestTest, MultipleRequests) { network_request_->AddHttpRequest(new CupEcdsaRequest(new SimpleRequest)); MultipleRequestsHelper(); } TEST_F(NetworkRequestTest, PostRequest) { network_request_->AddHttpRequest(new SimpleRequest); PostRequestHelper(); } TEST_F(NetworkRequestTest, PostRequestNegativeTest) { network_request_->AddHttpRequest(new SimpleRequest); PostRequestNegativeTestHelper(); } TEST_F(NetworkRequestTest, RetriesNegativeTest) { network_request_->AddHttpRequest(new SimpleRequest); RetriesNegativeTestHelper(); } // Network request can't be reused once canceled. TEST_F(NetworkRequestTest, CancelTest_CannotReuse) { network_request_->Cancel(); std::vector<uint8> response; CString url = _T("https://www.google.com/robots.txt"); EXPECT_EQ(GOOPDATE_E_CANCELLED, network_request_->Get(url, &response)); } TEST_F(NetworkRequestTest, CancelTest_DownloadFile) { HANDLE timer_queue = ::CreateTimerQueue(); ASSERT_TRUE(timer_queue); ON_SCOPE_EXIT(::DeleteTimerQueueEx, timer_queue, INVALID_HANDLE_VALUE); QueueTimer queue_timer(timer_queue, &NetworkRequestTest::CancelCallback, this); ASSERT_HRESULT_SUCCEEDED(queue_timer.Start(200, 0, WT_EXECUTEONLYONCE)); // Try a direct connection to a non-existent host and keep retrying until // canceled by the timer. ProxyConfig config; network_request_->set_proxy_configuration(&config); BitsRequest* bits_request(new BitsRequest); bits_request->set_minimum_retry_delay(60); bits_request->set_no_progress_timeout(5); network_request_->AddHttpRequest(bits_request); network_request_->set_num_retries(10); network_request_->set_time_between_retries(10); // 10 miliseconds. std::vector<uint8> response; CString url = _T("http://nohost/nofile"); EXPECT_EQ(GOOPDATE_E_CANCELLED, network_request_->DownloadFile(url, _T("c:\\foo"))); EXPECT_EQ(GOOPDATE_E_CANCELLED, network_request_->DownloadFile(url, _T("c:\\foo"))); } TEST_F(NetworkRequestTest, CancelTest_Get) { network_request_->AddHttpRequest(new SimpleRequest); CancelTest_GetHelper(); } } // namespace omaha
35.748718
123
0.678023
[ "vector" ]
f55d95db351851ccd756c2c4c8ab3f43d788e433
9,063
hpp
C++
include/RootMotion/FinalIK/InteractionTrigger.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/InteractionTrigger.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/RootMotion/FinalIK/InteractionTrigger.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.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: RootMotion::FinalIK namespace RootMotion::FinalIK { } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Transform class Transform; // Forward declaring type: RaycastHit struct RaycastHit; } // Completed forward declares // Type namespace: RootMotion.FinalIK namespace RootMotion::FinalIK { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: RootMotion.FinalIK.InteractionTrigger // [TokenAttribute] Offset: FFFFFFFF // [HelpURLAttribute] Offset: E2A8BC // [AddComponentMenu] Offset: E2A8BC class InteractionTrigger : public UnityEngine::MonoBehaviour { public: // Nested type: RootMotion::FinalIK::InteractionTrigger::CharacterPosition class CharacterPosition; // Nested type: RootMotion::FinalIK::InteractionTrigger::CameraPosition class CameraPosition; // Nested type: RootMotion::FinalIK::InteractionTrigger::Range class Range; // [TooltipAttribute] Offset: 0xE2D500 // public RootMotion.FinalIK.InteractionTrigger/RootMotion.FinalIK.Range[] ranges // Size: 0x8 // Offset: 0x18 ::Array<RootMotion::FinalIK::InteractionTrigger::Range*>* ranges; // Field size check static_assert(sizeof(::Array<RootMotion::FinalIK::InteractionTrigger::Range*>*) == 0x8); // Creating value type constructor for type: InteractionTrigger InteractionTrigger(::Array<RootMotion::FinalIK::InteractionTrigger::Range*>* ranges_ = {}) noexcept : ranges{ranges_} {} // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // Get instance field reference: public RootMotion.FinalIK.InteractionTrigger/RootMotion.FinalIK.Range[] ranges ::Array<RootMotion::FinalIK::InteractionTrigger::Range*>*& dyn_ranges(); // private System.Void OpenUserManual() // Offset: 0x1AD914C void OpenUserManual(); // private System.Void OpenScriptReference() // Offset: 0x1AD9198 void OpenScriptReference(); // private System.Void OpenTutorial4() // Offset: 0x1AD91E4 void OpenTutorial4(); // private System.Void SupportGroup() // Offset: 0x1AD9230 void SupportGroup(); // private System.Void ASThread() // Offset: 0x1AD927C void ASThread(); // private System.Void Start() // Offset: 0x1AD92C8 void Start(); // public System.Int32 GetBestRangeIndex(UnityEngine.Transform character, UnityEngine.Transform raycastFrom, UnityEngine.RaycastHit raycastHit) // Offset: 0x1AD92CC int GetBestRangeIndex(UnityEngine::Transform* character, UnityEngine::Transform* raycastFrom, UnityEngine::RaycastHit raycastHit); // public System.Void .ctor() // Offset: 0x1AD9660 // 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 InteractionTrigger* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::InteractionTrigger::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<InteractionTrigger*, creationType>())); } }; // RootMotion.FinalIK.InteractionTrigger #pragma pack(pop) static check_size<sizeof(InteractionTrigger), 24 + sizeof(::Array<RootMotion::FinalIK::InteractionTrigger::Range*>*)> __RootMotion_FinalIK_InteractionTriggerSizeCheck; static_assert(sizeof(InteractionTrigger) == 0x20); } DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::InteractionTrigger*, "RootMotion.FinalIK", "InteractionTrigger"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::OpenUserManual // Il2CppName: OpenUserManual template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::InteractionTrigger::*)()>(&RootMotion::FinalIK::InteractionTrigger::OpenUserManual)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::InteractionTrigger*), "OpenUserManual", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::OpenScriptReference // Il2CppName: OpenScriptReference template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::InteractionTrigger::*)()>(&RootMotion::FinalIK::InteractionTrigger::OpenScriptReference)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::InteractionTrigger*), "OpenScriptReference", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::OpenTutorial4 // Il2CppName: OpenTutorial4 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::InteractionTrigger::*)()>(&RootMotion::FinalIK::InteractionTrigger::OpenTutorial4)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::InteractionTrigger*), "OpenTutorial4", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::SupportGroup // Il2CppName: SupportGroup template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::InteractionTrigger::*)()>(&RootMotion::FinalIK::InteractionTrigger::SupportGroup)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::InteractionTrigger*), "SupportGroup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::ASThread // Il2CppName: ASThread template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::InteractionTrigger::*)()>(&RootMotion::FinalIK::InteractionTrigger::ASThread)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::InteractionTrigger*), "ASThread", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::Start // Il2CppName: Start template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::InteractionTrigger::*)()>(&RootMotion::FinalIK::InteractionTrigger::Start)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::InteractionTrigger*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::GetBestRangeIndex // Il2CppName: GetBestRangeIndex template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (RootMotion::FinalIK::InteractionTrigger::*)(UnityEngine::Transform*, UnityEngine::Transform*, UnityEngine::RaycastHit)>(&RootMotion::FinalIK::InteractionTrigger::GetBestRangeIndex)> { static const MethodInfo* get() { static auto* character = &::il2cpp_utils::GetClassFromName("UnityEngine", "Transform")->byval_arg; static auto* raycastFrom = &::il2cpp_utils::GetClassFromName("UnityEngine", "Transform")->byval_arg; static auto* raycastHit = &::il2cpp_utils::GetClassFromName("UnityEngine", "RaycastHit")->byval_arg; return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::InteractionTrigger*), "GetBestRangeIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{character, raycastFrom, raycastHit}); } }; // Writing MetadataGetter for method: RootMotion::FinalIK::InteractionTrigger::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
56.64375
258
0.737835
[ "object", "vector", "transform" ]
f55f2d4eb6f03cd9f5fe5652c1c7eb6a62cb8a4d
14,152
cpp
C++
runtime/loader/loader.cpp
gate-computer/gate
b5f1c3e7f5acefcde71861d8aafee0dfffd798f0
[ "BSD-3-Clause" ]
18
2020-07-08T22:26:05.000Z
2022-03-22T17:07:37.000Z
runtime/loader/loader.cpp
gate-computer/gate
b5f1c3e7f5acefcde71861d8aafee0dfffd798f0
[ "BSD-3-Clause" ]
17
2020-09-22T15:12:16.000Z
2022-02-08T06:39:32.000Z
runtime/loader/loader.cpp
gate-computer/gate
b5f1c3e7f5acefcde71861d8aafee0dfffd798f0
[ "BSD-3-Clause" ]
2
2020-10-25T08:59:03.000Z
2021-06-04T23:43:10.000Z
// Copyright (c) 2016 Timo Savola. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <csignal> #include <cstdbool> #include <cstddef> #include <cstdint> #include <cstring> #include <ctime> #include <elf.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include "align.hpp" #include "attribute.hpp" #include "debug.hpp" #include "errors.gen.hpp" #include "runtime.hpp" #include "syscall.hpp" #define SYS_SA_RESTORER 0x04000000 #define SIGACTION_FLAGS (SYS_SA_RESTORER | SA_SIGINFO) #ifdef __ANDROID__ #define ANDROID 1 #define MAYBE_MAP_FIXED 0 #else #define ANDROID 0 #define MAYBE_MAP_FIXED MAP_FIXED #endif #include "loader.hpp" extern "C" { // Avoiding function prototypes avoids GOT section. typedef const class { uint8_t dummy; } code; extern code current_memory; extern code grow_memory; extern code retpoline; extern code rt_debug; extern code rt_nop; extern code rt_poll; extern code rt_random; extern code rt_read8; extern code rt_read; extern code rt_start; extern code rt_start_no_sandbox; extern code rt_text_end; extern code rt_text_start; extern code rt_time; extern code rt_timemask; extern code rt_trap; extern code rt_write8; extern code rt_write; extern code signal_handler; extern code signal_restorer; extern code sys_exit; extern code trap_handler; } // extern "C" namespace { uintptr_t rt_func_addr(void const* new_base, code* func_ptr) { return uintptr_t(new_base) + uintptr_t(func_ptr) - uintptr_t(&rt_text_start); } int sys_close(int fd) { return syscall1(SYS_close, fd); } int sys_fcntl(int fd, int cmd, int arg) { return syscall3(SYS_fcntl, fd, cmd, arg); } void* sys_mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) { intptr_t ret = syscall6(SYS_mmap, uintptr_t(addr), length, prot, flags, fd, offset); if (ret < 0 && ret > -4096) return MAP_FAILED; return reinterpret_cast<void*>(ret); } int sys_mprotect(void* addr, size_t len, int prot) { return syscall3(SYS_mprotect, uintptr_t(addr), len, prot); } void* sys_mremap(void* old_addr, size_t old_size, size_t new_size, int flags) { intptr_t ret = syscall4(SYS_mremap, uintptr_t(old_addr), old_size, new_size, flags); if (ret < 0 && ret > -4096) return MAP_FAILED; return reinterpret_cast<void*>(ret); } int sys_personality(unsigned long persona) { return syscall1(SYS_personality, persona); } int sys_prctl(int option, unsigned long arg2) { return syscall2(SYS_prctl, option, arg2); } ssize_t sys_read(int fd, void* buf, size_t count) { return syscall3(SYS_read, fd, uintptr_t(buf), count); } ssize_t sys_recvmsg(int sockfd, msghdr* msg, int flags) { return syscall3(SYS_recvmsg, sockfd, uintptr_t(msg), flags); } int sys_setrlimit(int resource, rlim_t limit) { const rlimit buf = {limit, limit}; return syscall2(SYS_setrlimit, resource, uintptr_t(&buf)); } // This is like imageInfo in runtime/process.go struct ImageInfo { uint32_t magic_number_1; uint32_t page_size; uint64_t text_addr; uint64_t stack_addr; uint64_t heap_addr; uint64_t random[2]; uint32_t text_size; uint32_t stack_size; uint32_t stack_unused; uint32_t globals_size; uint32_t init_memory_size; uint32_t grow_memory_size; uint32_t init_routine; uint32_t start_addr; uint32_t entry_addr; uint32_t time_mask; uint64_t monotonic_time; uint64_t magic_number_2; } PACKED; // This is like stackVars in image/instance.go struct StackVars { uint32_t stack_unused; uint32_t current_memory_pages; // WebAssembly pages. uint64_t monotonic_time_snapshot; int32_t random_avail; uint32_t suspend_bits; // 0x1 = suspended | 0x2 = don't modify suspend reg uint64_t text_addr; uint64_t result[2]; // [0] is int, [1] is float. uint64_t magic[2]; } PACKED; int receive_info(ImageInfo* buf, int* text_fd, int* state_fd) { iovec iov = {buf, sizeof *buf}; union { char buf[CMSG_SPACE(3 * sizeof(int))]; cmsghdr alignment; } ctl; msghdr msg; memset(&msg, 0, sizeof msg); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = ctl.buf; msg.msg_controllen = sizeof ctl.buf; auto n = sys_recvmsg(GATE_INPUT_FD, &msg, MSG_CMSG_CLOEXEC); if (n < 0) return -1; if (n != sizeof(ImageInfo)) return -1; if (msg.msg_flags & MSG_CTRUNC) return -1; auto cmsg = CMSG_FIRSTHDR(&msg); if (cmsg == nullptr) return -1; if (cmsg->cmsg_level != SOL_SOCKET) return -1; if (cmsg->cmsg_type != SCM_RIGHTS) return -1; auto fds = reinterpret_cast<int const*>(CMSG_DATA(cmsg)); int debug_flag; if (cmsg->cmsg_len == CMSG_LEN(2 * sizeof(int))) { debug_flag = 0; *text_fd = fds[0]; *state_fd = fds[1]; } else if (cmsg->cmsg_len == CMSG_LEN(3 * sizeof(int))) { if (fds[0] != GATE_DEBUG_FD) return -1; debug_flag = 1; *text_fd = fds[1]; *state_fd = fds[2]; } else { return -1; } if (CMSG_NXTHDR(&msg, cmsg)) return -1; return debug_flag; } auto elf_section(Elf64_Ehdr const* elf, unsigned index) { return reinterpret_cast<Elf64_Shdr const*>(uintptr_t(elf) + elf->e_shoff + elf->e_shentsize * index); } auto elf_string(Elf64_Ehdr const* elf, unsigned strtab_index, unsigned str_index) { auto strtab = elf_section(elf, strtab_index); return reinterpret_cast<char const*>(uintptr_t(elf) + strtab->sh_offset + str_index); } int main2(Elf64_Ehdr const* vdso, uintptr_t loader_stack_end) { if (sys_prctl(PR_SET_PDEATHSIG, SIGKILL) != 0) return ERR_LOAD_PDEATHSIG; uintptr_t clock_gettime_addr = 0; for (unsigned i = 0; i < vdso->e_shnum; i++) { auto shdr = elf_section(vdso, i); if (shdr->sh_type != SHT_DYNSYM) continue; for (uint64_t off = 0; off < shdr->sh_size; off += shdr->sh_entsize) { auto vdso_addr = uintptr_t(vdso); auto sym = reinterpret_cast<Elf64_Sym const*>(vdso_addr + shdr->sh_offset + off); auto name = elf_string(vdso, shdr->sh_link, sym->st_name); if (!strcmp_clock_gettime(name)) continue; clock_gettime_addr = vdso_addr + sym->st_value; goto clock_gettime_found; } } return ERR_LOAD_NO_CLOCK_GETTIME; clock_gettime_found: // Miscellaneous preparations. if (MAYBE_MAP_FIXED == 0) { // Undo the ADDR_NO_RANDOMIZE setting as manually randomized // addresses might not be used. if (sys_personality(0) < 0) return ERR_LOAD_PERSONALITY_DEFAULT; } if (sys_setrlimit(RLIMIT_NOFILE, GATE_LIMIT_NOFILE) != 0) return ERR_LOAD_SETRLIMIT_NOFILE; if (sys_setrlimit(RLIMIT_NPROC, 0) != 0) return ERR_LOAD_SETRLIMIT_NPROC; if (GATE_SANDBOX) { if (sys_prctl(PR_SET_DUMPABLE, 0) != 0) return ERR_LOAD_PRCTL_NOT_DUMPABLE; } // Image info and file descriptors ImageInfo info; int text_fd = -1; int state_fd = -1; int debug_flag = receive_info(&info, &text_fd, &state_fd); if (debug_flag < 0) return ERR_LOAD_READ_INFO; if (info.magic_number_1 != GATE_MAGIC_NUMBER_1) return ERR_LOAD_MAGIC_1; if (info.magic_number_2 != GATE_MAGIC_NUMBER_2) return ERR_LOAD_MAGIC_2; // Time timespec t; auto gettime = reinterpret_cast<int (*)(clockid_t, timespec*)>(clock_gettime_addr); if (gettime(CLOCK_MONOTONIC_COARSE, &t) != 0) return ERR_LOAD_CLOCK_GETTIME; t.tv_sec--; // Ensure that rt_time never returns zero timestamp. t.tv_nsec &= uint64_t(info.time_mask); auto local_monotonic_time_base = uint64_t(t.tv_sec) * 1000000000ULL + uint64_t(t.tv_nsec); // RT: text at start, import vector at end (and maybe space for text) auto rt_map_size = info.page_size + (ANDROID ? info.text_size : 0); auto rt = sys_mmap(reinterpret_cast<void*>(info.text_addr - uintptr_t(info.page_size)), rt_map_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAYBE_MAP_FIXED, -1, 0); if (rt == MAP_FAILED) return ERR_LOAD_MMAP_VECTOR; auto rt_size = uintptr_t(&rt_text_end) - uintptr_t(&rt_text_start); memcpy(rt, &rt_text_start, rt_size); auto vector_end = reinterpret_cast<uint64_t*>(uintptr_t(rt) + info.page_size); // Text void* text_ptr = vector_end; if (ANDROID) { if (sys_read(text_fd, text_ptr, info.text_size) != info.text_size) return ERR_LOAD_READ_TEXT; } else { auto ret = sys_mmap(text_ptr, info.text_size, PROT_READ | PROT_EXEC, MAP_PRIVATE | MAP_FIXED, text_fd, 0); if (ret == MAP_FAILED) return ERR_LOAD_MMAP_TEXT; } if (sys_close(text_fd) != 0) return ERR_LOAD_CLOSE_TEXT; // Stack auto stack_buf = sys_mmap(reinterpret_cast<void*>(info.stack_addr), info.stack_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAYBE_MAP_FIXED, state_fd, 0); if (stack_buf == MAP_FAILED) return ERR_LOAD_MMAP_STACK; auto vars = reinterpret_cast<StackVars volatile*>(stack_buf); vars->stack_unused = 0; // Invalidate state (in case of re-entry). vars->current_memory_pages = info.init_memory_size >> 16; vars->monotonic_time_snapshot = info.monotonic_time; vars->random_avail = sizeof info.random; vars->suspend_bits = 0; vars->text_addr = uintptr_t(text_ptr); for (unsigned i = 0; i < sizeof vars->result / sizeof vars->result[0]; i++) vars->result[i] = 0x5adfad0cafe; for (unsigned i = 0; i < sizeof vars->magic / sizeof vars->magic[0]; i++) vars->magic[i] = GATE_STACK_MAGIC; auto stack_limit = uintptr_t(stack_buf) + GATE_STACK_LIMIT_OFFSET; auto stack_ptr = reinterpret_cast<uint64_t*>(stack_buf) + info.stack_unused / 8; if (info.stack_unused == info.stack_size) { // Synthesize initial stack frame for start or entry routine // (checked in runtime/process.go). *--stack_ptr = info.entry_addr; *--stack_ptr = info.start_addr; } // Globals and memory auto heap_offset = size_t(info.stack_size); auto heap_allocated = size_t(info.globals_size) + size_t(info.init_memory_size); auto heap_size = size_t(info.globals_size) + size_t(info.grow_memory_size); void* heap_ptr; if (ANDROID) { auto space = size_t(info.globals_size) + MEMORY_ADDRESS_RANGE; heap_ptr = sys_mmap(reinterpret_cast<void*>(info.heap_addr), space, PROT_READ | PROT_WRITE, MAP_SHARED, state_fd, heap_offset); if (heap_ptr == MAP_FAILED) return ERR_LOAD_MMAP_HEAP; auto ret = sys_mremap(heap_ptr, space, heap_allocated, 0); if (ret == MAP_FAILED || ret != heap_ptr) return ERR_LOAD_MREMAP_HEAP; } else { if (heap_size > 0) { heap_ptr = sys_mmap(reinterpret_cast<void*>(info.heap_addr), heap_size, PROT_NONE, MAP_SHARED | MAP_FIXED, state_fd, heap_offset); if (heap_ptr == MAP_FAILED) return ERR_LOAD_MMAP_HEAP; if (heap_allocated > 0) { if (sys_mprotect(heap_ptr, heap_allocated, PROT_READ | PROT_WRITE) != 0) return ERR_LOAD_MPROTECT_HEAP; } } else { // Memory address cannot be arbitrary (such as null), otherwise it // could be followed by other memory mappings. heap_ptr = reinterpret_cast<void*>(info.heap_addr); } } auto memory_addr = uintptr_t(heap_ptr) + info.globals_size; if (sys_close(state_fd) != 0) return ERR_LOAD_CLOSE_STATE; // Vector; runtime/text protection auto debug_func = debug_flag ? &rt_debug : &rt_nop; // These assignments reflect the functions map in runtime/abi/rt/rt.go // and rtFunctions map in runtime/abi/abi.go // TODO: check that runtime and vector contents don't overlap *(vector_end - 20) = rt_func_addr(rt, &rt_timemask); *(vector_end - 19) = rt_func_addr(rt, &rt_write8); *(vector_end - 18) = rt_func_addr(rt, &rt_read8); *(vector_end - 17) = rt_func_addr(rt, &rt_trap); *(vector_end - 16) = rt_func_addr(rt, debug_func); *(vector_end - 15) = rt_func_addr(rt, &rt_write); *(vector_end - 14) = rt_func_addr(rt, &rt_read); *(vector_end - 13) = rt_func_addr(rt, &rt_poll); *(vector_end - 12) = rt_func_addr(rt, &rt_time); *(vector_end - 11) = clock_gettime_addr; *(vector_end - 10) = local_monotonic_time_base; *(vector_end - 9) = info.time_mask; *(vector_end - 8) = info.random[0]; *(vector_end - 7) = info.random[1]; *(vector_end - 6) = rt_func_addr(rt, &rt_random); *(vector_end - 5) = info.grow_memory_size >> 16; *(vector_end - 4) = memory_addr; *(vector_end - 3) = rt_func_addr(rt, &current_memory); *(vector_end - 2) = rt_func_addr(rt, &grow_memory); *(vector_end - 1) = rt_func_addr(rt, &trap_handler); if (sys_mprotect(rt, rt_map_size, PROT_READ | PROT_EXEC) != 0) return ERR_LOAD_MPROTECT_VECTOR; // Non-blocking I/O. if (sys_fcntl(GATE_INPUT_FD, F_SETFL, O_NONBLOCK) != 0) return ERR_LOAD_FCNTL_INPUT; if (sys_fcntl(GATE_OUTPUT_FD, F_SETFL, O_NONBLOCK) != 0) return ERR_LOAD_FCNTL_OUTPUT; // Start runtime. auto start = GATE_SANDBOX ? &rt_start : &rt_start_no_sandbox; auto pagemask = uintptr_t(info.page_size) - 1; auto loader_stack_size = align_size(GATE_LOADER_STACK_SIZE, info.page_size); auto loader_stack = ((loader_stack_end + pagemask) & ~pagemask) - loader_stack_size; enter(stack_ptr, stack_limit, rt_func_addr(rt, start), loader_stack, loader_stack_size, rt_func_addr(rt, &signal_handler), rt_func_addr(rt, &signal_restorer), uintptr_t(text_ptr) + info.init_routine); __builtin_unreachable(); } template <typename T> void copy(T* dest, T const* src, size_t n) { for (size_t i = 0; i < n; i++) *dest++ = *src++; } } // namespace extern "C" { void* memcpy(void* dest, void const* src, size_t n) { // This is used to copy rt text, so put medium effort into optimization. struct Block64 { uint64_t data[8]; } PACKED; auto d = reinterpret_cast<Block64*>(dest); auto s = reinterpret_cast<Block64 const*>(src); size_t blocks = n / 64; copy(d, s, blocks); size_t tail = n & 63; if (tail) { d += blocks; s += blocks; copy(reinterpret_cast<uint8_t*>(d), reinterpret_cast<uint8_t const*>(s), tail); } return dest; } void* memset(void* dest, int c, size_t n) { auto d = reinterpret_cast<uint8_t*>(dest); for (size_t i = 0; i < n; i++) d[i] = c; return dest; } size_t strlen(char const* s) { size_t n = 0; while (*s++) n++; return n; } } // extern "C" SECTION(".text") int main(int argc UNUSED, char** argv, char** envp) { // _start smuggles vDSO ELF address as argv and stack address as envp. return main2(reinterpret_cast<Elf64_Ehdr const*>(argv), uintptr_t(envp)); }
26.651601
180
0.719969
[ "vector" ]
f55faff7d468df7a8ca90c4d682511f83ca296f4
2,980
cpp
C++
source/uwp/Renderer/lib/CustomElementWrapper.cpp
TemoeBOUISSOU/AdaptiveCards
61aa500b86bfe69bd0f68a27d0ea041c210b3890
[ "MIT" ]
2
2021-07-29T04:12:57.000Z
2021-09-12T13:16:50.000Z
source/uwp/Renderer/lib/CustomElementWrapper.cpp
TemoeBOUISSOU/AdaptiveCards
61aa500b86bfe69bd0f68a27d0ea041c210b3890
[ "MIT" ]
null
null
null
source/uwp/Renderer/lib/CustomElementWrapper.cpp
TemoeBOUISSOU/AdaptiveCards
61aa500b86bfe69bd0f68a27d0ea041c210b3890
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "pch.h" #include "CustomElementWrapper.h" using namespace Microsoft::WRL; using namespace ABI::AdaptiveCards::Rendering::Uwp; namespace AdaptiveCards::Rendering::Uwp { CustomElementWrapper::CustomElementWrapper(_In_ ABI::AdaptiveCards::Rendering::Uwp::IAdaptiveCardElement* cardElement) : BaseCardElement(AdaptiveCards::CardElementType::Custom), m_cardElement(cardElement) { BaseElement::SetId(GetCardElementId()); } bool CustomElementWrapper::GetSeparator() const { boolean hasSeparator; THROW_IF_FAILED(m_cardElement->get_Separator(&hasSeparator)); return hasSeparator; } void CustomElementWrapper::SetSeparator(bool value) { THROW_IF_FAILED(m_cardElement->put_Separator(value)); } Spacing CustomElementWrapper::GetSpacing() const { ABI::AdaptiveCards::Rendering::Uwp::Spacing spacing; THROW_IF_FAILED(m_cardElement->get_Spacing(&spacing)); return static_cast<Spacing>(spacing); } void CustomElementWrapper::SetSpacing(Spacing value) { THROW_IF_FAILED(m_cardElement->put_Spacing(static_cast<ABI::AdaptiveCards::Rendering::Uwp::Spacing>(value))); } void CustomElementWrapper::SetId(std::string&& value) { SetCardElementId(value); BaseElement::SetId(std::move(value)); } void CustomElementWrapper::SetId(const std::string& value) { SetCardElementId(value); BaseElement::SetId(value); } Json::Value CustomElementWrapper::SerializeToJsonValue() const { ComPtr<ABI::Windows::Data::Json::IJsonObject> jsonObject; THROW_IF_FAILED(m_cardElement->ToJson(&jsonObject)); Json::Value jsonCppValue; JsonObjectToJsonCpp(jsonObject.Get(), &jsonCppValue); return jsonCppValue; } void CustomElementWrapper::GetResourceInformation(std::vector<RemoteResourceInformation>& resourceInfo) { ComPtr<ABI::AdaptiveCards::Rendering::Uwp::IAdaptiveElementWithRemoteResources> remoteResources; if (SUCCEEDED(m_cardElement.As(&remoteResources))) { RemoteResourceElementToRemoteResourceInformationVector(remoteResources.Get(), resourceInfo); } } HRESULT CustomElementWrapper::GetWrappedElement(_COM_Outptr_ ABI::AdaptiveCards::Rendering::Uwp::IAdaptiveCardElement** cardElement) { return m_cardElement.CopyTo(cardElement); } std::string CustomElementWrapper::GetCardElementId() const { Wrappers::HString id; THROW_IF_FAILED(m_cardElement->get_Id(id.GetAddressOf())); return HStringToUTF8(id.Get()); } void CustomElementWrapper::SetCardElementId(const std::string& value) { Wrappers::HString id; THROW_IF_FAILED(UTF8ToHString(value, id.GetAddressOf())); THROW_IF_FAILED(m_cardElement->put_Id(id.Get())); } }
33.111111
136
0.705369
[ "vector" ]
f5602023c5c6755f1c40bc78f2526aa89c48bb1a
93,404
cpp
C++
ngraph/test/eval.cpp
ElenaGvozdeva/openvino
084aa4e5916fa2ed3e353dcd45d081ab11d9c75a
[ "Apache-2.0" ]
1
2022-02-10T08:05:09.000Z
2022-02-10T08:05:09.000Z
ngraph/test/eval.cpp
ElenaGvozdeva/openvino
084aa4e5916fa2ed3e353dcd45d081ab11d9c75a
[ "Apache-2.0" ]
40
2020-12-04T07:46:57.000Z
2022-02-21T13:04:40.000Z
ngraph/test/eval.cpp
ElenaGvozdeva/openvino
084aa4e5916fa2ed3e353dcd45d081ab11d9c75a
[ "Apache-2.0" ]
1
2021-08-18T14:29:37.000Z
2021-08-18T14:29:37.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <cmath> #include <cstddef> #include <string> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ngraph/node.hpp" #include "ngraph/node_output.hpp" #include "ngraph/op/abs.hpp" #include "ngraph/op/acos.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/asin.hpp" #include "ngraph/op/atan.hpp" #include "ngraph/op/broadcast.hpp" #include "ngraph/op/ceiling.hpp" #include "ngraph/op/concat.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/op/convert.hpp" #include "ngraph/op/cos.hpp" #include "ngraph/op/cosh.hpp" #include "ngraph/op/erf.hpp" #include "ngraph/op/exp.hpp" #include "ngraph/op/floor.hpp" #include "ngraph/op/gather.hpp" #include "ngraph/op/log.hpp" #include "ngraph/op/max_pool.hpp" #include "ngraph/op/min.hpp" #include "ngraph/op/minimum.hpp" #include "ngraph/op/negative.hpp" #include "ngraph/op/non_zero.hpp" #include "ngraph/op/not.hpp" #include "ngraph/op/parameter.hpp" #include "ngraph/op/range.hpp" #include "ngraph/op/reduce_logical_and.hpp" #include "ngraph/op/relu.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/op/round.hpp" #include "ngraph/op/scatter_elements_update.hpp" #include "ngraph/op/scatter_update.hpp" #include "ngraph/op/shape_of.hpp" #include "ngraph/op/sigmoid.hpp" #include "ngraph/op/sign.hpp" #include "ngraph/op/sin.hpp" #include "ngraph/op/sinh.hpp" #include "ngraph/op/sqrt.hpp" #include "ngraph/op/squeeze.hpp" #include "ngraph/op/tan.hpp" #include "ngraph/op/tanh.hpp" #include "ngraph/op/topk.hpp" #include "ngraph/op/unsqueeze.hpp" #include "ngraph/runtime/host_tensor.hpp" #include "ngraph/validation_util.hpp" #include "util/all_close_f.hpp" #include "util/ndarray.hpp" #include "util/test_tools.hpp" #include "util/type_prop.hpp" NGRAPH_SUPPRESS_DEPRECATED_START using namespace std; using namespace ngraph; #define ASSERT_FLOAT_VECTORS_EQ(expected, result) \ ASSERT_EQ(expected.size(), result.size()) << "Array sizes differ."; \ for (size_t i = 0; i < expected.size(); ++i) \ { \ ASSERT_FLOAT_EQ(expected[i], result[i]) << "at index: " << i; \ } TEST(eval, bad_get_data_ptr) { HostTensor c(element::f32, Shape{}); *c.get_data_ptr<float>() = 1.0; EXPECT_EQ(*c.get_data_ptr<element::Type_t::f32>(), 1.0); try { c.get_data_ptr<element::Type_t::f64>(); FAIL() << "Bad type not detected."; } catch (const CheckFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("get_data_ptr")); } try { c.get_data_ptr<element::Type_t::i32>(); FAIL() << "Bad type not detected."; } catch (const CheckFailure& error) { EXPECT_HAS_SUBSTRING(error.what(), std::string("get_data_ptr")); } } TEST(eval, max_eval_parameter) { auto p = make_shared<op::Parameter>(element::i64, Shape{}); auto result = maximum_value(p); EXPECT_FALSE(result.first); EXPECT_EQ(result.second, numeric_limits<uint64_t>::max()); } TEST(eval, max_eval_constant) { auto c = op::Constant::create<int64_t>(element::i64, Shape{}, {27}); auto result = maximum_value(c); ASSERT_TRUE(result.first); EXPECT_EQ(result.second, 27); } TEST(eval, max_eval_minimum_constant) { auto c = op::Constant::create<int64_t>(element::i64, Shape{}, {27}); auto p = make_shared<op::Parameter>(element::i64, Shape{}); auto m = make_shared<op::v1::Minimum>(c, p); auto result = maximum_value(m); ASSERT_TRUE(result.first); EXPECT_EQ(result.second, 27); } TEST(eval, max_eval_reduce_min) { auto concat = make_shared<op::v0::Convert>( make_shared<op::v0::Concat>( OutputVector{make_shared<op::v0::Parameter>(element::i64, Shape{4}), make_shared<op::v0::Constant>(element::i64, Shape{4}, 37)}, 0), element::i32); auto reduce = make_shared<op::v0::Convert>( make_shared<op::v1::ReduceMin>(concat, make_shared<op::v0::Constant>(element::i32, Shape{1}, 0)), element::i64); auto squeezes = make_shared<op::v0::Squeeze>( make_shared<op::v0::Unsqueeze>(reduce, make_shared<op::v0::Constant>(element::i32, Shape{1}, 0)), make_shared<op::v0::Constant>(element::i64, Shape{1}, 0)); EXPECT_EQ(maximum_value(squeezes).second, 37); } TEST(eval, evaluate_shape_of) { auto p = make_shared<op::Parameter>(element::f32, PartialShape{-1, -1}); auto so = make_shared<op::v0::ShapeOf>(p); auto fun = make_shared<Function>(OutputVector{so}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3}, {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f})})); EXPECT_EQ(result->get_element_type(), element::i64); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2})); auto result_shape = read_vector<int64_t>(result); vector<int64_t> arg_shape{2, 3}; ASSERT_EQ(result_shape, arg_shape); } TEST(eval, evaluate_dynamic_range_sum) { auto p_start = make_shared<op::Parameter>(element::f32, PartialShape{}); auto p_stop = make_shared<op::Parameter>(element::f32, PartialShape{}); auto p_step = make_shared<op::Parameter>(element::f32, PartialShape{}); auto p1 = make_shared<op::Parameter>(element::f32, PartialShape{}); auto range = make_shared<op::v0::Range>(p_start, p_stop, p_step); auto add = make_shared<op::v1::Add>(range, p1); auto fun = make_shared<Function>(OutputVector{add}, ParameterVector{p_start, p_stop, p_step, p1}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>({}, {1.0f}), make_host_tensor<element::Type_t::f32>({}, {10.0f}), make_host_tensor<element::Type_t::f32>({}, {3.0f}), make_host_tensor<element::Type_t::f32>({}, {7.0f})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3})); auto cval = read_vector<float>(result_tensor); vector<float> seq{8.0f, 11.0f, 14.0f}; ASSERT_EQ(cval, seq); } #ifdef NGRAPH_INTERPRETER_ENABLE TEST(eval, interpret_dynamic_range_sum) { auto p_start = make_shared<op::Parameter>(element::f32, PartialShape{}); auto p_stop = make_shared<op::Parameter>(element::f32, PartialShape{}); auto p_step = make_shared<op::Parameter>(element::f32, PartialShape{}); auto p1 = make_shared<op::Parameter>(element::f32, PartialShape{}); auto range = make_shared<op::v0::Range>(p_start, p_stop, p_step); auto add = make_shared<op::v1::Add>(range, p1); auto fun = make_shared<Function>(OutputVector{add}, ParameterVector{p_start, p_stop, p_step, p1}); auto backend = runtime::Backend::create("INTERPRETER"); auto p_start_val = backend->create_tensor(element::f32, Shape{}); copy_data(p_start_val, vector<float>{1.0f}); auto p_stop_val = backend->create_tensor(element::f32, Shape{}); copy_data(p_stop_val, vector<float>{10.0f}); auto p_step_val = backend->create_tensor(element::f32, Shape{}); copy_data(p_step_val, vector<float>{3.0f}); auto p1_val = backend->create_tensor(element::f32, Shape{}); copy_data(p1_val, vector<float>{7.0f}); auto result = backend->create_tensor(); auto cfun = backend->compile(fun); cfun->call({result}, {p_start_val, p_stop_val, p_step_val, p1_val}); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{3})); auto result_val = read_vector<float>(result); vector<float> seq{8.0f, 11.0f, 14.0f}; ASSERT_EQ(result_val, seq); } #endif TEST(eval, evaluate_broadcast_v3_bidirectional) { Shape shape_a{4, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int32_t>(element::i32, Shape{3}, {2, 1, 4}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape, op::BroadcastType::BIDIRECTIONAL); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{4, 1}, {1.0f, 2.0f, 3.0f, 4.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 4, 4})); auto result_val = read_vector<float>(result); vector<float> expec{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_bidirectional_target_rank_smaller_than_input) { Shape shape_a{1, 1, 1, 1, 1, 1, 1, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{4}, {1, 3, 1, 1}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape, op::BroadcastType::BIDIRECTIONAL); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(shape_a, {1.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{1, 1, 1, 1, 1, 3, 1, 1})); auto result_val = read_vector<float>(result); vector<float> expec{1.0f, 1.0f, 1.0f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_bidirectional_target_rank_smaller_than_input_2) { Shape shape_a{1, 3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int32_t>(element::i32, Shape{2}, {3, 1}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape, op::BroadcastType::BIDIRECTIONAL); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{1, 3, 1}, {1.0f, 2.0f, 3.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{1, 3, 1})); auto result_val = read_vector<float>(result); vector<float> expec{1.0f, 2.0f, 3.0f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_bidirectional_dyn) { Shape shape_a{4, 1}; auto A = make_shared<op::Parameter>(element::i32, shape_a); auto target_shape = make_shared<op::Parameter>(element::i32, Shape{3}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape, op::BroadcastType::BIDIRECTIONAL); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A, target_shape}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::i32>(Shape{4, 1}, {1, 2, 3, 4}), make_host_tensor<element::Type_t::i32>(Shape{3}, {2, 1, 4})})); EXPECT_EQ(result->get_element_type(), element::i32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 4, 4})); auto result_val = read_vector<int32_t>(result); vector<int32_t> expec{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_numpy) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{3}, {2, 3, 6}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_numpy_dyn) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = make_shared<op::Parameter>(element::i32, Shape{3}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A, target_shape}); auto result = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f}), make_host_tensor<element::Type_t::i32>(Shape{3}, {2, 3, 6})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_numpy_vs_bidi) { Shape in_shape{1, 4, 1}; auto A = make_shared<op::Parameter>(element::f32, in_shape); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{3}, {1, 4, 4}); auto bcast_v3_num = make_shared<op::v3::Broadcast>(A, target_shape, op::BroadcastType::NUMPY); auto fun_num = make_shared<Function>(OutputVector{bcast_v3_num}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun_num->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(in_shape, {1.0f, 2.0f, 3.0f, 4.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{1, 4, 4})); auto result_val = read_vector<float>(result); vector<float> expec{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}; ASSERT_EQ(expec, result_val); auto target_shape2 = op::Constant::create<int64_t>(element::i64, Shape{2}, {1, 4}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape2, op::BroadcastType::BIDIRECTIONAL); auto fun_bidi = make_shared<Function>(OutputVector{bcast_v3_num}, ParameterVector{A}); auto result2 = make_shared<HostTensor>(); ASSERT_TRUE(fun_bidi->evaluate( {result2}, {make_host_tensor<element::Type_t::f32>(in_shape, {1.0f, 2.0f, 3.0f, 4.0f})})); EXPECT_EQ(result2->get_element_type(), element::f32); EXPECT_EQ(result2->get_partial_shape(), (PartialShape{1, 4, 4})); auto result_val2 = read_vector<float>(result2); vector<float> expec2{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}; ASSERT_EQ(expec2, result_val2); } TEST(eval, evaluate_broadcast_v3_bidi_3d) { Shape in_shape{1, 4, 1}; auto A = make_shared<op::Parameter>(element::f32, in_shape); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{3}, {1, 1, 3}); auto bcast_v3_num = make_shared<op::v3::Broadcast>(A, target_shape, op::BroadcastType::BIDIRECTIONAL); auto fun_num = make_shared<Function>(OutputVector{bcast_v3_num}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun_num->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(in_shape, {1.0f, 2.0f, 3.0f, 4.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{1, 4, 3})); auto result_val = read_vector<float>(result); vector<float> expec{1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, 4.0f}; ASSERT_EQ(expec, result_val); } TEST(eval, evaluate_broadcast_v3_bidi_4d) { Shape in_shape{4, 1, 1}; Shape expec_shape{1, 4, 2, 2}; auto A = make_shared<op::Parameter>(element::f32, in_shape); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{4}, {1, 1, 2, 2}); auto bcast_v3 = make_shared<op::v3::Broadcast>(A, target_shape, op::BroadcastType::BIDIRECTIONAL); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(in_shape, {1.0f, 2.0f, 3.0f, 4.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{1, 4, 2, 2})); auto result_val = read_vector<float>(result); vector<float> expec{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_pdpd) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{3}, {2, 3, 6}); auto bcast_v3 = make_shared<op::v3::Broadcast>( A, target_shape, op::BroadcastModeSpec(op::BroadcastType::PDPD, 1)); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_pdpd_dyn) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = make_shared<op::Parameter>(element::i32, Shape{3}); auto bcast_v3 = make_shared<op::v3::Broadcast>( A, target_shape, op::BroadcastModeSpec(op::BroadcastType::PDPD, 1)); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A, target_shape}); auto result = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f}), make_host_tensor<element::Type_t::i32>(Shape{3}, {2, 3, 6})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v1_numpy) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{3}, {2, 3, 6}); auto bcast_v3 = make_shared<op::v1::Broadcast>(A, target_shape); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v1_numpy_dyn) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = make_shared<op::Parameter>(element::i64, Shape{3}); auto bcast_v3 = make_shared<op::v1::Broadcast>(A, target_shape); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A, target_shape}); auto result = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f}), make_host_tensor<element::Type_t::i64>(Shape{3}, {2, 3, 6})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v1_pdpd) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{3}, {2, 3, 6}); auto bcast_v3 = make_shared<op::v1::Broadcast>( A, target_shape, op::AutoBroadcastSpec(op::AutoBroadcastType::PDPD, 1)); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v1_pdpd_dyn) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = make_shared<op::Parameter>(element::i64, Shape{3}); auto bcast_v3 = make_shared<op::v1::Broadcast>( A, target_shape, op::AutoBroadcastSpec(op::AutoBroadcastType::PDPD, 1)); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A, target_shape}); auto result = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f}), make_host_tensor<element::Type_t::i64>(Shape{3}, {2, 3, 6})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 6})); auto result_val = read_vector<float>(result); vector<float> expec{ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, }; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v1_explicit) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = op::Constant::create<int64_t>(element::i64, Shape{3}, {2, 3, 1}); auto axes_mapping = op::Constant::create<int32_t>(element::i32, Shape{2}, {1, 2}); auto bcast_v3 = make_shared<op::v1::Broadcast>( A, target_shape, axes_mapping, op::AutoBroadcastSpec(op::AutoBroadcastType::EXPLICIT)); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 1})); auto result_val = read_vector<float>(result); vector<float> expec{1, 2, 3, 1, 2, 3}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v1_explicit_dyn) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = make_shared<op::Parameter>(element::i64, Shape{3}); auto axes_mapping = make_shared<op::Parameter>(element::i32, Shape{2}); auto bcast_v1 = make_shared<op::v1::Broadcast>( A, target_shape, axes_mapping, op::AutoBroadcastSpec(op::AutoBroadcastType::EXPLICIT)); auto fun = make_shared<Function>(OutputVector{bcast_v1}, ParameterVector{A, target_shape, axes_mapping}); auto result = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f}), make_host_tensor<element::Type_t::i64>(Shape{3}, {2, 3, 1}), make_host_tensor<element::Type_t::i32>(Shape{2}, {1, 2})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 1})); auto result_val = read_vector<float>(result); vector<float> expec{1, 2, 3, 1, 2, 3}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_broadcast_v3_explicit_dyn) { Shape shape_a{3, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); auto target_shape = make_shared<op::Parameter>(element::i64, Shape{3}); auto axes_mapping = make_shared<op::Parameter>(element::i32, Shape{2}); auto bcast_v3 = make_shared<op::v3::Broadcast>( A, target_shape, axes_mapping, op::BroadcastModeSpec(op::BroadcastType::EXPLICIT)); auto fun = make_shared<Function>(OutputVector{bcast_v3}, ParameterVector{A, target_shape, axes_mapping}); auto result = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 1}, {1.0f, 2.0f, 3.0f}), make_host_tensor<element::Type_t::i64>(Shape{3}, {2, 3, 1}), make_host_tensor<element::Type_t::i32>(Shape{2}, {1, 2})})); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3, 1})); auto result_val = read_vector<float>(result); vector<float> expec{1, 2, 3, 1, 2, 3}; ASSERT_EQ(result_val, expec); } TEST(eval, test_op_multi_out) { auto p = make_shared<op::Parameter>(element::f32, PartialShape{2, 3}); auto p2 = make_shared<op::Parameter>(element::f64, PartialShape{2, 2}); auto so = make_shared<TestOpMultiOut>(p, p2); auto fun = make_shared<Function>(OutputVector{so->output(0), so->output(1)}, ParameterVector{p, p2}); auto result = make_shared<HostTensor>(element::Type_t::f32, Shape{2, 3}); auto result2 = make_shared<HostTensor>(element::Type_t::f64, Shape{2, 2}); HostTensorVector ins{make_host_tensor<element::Type_t::f32>(Shape{2, 3}), make_host_tensor<element::Type_t::f64>(Shape{2, 2})}; ASSERT_TRUE(fun->evaluate({result, result2}, ins)); EXPECT_EQ(result->get_element_type(), element::f32); EXPECT_EQ(result->get_partial_shape(), (PartialShape{2, 3})); auto result_val = read_vector<float>(result); auto arg_val = read_vector<float>(ins[0]); ASSERT_EQ(result_val, arg_val); EXPECT_EQ(result2->get_element_type(), element::f64); EXPECT_EQ(result2->get_partial_shape(), (PartialShape{2, 2})); auto result_val2 = read_vector<double>(result2); auto arg_val2 = read_vector<double>(ins[1]); ASSERT_EQ(result_val2, arg_val2); } TEST(eval, evaluate_reshape_v1) { auto data = make_shared<op::Parameter>(element::f32, Shape{2, 5}); auto pattern = make_shared<op::Parameter>(element::i64, Shape{2}); auto dyn_reshape = make_shared<op::v1::Reshape>(data, pattern, false); auto func = make_shared<Function>(OutputVector{dyn_reshape}, ParameterVector{data, pattern}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(func->evaluate( {result_tensor}, {make_host_tensor<element::Type_t::f32>({2, 5}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}), make_host_tensor<element::Type_t::i64>({2}, {5, 2})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{5, 2})); auto computed_val = read_vector<float>(result_tensor); vector<float> expected_val{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_EQ(computed_val, expected_val); } TEST(eval, evaluate_reshape_v1_negative_index) { auto data = make_shared<op::Parameter>(element::f32, Shape{2, 5}); auto pattern = make_shared<op::Parameter>(element::i64, Shape{2}); auto dyn_reshape = make_shared<op::v1::Reshape>(data, pattern, false); auto func = make_shared<Function>(OutputVector{dyn_reshape}, ParameterVector{data, pattern}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(func->evaluate( {result_tensor}, {make_host_tensor<element::Type_t::f32>({2, 5}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}), make_host_tensor<element::Type_t::i64>({2}, {2, -1})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{2, 5})); auto computed_val = read_vector<float>(result_tensor); vector<float> expected_val{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; ASSERT_EQ(computed_val, expected_val); } TEST(eval, evaluate_reshape_v1_negative_index_zero_dim_zero_flag) { auto data = make_shared<op::Parameter>(element::f32, Shape{2, 2, 2, 2}); auto pattern = make_shared<op::Parameter>(element::i64, Shape{6}); auto dyn_reshape = make_shared<op::v1::Reshape>(data, pattern, true); auto func = make_shared<Function>(OutputVector{dyn_reshape}, ParameterVector{data, pattern}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE( func->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( {2, 2, 2, 2}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}), make_host_tensor<element::Type_t::i64>({6}, {2, 0, 1, -1, 1, 2})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{2, 2, 1, 2, 1, 2})); auto computed_val = read_vector<float>(result_tensor); vector<float> expected_val{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; ASSERT_EQ(computed_val, expected_val); } TEST(eval, evaluate_reshape_v1_pattern_int16) { auto data = make_shared<op::Parameter>(element::f32, Shape{2, 2, 2, 2}); auto pattern = make_shared<op::Parameter>(element::i16, Shape{6}); auto dyn_reshape = make_shared<op::v1::Reshape>(data, pattern, true); auto func = make_shared<Function>(OutputVector{dyn_reshape}, ParameterVector{data, pattern}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE( func->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( {2, 2, 2, 2}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}), make_host_tensor<element::Type_t::i16>({6}, {2, 0, 1, -1, 1, 2})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{2, 2, 1, 2, 1, 2})); auto computed_val = read_vector<float>(result_tensor); vector<float> expected_val{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; ASSERT_EQ(computed_val, expected_val); } TEST(eval, evaluate_convert) { auto p = make_shared<op::Parameter>(element::f32, PartialShape{-1, -1}); auto convert = make_shared<op::v0::Convert>(p, element::i64); auto fun = make_shared<Function>(OutputVector{convert}, ParameterVector{p}); std::vector<std::vector<float>> inputs{{-1, 1}}; std::vector<std::vector<int64_t>> expected_result{{-1, 1}}; for (size_t i = 0; i < inputs.size(); i++) { auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{1, 2}, inputs[i])})); EXPECT_EQ(result->get_element_type(), element::i64); EXPECT_EQ(result->get_shape(), (Shape{1, 2})); auto result_data = read_vector<int64_t>(result); ASSERT_EQ(result_data, expected_result[i]); } } TEST(eval, evaluate_abs) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 3}); auto abs = make_shared<op::Abs>(p); auto fun = make_shared<Function>(OutputVector{abs}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3}, {0.0f, -1.0f, -2.0f, -3.0f, 4.0f, 5.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_erf) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 3}); auto erf = make_shared<op::Erf>(p); auto fun = make_shared<Function>(OutputVector{erf}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3}, {0.0f, -1.0f, -2.0f, -3.0f, 4.0f, 5.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{std::erf(0.0f), std::erf(-1.0f), std::erf(-2.0f), std::erf(-3.0f), std::erf(4.0f), std::erf(5.0f)}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_exp) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 3}); auto exp = make_shared<op::Exp>(p); auto fun = make_shared<Function>(OutputVector{exp}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3}, {0.0f, -1.0f, -2.0f, -3.0f, 4.0f, 5.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{std::exp(0.0f), std::exp(-1.0f), std::exp(-2.0f), std::exp(-3.0f), std::exp(4.0f), std::exp(5.0f)}; ASSERT_FLOAT_VECTORS_EQ(expec, result_val); } TEST(eval, evaluate_floor) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 2}); auto floor = make_shared<op::Floor>(p); auto fun = make_shared<Function>(OutputVector{floor}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{2, 2}, {-2.5f, -2.0f, 0.3f, 4.8f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{-3.0f, -2.0f, 0.0f, 4.0f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_floor_int32) { auto p = make_shared<op::Parameter>(element::i32, Shape{2, 2}); auto floor = make_shared<op::Floor>(p); auto fun = make_shared<Function>(OutputVector{floor}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::i32>( Shape{2, 2}, {-2, -136314888, 0x40000010, 0x40000001})})); EXPECT_EQ(result->get_element_type(), element::i32); auto result_val = read_vector<int32_t>(result); vector<int32_t> expec{-2, -136314888, 0x40000010, 0x40000001}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_log) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 2, 2}); auto log = make_shared<op::Log>(p); auto fun = make_shared<Function>(OutputVector{log}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>( Shape{2, 2, 2}, {0.125f, 0.25f, 0.5f, 1.f, 2.f, 4.f, 8.f, 16.f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{std::log(0.125f), std::log(0.25f), std::log(0.5f), std::log(1.f), std::log(2.f), std::log(4.f), std::log(8.f), std::log(16.f)}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_negative_f32) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 5}); auto negate = make_shared<op::Negative>(p); auto fun = make_shared<Function>(OutputVector{negate}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>( Shape{2, 5}, {1.35f, 8.76f, -8.0f, 17.234f, -2.121f, 1.0f, 8.7f, -8.92f, 17.0f, -1.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{-1.35f, -8.76f, 8.0f, -17.234f, 2.121f, -1.0f, -8.7f, 8.92f, -17.0f, 1.0f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_negative_i32) { auto p = make_shared<op::Parameter>(element::i32, Shape{2, 5}); auto negate = make_shared<op::Negative>(p); auto fun = make_shared<Function>(OutputVector{negate}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::i32>( Shape{2, 5}, {1, 8, -8, 17, -2, 1, 8, -8, 17, 0})})); EXPECT_EQ(result->get_element_type(), element::i32); auto result_val = read_vector<int32_t>(result); vector<int32_t> expec{-1, -8, 8, -17, 2, -1, -8, 8, -17, 0}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_relu_2Ffprop_f32) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 5}); auto relu = make_shared<op::Relu>(p); auto fun = make_shared<Function>(OutputVector{relu}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>( Shape{2, 5}, {1, 8, -8, 17, -0.5, 0.1, 8.5, -8, 17, -0.5})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{1, 8, 0, 17, 0, 0.1, 8.5, 0, 17, 0}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_relu_2Ffprop_i32) { auto p = make_shared<op::Parameter>(element::i32, Shape{2, 5}); auto relu = make_shared<op::Relu>(p); auto fun = make_shared<Function>(OutputVector{relu}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::i32>( Shape{2, 5}, {1, 8, -8, 17, -2, 1, 8, -8, 17, -1})})); EXPECT_EQ(result->get_element_type(), element::i32); auto result_val = read_vector<int32_t>(result); vector<int32_t> expec{1, 8, 0, 17, 0, 1, 8, 0, 17, 0}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_round) { auto p = make_shared<op::Parameter>(element::f32, Shape{5}); auto round = make_shared<op::v5::Round>(p, op::v5::Round::RoundMode::HALF_TO_EVEN); auto fun = make_shared<Function>(OutputVector{round}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{5}, {0.9f, 2.5f, 2.3f, 1.5f, -4.5f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{1.0f, 2.0f, 2.0f, 2.0f, -4.0f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_round_2D) { auto p = make_shared<op::Parameter>(element::f32, Shape{3, 5}); auto round = make_shared<op::v5::Round>(p, op::v5::Round::RoundMode::HALF_TO_EVEN); auto fun = make_shared<Function>(OutputVector{round}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{3, 5}, {0.1f, 0.5f, 0.9f, 1.2f, 1.5f, 1.8f, 2.3f, 2.5f, 2.7f, -1.1f, -1.5f, -1.9f, -2.2f, -2.5f, -2.8f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{ 0.f, 0.f, 1.f, 1.f, 2.f, 2.f, 2.f, 2.f, 3.f, -1.f, -2.f, -2.f, -2.f, -2.f, -3.f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_sigmoid) { auto p = make_shared<op::Parameter>(element::f32, Shape{1, 1, 2, 2}); auto sigmoid = make_shared<op::Sigmoid>(p); auto fun = make_shared<Function>(OutputVector{sigmoid}, ParameterVector{p}); auto result = make_shared<HostTensor>(); float x1 = 1.0f; float x2 = 4.0f; float sigma1 = 1.0f / (1.0f + std::exp(-x1)); float sigma2 = 1.0f / (1.0f + std::exp(-x2)); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{1, 1, 2, 2}, {x1, x2, x1, x2})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{sigma1, sigma2, sigma1, sigma2}; EXPECT_EQ(result_val.size(), expec.size()); } TEST(eval, evaluate_sign) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 3}); auto sign = make_shared<op::Sign>(p); auto fun = make_shared<Function>(OutputVector{sign}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>(Shape{2, 3}, {1, -2, 0, -4.8f, 4.8f, -0.0f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{1, -1, 0, -1, 1, 0}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_sin) { auto p = make_shared<op::Parameter>(element::f32, Shape{11}); auto sin = make_shared<op::Sin>(p); auto fun = make_shared<Function>(OutputVector{sin}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::f32>( Shape{11}, {0.f, 0.25f, -0.25f, 0.5f, -0.5f, 1.f, -1.f, 2.f, -2.f, 4.f, -4.f})})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{0.00000000f, 0.24740396f, -0.24740396f, 0.47942554f, -0.47942554f, 0.84147098f, -0.84147098f, 0.90929743f, -0.90929743f, -0.75680250f, 0.75680250f}; ASSERT_FLOAT_VECTORS_EQ(expec, result_val); } TEST(eval, evaluate_sinh) { auto p = make_shared<op::Parameter>(element::f32, Shape{6}); auto sinh = make_shared<op::Sinh>(p); auto fun = make_shared<Function>(OutputVector{sinh}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{1.0f, 0.0f, -0.0f, -1.0f, 5.0f, -5.0f}; ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{6}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return sinhf(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_sqrt) { auto p = make_shared<op::Parameter>(element::f32, Shape{6}); auto sqrt = make_shared<op::Sqrt>(p); auto fun = make_shared<Function>(OutputVector{sqrt}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{16, 4, 81, 100, 10000, 0}; ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{6}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{4, 2, 9, 10, 100, 0}; ASSERT_FLOAT_VECTORS_EQ(expec, result_val); } TEST(eval, evaluate_acos) { auto p = make_shared<op::Parameter>(element::f32, Shape{11}); auto acos = make_shared<op::Acos>(p); auto fun = make_shared<Function>(OutputVector{acos}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{-1.f, -0.75f, -0.5f, -0.25f, -0.125f, 0.f, 0.125f, 0.25f, 0.5f, 0.75f, 1.f}; ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{11}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return std::acos(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_asin) { auto p = make_shared<op::Parameter>(element::f32, Shape{11}); auto asin = make_shared<op::Asin>(p); auto fun = make_shared<Function>(OutputVector{asin}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{-1.f, -0.75f, -0.5f, -0.25f, -0.125f, 0.f, 0.125f, 0.25f, 0.5f, 0.75f, 1.f}; ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{11}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return std::asin(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_atan) { auto p = make_shared<op::Parameter>(element::f32, Shape{11}); auto atan = make_shared<op::Atan>(p); auto fun = make_shared<Function>(OutputVector{atan}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{-4.f, -2.f, -1.f, -0.5f, -0.25f, 0.f, 0.25f, 0.5f, 1.f, 2.f, 4.f}; ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{11}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return std::atan(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_ceiling) { auto p = make_shared<op::Parameter>(element::f32, Shape{2, 2}); auto ceil = make_shared<op::Ceiling>(p); auto fun = make_shared<Function>(OutputVector{ceil}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{-2.5f, -2.0f, 0.3f, 4.8f}; ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{2, 2}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); vector<float> expec{-2.0f, -2.0f, 1.0f, 5.0f}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_cos) { auto p = make_shared<op::Parameter>(element::f32, Shape{11}); auto cos = make_shared<op::Cos>(p); auto fun = make_shared<Function>(OutputVector{cos}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{0.f, 0.25f, -0.25f, 0.5f, -0.5f, 1.f, -1.f, 2.f, -2.f, 4.f, -4.f}; ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{11}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return std::cos(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_cosh) { auto p = make_shared<op::Parameter>(element::f32, Shape{6}); auto cosh = make_shared<op::Cosh>(p); auto fun = make_shared<Function>(OutputVector{cosh}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{1.0f, 0.0f, -0.0f, -1.0f, 5.0f, -5.0f}; ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{6}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return std::cosh(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_tan) { auto p = make_shared<op::Parameter>(element::f32, Shape{11}); auto tan = make_shared<op::Tan>(p); auto fun = make_shared<Function>(OutputVector{tan}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{0.f, 0.25f, -0.25f, 0.5f, -0.5f, 1.f, -1.f, 2.f, -2.f, 4.f, -4.f}; ASSERT_TRUE( fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{11}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return std::tan(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_tanh) { auto p = make_shared<op::Parameter>(element::f32, Shape{6}); auto tanh = make_shared<op::Tanh>(p); auto fun = make_shared<Function>(OutputVector{tanh}, ParameterVector{p}); auto result = make_shared<HostTensor>(); vector<float> input{1.0f, 0.0f, -0.0f, -1.0f, 0.5f, -0.5f}; ASSERT_TRUE(fun->evaluate({result}, {make_host_tensor<element::Type_t::f32>(Shape{6}, input)})); EXPECT_EQ(result->get_element_type(), element::f32); auto result_val = read_vector<float>(result); std::transform( input.begin(), input.end(), input.begin(), [](float x) -> float { return std::tanh(x); }); ASSERT_FLOAT_VECTORS_EQ(input, result_val); } TEST(eval, evaluate_logical_not) { auto p = make_shared<op::Parameter>(element::boolean, Shape{2, 2}); auto logical_not = make_shared<op::v1::LogicalNot>(p); auto fun = make_shared<Function>(OutputVector{logical_not}, ParameterVector{p}); auto result = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate( {result}, {make_host_tensor<element::Type_t::boolean>(Shape{2, 2}, {1, 0, 1, 0})})); EXPECT_EQ(result->get_element_type(), element::boolean); auto result_val = read_vector<char>(result); vector<char> expec{0, 1, 0, 1}; ASSERT_EQ(result_val, expec); } TEST(eval, evaluate_dynamic_gather_v1) { auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto gather = make_shared<op::v1::Gather>(arg1, arg2, arg3); auto fun = make_shared<Function>(OutputVector{gather}, ParameterVector{arg1, arg2, arg3}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>({3}, {1.0f, 2.0f, 3.0f}), make_host_tensor<element::Type_t::i32>({2}, {1, 0}), make_host_tensor<element::Type_t::i32>({1}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{2})); auto cval = read_vector<float>(result_tensor); vector<float> out{2.0f, 1.0f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_gather_v1_scalar_axis) { auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto gather = make_shared<op::v1::Gather>(arg1, arg2, arg3); auto fun = make_shared<Function>(OutputVector{gather}, ParameterVector{arg1, arg2, arg3}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( {3, 3}, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f, 3.0f, 3.1f, 3.2f}), make_host_tensor<element::Type_t::i32>({1, 2}, {0, 2}), make_host_tensor<element::Type_t::u64>({}, {1})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 1, 2})); auto cval = read_vector<float>(result_tensor); vector<float> out{1.0f, 1.2f, 2.0f, 2.2f, 3.0f, 3.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_gather_v7) { auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); int64_t batch_dims = 1; int32_t axis = 1; auto gather = make_shared<op::v7::Gather>(arg1, arg2, arg3, batch_dims); auto fun = make_shared<Function>(OutputVector{gather}, ParameterVector{arg1, arg2, arg3}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>({2, 3}, {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}), make_host_tensor<element::Type_t::i32>({2, 2}, {1, 0, 1, 0}), make_host_tensor<element::Type_t::i32>({1}, {axis})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{2, 2})); auto cval = read_vector<float>(result_tensor); vector<float> out{2.0f, 1.0f, 5.0f, 4.0f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_gather_v7_axis_scalar) { auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); int64_t batch_dims = 0; int64_t axis = 1; auto gather = make_shared<op::v7::Gather>(arg1, arg2, arg3, batch_dims); auto fun = make_shared<Function>(OutputVector{gather}, ParameterVector{arg1, arg2, arg3}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( {3, 3}, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f, 3.0f, 3.1f, 3.2f}), make_host_tensor<element::Type_t::i32>({1, 2}, {0, 2}), make_host_tensor<element::Type_t::i64>({}, {axis})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 1, 2})); auto cval = read_vector<float>(result_tensor); vector<float> out{1.0f, 1.2f, 2.0f, 2.2f, 3.0f, 3.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_concat) { auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto concat = make_shared<op::v0::Concat>(NodeVector{arg1, arg2}, 1); auto fun = make_shared<Function>(OutputVector{concat}, ParameterVector{arg1, arg2}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>({1, 1}, {1.0f}), make_host_tensor<element::Type_t::f32>({1, 2}, {8.0f, 10.0f})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{1, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{1.0f, 8.0f, 10.0f}; ASSERT_EQ(cval, out); } TEST(eval, max_pool_v1_dynamic) { Shape window_shape{3}; auto A = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto f = make_shared<Function>( make_shared<op::v1::MaxPool>( A, Strides(), Shape(), Shape(), window_shape, op::RoundingType::FLOOR), ParameterVector{A}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(f->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( {1, 1, 14}, {0, 1, 0, 2, 1, 0, 3, 2, 0, 0, 2, 0, 0, 0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{1, 1, 12})); auto cval = read_vector<float>(result_tensor); vector<float> out{1, 2, 2, 2, 3, 3, 3, 2, 2, 2, 2, 0}; } TEST(eval, evaluate_static_scatter_elements_update_basic) { const Shape data_shape{3, 3}; const Shape indices_shape{2, 3}; auto arg1 = make_shared<op::Parameter>(element::f32, data_shape); auto arg2 = make_shared<op::Parameter>(element::i32, indices_shape); auto arg3 = make_shared<op::Parameter>(element::f32, indices_shape); auto arg4 = make_shared<op::Parameter>(element::i64, Shape{}); auto scatter_elements_update = make_shared<op::v3::ScatterElementsUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_elements_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 0, 2, 0, 2, 1}), make_host_tensor<element::Type_t::f32>(indices_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>({}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_shape(), (Shape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{2.f, 1.1f, 0.0f, 1.f, 0.0f, 2.2f, 0.f, 2.1f, 1.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_elements_update_basic) { const Shape data_shape{3, 3}; const Shape indices_shape{2, 3}; auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_elements_update = make_shared<op::v3::ScatterElementsUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_elements_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 0, 2, 0, 2, 1}), make_host_tensor<element::Type_t::f32>(indices_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>({}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{2.f, 1.1f, 0.0f, 1.f, 0.0f, 2.2f, 0.f, 2.1f, 1.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_elements_update_negative_axis) { const Shape data_shape{3, 3}; const Shape indices_shape{2, 3}; const Shape axis_shape{}; auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_elements_update = make_shared<op::v3::ScatterElementsUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_elements_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 0, 2, 0, 2, 1}), make_host_tensor<element::Type_t::f32>(indices_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>(axis_shape, {-1})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{1.1f, 1.0f, 1.2f, 2.0f, 2.2f, 2.1f, 0.0f, 0.0f, 0.0f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_elements_update_1d_axis) { const Shape data_shape{3, 3}; const Shape indices_shape{2, 3}; auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_elements_update = make_shared<op::v3::ScatterElementsUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_elements_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 0, 2, 0, 2, 1}), make_host_tensor<element::Type_t::f32>(indices_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>({1}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{2.f, 1.1f, 0.0f, 1.f, 0.0f, 2.2f, 0.f, 2.1f, 1.2f}; ASSERT_EQ(cval, out); } // Disabled test for disabled reference implementation TEST(eval, DISABLED_evaluate_dynamic_scatter_elements_update_3d_i16) { const Shape data_shape{3, 3, 3}; const Shape indices_shape{2, 2, 3}; auto arg1 = make_shared<op::Parameter>(element::i16, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i16, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::i16, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_elements_update = make_shared<op::v3::ScatterElementsUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_elements_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::i16>( data_shape, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}), make_host_tensor<element::Type_t::i16>( indices_shape, {1, 0, 2, 0, 2, 1, 2, 2, 2, 0, 1, 0}), make_host_tensor<element::Type_t::i16>( indices_shape, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}), make_host_tensor<element::Type_t::i64>({}, {1})})); EXPECT_EQ(result_tensor->get_element_type(), element::i16); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3, 3})); auto cval = read_vector<int16_t>(result_tensor); vector<int16_t> out{4, 2, 0, 1, 0, 6, 0, 5, 3, 10, 0, 12, 0, 11, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_elements_update_one_elem_i32) { const Shape data_shape{3, 3, 3}; const Shape indices_shape{1, 1, 1}; auto arg1 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_elements_update = make_shared<op::v3::ScatterElementsUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_elements_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::i32>( data_shape, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}), make_host_tensor<element::Type_t::i32>(indices_shape, {1}), make_host_tensor<element::Type_t::i32>(indices_shape, {2}), make_host_tensor<element::Type_t::i64>({}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::i32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3, 3})); auto cval = read_vector<int32_t>(result_tensor); vector<int32_t> out{0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; ASSERT_EQ(cval, out); } TEST(eval, topk_v1) { Shape shape{2, 3, 2}; Shape rshape{2, 2, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); const auto k = op::Constant::create(element::i32, Shape{}, {2}); auto B = make_shared<op::v1::TopK>(A, k, 1, "max", "index", element::i32); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 2, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 2, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 6, 3, 11, 7}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 0, 1, 2, 2}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v1_dyn) { Shape shape{2, 3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto k = make_shared<op::Parameter>(element::u32, Shape{}); auto B = make_shared<op::v1::TopK>(A, k, 1, "max", "index", element::i32); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i32>(Shape{}, {2})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 2, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 2, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 6, 3, 11, 7}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 0, 1, 2, 2}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v3_dyn) { Shape shape{2, 3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto k = make_shared<op::Parameter>(element::u32, Shape{}); auto B = make_shared<op::v3::TopK>(A, k, 1, "max", "index", element::i32); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i32>(Shape{}, {2})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 2, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 2, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 6, 3, 11, 7}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 0, 1, 2, 2}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v3_dyn_values) { Shape shape{2, 3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto k = make_shared<op::Parameter>(element::u32, Shape{}); auto B = make_shared<op::v3::TopK>(A, k, 1, "max", "value", element::i32); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i32>(Shape{}, {2})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 2, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 2, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 11, 7, 6, 3}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 2, 2, 0, 1}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v3_dyn_values_k0) { Shape shape{2, 3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto k = make_shared<op::Parameter>(element::u32, Shape{}); auto B = make_shared<op::v3::TopK>(A, k, 1, "max", "value", element::i32); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i32>(Shape{}, {0})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 3, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 3, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 8, 2, 11, 7, 6, 3, 5, 1}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 2, 0, 2, 2, 0, 1, 1, 0}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v1_dyn_k0) { Shape shape{2, 3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto k = make_shared<op::Parameter>(element::i64, Shape{}); element::Type result_et{element::i32}; auto B = make_shared<op::v1::TopK>( A, k, 1, op::v1::TopK::Mode::MAX, op::v1::TopK::SortType::SORT_VALUES, result_et); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i64>(Shape{}, {0})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 3, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 3, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 8, 2, 11, 7, 6, 3, 5, 1}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 2, 0, 2, 2, 0, 1, 1, 0}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v3_param_dyn_values_k0) { auto A = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto k = make_shared<op::Parameter>(element::u32, Shape{}); auto B = make_shared<op::v3::TopK>(A, k, 1, "max", "value", element::i32); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i32>(Shape{}, {0})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 3, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 3, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 8, 2, 11, 7, 6, 3, 5, 1}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 2, 0, 2, 2, 0, 1, 1, 0}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v3_param_dyn_values_k2) { auto A = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto k = make_shared<op::Parameter>(element::u32, Shape{}); auto B = make_shared<op::v3::TopK>(A, k, 1, "max", "value", element::i32); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i32>(Shape{}, {2})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 2, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 2, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 11, 7, 6, 3}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 2, 2, 0, 1}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v1_param_dyn_k2) { auto A = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto k = make_shared<op::Parameter>(element::i64, Shape{}); auto axis = 1; element::Type result_et{element::i32}; auto B = make_shared<op::v1::TopK>( A, k, axis, op::v1::TopK::Mode::MAX, op::v1::TopK::SortType::SORT_VALUES, result_et); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i64>(Shape{}, {2})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 2, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 2, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 11, 7, 6, 3}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 2, 2, 0, 1}; ASSERT_EQ(result1_val, expec1); } TEST(eval, topk_v1_param_dyn_k0) { auto A = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto k = make_shared<op::Parameter>(element::i64, Shape{}); element::Type result_et{element::i32}; auto B = make_shared<op::v1::TopK>( A, k, 1, op::v1::TopK::Mode::MAX, op::v1::TopK::SortType::SORT_VALUES, result_et); auto fun = make_shared<Function>(OutputVector{B->output(0), B->output(1)}, ParameterVector{A, k}); auto result0 = make_shared<HostTensor>(); auto result1 = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result0, result1}, {make_host_tensor<element::Type_t::f32>( Shape{2, 3, 2}, {12, 2, 10, 9, 8, 4, 6, 1, 5, 3, 11, 7}), make_host_tensor<element::Type_t::i64>(Shape{}, {0})})); EXPECT_EQ(result0->get_element_type(), element::f32); EXPECT_EQ(result0->get_partial_shape(), (PartialShape{2, 3, 2})); EXPECT_EQ(result1->get_element_type(), element::i32); EXPECT_EQ(result1->get_partial_shape(), (PartialShape{2, 3, 2})); auto result0_val = read_vector<float>(result0); auto result1_val = read_vector<int32_t>(result1); vector<float> expec0{12, 9, 10, 4, 8, 2, 11, 7, 6, 3, 5, 1}; ASSERT_EQ(result0_val, expec0); vector<int32_t> expec1{0, 1, 1, 2, 2, 0, 2, 2, 0, 1, 1, 0}; ASSERT_EQ(result1_val, expec1); } TEST(eval, reduce_logical_and__neg_axis) { const auto data = make_shared<op::Parameter>(element::boolean, Shape{2, 2, 2}); const auto axes = make_shared<op::Parameter>(element::i64, Shape{}); const auto op = make_shared<op::v1::ReduceLogicalAnd>(data, axes); auto fun = make_shared<Function>(op, ParameterVector{data, axes}); auto result = make_shared<HostTensor>(); // when ReduceLogicalAnd node evaluator returns false -> the Function object throws EXPECT_THROW( fun->evaluate({result}, { make_host_tensor<element::Type_t::boolean>( Shape{2, 2, 2}, {true, false, true, false, true, false, true, false}), make_host_tensor<element::Type_t::i64>(Shape{}, {-1}), }), ngraph::ngraph_error); } TEST(eval, evaluate_static_scatter_update_basic_axes_indices_i32) { const Shape data_shape{3, 3}; const Shape indices_shape{1, 2}; const Shape updates_shape{1, 2, 3}; auto arg1 = make_shared<op::Parameter>(element::f32, data_shape); auto arg2 = make_shared<op::Parameter>(element::i32, indices_shape); auto arg3 = make_shared<op::Parameter>(element::f32, updates_shape); auto arg4 = make_shared<op::Parameter>(element::i32, Shape{}); auto scatter_update = make_shared<op::v3::ScatterUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, std::vector<float>(shape_size(data_shape))), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 2}), make_host_tensor<element::Type_t::f32>( updates_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i32>({}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_shape(), (Shape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{0.f, 0.f, 0.f, 1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_static_scatter_update_basic_axes_indices_i64) { const Shape data_shape{3, 3}; const Shape indices_shape{1, 2}; const Shape updates_shape{1, 2, 3}; auto arg1 = make_shared<op::Parameter>(element::f32, data_shape); auto arg2 = make_shared<op::Parameter>(element::i64, indices_shape); auto arg3 = make_shared<op::Parameter>(element::f32, updates_shape); auto arg4 = make_shared<op::Parameter>(element::i64, Shape{}); auto scatter_update = make_shared<op::v3::ScatterUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, std::vector<float>(shape_size(data_shape))), make_host_tensor<element::Type_t::i64>(indices_shape, {1, 2}), make_host_tensor<element::Type_t::f32>( updates_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>({}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_shape(), (Shape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{0.f, 0.f, 0.f, 1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_update_basic) { const Shape data_shape{3, 3}; const Shape indices_shape{1, 2}; const Shape updates_shape{1, 2, 3}; auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_update = make_shared<op::v3::ScatterUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, std::vector<float>(shape_size(data_shape))), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 2}), make_host_tensor<element::Type_t::f32>( updates_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>({}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{0.f, 0.f, 0.f, 1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_update_negative_axis) { const Shape data_shape{3, 3}; const Shape indices_shape{1, 2}; const Shape updates_shape{3, 1, 2}; const Shape axis_shape{}; auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_update = make_shared<op::v3::ScatterUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, std::vector<float>(shape_size(data_shape))), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 2}), make_host_tensor<element::Type_t::f32>( updates_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>(axis_shape, {-1})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{0.f, 1.0f, 1.1f, 0.0f, 1.2f, 2.0f, 0.0f, 2.1f, 2.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_update_1d_axis) { const Shape data_shape{3, 3}; const Shape indices_shape{1, 2}; const Shape updates_shape{3, 1, 2}; auto arg1 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::f32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_update = make_shared<op::v3::ScatterUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE(fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::f32>( data_shape, std::vector<float>(shape_size(data_shape))), make_host_tensor<element::Type_t::i32>(indices_shape, {1, 2}), make_host_tensor<element::Type_t::f32>( updates_shape, {1.0f, 1.1f, 1.2f, 2.0f, 2.1f, 2.2f}), make_host_tensor<element::Type_t::i64>({1}, {1})})); EXPECT_EQ(result_tensor->get_element_type(), element::f32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3})); auto cval = read_vector<float>(result_tensor); vector<float> out{0.f, 1.0f, 1.1f, 0.0f, 1.2f, 2.0f, 0.0f, 2.1f, 2.2f}; ASSERT_EQ(cval, out); } TEST(eval, evaluate_dynamic_scatter_update_one_elem_i32) { const Shape data_shape{3, 3, 2}; const Shape indices_shape{1, 1}; const Shape updates_shape{1, 1, 3, 2}; auto arg1 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg2 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg3 = make_shared<op::Parameter>(element::i32, PartialShape::dynamic()); auto arg4 = make_shared<op::Parameter>(element::i64, PartialShape::dynamic()); auto scatter_update = make_shared<op::v3::ScatterUpdate>(arg1, arg2, arg3, arg4); auto fun = make_shared<Function>(OutputVector{scatter_update}, ParameterVector{arg1, arg2, arg3, arg4}); auto result_tensor = make_shared<HostTensor>(); ASSERT_TRUE( fun->evaluate({result_tensor}, {make_host_tensor<element::Type_t::i32>( data_shape, std::vector<int32_t>(shape_size(data_shape))), make_host_tensor<element::Type_t::i32>(indices_shape, {1}), make_host_tensor<element::Type_t::i32>(updates_shape, {1, 2, 3, 4, 5, 6}), make_host_tensor<element::Type_t::i64>({}, {0})})); EXPECT_EQ(result_tensor->get_element_type(), element::i32); EXPECT_EQ(result_tensor->get_partial_shape(), (PartialShape{3, 3, 2})); auto cval = read_vector<int32_t>(result_tensor); vector<int32_t> out{0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0}; ASSERT_EQ(cval, out); }
46.446544
116
0.613271
[ "object", "shape", "vector", "transform" ]
f56534da58a5b1682bfa9bc9c37bf0f726cdc260
1,972
cpp
C++
basic_operations/vector_substraction.cpp
jcheng123/Perelman
a4e504391b4265c7e9ca0e4450e29e719911045b
[ "MIT" ]
null
null
null
basic_operations/vector_substraction.cpp
jcheng123/Perelman
a4e504391b4265c7e9ca0e4450e29e719911045b
[ "MIT" ]
null
null
null
basic_operations/vector_substraction.cpp
jcheng123/Perelman
a4e504391b4265c7e9ca0e4450e29e719911045b
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> using namespace std; int VecSubstraction(const vector<float>& m, const float& alpha, vector<float> &res) { int ret = 0; if (m.empty()) { cout << "The input vector should \ not be empty." << endl; ret = -1; return ret; } for (int i = 0; i < m.size(); ++i) res.push_back(m[i] - alpha); return ret; } int VecSubstraction(const vector<float>& m, const vector<float>& n, vector<float> &res) { int ret = 0; if (m.empty() || n.empty()) { cout << "The input vectors should \ not be empty." << endl; ret = -1; return ret; } if (m.size() != n.size()) { cout << "The two input vectors should \ be of the same length." << endl; ret = -2; return ret; } for (int i = 0; i < m.size(); ++i) res.push_back(m[i] - n[i]); return ret; } void unitest(void) { /* Test VecSubstraction */ vector<float> test_case = {1.0, 3.2, 10.3, -2.3, 0.0}; float alpha = 10.0; vector<float> result; int ret = VecSubstraction(test_case, alpha, result); for (int i = 0; i < result.size(); ++i) { cout << "Testing VecSubstraction: " << i << '\t' << test_case[i] << '\t' << alpha << '\t' << result[i] << '\t' << endl; } vector<float> test_case_1 = {1.0, 2.0, 3.0, -1.0, -2.0, -3.0}; vector<float> test_case_2 = {0.5, 0.0, -0.2, -0.4, 0.1, 0.9}; vector<float> res; ret = VecSubstraction(test_case_1, test_case_2, res); for (int i = 0; i < test_case_1.size(); ++i) cout << "Testing VecSubstraction: " << i << '\t' << test_case_1[i] << '\t' << test_case_2[i] << '\t' << res[i] << '\t' << endl; } int main() { unitest(); return 0; }
23.2
87
0.471602
[ "vector" ]
f565c0edbc576b287d9bc4e217e1fd4001d8a3ec
1,476
cpp
C++
codes/CF/1325/CF_1325C.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
2
2021-03-07T03:34:02.000Z
2021-03-09T01:22:21.000Z
codes/CF/1325/CF_1325C.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T15:01:23.000Z
2021-03-27T15:55:34.000Z
codes/CF/1325/CF_1325C.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T05:02:33.000Z
2021-03-27T05:02:33.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <ctime> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <random> #include <chrono> #define cont continue #define pow2(n) (1 << (n)) #define ll long long #define pii pair<int, int> #define pb push_back #define mp make_pair #define lsb(n) ((n)&(-(n))) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define add(a, b) (((a)%mod + (b)%mod)%mod) #define mul(a, b) (((a)%mod * (b)%mod)%mod) #define init(arr, val) memset(arr, val, sizeof(arr)) const ll mod = 1e9 + 7; const int MX = 1e5 +10, int_max = 0x3f3f3f3f; using namespace std; void setIO(const string& file_name){ freopen((file_name+".in").c_str(), "r", stdin); freopen((file_name+".out").c_str(), "w+", stdout); } vector<pii> adj[MX]; int ans[MX], cnt = 0, n; int main(){ cin.tie(0) -> sync_with_stdio(0); mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); cin >> n; for(int i = 1; i<n; i++){ int a, b; cin >> a >> b; adj[a].pb(mp(b, i)); adj[b].pb(mp(a, i)); } for(int i = 1; i<=n; i++){ if(adj[i].size() >= 3){ for(int j = 0; j<3; j++){ //cout << i << " " << adj[i][j].first << " " << adj[i][j].second << endl; ans[adj[i][j].second] = ++cnt; } break; } } for(int i = 1; i<n; i++){ if(ans[i]) cout << ans[i] - 1 << '\n'; else cout << cnt++ << '\n'; } return 0; }
21.705882
81
0.54607
[ "vector" ]
f566b1db192f18ac739d2e2d3d7a1cb3bfcee3ec
8,656
cpp
C++
src/defin/definComponent.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
1
2021-03-04T02:35:47.000Z
2021-03-04T02:35:47.000Z
src/defin/definComponent.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
null
null
null
src/defin/definComponent.cpp
mgwoo/OpenDB
8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2019, Nefelus 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 copyright holder 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 <stdlib.h> #include <stdio.h> #include <ctype.h> #include "definComponent.h" #include "db.h" #include "dbTransform.h" namespace odb { definComponent::definComponent() { init(); } definComponent::~definComponent() { MasterMap::iterator mitr; for( mitr = _masters.begin(); mitr != _masters.end(); ++mitr ) free( (void *) (*mitr).first ); SiteMap::iterator sitr; for( sitr = _sites.begin(); sitr != _sites.end(); ++sitr ) free( (void *) (*sitr).first ); } void definComponent::init() { definBase::init(); _libs.clear(); MasterMap::iterator mitr; for( mitr = _masters.begin(); mitr != _masters.end(); ++mitr ) free( (void *) (*mitr).first ); _masters.clear(); SiteMap::iterator sitr; for( sitr = _sites.begin(); sitr != _sites.end(); ++sitr ) free( (void *) (*sitr).first ); _sites.clear(); _inst_cnt = 0; _iterm_cnt = 0; _cur_inst = NULL; } dbMaster * definComponent::getMaster( const char * name ) { MasterMap::iterator mitr; mitr = _masters.find( name ); if ( mitr != _masters.end() ) { dbMaster * master = (*mitr).second; return master; } std::vector<dbLib *>::iterator litr; for( litr = _libs.begin(); litr != _libs.end(); ++litr ) { dbLib * lib = * litr; dbMaster * master = lib->findMaster( name ); if ( master ) { const char * n = strdup(name); assert(n); _masters[n] = master; return master; } } return NULL; } dbSite * definComponent::getSite( const char * name ) { SiteMap::iterator mitr; mitr = _sites.find( name ); if ( mitr != _sites.end() ) { dbSite * site = (*mitr).second; return site; } std::vector<dbLib *>::iterator litr; for( litr = _libs.begin(); litr != _libs.end(); ++litr ) { dbLib * lib = * litr; dbSite * site = lib->findSite( name ); if ( site ) { const char * n = strdup(name); assert(n); _sites[n] = site; return site; } } return NULL; } void definComponent::begin( const char * iname, const char * mname ) { assert(_cur_inst == NULL); dbMaster * master = getMaster( mname ); if ( master == NULL ) { notice(0,"error: unknown library cell referenced (%s) for instance (%s)\n", mname, iname ); _errors++; return; } _cur_inst = dbInst::create( _block, master, iname ); if ( _cur_inst == NULL ) { notice(0,"error: duplicate instance definition(%s)\n", iname ); _errors++; return; } _iterm_cnt += master->getMTermCount(); _inst_cnt++; if ( _inst_cnt % 100000 == 0) notice(0,"\t\tCreated %d Insts\n", _inst_cnt); } void definComponent::placement( defPlacement status, int x, int y, defOrient orient ) { if (_cur_inst == NULL) return; switch( status ) { case DEF_PLACEMENT_FIXED: _cur_inst->setPlacementStatus(dbPlacementStatus::FIRM); break; case DEF_PLACEMENT_COVER: _cur_inst->setPlacementStatus(dbPlacementStatus::COVER); break; case DEF_PLACEMENT_PLACED: _cur_inst->setPlacementStatus(dbPlacementStatus::PLACED); break; case DEF_PLACEMENT_UNPLACED: _cur_inst->setPlacementStatus(dbPlacementStatus::UNPLACED); break; } switch (orient) { case DEF_ORIENT_N: _cur_inst->setOrient( dbOrientType::R0 ); break; case DEF_ORIENT_S: _cur_inst->setOrient( dbOrientType::R180 ); break; case DEF_ORIENT_E: _cur_inst->setOrient( dbOrientType::R270 ); break; case DEF_ORIENT_W: _cur_inst->setOrient( dbOrientType::R90 ); break; case DEF_ORIENT_FN: _cur_inst->setOrient( dbOrientType::MY ); break; case DEF_ORIENT_FS: _cur_inst->setOrient( dbOrientType::MX ); break; case DEF_ORIENT_FE: _cur_inst->setOrient( dbOrientType::MYR90 ); break; case DEF_ORIENT_FW: _cur_inst->setOrient( dbOrientType::MXR90 ); break; } dbMaster * master = _cur_inst->getMaster(); adsRect bbox; master->getPlacementBoundary(bbox); dbTransform t(_cur_inst->getOrient()); t.apply(bbox); _cur_inst->setOrigin(dbdist(x) - bbox.xMin(),dbdist(y) - bbox.yMin()); } void definComponent::halo( int left, int bottom, int right, int top ) { dbBox::create( _cur_inst, dbdist(left), dbdist(bottom), dbdist(right), dbdist(top) ); } void definComponent::region( const char * name ) { if (_cur_inst == NULL) return; dbRegion * region = _block->findRegion( name ); if ( region == NULL ) region = dbRegion::create(_block, name); region->addInst(_cur_inst); } void definComponent::source( defSource source ) { if (_cur_inst == NULL) return; switch( source) { case DEF_DIST: _cur_inst->setSourceType( dbSourceType::DIST ); break; case DEF_NETLIST: _cur_inst->setSourceType( dbSourceType::NETLIST ); break; case DEF_TEST: _cur_inst->setSourceType( dbSourceType::TEST ); break; case DEF_TIMING: _cur_inst->setSourceType( dbSourceType::TIMING ); break; case DEF_USER: _cur_inst->setSourceType( dbSourceType::USER ); break; } } void definComponent::weight( int weight ) { if (_cur_inst == NULL) return; _cur_inst->setWeight( weight ); } void definComponent::property( const char * name, const char * value ) { if ( _cur_inst == NULL ) return; dbProperty * p = dbProperty::find(_cur_inst,name); if ( p ) dbProperty::destroy(p); dbStringProperty::create(_cur_inst,name,value); } void definComponent::property( const char * name, int value ) { if ( _cur_inst == NULL ) return; dbProperty * p = dbProperty::find(_cur_inst,name); if ( p ) dbProperty::destroy(p); dbIntProperty::create(_cur_inst,name,value); } void definComponent::property( const char * name, double value ) { if ( _cur_inst == NULL ) return; dbProperty * p = dbProperty::find(_cur_inst,name); if ( p ) dbProperty::destroy(p); dbDoubleProperty::create(_cur_inst,name,value); } void definComponent::end() { if ( _cur_inst == NULL ) return; dbSet<dbProperty> props = dbProperty::getProperties(_cur_inst); if ( !props.empty() && props.orderReversed() ) props.reverse(); _cur_inst = NULL; } } // namespace
25.533923
99
0.596811
[ "vector" ]
f56b2ab661a9d8002048dd3c697c022b724c24c4
17,353
cpp
C++
src/hssh/global_topological/mapping/lazy_evaluation_mapper.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
3
2020-03-05T23:56:14.000Z
2021-02-17T19:06:50.000Z
src/hssh/global_topological/mapping/lazy_evaluation_mapper.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-07T01:23:47.000Z
2021-03-07T01:23:47.000Z
src/hssh/global_topological/mapping/lazy_evaluation_mapper.cpp
anuranbaka/Vulcan
56339f77f6cf64b5fda876445a33e72cd15ce028
[ "MIT" ]
1
2021-03-03T07:54:16.000Z
2021-03-03T07:54:16.000Z
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file lazy_evaluation_mapper.cpp * \author Collin Johnson * * Definition of LazyEvaluationMapper. */ #include "hssh/global_topological/mapping/lazy_evaluation_mapper.h" #include "hssh/global_topological/mapping/localizer.h" #include "hssh/global_topological/mapping/map_optimizer.h" #include "utils/timestamp.h" #include <algorithm> #include <cassert> #include <cstdint> #include <inttypes.h> #include <iostream> #define DEBUG_HYPOTHESES #define DEBUG_TOTAL_HYPOTHESES // #define DEBUG_EVENTS #define DEBUG_LOG_RESULTS namespace vulcan { namespace hssh { LazyEvaluationMapper::LazyEvaluationMapper(const topological_mapper_params_t& params, MetricMapCache& manager) : TopologicalMapper(manager) , pathEvents(1) , probabilityEvaluator(params.lazyEvaluationParams.probabilityParams) , params(params.lazyEvaluationParams) , evaluationLog("lazy_evaluation_results.log") , leafDepthLog("leaf_depths.log") { localizer = create_topological_localizer(params.localizerType); optimizer = create_map_optimizer(params.optimizerType, params.optimizerParams); } void LazyEvaluationMapper::setCorrectMap(uint32_t id) { setCorrectMap(tree.getMapFromId(id)); } void LazyEvaluationMapper::setCorrectMap(TopoMapPtr map) { // For setting the correct map, all events in the queue that happened before its depth can, and must, be erased // they no longer matter because absolute truth up to the current point has been established // After erasing the queue, let the normal TopologicalMapper method do its thing if (map && !events.empty()) { uint32_t numEvents = events.size(); // enforce a 32-bit size because size_type is 64-bits on 64-bit Linux // so std::min() fails in that circumstance std::size_t numEventsToErase = std::min(numEvents, map->getDepth()); events.erase(events.begin(), events.begin() + numEventsToErase); pathEvents.erase(pathEvents.begin(), pathEvents.begin() + numEventsToErase); } mostLikelyHypothesis = map; TopologicalMapper::setCorrectMap(map); assert(pathEvents.size() == events.size() + 1); pathEvents.front().clear(); // erase any remaining path events floating around from a previous run } void LazyEvaluationMapper::updateMap(const topology_action_t& action, const topology_measurements_t& measurements) { addEventToQueue(action, measurements); if (action.haveExited) { handleExitedEvent(action, measurements); } if (action.haveEntered) { handleEnteredEvent(action, measurements); } if (action.haveReverse) { handleReverseEvent(action, measurements); } assert(pathEvents.size() == events.size() + 1); } void LazyEvaluationMapper::addEventToQueue(const topology_action_t& action, const topology_measurements_t& measurements) { // If entering a new place, then need to add a new event. If exiting, just update the current event if (action.haveEntered) { events.push_back(topology_event_t(action, measurements)); pathEvents.push_back(reverse_actions_t()); } if (action.haveExited) { if (!events.empty()) { events.back().exitedAction = action.exitedAction; } else { std::cerr << "WARNING:GlobalTopo: Had an exited place action before an entered action event occurred! " "Exited place not added to map.\n"; } } if (action.haveReverse) { pathEvents.back().push_back(action.reverseAction); } } void LazyEvaluationMapper::handleExitedEvent(const topology_action_t& action, const topology_measurements_t& measurements) { // When exiting a place, the action only applies to the complete hypotheses of the tree consistent with all events // in the queue. These hypotheses should be localized to include the new exited action so the anything using the // output maps doesn't need to wait until a new place is entered before seeing the global location change. auto leaves = tree.getCompleteHypotheses(); for (auto leafIt = leaves.begin(), leafEnd = leaves.end(); leafIt != leafEnd; ++leafIt) { localizer->localize(*leafIt, action); } } void LazyEvaluationMapper::handleEnteredEvent(const topology_action_t& action, const topology_measurements_t& measurements) { if (initializeIfNeeded(action, measurements)) { return; } int64_t startTime = utils::system_time_us(); #ifdef DEBUG_EVENTS std::cout << "DEBUG:LazyEval: Updating.Star:" << action.enteredAction.enteredAction.topology << " Entry frag:" << (int)action.enteredAction.enteredAction.entryPath.fragmentId << ':' << action.enteredAction.enteredAction.entryPath.gateway.getCenter() << '\n'; #endif constructHypothesisQueue(); numHypothesesExpanded = 0; numHypothesesEvaluated = 0; while (!mapQueue.empty() && !haveFinishedUpdate()) { // Pop before expanding, otherwise the wrong value could be popped, as the new hypotheses will be queued during // expansion TopoMapPtr mapToExpand = mapQueue.top(); mapQueue.pop(); expandHypothesis(mapToExpand); ++numHypothesesExpanded; std::cout << "num expanded:" << numHypothesesExpanded << " most likely:" << mostLikelyHypothesis->getLogPosterior() << " depth:" << mostLikelyHypothesis->getDepth() << '\n'; } int64_t finishTime = utils::system_time_us(); #ifdef DEBUG_TOTAL_HYPOTHESES std::cout << "DEBUG:LazyEval:Leaves:" << tree.getLeaves().size() << " Expanded:" << numHypothesesExpanded << " Evaluated:" << numHypothesesEvaluated << " Time:" << ((finishTime - startTime) / 1000) << '\n'; #endif #ifdef DEBUG_LOG_RESULTS evaluationLog << (tree.getHeight() - 1) << ' ' << tree.getLeaves().size() << ' ' << numHypothesesExpanded << ' ' << numHypothesesEvaluated << ' ' << (finishTime - startTime) << std::endl; auto leaves = tree.getLeaves(); for (auto leafIt = leaves.begin(), leafEnd = leaves.end(); leafIt != leafEnd; ++leafIt) { leafDepthLog << (*leafIt)->getDepth() << ' '; } leafDepthLog << std::endl; #endif } void LazyEvaluationMapper::handleReverseEvent(const topology_action_t& action, const topology_measurements_t& measurements) { auto leaves = tree.getCompleteHypotheses(); for (auto leafIt = leaves.begin(), leafEnd = leaves.end(); leafIt != leafEnd; ++leafIt) { localizer->localize(*leafIt, action); } } bool LazyEvaluationMapper::initializeIfNeeded(const topology_action_t& action, const topology_measurements_t& measurements) { if (tree.getHeight() == 0) { initializeTree(action, measurements); heuristicLikelihood.push_back(0.0); // no change in log-likelihood at the root heuristicPrior.push_back(0.0); mostLikelyHypothesis = *(tree.getLeaves().begin()); return true; } return false; } void LazyEvaluationMapper::constructHypothesisQueue(void) { const std::set<TopoMapPtr>& leaves = tree.getLeaves(); // Only way to erase the old queue mapQueue = std::priority_queue<TopoMapPtr, std::vector<TopoMapPtr>, TopoMapPriority>(); for (auto leafIt = leaves.begin(), leafEnd = leaves.end(); leafIt != leafEnd; ++leafIt) { const TopoMapPtr& leaf = *leafIt; assert(!leaf->wasPruned()); hypothesis_probability_t leafProbability = leaf->getProbability(); calculateEstimatedProbabilities(leaf->getDepth(), leafProbability); leaf->setProbability(leafProbability); mapQueue.push(leaf); } } void LazyEvaluationMapper::expandHypothesis(TopoMapPtr& hypothesis) { // Ensure there is a next event, otherwise something is broken. getDepth() == event of creation, + 1 = next event. assert(hypothesis.get()); assert(hypothesis->getDepth() + 1 < events.size()); assert(!hypothesis->wasPruned()); const topology_event_t& eventToProcess = enteredPlaceEvent(hypothesis); #ifdef DEBUG_HYPOTHESES std::cout << "DEBUG:LazyEval:Expanding map. Depth:" << hypothesis->getDepth() << " Log:" << hypothesis->getLogPosterior() << " Est:" << hypothesis->getEstimatedLogPosterior() << ' '; #endif localizeHypothesis(hypothesis); GlobalLocation location = hypothesis->getGlobalLocation(); LargeScaleStar actionStar(eventToProcess.enteredAction.enteredAction.topology, eventToProcess.enteredAction.enteredAction.entryPath); assert(eventToProcess.enteredAction.enteredAction.entryPath.fragmentId == actionStar.getEntryPathFragment().fragmentId); // If at a frontier, then both loop closures and adding a new place are needed if (location.placeId == PLACE_FRONTIER_ID) { #ifdef DEBUG_HYPOTHESES std::cout << "Reached new place.\n"; #endif addNewPlace(hypothesis, actionStar, eventToProcess.measurements); closeLoops(hypothesis, actionStar, eventToProcess.measurements); } else if (isValidHypothesis( hypothesis, actionStar)) // moved to a known place, so just propagate the map along the tree without branching { #ifdef DEBUG_HYPOTHESES std::cout << "Arrived at known place.\n"; #endif movedToKnownPlace(hypothesis, actionStar, eventToProcess); } else { #ifdef DEBUG_HYPOTHESES const LargeScaleStar& expectedStar = hypothesis->getPlace(location.pathState.entryPlaceId).getStar(); std::cout << "Pruning. Expected:" << expectedStar << ':' << expectedStar.getEntryPathFragment().fragmentId << " Instead:" << actionStar << ':' << actionStar.getEntryPathFragment().fragmentId << '\n'; #endif tree.prune(hypothesis); } } void LazyEvaluationMapper::localizeHypothesis(TopoMapPtr& hypothesis) { // When a new hypothesis is created, it is localized up to the point of the entered action. If a hypothesis is a // leaf consistent with all events in the queue, then its localization is updated when an exited event arrives to // make that hypothesis consistent with all actions that have occurred if it is being used for planning. Thus, if a // hypothesis is on a path, then the exited event and all path events don't need to be processed. If the hypothesis // isn't on a path, then the hypothesis is being expanded from further up the tree so the full localization needs to // occur. if (!hypothesis->getGlobalLocation().onPath) { localizer->localize(hypothesis, exitedPlaceEvent(hypothesis).exitedAction); for (auto actionIt = reverseActions(hypothesis).begin(), actionEnd = reverseActions(hypothesis).end(); actionIt != actionEnd; ++actionIt) { localizer->localize(hypothesis, *actionIt); } } localizer->localize(hypothesis, enteredPlaceEvent(hypothesis).enteredAction); } void LazyEvaluationMapper::movedToKnownPlace(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar, const topology_event_t& event) { TopoMapPtr child = moveAlongKnownPath(placeStar, event.measurements.lambda, event.measurements.placeId, hypothesis); processNewMapHypothesis(child, hypothesis, event.measurements); } void LazyEvaluationMapper::addNewPlace(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar, const topology_measurements_t& measurements) { TopoMapPtr child = createNewPlaceHypothesis(placeStar, measurements.lambda, measurements.placeId, hypothesis); processNewMapHypothesis(child, hypothesis, measurements); } void LazyEvaluationMapper::closeLoops(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar, const topology_measurements_t& measurements) { std::vector<TopoMapPtr> children = createLoopClosureHypotheses(placeStar, measurements.lambda, measurements.placeId, hypothesis); std::for_each(children.begin(), children.end(), [&](TopoMapPtr& child) { processNewMapHypothesis(child, hypothesis, measurements); }); } void LazyEvaluationMapper::processNewMapHypothesis(TopoMapPtr& child, TopoMapPtr& parent, const topology_measurements_t& measurements) { ++numHypothesesEvaluated; calculateHypothesisLikelihood(child, parent, measurements); updateHeuristic(child, parent); // If this hypothesis isn't at the bottom of the tree, then put it back into the queue if (!hypothesisContainsAllEvents(child->getDepth())) { mapQueue.push(child); } // If the first child to hit the bottom of the tree, then it is automatically the most likely else if (mostLikelyHypothesis->getDepth() < child->getDepth()) { mostLikelyHypothesis = child; } // otherwise, see if it has become the most likely hypothesis else if (child->getLogPosterior() > mostLikelyHypothesis->getLogPosterior()) { mostLikelyHypothesis = child; } } void LazyEvaluationMapper::calculateHypothesisLikelihood(TopoMapPtr& child, TopoMapPtr& parent, const topology_measurements_t& measurements) { if (child->shouldOptimize()) { child->setChi(optimizer->optimizeMap(*(child.get()))); } hypothesis_probability_t probability = probabilityEvaluator.calculateProbability(child, parent, measurements, manager); calculateEstimatedProbabilities(child->getDepth(), probability); child->setProbability(probability); } void LazyEvaluationMapper::calculateEstimatedProbabilities(uint32_t depth, hypothesis_probability_t& probability) { probability.estimatedLogLikelihood = probability.logLikelihood; probability.estimatedLogPrior = probability.logPrior; if (params.useHeuristic && !hypothesisContainsAllEvents(depth)) { probability.estimatedLogLikelihood += likelihoodHeurstic(depth); probability.estimatedLogPrior = priorHeuristic(depth, probability.logPrior); } probability.estimatedLogPosterior = probability.estimatedLogLikelihood + probability.estimatedLogPrior; } void LazyEvaluationMapper::updateHeuristic(TopoMapPtr& child, TopoMapPtr& parent) { hypothesis_probability_t childProbability = child->getProbability(); hypothesis_probability_t parentProbability = parent->getProbability(); double logLikelihoodChange = childProbability.logLikelihood - parentProbability.logLikelihood; if ((child->getDepth() < heuristicLikelihood.size()) && (logLikelihoodChange > heuristicLikelihood[child->getDepth()])) { heuristicLikelihood[child->getDepth()] = logLikelihoodChange; } else if (child->getDepth() == heuristicLikelihood.size()) { heuristicLikelihood.push_back(logLikelihoodChange); } if (child->getDepth() == heuristicPrior.size()) { heuristicPrior.push_back(childProbability.logPrior); } // There is only a single heuristic prior for the whole tree, as the prior is not recursive // If this child is at the bottom of the tree and has the best prior, that becomes the heuristic for ALL nodes if (hypothesisContainsAllEvents(child->getDepth()) && (childProbability.logPrior >= heuristicPrior[child->getDepth()])) { std::fill(heuristicPrior.begin(), heuristicPrior.end(), childProbability.logPrior); } } double LazyEvaluationMapper::likelihoodHeurstic(uint32_t hypothesisDepth) { assert(hypothesisDepth < heuristicLikelihood.size()); return std::accumulate(heuristicLikelihood.begin() + hypothesisDepth + 1, heuristicLikelihood.end(), 0.0); } double LazyEvaluationMapper::priorHeuristic(uint32_t depth, double calculatedPrior) { assert(depth < heuristicPrior.size()); return (heuristicPrior[depth] < calculatedPrior) ? heuristicPrior[depth] : calculatedPrior; } bool LazyEvaluationMapper::isValidHypothesis(TopoMapPtr& hypothesis, const LargeScaleStar& placeStar) { GlobalLocation mapState = hypothesis->getGlobalLocation(); return (mapState.placeId == PLACE_FRONTIER_ID) || (mapState.placeId >= 0); } bool LazyEvaluationMapper::haveFinishedUpdate(void) { return (numHypothesesExpanded >= params.minHypothesesToExpand) && (mostLikelyHypothesis->getLogPosterior() > mapQueue.top()->getEstimatedLogPosterior()) && hypothesisContainsAllEvents(mostLikelyHypothesis->getDepth()) && (numHypothesesEvaluated > 0); } } // namespace hssh } // namespace vulcan
37.723913
120
0.688526
[ "vector" ]
f570428ee192772fc25d74c4442509a99bcfb343
81,013
cpp
C++
IGC/VectorCompiler/lib/GenXCodeGen/GenXArgIndirection.cpp
zboszor/intel-graphics-compiler
c894e48d9efbf72950b74f9d4a1cf58be023d791
[ "Intel", "MIT" ]
null
null
null
IGC/VectorCompiler/lib/GenXCodeGen/GenXArgIndirection.cpp
zboszor/intel-graphics-compiler
c894e48d9efbf72950b74f9d4a1cf58be023d791
[ "Intel", "MIT" ]
null
null
null
IGC/VectorCompiler/lib/GenXCodeGen/GenXArgIndirection.cpp
zboszor/intel-graphics-compiler
c894e48d9efbf72950b74f9d4a1cf58be023d791
[ "Intel", "MIT" ]
null
null
null
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ // /// GenXArgIndirection /// ------------------ /// /// The GenXArgIndirection pass runs very late, after coalescing and address /// commoning, to change arguments and return values that were originally by ref /// to use address registers. This saves copies and register pressure. /// /// Recall that, very early on in CMABI, a by ref argument is transformed into /// copy-in copy-out semantics. /// /// This pass is run very late on for two reasons: /// /// 1. There is no convenient way to represent passing an argument using an /// address register in LLVM IR. We don't want to pretend that the address /// register is a pointer, and the GRF is an area of memory, as that would /// stop us using Values to represent registers normally, and so would stop /// us using lots of LLVM optimizations. /// /// Running the pass this late means that the IR afterwards does not have to /// strictly represent the semantics, as nothing else happens to it before /// generating the output code. So uses and defs of the indirected argument /// (and other Values coalesced with it) still use the same Values, but that /// live range has no register allocated (it is category NONE), and all /// accesses are indirected. We rely on the LLVM IR together with the /// liveness information representing the code well enough for register /// allocation and code generation to work. /// /// 2. We cannot tell whether we want to perform this transformation until we can /// see how Values have coalesced. /// /// Action of GenXArgIndirection /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /// /// An argument for a subroutine call can generate a bunch of mov instructions in /// two circumstances: /// /// 1. Coalescing failed to coalesce this call argument, so the argument in the /// caller and the argument in the subroutine are in different registers /// (different coalesced live ranges). In this case, GenXCoalescing has to /// generate a sequence of baled together rdregion-wrregion intrinsic pairs, /// each generating a mov instruction, to copy the value. /// /// 2. The argument was originally a by ref CM select(), so is an rdregion, /// legalized into a sequence of baled together rdregion-wrregion pairs. /// /// The argument indirection pass attempts to spot these cases. The regions at /// each call site must be similar (same region parameters except start index) /// and contiguous. /// /// The pass modifies each call to pass an address register into the subroutine /// as an extra argument, using it to indirecting all accesses to the subroutine /// argument and other Values coalesced with it. It then removes the rd-wr /// sequence so it does not generate any code. /// /// Indirecting all accesses to the subroutine argument is only possible if each /// one would be legal as an indirect region. The pass uses the /// hasIndirectGRFCrossing feature from GenXSubtarget to tell whether it would /// be legal. The optimization can fail for this reason, and that is more common /// on pre-SKL where there is no indirect region GRF crossing. /// /// The pass deals with one subroutine argument in one subroutine at a time. It /// looks at all call sites to see if there is anything that stops this /// transformation happening at all, and whether there is any call site that /// would benefit from the transformation. /// /// Coalesced return value /// """""""""""""""""""""" /// /// If the subroutine argument is coalesced with a return value from the call, /// then argument indirection can succeed only if the return value at each call /// site is written (similarly using a rd-wr sequence) to exactly the same /// region in a vector that is coalesced (so same register) with the input /// vector to the rd-wr sequence for the argument. /// /// No coalesced return value /// """"""""""""""""""""""""" /// /// If the subroutine argument is _not_ coalesced with a return value from the /// call, so only the arg could be indirected, indirection can only occur if one /// of these conditions is met: /// /// 1. the live range being indirected is not live over the call (so it does not /// matter if the subroutine writes to the same register), or /// /// 2. the subroutine does not write to the same register (i.e. there are no defs /// in the subroutine arg's live range other than args and coalesced /// bitcasts). /// /// Constant argument and rd-wr sequence return value /// """"""""""""""""""""""""""""""""""""""""""""""""" /// /// Where the original source initializes a big vector or matrix to constant and /// then calls a subroutine passing the vector by ref, the IR that this pass sees /// is that the argument passed to the call is constant, and the rd-wr sequence /// for the return value has an "old value" input that is another constant /// (including undef). /// /// GenXArgIndirection spots this case, and transforms the code to load the /// combination of the two constants before the call and pass an address register /// set to the appropriate point. /// /// Indirection of subroutine /// """"""""""""""""""""""""" /// /// If an argument is being indirected, all references to that register /// (coalesced live range) inside the subroutine and everything it calls must be /// indirected. /// /// GenXArgIndirection does not include the facility to split up a bale if it /// would become illegal when indirected. This is only a problem in BDW and /// earlier, where an indirect region is not allowed to cross even one GRF /// boundary. If it sees an access with a region that would become illegal if /// indirected, it abandons indirection of that argument. /// /// Warning messages /// ^^^^^^^^^^^^^^^^ /// /// Where GenXArgIndirection sees a suitably large uncoalesced call arg that /// would benefit from arg indirection, but it fails to satisfy the criteria, /// the pass outputs a warning message. The idea is that the CM programmer /// might consider some changes to his/her kernel to optimize it. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "GENX_ARGINDIRECTION" #include "FunctionGroup.h" #include "GenX.h" #include "GenXAlignmentInfo.h" #include "GenXBaling.h" #include "GenXConstants.h" #include "GenXIntrinsics.h" #include "GenXLiveness.h" #include "GenXModule.h" #include "GenXNumbering.h" #include "GenXRegion.h" #include "GenXSubtarget.h" #include "GenXUtil.h" #include "vc/GenXOpts/Utils/KernelInfo.h" #include "vc/GenXOpts/Utils/RegCategory.h" #include "llvm/GenXIntrinsics/GenXIntrinsics.h" #include "llvm/GenXIntrinsics/GenXMetadata.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/ValueHandle.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "Probe/Assertion.h" #include "llvmWrapper/IR/DerivedTypes.h" using namespace llvm; using namespace genx; static cl::opt<unsigned> LimitGenXArgIndirection("limit-genx-arg-indirection", cl::init(UINT_MAX), cl::Hidden, cl::desc("Limit GenX argument indirection.")); namespace { class GenXArgIndirection; class SubroutineArg; // Diagnostic information for error/warning relating arg indirection. class DiagnosticInfoArgIndirection : public DiagnosticInfo { private: std::string Description; StringRef Filename; unsigned Line; unsigned Col; static int KindID; static int getKindID() { if (KindID == 0) KindID = llvm::getNextAvailablePluginDiagnosticKind(); return KindID; } public: // Initialize from an Instruction and an Argument. DiagnosticInfoArgIndirection(Instruction *Inst, Argument *Arg, const Twine &Desc, DiagnosticSeverity Severity = DS_Error); void print(DiagnosticPrinter &DP) const override; static bool classof(const DiagnosticInfo *DI) { return DI->getKind() == getKindID(); } }; int DiagnosticInfoArgIndirection::KindID = 0; // processArgLR relies on these being in this order. // checkIndirectability relies on these being powers of 2 (except // CALLER_INDIRECTING being 0) enum Indirectability { CALLER_INDIRECTING = 0, NO_OPTIMIZATION = 1, WANT_INDIRECTION = 2, WANT_SOME_INDIRECTION = 4, CANNOT_INDIRECT = 8 }; // A call site and the action that we want to take when indirecting the arg. // This is then subclassed by the *CallSite classes below. class CallSite { public: CallInst *CI; protected: Indirectability State; Value *Index; public: CallSite(CallInst *CI, Indirectability State, Value *Index) : CI(CI), State(State), Index(Index) {} virtual ~CallSite() {} Indirectability getState() const { return State; } Value *getIndex() const { return Index; } virtual Value *process(GenXArgIndirection *Pass, SubroutineArg *SubrArg) = 0; virtual void printImpl(raw_ostream &OS) const = 0; void print(raw_ostream &OS) const { printImpl(OS); } }; raw_ostream &operator<<(raw_ostream &OS, const CallSite &CS) { CS.print(OS); return OS; } // A call site in a subroutine that is itself indirecting the arg. class CallerIndirectingCallSite : public CallSite { SubroutineArg *CallerSubrArg; public: CallerIndirectingCallSite(CallInst *CI, SubroutineArg *CallerSubrArg) : CallSite(CI, Indirectability::CALLER_INDIRECTING, nullptr), CallerSubrArg(CallerSubrArg) {} virtual Value *process(GenXArgIndirection *Pass, SubroutineArg *SubrArg); virtual void printImpl(raw_ostream &OS) const { OS << "CallerIndirectingCallSite " << *CI; } }; // A call site where indirecting the arg does not give any optimization because // we did not find copies or rd/wr regions that we can get rid of. We can still // indirect it though if other call sites do get an optimization. class NoOptCallSite : public CallSite { public: NoOptCallSite(CallInst *CI) : CallSite(CI, Indirectability::NO_OPTIMIZATION, nullptr) {} virtual Value *process(GenXArgIndirection *Pass, SubroutineArg *SubrArg); virtual void printImpl(raw_ostream &OS) const { OS << "NoOptCallSite " << *CI; } }; // A call site where the arg is constant (including undef) and the arg is // coalesced with a retval that is used only in a legalized wrregion // whose "old value" input is constant. class ConstArgRetCallSite : public CallSite { Constant *LdConst; // the constant that needs to be loaded AssertingVH<Instruction> RetEndWr; // the last wrregion in the sequence for the retval public: ConstArgRetCallSite(CallInst *CI, Constant *LdConst, Instruction *RetEndWr, Value *Index) : CallSite(CI, Indirectability::WANT_INDIRECTION, Index), LdConst(LdConst), RetEndWr(RetEndWr) {} virtual Value *process(GenXArgIndirection *Pass, SubroutineArg *SubrArg); virtual void printImpl(raw_ostream &OS) const { OS << "ConstArgRetCallSite " << *CI << "\n LdConst " << *LdConst << " \n RetEndWr " << *RetEndWr << "\n Index " << *Index; } }; // A call site where the arg is a legalized rdregion or copy, and there is no // retval coalesced with it. class IndirectArgCallSite : public CallSite { protected: // Some use of input (arg or inst) in legalized rdregion or copy. This is // kept as a Use * rather than the value it actually uses to allow for the // case that the value is something that will be replaced and erased by // another call site processing the same ArgLR. Use *InputUse; public: IndirectArgCallSite(CallInst *CI, Use *InputUse, Value *Index) : CallSite(CI, Indirectability::WANT_INDIRECTION, Index), InputUse(InputUse) {} virtual Value *process(GenXArgIndirection *Pass, SubroutineArg *SubrArg); virtual void printImpl(raw_ostream &OS) const { OS << "IndirectArgCallSite " << *CI << "\n Input " << (*InputUse)->getName() << " Index " << *Index; } }; // A call site where the arg is a legalized rdregion or copy, and the arg is // coalesced with a retval that is used only in a legalized wrregion or copy. class IndirectArgRetCallSite : public IndirectArgCallSite { AssertingVH<Instruction> RetEndWr; // the last wrregion in the sequence for the retval public: IndirectArgRetCallSite(CallInst *CI, Use *InputUse, Instruction *RetEndWr, Value *Index) : IndirectArgCallSite(CI, InputUse, Index), RetEndWr(RetEndWr) {} virtual Value *process(GenXArgIndirection *Pass, SubroutineArg *SubrArg); virtual void printImpl(raw_ostream &OS) const { OS << "IndirectArgRetCallSite " << *CI << "\n Input " << (*InputUse)->getName() << " RetEndWr " << RetEndWr->getName() << " Index " << *Index; } }; class GenXArgIndirection; // A subroutine arg that we might want to indirect class SubroutineArg { GenXArgIndirection *Pass = nullptr; public: LiveRange *ArgLR = nullptr; Argument *Arg = nullptr; private: int CoalescedRetIdx = -1; bool CanCoalesceWithoutKill = false; SmallVector<CallSite *, 4> CallSites; Alignment Align; Function *F = nullptr; Function *NewFunc = nullptr; public: Argument *AddressArgument; SubroutineArg(GenXArgIndirection *Pass, LiveRange *ArgLR, Argument *Arg) : Pass(Pass), ArgLR(ArgLR), Arg(Arg), F(Arg->getParent()), NewFunc(nullptr) {} ~SubroutineArg() { for (auto i = CallSites.begin(), e = CallSites.end(); i != e; ++i) delete *i; } Indirectability checkIndirectability(); CallSite *createCallSite(CallInst *CI); Alignment getIndirectAlignment(unsigned GRFWidth) const; void gatherBalesToModify(Alignment Align); std::pair<Value *, Value *> addAddressArg(); void fixCallSites(); void coalesceAddressArgs(); void replaceFunction(); private: static Value *getRetVal(CallInst *CI, unsigned RetNum); }; // GenX arg indirection pass class GenXArgIndirection : public FunctionGroupPass { friend CallSite; friend SubroutineArg; friend NoOptCallSite; friend ConstArgRetCallSite; friend IndirectArgCallSite; friend IndirectArgRetCallSite; private: FunctionGroup *FG = nullptr; FunctionGroupAnalysis *FGA = nullptr; GenXBaling *Baling = nullptr; GenXLiveness *Liveness = nullptr; GenXNumbering *Numbering = nullptr; AlignmentInfo *AI = nullptr; const GenXSubtarget *ST = nullptr; const DataLayout *DL = nullptr; // List of arg live ranges to consider. SmallVector<LiveRange *, 4> ArgLRs; // For the ArgLR being processed: // List of subroutine args in the ArgLR. SmallVector<SubroutineArg, 4> SubrArgs; // Bales that need modifying for indirection. SmallVector<Instruction *, 4> BalesToModify; // Map from function back to the SubroutineArg for it. std::map<Function *, SubroutineArg *> FuncMap; // List of LRs that we need to recalculate. SmallVector<LiveRange *, 4> LRsToCalculate; public: static char ID; explicit GenXArgIndirection() : FunctionGroupPass(ID) { } virtual StringRef getPassName() const { return "GenX arg indirection"; } void getAnalysisUsage(AnalysisUsage &AU) const { FunctionGroupPass::getAnalysisUsage(AU); AU.addRequired<FunctionGroupAnalysis>(); AU.addRequired<GenXNumbering>(); AU.addRequired<GenXLiveness>(); AU.addRequired<GenXGroupBaling>(); AU.addRequired<GenXModule>(); AU.addPreserved<GenXGroupBaling>(); AU.addPreserved<GenXLiveness>(); AU.addPreserved<GenXNumbering>(); AU.addPreserved<GenXModule>(); AU.addPreserved<FunctionGroupAnalysis>(); } bool runOnFunctionGroup(FunctionGroup &FG); // createPrinterPass : get a pass to print the IR, together with the GenX // specific analyses virtual Pass *createPrinterPass(raw_ostream &O, const std::string &Banner) const { return createGenXGroupPrinterPass(O, Banner); } private: void gatherArgLRs(); bool processArgLR(LiveRange *ArgLR); bool gatherBalesToModify(LiveRange *ArgLR, Alignment Align); bool checkIndirectBale(Bale *B, LiveRange *ArgLR, Alignment Align); void indirectBale(Bale *B, LiveRange *ArgLR, Argument *AddressArg); void indirectRegion(Use *U, Value *AddressArg, Instruction *InsertBefore); static Argument *getArgForFunction(LiveRange *LR, Function *F); void replaceAndEraseSequence(Instruction *RetEndWr, Value *V); struct ArgToConvertAddr { Value *Arg; Value *ConvertAddr; }; std::vector<ArgToConvertAddr> collectAlreadyIndirected(LiveRange *ArgLR); }; } // end anonymous namespace char GenXArgIndirection::ID = 0; namespace llvm { void initializeGenXArgIndirectionPass(PassRegistry &); } INITIALIZE_PASS_BEGIN(GenXArgIndirection, "GenXArgIndirection", "GenXArgIndirection", false, false) INITIALIZE_PASS_DEPENDENCY(GenXGroupBaling) INITIALIZE_PASS_DEPENDENCY(GenXNumbering) INITIALIZE_PASS_DEPENDENCY(GenXLiveness) INITIALIZE_PASS_END(GenXArgIndirection, "GenXArgIndirection", "GenXArgIndirection", false, false) FunctionGroupPass *llvm::createGenXArgIndirectionPass() { initializeGenXArgIndirectionPass(*PassRegistry::getPassRegistry()); return new GenXArgIndirection(); } /*********************************************************************** * runOnFunctionGroup : run the coalescing pass for this FunctionGroup */ bool GenXArgIndirection::runOnFunctionGroup(FunctionGroup &ArgFG) { FG = &ArgFG; unsigned Modified = 0; // Get analyses that we use and/or modify. FGA = &getAnalysis<FunctionGroupAnalysis>(); Baling = &getAnalysis<GenXGroupBaling>(); Numbering = &getAnalysis<GenXNumbering>(); Liveness = &getAnalysis<GenXLiveness>(); AI = new AlignmentInfo; ST = getAnalysis<GenXModule>().getSubtarget(); DL = &ArgFG.getModule()->getDataLayout(); // Gather list of LRs containing an arg that we want to consider. (Two // args might be coalesced together, so we consider a whole arg-containing // LR at a time.) gatherArgLRs(); // Process them. for (auto i = ArgLRs.begin(), e = ArgLRs.end(); i != e && Modified < LimitGenXArgIndirection; ++i) { if (processArgLR(*i)) { ++Modified; if (LimitGenXArgIndirection != UINT_MAX) dbgs() << "genx-arg-indirection " << Modified << "\n"; } } ArgLRs.clear(); SubrArgs.clear(); BalesToModify.clear(); FuncMap.clear(); LRsToCalculate.clear(); delete AI; return Modified != 0; } /*********************************************************************** * gatherArgLRs : gather a list of LRs containing an arg that we want to * consider */ void GenXArgIndirection::gatherArgLRs() { std::set<LiveRange *> Seen; // For a kernel arg, add it to Seen but not to the list, so it will not get // added to the list. We cannot indirect a kernel arg. for (auto ai = FG->at(0)->arg_begin(), ae = FG->at(0)->arg_end(); ai != ae; ++ai) Seen.insert(Liveness->getLiveRange(&*ai)); // For a subroutine arg, add its LR to the list if it is not already in Seen. for (auto fgi = FG->begin() + 1, fge = FG->end(); fgi != fge; ++fgi) { if (genx::requiresStackCall(*fgi)) continue; for (auto ai = (*fgi)->arg_begin(), ae = (*fgi)->arg_end(); ai != ae; ++ai) { Argument *Arg = &*ai; // Only process an arg that is bigger than 2 GRFs. if (Arg->getType()->getPrimitiveSizeInBits() <= ST->getGRFWidth() * 16) continue; LiveRange *LR = Liveness->getLiveRange(Arg); if (Seen.insert(LR).second) ArgLRs.push_back(LR); } } } // A simple helper function for // GenXArgIndirection::collectAlreadyIndirected. It tries to find the original // argument in wrr and rdr sequence. static Value *searchForArg(Value *V) { IGC_ASSERT(V); while (!isa<Argument>(V)) { auto *I = dyn_cast<Instruction>(V); if (I && (GenXIntrinsic::isRdRegion(I) || GenXIntrinsic::isWrRegion(I))) V = I->getOperand(0); else return nullptr; } return V; } /*********************************************************************** * collectAlreadyIndirected : Some values in the ArgLR may be already * indirected. It collects genx.convert.addr (indirection) and an argument that * was the base. * * Return: A vector with collected values. */ std::vector<GenXArgIndirection::ArgToConvertAddr> GenXArgIndirection::collectAlreadyIndirected(LiveRange *ArgLR) { std::vector<GenXArgIndirection::ArgToConvertAddr> IndirectedArgInfo; for (auto VI : ArgLR->getValues()) { Value *Base = VI.getValue(); std::vector<Value *> Addrs = Liveness->getAddressWithBase(Base); // Not a base if (Addrs.empty()) continue; // A chain of // @bar (%arg) { // ... // %1 = genx.convert.addr // %2 = call foo(..., %1) // %dummy_use_for_indirection = bitcast ... // } // ArgLR: ..., %arg, %dummy_use_for_indirection, ... // is expected. The bitcast is a dummy instruction that holds a base for the // genx.convert.addr. If the bitcast is in ArgLR which will be set to NONE // category, we must find another base for the genx.convert.addr. The idea // is that the bitcast operand originates from the %arg (because both of // them are in ArgLR) and the base for genx.convert.addr may be taken as // indirected %arg. This indirected arg will have ADDRESS category and // genx.convert.addr will be just an offset in this address. auto *DummyBC = dyn_cast<BitCastInst>(Base); IGC_ASSERT_MESSAGE(DummyBC, "Unexpected base: not a dummy bitcast."); Value *Arg = searchForArg(DummyBC->getOperand(0)); IGC_ASSERT_MESSAGE(Arg, "Cannot find original argument"); std::transform(Addrs.begin(), Addrs.end(), std::back_inserter(IndirectedArgInfo), [Arg](Value *Addr) { return ArgToConvertAddr{Arg, Addr}; }); } return IndirectedArgInfo; } /*********************************************************************** * processArgLR : process one live range containing at least one subroutine arg * * Return: true = some modifications made */ bool GenXArgIndirection::processArgLR(LiveRange *ArgLR) { // Get a list of args in this live range. SubrArgs.clear(); FuncMap.clear(); LLVM_DEBUG(dbgs() << "processArgLR: " << *ArgLR << "\n"); for (auto vi = ArgLR->value_begin(), ve = ArgLR->value_end(); vi != ve; ++vi) if (auto Arg = dyn_cast<Argument>(vi->getValue())) { SubrArgs.push_back(SubroutineArg(this, ArgLR, Arg)); FuncMap[Arg->getParent()] = &SubrArgs.back(); } // For each arg, see if we can or want to indirect. Indirectability Res = Indirectability::NO_OPTIMIZATION; for (auto SubrArg = SubrArgs.begin(), e = SubrArgs.end(); SubrArg != e; ++SubrArg) { LLVM_DEBUG(dbgs() << " checkIndirectability on arg " << SubrArg->Arg->getArgNo() << " (" << (SubrArg->Arg->getType()->getPrimitiveSizeInBits() / 8U) << " bytes) in " << SubrArg->Arg->getParent()->getName() << "\n"); Res = std::max(Res, SubrArg->checkIndirectability()); } if (Res == Indirectability::NO_OPTIMIZATION) { LLVM_DEBUG(dbgs() << "NO_OPTIMIZATION\n"); return false; // no indirection needed } if (Res == Indirectability::CANNOT_INDIRECT) { LLVM_DEBUG(dbgs() << "CANNOT_INDIRECT\n"); return false; // cannot indirect this ArgLR } // Get the worst case alignment of the indices from the call sites if we // indirect this arg. Alignment Align = Alignment(genx::log2(ST->getGRFWidth()), 0); for (auto SubrArg = SubrArgs.begin(), e = SubrArgs.end(); SubrArg != e; ++SubrArg) { auto ThisAlign = SubrArg->getIndirectAlignment(ST->getGRFWidth()); Align = Align.merge(ThisAlign); } // Gather the bales that need indirecting, and check whether indirection is // possible. if (!gatherBalesToModify(ArgLR, Align)) return false; LLVM_DEBUG(dbgs() << "GenXArgIndirection is going to indirect " << *ArgLR << "\n"); LRsToCalculate.clear(); if (Res == Indirectability::WANT_SOME_INDIRECTION) { // The arg that we're indirecting is coalesced at some call site where we // are going to indirect it (represented by a NoOptCallSite). To avoid the // coalesced LR also being live at other call sites where the arg is in // fact in some other register, we need to uncoalesce. We take the values // in ArgLR and separate into two piles: one defined outside subroutines // where ArgLR has an arg, and one defined inside such subroutines. Then // the two piles get a live range each, and the latter one is marked as not // needing a register allocating. SmallVector<SimpleValue, 4> OutsidePile; SmallVector<SimpleValue, 4> InsidePile; for (auto vi = ArgLR->value_begin(), ve = ArgLR->value_end(); vi != ve; ++vi) { auto SV = *vi; Function *ContainingFunc = Liveness->isUnifiedRet(SV.getValue()); if (!ContainingFunc) { if (auto VArg = dyn_cast<Argument>(SV.getValue())) ContainingFunc = VArg->getParent(); else ContainingFunc = cast<Instruction>(SV.getValue()) ->getParent()->getParent(); } if (!FuncMap[ContainingFunc]) OutsidePile.push_back(SV); else InsidePile.push_back(SV); } IGC_ASSERT(!InsidePile.empty()); if (!OutsidePile.empty()) { Liveness->removeValuesNoDelete(ArgLR); LiveRange *OutsideLR = Liveness->getOrCreateLiveRange(OutsidePile[0]); OutsideLR->setCategory(ArgLR->getCategory()); for (auto vi = OutsidePile.begin() + 1, ve = OutsidePile.end(); vi != ve; ++vi) Liveness->setLiveRange(*vi, OutsideLR); for (auto vi = InsidePile.begin(), ve = InsidePile.end(); vi != ve; ++vi) Liveness->setLiveRange(*vi, ArgLR); LLVM_DEBUG(dbgs() << " Uncoalesced ArgLR into " << *OutsideLR << "\n and " << *ArgLR << "\n"); LRsToCalculate.push_back(OutsideLR); } } auto IndirectedArgInfo = collectAlreadyIndirected(ArgLR); // ArgLR now contains only these values: // - args that we are indirecting // - other values inside the subroutines that we are indirecting // We do not want it to get a register allocated, since those values will be // indirected. We achieve that by setting ArgLR's category to NONE. ArgLR->setCategory(RegCategory::NONE); LLVM_DEBUG(dbgs() << " Not allocating register for arg's LR\n"); // Arg to indirected arg map. std::map<Value *, Value *> ArgToAddressArg; // For each subroutine, replace the func with a new one that has an extra // address arg. for (auto SubrArg = SubrArgs.begin(), e = SubrArgs.end(); SubrArg != e; ++SubrArg) ArgToAddressArg.insert(SubrArg->addAddressArg()); // Since the ArgLR has been set to NONE category, it cannot be used as a base // register and the indirected argument address should be used instead. for (auto Info : IndirectedArgInfo) { IGC_ASSERT_MESSAGE(ArgToAddressArg.count(Info.Arg), "Cannot find indirected arg"); Liveness->setArgAddressBase(Info.ConvertAddr, ArgToAddressArg[Info.Arg]); } // For each subroutine, fix up its call sites. for (auto SubrArg = SubrArgs.begin(), e = SubrArgs.end(); SubrArg != e; ++SubrArg) SubrArg->fixCallSites(); // Replace old function with new function. for (auto SubrArg = SubrArgs.begin(), e = SubrArgs.end(); SubrArg != e; ++SubrArg) SubrArg->replaceFunction(); // Run gatherBalesToModify again, as the list it made last time is now invalid // due to code being changed. if (!gatherBalesToModify(ArgLR, Align)) IGC_ASSERT_EXIT_MESSAGE(0, "not expecting indirection to have become invalid in second run"); // Indirect the bales. for (auto bi = BalesToModify.begin(), be = BalesToModify.end(); bi != be; ++bi) { Instruction *Inst = *bi; Bale B; Baling->buildBale(Inst, &B); auto argIter = Inst->getParent()->getParent()->arg_begin(); std::advance(argIter, Inst->getParent()->getParent()->arg_size() - 1); Argument *AddressArg = &*argIter; indirectBale(&B, ArgLR, AddressArg); } // Recalculate live ranges as required. Rebuild the call graph first, as it // has been made invalid by us replacing some functions. { Liveness->rebuildCallGraph(); std::set<LiveRange *> LRsSeen; for (auto i = LRsToCalculate.begin(), e = LRsToCalculate.end(); i != e; ++i) { LiveRange *LR = *i; if (LRsSeen.insert(LR).second) { Liveness->rebuildLiveRange(LR); LLVM_DEBUG(dbgs() << " recalculated " << *LR << "\n"); } } } // Coalesce (or insert copy on coalesce failure) new address args. for (auto SubrArg = SubrArgs.begin(), e = SubrArgs.end(); SubrArg != e; ++SubrArg) SubrArg->coalesceAddressArgs(); return true; } /*********************************************************************** * checkIndirectability : check whether we want to and can indirect a * subroutine argument, populating the SubrArg struct so we have the * information needed to indirect it * * Return: NO_OPTIMIZATION : can indirect, but no optimization in terms of * saving instructions or register pressure * WANT_INDIRECTION : can indirect and it is an optimization. The live * range does not include anything outside of subroutines where * it is an arg, thus we need to ensure that no register is * allocated to it. * WANT_SOME_INDIRECTION : can indirect and it is an optimization. The * live range does include something outside of subroutines where * it is an arg, so we need to ensure that a register is allocated * to it. We get this if some call sites are WANT_INDIRECTION and * some are NO_OPTIMIZATION. * CANNOT_INDIRECT : cannot indirect this live range at all. */ Indirectability SubroutineArg::checkIndirectability() { if (genx::requiresStackCall(F)) return CANNOT_INDIRECT; // See if there is a return value that is coalesced with the arg. CoalescedRetIdx = -1; for (unsigned ri = 0, re = IndexFlattener::getNumElements(F->getReturnType()); ri != re; ++ri) { if (Pass->Liveness->getLiveRange( SimpleValue(Pass->Liveness->getUnifiedRet(F), ri)) == ArgLR) { if (CoalescedRetIdx >= 0) { for (auto *U: F->users()) { if (auto *CI = checkFunctionCall(U, F)) { DiagnosticInfoArgIndirection Warn( CI, Arg, "Argument coalesced with multiple return values", DS_Warning); CI->getContext().diagnose(Warn); } } return Indirectability::CANNOT_INDIRECT; } CoalescedRetIdx = ri; } } // If there is no return value, check whether it is OK to indirect a call arg // even if the call arg is not killed at the call. This is the case if there // is no write to the subroutine arg's live range inside the subroutine(s) // other than args and coalesced bitcasts. CanCoalesceWithoutKill = true; if (CoalescedRetIdx < 0) { for (auto vi = ArgLR->value_begin(), ve = ArgLR->value_end(); vi != ve; ++vi) { auto Inst = dyn_cast<Instruction>(vi->getValue()); if (!Inst) continue; // it's an arg, not an instruction Function *Func = Pass->Liveness->isUnifiedRet(Inst); if (!Func) Func = Inst->getParent()->getParent(); else continue; if (Pass->FuncMap.find(Func) == Pass->FuncMap.end()) continue; // value not in one of the subroutines where the arg is indirected auto *CI = dyn_cast<CastInst>(Inst); if (!CI || !genx::isNoopCast(CI) || !Pass->Liveness->isNoopCastCoalesced(CI)) { CanCoalesceWithoutKill = false; break; } } } // Create an object of some subclass of CallSite for each call site. for (auto &U: F->uses()) { if (auto *CI = checkFunctionCall(U.getUser(), F)) { IGC_ASSERT(U.getOperandNo() == CI->getNumArgOperands()); auto CallSite = createCallSite(CI); if (!CallSite) return Indirectability::CANNOT_INDIRECT; CallSites.push_back(CallSite); LLVM_DEBUG(dbgs() << " " << *CallSite << "\n"); } } // Check indirection state for each call site. unsigned States = 0; for (auto csi = CallSites.begin(), cse = CallSites.end(); csi != cse; ++csi) { auto CallSite = *csi; States |= CallSite->getState(); } switch (States & (Indirectability::NO_OPTIMIZATION | Indirectability::WANT_INDIRECTION)) { case Indirectability::NO_OPTIMIZATION | Indirectability::WANT_INDIRECTION: return Indirectability::WANT_SOME_INDIRECTION; case Indirectability::WANT_INDIRECTION: return Indirectability::WANT_INDIRECTION; } return Indirectability::NO_OPTIMIZATION; } /*********************************************************************** * createCallSite : create a CallSite object for this call * * Enter: CI = CallInst * this->Arg = the Argument to look at * this->ArgLR = its LiveRange * this->CoalescedRetIdx = -1 else struct index of coalesced return value * * Return: 0 if this call stops arg indirection happening for this arg * otherwise object of some subclass of CallSite */ CallSite *SubroutineArg::createCallSite(CallInst *CI) { // Check if this call site is in a function that is itself indirecting the // arg. if (auto SubrArg = Pass->FuncMap[CI->getParent()->getParent()]) return new CallerIndirectingCallSite(CI, SubrArg); // Look at the call arg. Value *V = CI->getArgOperand(Arg->getArgNo()); // Skip any coalesced bitcasts. while (auto BC = dyn_cast<BitCastInst>(V)) { if (Pass->Liveness->getLiveRangeOrNull(BC->getOperand(0)) != ArgLR) break; V = BC->getOperand(0); } // If the call arg (before coalesced bitcasts) is a wrregion where the arg // is the only use, try and parse it as a rd-wr sequence that reads a // contiguous region and writes the whole of Arg. RdWrRegionSequence ArgRWS; if (!V->hasOneUse() || !GenXIntrinsic::isWrRegion(V) || !ArgRWS.buildFromWr(cast<Instruction>(V), Pass->Baling) || !ArgRWS.RdR.isContiguous() || !ArgRWS.WrR.isWhole(Arg->getType())) { // Failed to find such a rd-wr sequence. Set ArgRWS to null. ArgRWS = RdWrRegionSequence(); } // Look at the retval. RdWrRegionSequence RetRWS; if (CoalescedRetIdx >= 0) { Value *RetVal = getRetVal(CI, CoalescedRetIdx); if (!RetVal) { // getRetVal could not determine what happens to this return value. DiagnosticInfoArgIndirection Warn(CI, Arg, "Coalesced return value has unknown uses", DS_Warning); CI->getContext().diagnose(Warn); return nullptr; } if (!isa<UndefValue>(RetVal)) { // See if the return value has a single use in (after skipping coalesced // bitcasts) a single wrregion or a rd-wr sequence. // First skip single use coalesced bitcasts. while (!RetVal->use_empty()) { auto User = cast<Instruction>(RetVal->use_begin()->getUser()); if (RetVal->hasOneUse()) { if (auto BC = dyn_cast<BitCastInst>(User)) { if (Pass->Liveness->getLiveRange(BC) == ArgLR) { // Skip coalesced bitcast. RetVal = BC; continue; } } } // Attempt to parse as a rd-wr sequence that reads the whole of RetVal // and writes a contiguous region, so it is either a legalized copy, or // a legalized contiguous wrregion, and it is the only use of the input. if (!GenXIntrinsic::isRdRegion(User) || RetVal->use_begin()->getOperandNo() != GenXIntrinsic::GenXRegion::OldValueOperandNum || !RetRWS.buildFromRd(User, Pass->Baling) || !RetRWS.WrR.isContiguous() || !RetRWS.RdR.isWhole(RetVal->getType()) || !RetRWS.isOnlyUseOfInput()) { // That failed, so make RetRWS null. RetRWS = RdWrRegionSequence(); } break; } } } // Now check the various cases. This results in the creation of an object of // some subclass of CallSite. // Check that the regions are contiguous, and report if they are not. if (ArgRWS.isNull() && !ArgRWS.RdR.isContiguous()) { DiagnosticInfoArgIndirection Warn(CI, Arg, "Non-contiguous region", DS_Warning); CI->getContext().diagnose(Warn); return new NoOptCallSite(CI); } if (RetRWS.isNull() && !RetRWS.WrR.isContiguous()) { DiagnosticInfoArgIndirection Warn(CI, Arg, "Non-contiguous region for coalesced return value", DS_Warning); CI->getContext().diagnose(Warn); return new NoOptCallSite(CI); } // Case 1: The call arg is constant (inc undef, or a legalized constant // load), and the retval is input to a wrregion sequence where the "old // value" input is also a constant (a legalized constant load, also allowing // for a bitcast). This typically happens when the arg and ret were a by ref // region of a matrix, but the matrix was initialized to constant, or not // initialized at all, before the call, so the rdregion got simplified away. if (!RetRWS.isNull()) { Value *RetOldVal = RetRWS.OldVal; while (auto BC = dyn_cast<BitCastInst>(RetOldVal)) RetOldVal = BC->getOperand(0); auto *RetOldValC = dyn_cast<Constant>(RetOldVal); if (!RetOldValC && GenXIntrinsic::isWrRegion(RetOldVal)) { RdWrRegionSequence ConstRWS; if (ConstRWS.buildFromWr(cast<Instruction>(RetOldVal), Pass->Baling)) RetOldValC = dyn_cast<Constant>(ConstRWS.Input); } if (RetOldValC) { Constant *Input; if (!ArgRWS.isNull()) Input = dyn_cast<Constant>(ArgRWS.Input); else Input = dyn_cast<Constant>(CI->getArgOperand(Arg->getArgNo())); if (Input) { // Get the Input constant to the same element type as RetOldValC. if (RetOldValC->getType()->getScalarType() != Input->getType()->getScalarType()) { Type *ElTy = RetOldValC->getType()->getScalarType(); IGC_ASSERT(ElTy->getPrimitiveSizeInBits()); Input = ConstantExpr::getBitCast( Input, IGCLLVM::FixedVectorType::get( ElTy, Input->getType()->getPrimitiveSizeInBits() / ElTy->getPrimitiveSizeInBits())); } // Construct the constant that needs to be loaded. IGC_ASSERT(RetOldValC->getType()->getScalarType() == Input->getType()->getScalarType()); auto LdConst = RetRWS.WrR.evaluateConstantWrRegion(RetOldValC, Input); // Create the ConstArgRetCallSite object. return new ConstArgRetCallSite(CI, LdConst, RetRWS.EndWr, RetRWS.getWrIndex()); } } } // Case 2: The call arg is a legalized contiguous rdregion or copy of // non-constant, and there is no retval coalesced with it. if (RetRWS.isNull() && !ArgRWS.isNull() && CoalescedRetIdx < 0 && !isa<Constant>(ArgRWS.Input) && !GenXIntrinsic::isReadPredefReg(ArgRWS.getInputUse()->get())) { // It is valid to indirect this arg only if one of these is true: // 1. the input to ArgRWS is not live over the call, or // 2. the coalesced live range for the arg is not written to inside the // subroutine or anything it calls. if (CanCoalesceWithoutKill || !Pass->Liveness->getLiveRange(ArgRWS.Input) ->contains(Pass->Numbering->getNumber(CI))) return new IndirectArgCallSite(CI, ArgRWS.getInputUse(), ArgRWS.getRdIndex()); DiagnosticInfoArgIndirection Warn(CI, Arg, "Argument is region in value that is live over call", DS_Warning); CI->getContext().diagnose(Warn); return nullptr; } // Case 3: The call arg is a legalized rdregion or copy of non-constant, and // the coalesced retval is a legalized wrregion or copy with the same region // and the same base register. if (!RetRWS.isNull() && !ArgRWS.isNull() && CoalescedRetIdx >= 0 && !isa<Constant>(ArgRWS.Input)) { // Check the regions are the same. if (ArgRWS.RdR == RetRWS.WrR) { // Check the base registers are the same. if (Pass->Liveness->getLiveRange(ArgRWS.Input) == Pass->Liveness->getLiveRange(RetRWS.EndWr)) return new IndirectArgRetCallSite(CI, ArgRWS.getInputUse(), RetRWS.EndWr, ArgRWS.getRdIndex()); } DiagnosticInfoArgIndirection Warn(CI, Arg, "Coalesced return value does not match argument", DS_Warning); CI->getContext().diagnose(Warn); return nullptr; } // Case 4: No optimization for this call site, and cannot even indirect it // unless either there is a coalesced retval, or the subroutine arg's LR is // not written inside the subroutines, or the call arg is killed at the call. if (!CanCoalesceWithoutKill && !ArgRWS.isNull() && !isa<Constant>(ArgRWS.Input) && Pass->Liveness->getLiveRange(ArgRWS.Input) ->contains(Pass->Numbering->getNumber(CI))) { DiagnosticInfoArgIndirection Warn(CI, Arg, "Argument is value that is live over call", DS_Warning); CI->getContext().diagnose(Warn); return nullptr; } // Case 5: No optimization for this call site (but it can still be indirected // if some other call site would get optimized). return new NoOptCallSite(CI); } /*********************************************************************** * getIndirectAlignment : get worst-case alignment of indices if we indirect * this arg and retval */ Alignment SubroutineArg::getIndirectAlignment(unsigned GRFWidth) const { Alignment Align(genx::log2(GRFWidth), 0); // best case is GRF aligned for (auto csi = CallSites.begin(), cse = CallSites.end(); csi != cse; ++csi) { auto CallSite = *csi; Value *Index = CallSite->getIndex(); if (!Index) continue; Align = Align.merge(Pass->AI->get(Index)); } return Align; } /*********************************************************************** * gatherBalesToModify : check whether the arg can be indirected and * gather the bales that need modifying * * Enter: Align = the worst case alignment of the indirection * this->BalesToModify = vector to populate * * Return: true if can be indirected, with * BalesToModify populated with bales that need indirecting */ bool GenXArgIndirection::gatherBalesToModify(LiveRange *ArgLR, Alignment Align) { LLVM_DEBUG(dbgs() << "gatherBalesToModify: alignment " << Align << "\n"); BalesToModify.clear(); // We call SubroutineArg::gatherBalesToModify for each subroutine that has // an arg in this live range. Just gathering bales for all instructions and // args in the live range in one go would not work, because there might be a // call site where the call arg is coalesced, and we would end up indirecting // it and other things it is coalesced with. for (auto si = SubrArgs.begin(), se = SubrArgs.end(); si != se; ++si) si->gatherBalesToModify(Align); // Check the bales to see if we can legally indirect accesses to any value in // ArgLR (i.e. the arg, the retval, and anything coalesced with it) by doing // a dry run of modifying them. for (auto btmi = BalesToModify.begin(), btme = BalesToModify.end(); btmi != btme; ++btmi) { Bale B; Baling->buildBale(*btmi, &B); if (!checkIndirectBale(&B, ArgLR, Align)) { // Failure. For error reporting, get the arg for the function in which the // failure occurred. Argument *Arg = getArgForFunction(ArgLR, B.getHead()->Inst->getParent() ->getParent()); DiagnosticInfoArgIndirection Warn(B.getHead()->Inst, Arg, "Use of argument cannot be indirected", DS_Warning); B.getHead()->Inst->getContext().diagnose(Warn); return false; } } return true; } /*********************************************************************** * gatherBalesToModify : gather the bales that need modifying for this one * subroutine arg * * Enter: Align = the worst case alignment of the indirection * Pass->BalesToModify = vector to populate * * Return: BalesToModify populated with bales that need indirecting */ void SubroutineArg::gatherBalesToModify(Alignment Align) { std::set<Instruction *> BalesSeen; for (auto vi = ArgLR->value_begin(), ve = ArgLR->value_end(); vi != ve; ++vi) { Value *V = vi->getValue(); if (Pass->Liveness->isUnifiedRet(V)) continue; // ignore unified ret if (auto Inst = dyn_cast<Instruction>(V)) { if (Inst->getParent()->getParent() != F) continue; // ignore instruction in wrong function // Add the def to the list of bales that will need modifying, unless // it is a phi node or coalesced bitcast or insert/extract in struct // or a non-intrinsic call. if (!isa<PHINode>(Inst) && (!isa<BitCastInst>(Inst) || Pass->Liveness->getLiveRange(Inst->getOperand(0)) != ArgLR) && !isa<InsertValueInst>(Inst) && !isa<ExtractValueInst>(Inst) && (!isa<CallInst>(Inst) || GenXIntrinsic::isAnyNonTrivialIntrinsic(Inst))) if (BalesSeen.insert(Inst).second) Pass->BalesToModify.push_back(Inst); } else if (V != Arg) continue; // ignore arg in wrong function for (auto ui = V->use_begin(), ue = V->use_end(); ui != ue; ++ui) { auto User = cast<Instruction>(ui->getUser()); if (auto CI = dyn_cast<CallInst>(User)) { Function *CF = CI->getCalledFunction(); if (!GenXIntrinsic::isAnyNonTrivialIntrinsic(CF) && !genx::requiresStackCall(CF)) { // Non-intrinsic call. Ignore. (A call site using an arg being // indirected gets handled differently.) // Cannot indirect if there is a stack call. Do not ignore stack // calls here and add them to BalesToModify. In checkIndirectBale // report that such bale cannot be indirected. This method is // confusing, must be improved. continue; } } else { if (isa<StructType>(User->getType())) continue; // Ignore call with multiple retvals, or insert used to do // multiple retvals if (isa<ExtractValueInst>(User)) continue; // Ignore extract in struct used to do multiple retvals if (isa<PHINode>(User)) continue; // Ignore phi nodes if (isa<ReturnInst>(User)) continue; // Ignore return instruction if (isa<BitCastInst>(User) && Pass->Liveness->getLiveRange(User) == ArgLR) continue; // Ignore coalesced bitcast } // Add the head of the bale to the list of bales that will need modifying. auto UserHead = Pass->Baling->getBaleHead(User); if (BalesSeen.insert(UserHead).second) Pass->BalesToModify.push_back(UserHead); } } } /*********************************************************************** * checkIndirectBale : check if a bale can be indirected * * Enter: B = bale to check * ArgLR = live range of values that need to be indirected * Align = alignment of index being introduced * * Return: true if can be indirected */ bool GenXArgIndirection::checkIndirectBale(Bale *B, LiveRange *ArgLR, Alignment Align) { auto MainInst = B->getMainInst(); if (MainInst) { // Check for things about the main instruction that stop us indexing // operand(s) or result in this bale. if (MainInst->Inst->getType()->getPrimitiveSizeInBits() / genx::ByteBits > ST->getGRFWidth() && !ST->hasIndirectGRFCrossing()) { // An execution size bigger than 1 GRF disqualifies the main // instruction on <= BDW. LLVM_DEBUG(dbgs() << "execution size bigger than GRF\n"); return false; } unsigned IID = GenXIntrinsic::getAnyIntrinsicID(MainInst->Inst); if (GenXIntrinsic::isAnyNonTrivialIntrinsic(IID)) { auto IntrInfo = GenXIntrinsicInfo(IID); // Cannot indirect a raw or direct only operand. bool RawOrDirectOnly = std::any_of(MainInst->Inst->op_begin(), MainInst->Inst->op_end(), [&IntrInfo](Use &U) { auto AI = IntrInfo.getArgInfo(U.getOperandNo()); return AI.isRaw() || AI.isDirectOnly(); }); if (RawOrDirectOnly) { LLVM_DEBUG(dbgs() << *MainInst->Inst << "\n\tintrinsic has raw or direct only operand\n"); return false; } if (IntrInfo.getRetInfo().isRaw()) { LLVM_DEBUG(dbgs() << *MainInst->Inst << "\n\tintrinsic with raw return value\n"); return false; } } else if (auto *CI = dyn_cast<CallInst>(MainInst->Inst)) { auto *Callee = CI->getCalledFunction(); IGC_ASSERT_MESSAGE(genx::requiresStackCall(Callee), "Expect a stack call to stop indirection. See " "SubroutineArg::gatherBalesToModify"); LLVM_DEBUG(dbgs() << *CI << "\n\tcalls stack call function\n"); return false; } } // Check the rdregion(s) and wrregion. for (auto bi = B->begin(), be = B->end(); bi != be; ++bi) { switch (bi->Info.Type) { case BaleInfo::WRREGION: // Check wrregion if its result is coalesced with arg. if (Liveness->getLiveRange(bi->Inst) == ArgLR) { Region R(bi->Inst, bi->Info); if (R.Indirect) break; // already indirect // Fake up scalar indirect index for the benefit of getLegalSize. // It doesn't matter what the value is, as long as it is scalar. R.Indirect = bi->Inst->getOperand( GenXIntrinsic::GenXRegion::WrIndexOperandNum); if (R.NumElements != R.getLegalSize(0, /*Allow2D=*/false, /*InputNumElements=*/UINT_MAX, ST, Align)) { LLVM_DEBUG(dbgs() << "wrregion cannot be indirected: " << R << "\n"); return false; } } break; case BaleInfo::RDREGION: // Check rdregion if its input is coalesced with arg. if (Liveness->getLiveRange(bi->Inst->getOperand(0)) == ArgLR) { Region R(bi->Inst, bi->Info); if (R.Indirect) break; // already indirect // Fake up scalar indirect index for the benefit of getLegalSize. // It doesn't matter what the value is, as long as it is scalar. R.Indirect = bi->Inst->getOperand( GenXIntrinsic::GenXRegion::RdIndexOperandNum); if (R.NumElements != R.getLegalSize(0, /*Allow2D=*/true, /*InputNumElements=*/UINT_MAX, ST, Align)) { LLVM_DEBUG(dbgs() << "rdregion cannot be indirected: " << R << "\n"; dbgs() << R.getLegalSize(0, /*Allow2D=*/true, /*InputNumElements=*/UINT_MAX, ST, Align) << "\n"); return false; } } break; default: break; } } return true; } /*********************************************************************** * addAddressArg : for this subroutine, replace the Function with a new * one with an extra address arg, and modify all call sites * * This sets this->NewFunc, and modifies this->Arg to the argument in the * new function. * * Return: a pair containing pointer to the old Arg and created AddressArg. */ std::pair<Value *, Value *> SubroutineArg::addAddressArg() { // Create the new function type. auto FTy = F->getFunctionType(); SmallVector<Type *, 4> ArgTys; for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) ArgTys.push_back(FTy->getParamType(i)); ArgTys.push_back(Type::getInt16Ty(F->getContext())); FTy = FunctionType::get(FTy->getReturnType(), ArgTys, false); // Create the new function. NewFunc = Function::Create(FTy, F->getLinkage(), ""); NewFunc->takeName(F); NewFunc->copyAttributesFrom(F); F->getParent()->getFunctionList().insert(F->getIterator(), NewFunc); // Set the new function's number to the same as the old function. Pass->Numbering->setNumber(NewFunc, Pass->Numbering->getNumber(F)); // Move the original function's unified return value across to the new // function. Pass->Liveness->moveUnifiedRet(F, NewFunc); // The Function itself has a live range to represent the ranges of the // subroutine itself and everything it calls. Change the Function in that // live range. Pass->Liveness->replaceValue(F, NewFunc); // Populate arrays OldArgs (the original func's args) and NewArgs (the new // func's args). SmallVector<Argument *, 4> OldArgs, NewArgs; for (auto ai = F->arg_begin(), ae = F->arg_end(); ai != ae; ++ai) OldArgs.push_back(&*ai); for (auto ai = NewFunc->arg_begin(), ae = NewFunc->arg_end(); ai != ae; ++ai) NewArgs.push_back(&*ai); // For the original args, change uses to use the new args instead. Also // change the old arg's live range to have the new arg instead. for (unsigned ArgNum = 0; ArgNum != OldArgs.size(); ++ArgNum) { NewArgs[ArgNum]->setName(OldArgs[ArgNum]->getName()); OldArgs[ArgNum]->replaceAllUsesWith(NewArgs[ArgNum]); Pass->Liveness->replaceValue(OldArgs[ArgNum], NewArgs[ArgNum]); } // Change the Arg in the current SubroutineArg, and save the address arg. Value *OldArg = Arg; Arg = NewArgs[Arg->getArgNo()]; AddressArgument = NewArgs.back(); // Give the address arg a live range, and mark that it needs calculating. auto LR = Pass->Liveness->getOrCreateLiveRange(AddressArgument); LR->setCategory(RegCategory::ADDRESS); Pass->LRsToCalculate.push_back(LR); // Set the name of the new address arg. NewArgs[OldArgs.size()]->setName(Arg->getName() + ".addr"); // Move the function code across. NewFunc->getBasicBlockList().splice(NewFunc->begin(), F->getBasicBlockList()); return std::make_pair(OldArg, AddressArgument); } /*********************************************************************** * fixCallSites : fix up a call to the subroutine, so it calls the new * function instead and passes the extra address arg * * For each call site, this calls the process() method on the object of a * subclass of CallSite set up by createCallSite(). That returns the extra * address arg, which this function then uses to create a replacement call * instruction. */ void SubroutineArg::fixCallSites() { for (auto csi = CallSites.begin(), cse = CallSites.end(); csi != cse; ++csi) { auto CallSite = *csi; LLVM_DEBUG(dbgs() << " fixCallSites: [" << Pass->Numbering->getNumber(CallSite->CI) << "] " << *CallSite << "\n"); // Process the call site. // Create the replacement call instruction, with an added address arg that // for now we set to undef. We do this first so that process() called below // can modify the arg being indirected such that the eraseUnusedTree erases // the rd-wr sequence that sets up the arg in the old call. SmallVector<Value *, 4> Args; for (unsigned oi = 0, oe = CallSite->CI->getNumArgOperands(); oi != oe; ++oi) Args.push_back(CallSite->CI->getArgOperand(oi)); Args.push_back(UndefValue::get(Type::getInt16Ty(CallSite->CI->getContext()))); CallInst *OldCI = CallSite->CI; CallSite->CI = CallInst::Create(NewFunc, Args, "", OldCI); CallSite->CI->takeName(OldCI); CallSite->CI->setDebugLoc(OldCI->getDebugLoc()); Pass->Numbering->setNumber(CallSite->CI, Pass->Numbering->getNumber(OldCI)); Pass->Numbering->setStartNumber(CallSite->CI, Pass->Numbering->getStartNumber(OldCI)); // Get the subclass of CallSite to do its processing, returning the extra // address arg for the call. Value *AddressArg = CallSite->process(Pass, this); LLVM_DEBUG(dbgs() << " AddressArg is " << AddressArg->getName() << "\n"); if (!isa<UndefValue>(AddressArg)) { // Create a live range for the address arg, and ensure it is recalculated. LiveRange *AddressArgLR = Pass->Liveness->getOrCreateLiveRange(AddressArg); AddressArgLR->setCategory(RegCategory::ADDRESS); Pass->LRsToCalculate.push_back(AddressArgLR); } // Use the address arg in the new call. CallSite->CI->setOperand(Args.size() - 1, AddressArg); // Replace the old call with the new one, and erase the old one. We use // eraseUnusedTree so that any rd-wr sequence for the indirected arg is also // erased. OldCI->replaceAllUsesWith(CallSite->CI); Pass->Liveness->replaceValue(OldCI, CallSite->CI); Pass->Liveness->eraseUnusedTree(OldCI); } } /*********************************************************************** * CallerIndirectingCallSite::process : arg indirection processing for a call * site in a subroutine that is itself indirecting the arg * * Return: the address arg that needs to be passed to the call */ Value *CallerIndirectingCallSite::process(GenXArgIndirection *Pass, SubroutineArg *SubrArg) { return CallerSubrArg->AddressArgument; } /*********************************************************************** * NoOptCallSite::process : arg indirection processing for a call site where * no optimization is possible, but we can still indirect * * Return: the address arg that needs to be passed to the call */ Value *NoOptCallSite::process(GenXArgIndirection *Pass, SubroutineArg *SubrArg) { unsigned InsertNumber = Pass->Numbering->getArgIndirectionNumber( CI, CI->getNumArgOperands() - 1, 0); Instruction *InsertBefore = CI; Type *I16Ty = Type::getInt16Ty(CI->getContext()); // If the arg is undef, we can just use an undef address. if (isa<UndefValue>(CI->getArgOperand(SubrArg->Arg->getArgNo()))) return UndefValue::get(I16Ty); // Create a convert.addr of index 0, just before the call with the number of // the arg pre-copy site for the new address argument that will be added. auto Conv = createConvertAddr(ConstantInt::get(I16Ty, 0), 0, SubrArg->Arg->getName() + ".indirect", InsertBefore); Conv->setDebugLoc(CI->getDebugLoc()); Pass->Numbering->setNumber(Conv, InsertNumber); // Tell GenXLiveness the base register for this address register. The normal // mechanism of tracing through to a user of the address does not work for an // indirected arg. Pass->Liveness->setArgAddressBase(Conv, CI->getArgOperand(SubrArg->Arg->getArgNo())); // If the live range of the input does not reach over the call, add a // use of it (an unused bitcast) after the call and recalculate the // live range. unsigned CINumber = Pass->Numbering->getNumber(CI); Value *Input = CI->getOperand(SubrArg->Arg->getArgNo()); LiveRange *InputLR = Pass->Liveness->getLiveRange(Input); if (!InputLR->contains(CINumber)) { auto BC = CastInst::Create(Instruction::BitCast, Input, Input->getType(), Input->getName() + ".dummy_use_for_indirection", CI->getNextNode()); Pass->Liveness->setLiveRange(BC, InputLR); Pass->Numbering->setNumber(BC, CINumber + 1); Pass->LRsToCalculate.push_back(InputLR); } return Conv; } /*********************************************************************** * ConstArgRetCallSite::process : arg indirection processing for a call site * where the arg is constant (including undef) and the arg is coalesced * with a retval that is used only in a legalized wrregion whose "old * value" input is constant. * * Return: the address arg that needs to be passed to the call */ Value *ConstArgRetCallSite::process(GenXArgIndirection *Pass, SubroutineArg *SubrArg) { // checkCallSites detected the situation where the arg is a constant // (probably a legalized constant load, detected by RdWrRegionSequence, // but also including undef), and the ret is wrregioned (probably // legalized) with a constant as the "old value" operand (including // undef). // // To handle this, we create a new constant load of the two constants // combined, before the call, to turn it back into the normal situation // of a legalized rdregion before the call and a legalized wrregion // after the call. (However we don't actually create the legalized // rdregion and wrregion.) // // The combined constant was created in checkCallSites, and in this object // it is LdConst. // // Any new instruction is inserted just before the call, and given the // instruction number of the address arg's pre-copy slot. Instruction *InsertBefore = CI; unsigned InsertNumber = Pass->Numbering->getArgIndirectionNumber( CI, CI->getNumArgOperands() - 1, 0); // Insert a load the constant. Bitcast it to the right type to replace // RetEndWr. SmallVector<Instruction *, 4> AddedInsts; ConstantLoader CL(LdConst, *Pass->ST, *Pass->DL, nullptr, &AddedInsts); auto LoadedConst = CL.loadBig(InsertBefore); IGC_ASSERT(LoadedConst); if (LoadedConst->getType() != RetEndWr->getType()) { LoadedConst = CastInst::Create(Instruction::BitCast, LoadedConst, RetEndWr->getType(), LoadedConst->getName() + ".bitcast", InsertBefore); AddedInsts.push_back(LoadedConst); } // An added instruction (from the constant load) is allocated a live range as // follows: // 1. An instruction with the right result size is assumed to be coalesceable // with the final result, and so put in the same live range as the retval's // wrregion. // 2. A (smaller) wrregion is assumed to be coalesceable with its "old value" // input, if that is an instruction. // 3. Otherwise it gets its own new live range. // A wrregion also needs to be marked as such in baling. auto RetValWrLR = Pass->Liveness->getLiveRange(RetEndWr); unsigned LoadedConstSize = LoadedConst->getType()->getPrimitiveSizeInBits(); for (auto i = AddedInsts.begin(), e = AddedInsts.end(); i != e; ++i) { auto Inst = *i; Pass->Numbering->setNumber(Inst, InsertNumber); LiveRange *LR = nullptr; if (Inst->getType()->getPrimitiveSizeInBits() == LoadedConstSize) Pass->Liveness->setLiveRange(Inst, LR = RetValWrLR); if (GenXIntrinsic::isWrRegion(Inst)) { BaleInfo BI(BaleInfo::WRREGION); if (isa<Instruction>(Inst->getOperand( GenXIntrinsic::GenXRegion::NewValueOperandNum))) BI.setOperandBaled(GenXIntrinsic::GenXRegion::NewValueOperandNum); Pass->Baling->setBaleInfo(Inst, BI); if (auto InInst = dyn_cast<Instruction>( Inst->getOperand(GenXIntrinsic::GenXRegion::OldValueOperandNum))) if (!LR) Pass->Liveness->setLiveRange(Inst, LR = Pass->Liveness->getLiveRange(InInst)); } if (!LR) { LR = Pass->Liveness->getOrCreateLiveRange(Inst); LR->setCategory(RegCategory::GENERAL); } Pass->LRsToCalculate.push_back(LR); } // Create the genx.convert.addr for the region of that constant load. We // use the offset of the retval's legalized wrregion. auto AddressArg = createConvertAddr(Index, 0, SubrArg->Arg->getName() + ".indirect", InsertBefore); AddressArg->setDebugLoc(CI->getDebugLoc()); Pass->Numbering->setNumber(AddressArg, InsertNumber); // Tell GenXLiveness the base register for this address register. // The normal mechanism of tracing through to a user of the address // does not work for an indirected arg. Pass->Liveness->setArgAddressBase(AddressArg, LoadedConst); // Undef out the arg in the call, so the old code to load the constant (if // any) gets erased when the call is erased. unsigned CallArgNum = SubrArg->Arg->getArgNo(); CI->setOperand(CallArgNum, UndefValue::get(CI->getOperand(CallArgNum)->getType())); // Replace uses of the (legalized) wrregion sequence with the newly inserted // constant load, then erase the sequence. Instruction *ToErase = RetEndWr; RetEndWr = nullptr; // need to do this as RetEndWr is an AssertingVH Pass->replaceAndEraseSequence(ToErase, LoadedConst); return AddressArg; } /*********************************************************************** * IndirectArgCallSite::process : arg indirection processing for a call site * where the arg is a legalized rdregion or copy, and there is no retval * coalesced with it. * * Return: the address arg that needs to be passed to the call */ Value *IndirectArgCallSite::process(GenXArgIndirection *Pass, SubroutineArg *SubrArg) { // Any new instruction is inserted just before the call, and given the // instruction number of the address arg's pre-copy slot. Instruction *InsertBefore = CI; unsigned InsertNumber = Pass->Numbering->getArgIndirectionNumber(CI, CI->getNumArgOperands() - 1, 0); Value *AddressArg = nullptr; if (isa<Constant>(Index)) { // Constant index for the region. Add a convert.addr to load it into an // address register. auto Conv = createConvertAddr(Index, 0, SubrArg->Arg->getName() + ".indirect", InsertBefore); Conv->setDebugLoc(CI->getDebugLoc()); Pass->Numbering->setNumber(Conv, InsertNumber); AddressArg = Conv; } else { // Variable index for the region. The index is already converted to an // address. It might be a genx.add.addr baled in to the rdregion; if so // unbale it. if (auto IndexInst = dyn_cast<Instruction>(Index)) Pass->Baling->unbale(IndexInst); AddressArg = Index; } // Tell GenXLiveness the base register for this address register. // The normal mechanism of tracing through to a user of the address // does not work for an indirected arg. LiveRange *InputLR = Pass->Liveness->getLiveRange(*InputUse); // Add a use of the input (an unused bitcast) in case: // 1. the live range does not reach over the call (in which case we need to // recalculate the live range after adding this use), or // 2. later on, another arg indirection removes a use, meaning that the live // range no longer reaches over the call (in which case we don't need to // recalculate the live range yet). auto BC = CastInst::Create(Instruction::BitCast, *InputUse, (*InputUse)->getType(), (*InputUse)->getName() + ".dummy_use_for_indirection", CI->getNextNode()); Pass->Liveness->setLiveRange(BC, InputLR); Pass->Liveness->setArgAddressBase(AddressArg, BC); unsigned CINumber = Pass->Numbering->getNumber(CI); Pass->Numbering->setNumber(BC, CINumber + 1); if (!InputLR->contains(CINumber)) Pass->LRsToCalculate.push_back(InputLR); // Undef out the arg in the call, so the old rd-wr sequence for the arg gets // erased when the call is erased. unsigned CallArgNum = SubrArg->Arg->getArgNo(); CI->setOperand(CallArgNum, UndefValue::get(CI->getOperand(CallArgNum)->getType())); return AddressArg; } /*********************************************************************** * IndirectArgRetCallSite::process : arg indirection processing for a call site * where the arg is a legalized rdregion or copy, and the arg is coalesced * with a retval that is used only in a legalized wrregion or copy. * * Return: the address arg that needs to be passed to the call */ Value *IndirectArgRetCallSite::process(GenXArgIndirection *Pass, SubroutineArg *SubrArg) { // Common code with IndirectArgCallSite above: auto AddressArg = IndirectArgCallSite::process(Pass, SubrArg); // Replace uses of the (legalized) wrregion sequence with the input to the // legalized rdregion before the call. Instruction *ToReplace = RetEndWr; RetEndWr = nullptr; // Needed as RetEndWr is an AssertingVH Pass->replaceAndEraseSequence(ToReplace, *InputUse); return AddressArg; } /*********************************************************************** * GenXArgIndirection::replaceAndEraseSequence : replace uses of a wrregion * sequence with a different value and erase the sequence, coping with * different types due to bitcast * * Enter: RetEndWr = end of wrregion sequence * V = value to replace its uses with (not constant, so it has a * live range) */ void GenXArgIndirection::replaceAndEraseSequence(Instruction *RetEndWr, Value *V) { // See if the types are different due to some bitcasting somewhere. First // handle the case that V is the result of a bitcast whose input is the type // we want. We can just use that input. if (V->getType() != RetEndWr->getType()) if (auto BC = dyn_cast<BitCastInst>(V)) if (BC->getOperand(0)->getType() == RetEndWr->getType()) V = BC->getOperand(0); // Then handle other different type cases by inserting our own bitcast. if (V->getType() != RetEndWr->getType()) { auto BC = CastInst::Create(Instruction::BitCast, V, RetEndWr->getType(), V->getName() + ".bitcast", RetEndWr); Numbering->setNumber(BC, Numbering->getNumber(RetEndWr)); Liveness->setLiveRange(BC, Liveness->getLiveRange(V)); V = BC; } // Replace uses and erase resulting tree of unused instructions. RetEndWr->replaceAllUsesWith(V); Liveness->eraseUnusedTree(RetEndWr); } /*********************************************************************** * coalesceAddressArgs : for the new address arg, attempt to coalesce at * each call site, inserting a copy on failure to coalesce */ void SubroutineArg::coalesceAddressArgs() { LiveRange *AddressLR = Pass->Liveness->getLiveRange(AddressArgument); unsigned ArgNum = AddressArgument->getArgNo(); for (unsigned csi = 0, cse = CallSites.size(); csi != cse; ++csi) { auto CallSite = CallSites[csi]; Value *CallArg = CallSite->CI->getArgOperand(ArgNum); if (isa<UndefValue>(CallArg)) continue; LiveRange *CallArgLR = Pass->Liveness->getLiveRange(CallArg); if (AddressLR == CallArgLR) continue; if (!Pass->Liveness->interfere(AddressLR, CallArgLR)) { // No interference -- we can coalesce. AddressLR = Pass->Liveness->coalesce(AddressLR, CallArgLR, /*DisallowCASC=*/true); continue; } // There is interference. This should not happen if the caller is another // subroutine where we are indirecting the arg -- the new address args // for each subroutine should coalesce together. LLVM_DEBUG(dbgs() << "Failed to coalesce:\n " << *AddressLR << "\n " << *CallArgLR << "\n"); IGC_ASSERT_MESSAGE(!Pass->FuncMap[CallSite->CI->getParent()->getParent()], "new address args should coalesce together"); // We need to insert a copy, in the address arg's pre-copy slot. An address // copy is done with a genx.convert, even though it is not actually doing a // conversion. auto Copy = createConvert(CallArg, CallArg->getName() + ".coalescefail", CallSite->CI); Copy->setDebugLoc(CallSite->CI->getDebugLoc()); Pass->Numbering->setNumber(Copy, Pass->Numbering->getArgPreCopyNumber( CallSite->CI, ArgNum, 0)); // Add the new value in to AddressLR. Pass->Liveness->setLiveRange(Copy, AddressLR); CallSite->CI->setOperand(ArgNum, Copy); } } /*********************************************************************** * replaceFunction : replace the old function with the new function * * This replaces the function in the FunctionGroup, and then erases the old * function. */ void SubroutineArg::replaceFunction() { Pass->FGA->replaceFunction(F, NewFunc); F->eraseFromParent(); F = NewFunc; } /*********************************************************************** * indirectBale : modify a bale to be indirect * * Enter: B = bale to modify * ArgLR = live range of values that need to be indirected * AddressArg = new argument for address * * On return, the bale struct is no longer valid. */ void GenXArgIndirection::indirectBale(Bale *B, LiveRange *ArgLR, Argument *AddressArg) { // Indirect the head of the bale, if its result is in ArgLR. auto Inst = B->getHead()->Inst; if (Liveness->getLiveRange(Inst) == ArgLR) { if (B->getHead()->Info.Type == BaleInfo::WRREGION) { // wrregion: just modify the index to indirect it. indirectRegion(&Inst->getOperandUse( GenXIntrinsic::GenXRegion::WrIndexOperandNum), AddressArg, Inst); } else { // No wrregion: we need to add one, and ensure that the original // instruction is baled into it. Region R(Inst); R.Indirect = AddressArg; SmallVector<Use *, 4> Uses; for (auto ui = Inst->use_begin(), ue = Inst->use_end(); ui != ue; ++ui) Uses.push_back(&*ui); auto NewWr = R.createWrRegion(UndefValue::get(Inst->getType()), Inst, Inst->getName() + ".indirected", Inst->getNextNode(), Inst->getDebugLoc()); Liveness->setLiveRange(NewWr, ArgLR); Liveness->removeValue(Inst); for (auto ui = Uses.begin(), ue = Uses.end(); ui != ue; ++ui) **ui = NewWr; BaleInfo BI(BaleInfo::WRREGION); BI.setOperandBaled(GenXIntrinsic::GenXRegion::NewValueOperandNum); Baling->setBaleInfo(NewWr, BI); } } // Process operands in each instruction of the bale. for (auto bi = B->begin(), be = B->end(); bi != be; ++bi) { Inst = bi->Inst; for (unsigned oi = 0, oe = Inst->getNumOperands(); oi != oe; ++oi) { if (bi->Info.isOperandBaled(oi)) continue; // Ignore within-bale operands if (!oi && bi->Info.Type == BaleInfo::WRREGION) continue; // Ignore "old value" input to wrregion Value *Opnd = Inst->getOperand(oi); if (Liveness->getLiveRangeOrNull(Opnd) != ArgLR) continue; // Not in ArgLR, does not need indirecting if (bi->Info.Type == BaleInfo::RDREGION && oi == GenXIntrinsic::GenXRegion::OldValueOperandNum) { // input to rdregion: just modify the index to indirect it. indirectRegion(&bi->Inst->getOperandUse( GenXIntrinsic::GenXRegion::RdIndexOperandNum), AddressArg, Inst); } else { // No rdregion: we need to add one, and ensure that it is baled in // to the original instruction. Region R(Opnd); R.Indirect = AddressArg; auto NewRd = R.createRdRegion(Opnd, Opnd->getName() + ".indirected", Inst, Inst->getDebugLoc()); Inst->setOperand(oi, NewRd); BaleInfo BI = bi->Info; BI.setOperandBaled(oi); Baling->setBaleInfo(Inst, BI); BaleInfo NewRdBI(BaleInfo::RDREGION); Baling->setBaleInfo(NewRd, NewRdBI); } } } } /*********************************************************************** * indirectRegion : convert a rdregion/wrregion index operand to indirect * * Enter: U = the rdregion/wrregion index operand use * AddressArg = the index to use * InsertBefore = where to insert new instructions * * If the rdregion/wrregion already has a variable index, then we create an * instruction to remove its genx.convert.addr and add it to AddressArg with * genx.add.addr. */ void GenXArgIndirection::indirectRegion(Use *U, Value *AddressArg, Instruction *InsertBefore) { Value *Addr = *U; if (auto CI = dyn_cast<Constant>(Addr)) { // Currently the index is constant. if (CI->isNullValue()) { *U = AddressArg; return; } // Create a genx.add.addr and give it an instruction number one less // than InsertBefore. auto NewAdd = createAddAddr(AddressArg, CI, "indirect.offset", InsertBefore); Numbering->setNumber(NewAdd, Numbering->getNumber(InsertBefore) - 1); *U = NewAdd; // If the constant is within offset range, bale the new genx.add.addr into // its user. if (GenXBaling::isBalableIndexAdd(NewAdd)) { auto User = cast<Instruction>(U->getUser()); BaleInfo BI = Baling->getBaleInfo(User); BI.setOperandBaled(U->getOperandNo()); Baling->setBaleInfo(User, BI); } else { // Otherwise, give it a live range, and mark it as needing calculating. auto LR = Liveness->getOrCreateLiveRange(NewAdd); LR->setCategory(RegCategory::ADDRESS); LRsToCalculate.push_back(LR); } return; } // The index is already variable. // Trace back through add_addr instructions until we find one of: // 1. The convert_addr instruction set up by GenXCategory, and possibly // commoned up by GenXAddressCommoning. We replace that with an // add_addr instruction that adds the convert_addr's input to AddressArg. // or // 2. An Argument, so another user of the same address must have already // found and replaced (1). for (;;) { if (isa<Argument>(Addr)) return; auto IntrinsicID = GenXIntrinsic::getGenXIntrinsicID(Addr); switch (IntrinsicID) { case GenXIntrinsic::genx_add_addr: Addr = cast<Instruction>(Addr)->getOperand(0); continue; case GenXIntrinsic::genx_rdregioni: Addr = cast<Instruction>(Addr)->getOperand( GenXIntrinsic::GenXRegion::OldValueOperandNum); continue; case GenXIntrinsic::genx_convert_addr: // we've found what we wanted break; default: IGC_ASSERT_EXIT_MESSAGE(0, "unsupported instruction"); } break; } IGC_ASSERT(GenXIntrinsic::getGenXIntrinsicID(Addr) == GenXIntrinsic::genx_convert_addr); auto AddrInst = cast<Instruction>(Addr); auto AddrSrc = AddrInst->getOperand(0); // Create an add_addr to replace the convert_addr. It needs a live range with // ADDRESS category. auto NewAddAddr = createAddAddr(AddressArg, AddrSrc, AddrInst->getName() + ".indirectedaddr", AddrInst); NewAddAddr->setDebugLoc(AddrInst->getDebugLoc()); Numbering->setNumber(NewAddAddr, Numbering->getNumber(AddrInst) - 1); AddrInst->replaceAllUsesWith(NewAddAddr); LiveRange *LR = Liveness->getOrCreateLiveRange(NewAddAddr); LR->setCategory(RegCategory::ADDRESS); LRsToCalculate.push_back(LR); // AddrSrc (source of convert_addr) should get a live range as well LiveRange *SrcLR = Liveness->getOrCreateLiveRange(AddrSrc); SrcLR->setCategory(RegCategory::GENERAL); LRsToCalculate.push_back(SrcLR); // remove the old convert_addr Liveness->eraseLiveRange(AddrInst); AddrInst->eraseFromParent(); } /*********************************************************************** * getArgForFunction : find the arg in a live range that belongs to a func */ Argument *GenXArgIndirection::getArgForFunction(LiveRange *LR, Function *F) { for (auto vi = LR->value_begin(), ve = LR->value_end(); vi != ve; ++vi) { Value *V = vi->getValue(); if (auto Arg = dyn_cast<Argument>(V)) if (Arg->getParent() == F) return Arg; } return nullptr; } /*********************************************************************** * getRetVal : get return value for possibly multi return value call * * Enter: CI = call instruction * RetNum = return value number * * Return: the return value (which is either a CallInst or an * ExtractValueInst), or 0 if unknown use, or undef if it is shown * that the requested return value is never extracted from the struct */ Value *SubroutineArg::getRetVal(CallInst *CI, unsigned RetNum) { auto ST = dyn_cast<StructType>(CI->getType()); if (!ST) { IGC_ASSERT(!RetNum); return CI; } Value *RetVal = UndefValue::get(ST->getElementType(RetNum)); for (auto ui = CI->use_begin(), ue = CI->use_end(); ui != ue; ++ui) { auto EVI = dyn_cast<ExtractValueInst>(ui->getUser()); if (!EVI || EVI->getNumIndices() != 1) return nullptr; // unknown use if (EVI->getIndices()[0] == RetNum) { if (isa<UndefValue>(RetVal)) RetVal = EVI; else return nullptr; // multiple extractelements of the same retval } } return RetVal; } /*********************************************************************** * DiagnosticInfoArgIndirection initializer from Instruction * * If the Instruction has a DebugLoc, then that is used for the error * location. * Otherwise, the location is unknown. */ DiagnosticInfoArgIndirection::DiagnosticInfoArgIndirection(Instruction *Inst, Argument *Arg, const Twine &Desc, DiagnosticSeverity Severity) : DiagnosticInfo(getKindID(), Severity), Line(0), Col(0) { auto DL = Inst->getDebugLoc(); if (DL) { Filename = DL->getFilename(); Line = DL.getLine(); Col = DL.getCol(); } Description = (Twine("GenXArgIndirection failed for argument ") + Twine(Arg->getArgNo() + 1) + " in " + Arg->getParent()->getName() + ": " + Desc).str(); } /*********************************************************************** * DiagnosticInfoArgIndirection::print : print the error/warning message */ void DiagnosticInfoArgIndirection::print(DiagnosticPrinter &DP) const { std::string Loc( (Twine(!Filename.empty() ? Filename : "<unknown>") + ":" + Twine(Line) + (!Col ? Twine() : Twine(":") + Twine(Col)) + ": ") .str()); DP << Loc << Description; }
42.392988
110
0.656981
[ "object", "vector", "transform" ]
f579e5caa8abed724fad527ca39d6575e047b285
2,649
cpp
C++
test/filter/JournalIOFactory.cpp
CuSO4Gem/jrm
8ad1e5c785b193cd917e08d55f3edb068e007304
[ "Apache-2.0" ]
null
null
null
test/filter/JournalIOFactory.cpp
CuSO4Gem/jrm
8ad1e5c785b193cd917e08d55f3edb068e007304
[ "Apache-2.0" ]
null
null
null
test/filter/JournalIOFactory.cpp
CuSO4Gem/jrm
8ad1e5c785b193cd917e08d55f3edb068e007304
[ "Apache-2.0" ]
null
null
null
/* Copyright 2022 Zorn Link 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 "JournalIOFactory.h" #include "debug_print.h" shared_ptr<JournalIOBase> JournalIOFactory::getJournalIO(string journalPath) { if (journalPath.length() == 0) { JLOGW("[W] ournalIOFactory::%s, get null file name", __func__); return nullptr; } /*load all journal IO*/ vector<shared_ptr<JournalIOBase>> ioVector; ioVector.push_back(make_shared<TxtJournalIO>()); JLOGD("[D] load TxtJournal at 0"); size_t i = 1; list<string> plugins = JrmeConfig::getJournalIOPluginNames(); for (auto &it:plugins) { shared_ptr<PluginJournalIO> pluginIO = make_shared<PluginJournalIO>(); if (pluginIO->loadPlugin(it)) { JLOGD("[D] load plaugin %s at %d", it.c_str(), i); i++; ioVector.push_back(pluginIO); } } /*get postfix*/ size_t pos; for (pos = journalPath.length()-1; pos >= 0; pos--) { if (journalPath[pos] == '.') break; } string postfix = string(); if (pos>0 && pos<journalPath.length()-1) { postfix = journalPath.substr(pos+1, journalPath.length()-pos-1); } /*find postfix, so select journalIO by postfix*/ i=0; if (postfix.length()>0) { for (auto &it:ioVector) { vector<string> formates = it->formateSupport(); for (auto &itf:formates) { if (itf==postfix && it->open(journalPath)) { it->close(); JLOGD("[D] match postfix return journalIO %d", i); return it; } } i++; } } /*not get postfix or can not open journal by postfix so we open journal one by one*/ i=0; for (auto &it:ioVector) { if (it->open(journalPath)) { JLOGD("[D] not match postfix return journalIO %d", i); it->close(); return it; } i++; } JLOGW("[W] JournalIOFactory create journalIO failed!"); return nullptr; }
28.180851
78
0.579841
[ "vector" ]
f57c81dc05698e3643fa2208d3907316dbfa6a26
687
hpp
C++
include/rive/generated/container_component_base.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
139
2020-08-17T20:10:24.000Z
2022-03-28T12:22:44.000Z
include/rive/generated/container_component_base.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
89
2020-08-28T16:41:01.000Z
2022-03-28T19:10:49.000Z
include/rive/generated/container_component_base.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
19
2020-10-19T00:54:40.000Z
2022-02-28T05:34:17.000Z
#ifndef _RIVE_CONTAINER_COMPONENT_BASE_HPP_ #define _RIVE_CONTAINER_COMPONENT_BASE_HPP_ #include "rive/component.hpp" namespace rive { class ContainerComponentBase : public Component { protected: typedef Component Super; public: static const uint16_t typeKey = 11; /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. bool isTypeOf(uint16_t typeKey) const override { switch (typeKey) { case ContainerComponentBase::typeKey: case ComponentBase::typeKey: return true; default: return false; } } uint16_t coreType() const override { return typeKey; } protected: }; } // namespace rive #endif
20.205882
74
0.730713
[ "object" ]
f57c8d08d97c66a3a7c0c79fcdeb2417323d4d33
6,130
cpp
C++
Data Structures/HLD.cpp
IamODJ/Competitive-Programming
a084456ee2819ae3df2bf83140e1f9eb10a5f779
[ "MIT" ]
2
2020-11-11T19:18:07.000Z
2021-01-01T14:29:49.000Z
Data Structures/HLD.cpp
Elsaadany427/Competitive-Programming
7498c26c1fdf6e74a774df6f3a9fc8f9c550bbd5
[ "MIT" ]
null
null
null
Data Structures/HLD.cpp
Elsaadany427/Competitive-Programming
7498c26c1fdf6e74a774df6f3a9fc8f9c550bbd5
[ "MIT" ]
null
null
null
// Heavy-light decomposition (HLD) is a data structure to answer queries and update values on tree // Splitting the trees into separate paths that allows us to use another data structure such as segment tree on a tree // As we decompose the tree, we have enough information to build a lca function (which will be useful as an intermediate step for many types of queries) // For this example, we will answer maximum edge cost query on the path between two nodes // Problem link: https://www.spoj.com/problems/QTREE/ // Each edge is represented by the node that is further away to the root // => Each node is associated only one unique edge, except the root node // num_child[u] = number of children the u (including itself) // par[u] = parent node of u // dep[u] = distance of u from the root // chainNum = number of decomposed chains // chainSize[s] = number of nodes in chain s // chainHead[s] = the node closest to the root in chain s // chainId[u] = the chain that node u belongs to // chainPos[u] = the position of node u in the chain it belongs to (aka chainInd[u]) // adj: adjacency list // edges: edge list // arr: array storing edge costs based on HLD // st_pos: position of edges based on HLD // st: segment tree #include <bits/stdc++.h> using namespace std; #define ar array #define ll long long const int MAX_N = 1e4 + 1; const int MOD = 1e9 + 7; const int INF = 1e9; const ll LINF = 1e18; int n, pos; int par[MAX_N], num_child[MAX_N], dep[MAX_N]; int chainNum, chainSize[MAX_N], chainHead[MAX_N], chainId[MAX_N], chainPos[MAX_N]; int arr[MAX_N], st_pos[MAX_N], st[4 * MAX_N]; ar<int,2> edges[MAX_N]; vector<ar<int,2>> adj[MAX_N]; void build_st(int node, int start, int end) { if (start == end) { st[node] = arr[start]; return; } int mid = (start + end) / 2; build_st(2 * node, start, mid); build_st(2 * node + 1, mid + 1, end); st[node] = max(st[2 * node], st[2 * node + 1]); } void update_st(int node, int start, int end, int idx, int val) { if (start == end) { st[node] = val; return; } int mid = (start + end) / 2; if (idx <= mid) update_st(2 * node, start, mid, idx, val); else update_st(2 * node + 1, mid + 1, end, idx, val); st[node] = max(st[2 * node], st[2 * node + 1]); } int query_st(int node, int start, int end, int l, int r) { if (start > r || end < l) return 0; if (l <= start && end <= r) return st[node]; int mid = (start + end) / 2; return max(query_st(2 * node, start, mid, l, r), query_st(2 * node + 1, mid + 1, end, l, r)); } void dfs(int u = 1, int p = 0, int d = 0) { par[u] = p; num_child[u] = 1; dep[u] = d; for (auto [v, w] : adj[u]) { if (v != p) { dfs(v, u, d + 1); num_child[u] += num_child[v]; } } } // there is no edge associated with node 1 (root), so set val to 0 // can pass in more information depending on the type of queries neede void hld(int u = 1, int val = 0) { if (chainHead[chainNum] == -1) chainHead[chainNum] = u; chainId[u] = chainNum; chainPos[u] = chainSize[chainNum]; chainSize[chainNum]++; st_pos[u] = ++pos; arr[pos] = val; int heaviest = -1, max_cost; for (auto [v, w] : adj[u]) if (v != par[u]) // find the heaviest path from node u if (heaviest == -1 || num_child[v] > num_child[heaviest]) heaviest = v, max_cost = w; // if not leaf node, then extend the chain if (heaviest != -1) hld(heaviest, max_cost); // extend to all other light paths for (auto [v, w] : adj[u]) { if (v != par[u] && v != heaviest) { chainNum++; hld(v, w); } } } void update(int idx, int val) { // representative of an edge is the node that is further away from the root auto [u, v] = edges[idx]; int node = dep[u] > dep[v] ? u : v; update_st(1, 1, n, st_pos[node], val); } int lca(int u, int v) { // bring u and v to the same chain, then one must be the lca of the other while (chainId[u] != chainId[v]) { if (dep[chainHead[chainId[u]]] > dep[chainHead[chainId[v]]]) u = par[chainHead[chainId[u]]]; else v = par[chainHead[chainId[v]]]; } return dep[u] < dep[v] ? u : v; } // mid is the ancestor of u (lca of u and v) int query_up(int u, int mid) { int res = 0; while (true) { if (u == mid) break; if (chainId[u] == chainId[mid]) { res = max(res, query_st(1, 1, n, st_pos[mid] + 1, st_pos[u])); break; } res = max(res, query_st(1, 1, n, st_pos[chainHead[chainId[u]]], st_pos[u])); u = par[chainHead[chainId[u]]]; } return res; } // maximum edge cost from u to v int query(int u, int v) { int mid = lca(u, v); return max(query_up(u, mid), query_up(v, mid)); } void reset() { memset(st, 0, sizeof st); memset(chainHead, -1, sizeof chainHead); for (int i = 1; i <= n; i++) adj[i].clear(); chainNum = 1; pos = 0; } void solve() { reset(); cin >> n; for (int i = 1; i <= n - 1; i++) { int u, v, w; cin >> u >> v >> w; adj[u].push_back({v, w}); adj[v].push_back({u, w}); edges[i] = {u, v}; } dfs(); hld(); build_st(1, 1, n); while (true) { string s; cin >> s; if (s == "DONE") return; if (s == "CHANGE") { int idx, val; cin >> idx >> val; update(idx, val); } else { int u, v; cin >> u >> v; cout << query(u, v) << "\n"; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int tc; cin >> tc; for (int t = 1; t <= tc; t++) { // cout << "Case #" << t << ": "; solve(); } }
30.65
153
0.537194
[ "vector" ]
f57ef57bb681d7cdb7b4c8ebb1a592537295f3cc
3,641
cpp
C++
samples/snippets/cpp/VS_Snippets_Winforms/FontDialog.ShowApply/CPP/form1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Winforms/FontDialog.ShowApply/CPP/form1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Winforms/FontDialog.ShowApply/CPP/form1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
#using <System.dll> #using <System.Drawing.dll> #using <System.Windows.Forms.dll> #using <System.Data.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; namespace FontDialog_cs { /// <summary> /// Summary description for Form1. /// </summary> public ref class Form1: public System::Windows::Forms::Form { private: System::Windows::Forms::Button^ button1; System::Windows::Forms::FontDialog^ fontDialog1; System::Windows::Forms::RichTextBox^ richTextBox1; /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container^ components; public: Form1() { components = nullptr; // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } public: /// <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->button1 = gcnew System::Windows::Forms::Button; this->fontDialog1 = gcnew System::Windows::Forms::FontDialog; this->richTextBox1 = gcnew System::Windows::Forms::RichTextBox; this->SuspendLayout(); // // button1 // this->button1->Location = System::Drawing::Point( 32, 8 ); this->button1->Name = "button1"; this->button1->TabIndex = 0; this->button1->Text = "button1"; this->button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click ); // // fontDialog1 // this->fontDialog1->Apply += gcnew System::EventHandler( this, &Form1::fontDialog1_Apply ); // // richTextBox1 // this->richTextBox1->Location = System::Drawing::Point( 56, 72 ); this->richTextBox1->Name = "richTextBox1"; this->richTextBox1->TabIndex = 1; this->richTextBox1->Text = "richTextBox1"; // // Form1 // this->ClientSize = System::Drawing::Size( 292, 273 ); array<System::Windows::Forms::Control^>^formControls = {this->richTextBox1,this->button1}; this->Controls->AddRange( formControls ); this->Name = "Form1"; this->Text = "Form1"; this->ResumeLayout( false ); } //<snippet1> private: void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { // Sets the ShowApply property, then displays the dialog. fontDialog1->ShowApply = true; fontDialog1->ShowDialog(); } void fontDialog1_Apply( Object^ /*sender*/, System::EventArgs^ /*e*/ ) { // Applies the selected font to the selected text. richTextBox1->Font = fontDialog1->Font; } //</snippet1> }; } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] int main() { Application::Run( gcnew FontDialog_cs::Form1 ); }
27.583333
100
0.556166
[ "object" ]
f582a90823fd00d35c7c4e59104e66fc92da10db
270
cpp
C++
Unfair Coin/Unfair Coin/Model.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
Unfair Coin/Unfair Coin/Model.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
Unfair Coin/Unfair Coin/Model.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
#include "Model.h" void Model::create() { } void Model::destroy() { } void Model::draw() { glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer); glDrawElements(GL_TRIANGLES, _indexCount, GL_UNSIGNED_BYTE, 0); }
16.875
67
0.733333
[ "model" ]
f585e4d3066512753ccf9bf00fcbdefe2bd1c4d8
1,335
cpp
C++
src/game/client/components/damageind.cpp
noother/ddracemax_old
f383b56de7827b6f1de7cff70dad836768e07d76
[ "Zlib" ]
2
2017-09-30T22:06:07.000Z
2021-07-20T23:50:33.000Z
src/game/client/components/damageind.cpp
floff/ddracemax_old
f1356177c49a3bc20632df9a84a51bc491c37f7d
[ "Zlib" ]
1
2017-11-22T15:10:02.000Z
2019-06-21T05:13:30.000Z
src/game/client/components/damageind.cpp
floff/ddracemax_old
f1356177c49a3bc20632df9a84a51bc491c37f7d
[ "Zlib" ]
3
2018-05-12T00:10:43.000Z
2021-07-16T13:25:57.000Z
#include <engine/e_client_interface.h> #include <game/generated/g_protocol.hpp> #include <game/generated/gc_data.hpp> #include <game/gamecore.hpp> // get_angle #include <game/client/ui.hpp> #include <game/client/render.hpp> #include "damageind.hpp" DAMAGEIND::DAMAGEIND() { lastupdate = 0; num_items = 0; } DAMAGEIND::ITEM *DAMAGEIND::create_i() { if (num_items < MAX_ITEMS) { ITEM *p = &items[num_items]; num_items++; return p; } return 0; } void DAMAGEIND::destroy_i(DAMAGEIND::ITEM *i) { num_items--; *i = items[num_items]; } void DAMAGEIND::create(vec2 pos, vec2 dir) { ITEM *i = create_i(); if (i) { i->pos = pos; i->life = 0.75f; i->dir = dir*-1; i->startangle = (( (float)rand()/(float)RAND_MAX) - 1.0f) * 2.0f * pi; } } void DAMAGEIND::on_render() { gfx_texture_set(data->images[IMAGE_GAME].id); gfx_quads_begin(); for(int i = 0; i < num_items;) { vec2 pos = mix(items[i].pos+items[i].dir*75.0f, items[i].pos, clamp((items[i].life-0.60f)/0.15f, 0.0f, 1.0f)); items[i].life -= client_frametime(); if(items[i].life < 0.0f) destroy_i(&items[i]); else { gfx_setcolor(1.0f,1.0f,1.0f, items[i].life/0.1f); gfx_quads_setrotation(items[i].startangle + items[i].life * 2.0f); select_sprite(SPRITE_STAR1); draw_sprite(pos.x, pos.y, 48.0f); i++; } } gfx_quads_end(); }
19.925373
112
0.648689
[ "render" ]
f58c0f46e295564dcb12bdea34f6e78f9ee073e2
6,525
cc
C++
inet/src/inet/networklayer/rsvp_te/SimpleClassifier.cc
googleinterns/vectio
0d8ef1d504c821de733110c82b16b2ae43332c5c
[ "Apache-2.0" ]
1
2020-05-21T07:48:00.000Z
2020-05-21T07:48:00.000Z
inet/src/inet/networklayer/rsvp_te/SimpleClassifier.cc
googleinterns/vectio
0d8ef1d504c821de733110c82b16b2ae43332c5c
[ "Apache-2.0" ]
4
2020-07-06T15:58:14.000Z
2020-07-15T21:56:36.000Z
inet/src/inet/networklayer/rsvp_te/SimpleClassifier.cc
googleinterns/vectio
0d8ef1d504c821de733110c82b16b2ae43332c5c
[ "Apache-2.0" ]
1
2020-10-02T04:12:51.000Z
2020-10-02T04:12:51.000Z
// // (C) 2005 Vojtech Janota // // 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 of the License, or any later version. // The 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. // #include <iostream> #include "inet/networklayer/rsvp_te/SimpleClassifier.h" #include "inet/common/XMLUtils.h" #include "inet/networklayer/mpls/LIBTable.h" #include "inet/networklayer/ipv4/IIPv4RoutingTable.h" #include "inet/common/ModuleAccess.h" #include "inet/networklayer/rsvp_te/RSVP.h" namespace inet { Define_Module(SimpleClassifier); using namespace xmlutils; void SimpleClassifier::initialize(int stage) { cSimpleModule::initialize(stage); if (stage == INITSTAGE_LOCAL) { maxLabel = 0; WATCH_VECTOR(bindings); } else if (stage == INITSTAGE_ROUTING_PROTOCOLS) { IIPv4RoutingTable *rt = getModuleFromPar<IIPv4RoutingTable>(par("routingTableModule"), this); routerId = rt->getRouterId(); lt = getModuleFromPar<LIBTable>(par("libTableModule"), this); rsvp = getModuleFromPar<RSVP>(par("rsvpModule"), this); readTableFromXML(par("config").xmlValue()); } } void SimpleClassifier::handleMessage(cMessage *) { ASSERT(false); } // IClassifier implementation (method invoked by MPLS) bool SimpleClassifier::lookupLabel(IPv4Datagram *ipdatagram, LabelOpVector& outLabel, std::string& outInterface, int& color) { // never label OSPF(TED) and RSVP traffic switch (ipdatagram->getTransportProtocol()) { case IP_PROT_OSPF: case IP_PROT_RSVP: return false; default: break; } // forwarding decision for non-labeled datagrams std::vector<FECEntry>::iterator it; for (it = bindings.begin(); it != bindings.end(); it++) { if (!it->dest.isUnspecified() && !it->dest.equals(ipdatagram->getDestAddress())) continue; if (!it->src.isUnspecified() && !it->src.equals(ipdatagram->getSrcAddress())) continue; EV_DETAIL << "packet belongs to fecid=" << it->id << endl; if (it->inLabel < 0) return false; return lt->resolveLabel("", it->inLabel, outLabel, outInterface, color); } return false; } // IRSVPClassifier implementation (method invoked by RSVP) void SimpleClassifier::bind(const SessionObj_t& session, const SenderTemplateObj_t& sender, int inLabel) { std::vector<FECEntry>::iterator it; for (it = bindings.begin(); it != bindings.end(); it++) { if (it->session != session) continue; if (it->sender != sender) continue; it->inLabel = inLabel; } } // IScriptable implementation (method invoked by ScenarioManager) void SimpleClassifier::processCommand(const cXMLElement& node) { if (!strcmp(node.getTagName(), "bind-fec")) { readItemFromXML(&node); } else ASSERT(false); } // binding configuration void SimpleClassifier::readTableFromXML(const cXMLElement *fectable) { ASSERT(fectable); ASSERT(!strcmp(fectable->getTagName(), "fectable")); checkTags(fectable, "fecentry"); cXMLElementList list = fectable->getChildrenByTagName("fecentry"); for (cXMLElementList::iterator it = list.begin(); it != list.end(); it++) readItemFromXML(*it); } void SimpleClassifier::readItemFromXML(const cXMLElement *fec) { ASSERT(fec); ASSERT(!strcmp(fec->getTagName(), "fecentry") || !strcmp(fec->getTagName(), "bind-fec")); int fecid = getParameterIntValue(fec, "id"); std::vector<FECEntry>::iterator it = findFEC(fecid); if (getUniqueChildIfExists(fec, "label")) { // bind-fec to label checkTags(fec, "id label destination source"); EV_INFO << "binding to a given label" << endl; FECEntry newFec; newFec.id = fecid; newFec.dest = getParameterIPAddressValue(fec, "destination"); newFec.src = getParameterIPAddressValue(fec, "source", IPv4Address()); newFec.inLabel = getParameterIntValue(fec, "label"); if (it == bindings.end()) { // create new binding bindings.push_back(newFec); } else { // update existing binding *it = newFec; } } else if (getUniqueChildIfExists(fec, "lspid")) { // bind-fec to LSP checkTags(fec, "id destination source tunnel_id extended_tunnel_id endpoint lspid"); EV_INFO << "binding to a given path" << endl; FECEntry newFec; newFec.id = fecid; newFec.dest = getParameterIPAddressValue(fec, "destination"); newFec.src = getParameterIPAddressValue(fec, "source", IPv4Address()); newFec.session.Tunnel_Id = getParameterIntValue(fec, "tunnel_id"); newFec.session.Extended_Tunnel_Id = getParameterIPAddressValue(fec, "extened_tunnel_id", routerId).getInt(); newFec.session.DestAddress = getParameterIPAddressValue(fec, "endpoint", newFec.dest); // ??? always use newFec.dest ??? newFec.sender.Lsp_Id = getParameterIntValue(fec, "lspid"); newFec.sender.SrcAddress = routerId; newFec.inLabel = rsvp->getInLabel(newFec.session, newFec.sender); if (it == bindings.end()) { // create new binding bindings.push_back(newFec); } else { // update existing binding *it = newFec; } } else { // un-bind checkTags(fec, "id"); if (it != bindings.end()) { bindings.erase(it); } } } std::vector<SimpleClassifier::FECEntry>::iterator SimpleClassifier::findFEC(int fecid) { std::vector<FECEntry>::iterator it; for (it = bindings.begin(); it != bindings.end(); it++) { if (it->id != fecid) continue; break; } return it; } std::ostream& operator<<(std::ostream& os, const SimpleClassifier::FECEntry& fec) { os << "id:" << fec.id; os << " dest:" << fec.dest; os << " src:" << fec.src; os << " session:" << fec.session; os << " sender:" << fec.sender; os << " inLabel:" << fec.inLabel; return os; } } // namespace inet
28.871681
131
0.634943
[ "vector" ]
f590f693cf7b939c24635369fa2eaa098ee107fe
2,822
cc
C++
example-1.cc
Leedehai/ccindex
5ba576a1df950424065fbeec5cd6093ddbbc21ff
[ "MIT" ]
null
null
null
example-1.cc
Leedehai/ccindex
5ba576a1df950424065fbeec5cd6093ddbbc21ff
[ "MIT" ]
null
null
null
example-1.cc
Leedehai/ccindex
5ba576a1df950424065fbeec5cd6093ddbbc21ff
[ "MIT" ]
null
null
null
// this is a test input with grammar errors #include <vector> #include <map> #include "example-2.h" using namespace std; const int independentVariable = 1; int independentFunction(); typedef std::vector<int> Int; /** comment for MyClass */ class MyClass { int property1; static void method1(); public: /** comment for MyClass() */ MyClass(); MyClass(const MyClass &); MyClass(int a, Int b) : property2(a) {} /*< comment for MyClass(int, Int) */ Int method2(); MyClass(MyClass &&); MyClass operator+(const MyClass &) noexcept; operator int(); private: /** comment for property2 */ Int property2; /** * comment for property 3 * still comment for property 3 */ const float propertye3; class InnerClass { double b; }; virtual void method3() const = 0; template <typename T> void fooInClass(T &in); }; // non-doc comment int baz(); /* non-doc comment */ template <typename T, typename U=Int, int N=1> int templateFunc(T *pt, U *pu, int n=N); /** comment for foo() */ int foo(int a, Int b); // function bodies are skipped MyClass::MyClass(int a, Int b) { int aa = a; Int bb = b; } namespace NS2 { /* class template */ template <typename T, char C> class templateClass { T t_; char c_ = C; }; } enum E : int { a = 1, b }; /** comment for namespace */ namespace customNS { int foo(); class Class; } static int staticGlobal; class customNS::Class final { static int staticData; const int constData; static const int staticConstData; int b; friend class classFriend; friend int fooFriend(); size_t returnSizeT_int(int a); bool returnBool_string_myclass_anotherclass(string s, MyClass obj, Another obj2); std::vector<int> &returnVector_float_vector(float a, std::vector<int> b); }; class classFriend {}; int fooFriend(); int a1, *a2; std::map<int, int> m; int foo() { int aaa = 0; return aaa; } Another ano; struct EEClass { enum class EE : char { ee1, ee2 }; }; typedef enum { eee1, eee2 } EnumTy; enum { aaaaa, bbbbb }; class BaseClass {}; template <typename T> struct BaseClass2 {}; template <typename T> class ClassAgain {}; template <typename T> class BaseClassWithAVeryUglyName_i_am_really_long_too {}; typedef BaseClassWithAVeryUglyName_i_am_really_long_too<char> TypeDefTemplateBase; class VClass final : private BaseClass, BaseClass2<ClassAgain<int>>, public virtual EEClass, protected TypeDefTemplateBase { public: VClass(); virtual ~VClass() = 0; virtual void foo() = 0; }; template <typename T> class TemplateInheritanceChild : BaseClass2<T> {}; int *arrIntPtr[5]; char arrChar[] = { 'h', 'e', 'l', 'l', 'o', '\n' }; BaseClass arrVar[]; #define FUNCS(func_name, T) \ void func_name(T &in) noexcept {} \ void func_name(T &&in) throw() {} FUNCS(returnVoid, char *) // two functions in one line; they'll have the same source location
20.014184
105
0.689936
[ "vector" ]
f595979f03563ce8dd44ff50002924c6c8492006
5,762
cc
C++
modules/planning/planner/rtk/rtk_replay_planner.cc
fxbupt/apollo
65bda57aa2f01b045ecf9cff95d9e6fd80ed091f
[ "Apache-2.0" ]
1
2021-03-08T06:35:35.000Z
2021-03-08T06:35:35.000Z
modules/planning/planner/rtk/rtk_replay_planner.cc
fxbupt/apollo
65bda57aa2f01b045ecf9cff95d9e6fd80ed091f
[ "Apache-2.0" ]
null
null
null
modules/planning/planner/rtk/rtk_replay_planner.cc
fxbupt/apollo
65bda57aa2f01b045ecf9cff95d9e6fd80ed091f
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/planning/planner/rtk/rtk_replay_planner.h" #include <fstream> #include <utility> #include "modules/common/log.h" #include "modules/common/util/string_tokenizer.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::ErrorCode; using apollo::common::Status; RTKReplayPlanner::RTKReplayPlanner() { ReadTrajectoryFile(FLAGS_rtk_trajectory_filename); } Status RTKReplayPlanner::Init(const PlanningConfig&) { return Status::OK(); } Status RTKReplayPlanner::Plan(const TrajectoryPoint& planning_init_point, Frame*, ReferenceLineInfo* reference_line_info) { if (complete_rtk_trajectory_.empty() || complete_rtk_trajectory_.size() < 2) { std::string msg( "RTKReplayPlanner doesn't have a recorded trajectory or " "the recorded trajectory doesn't have enough valid trajectory " "points."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::uint32_t matched_index = QueryPositionMatchedPoint(planning_init_point, complete_rtk_trajectory_); std::uint32_t forward_buffer = FLAGS_rtk_trajectory_forward; std::uint32_t end_index = matched_index + forward_buffer >= complete_rtk_trajectory_.size() ? complete_rtk_trajectory_.size() - 1 : matched_index + forward_buffer - 1; // auto* trajectory_points = trajectory_pb->mutable_trajectory_point(); std::vector<TrajectoryPoint> trajectory_points( complete_rtk_trajectory_.begin() + matched_index, complete_rtk_trajectory_.begin() + end_index + 1); // reset relative time double zero_time = complete_rtk_trajectory_[matched_index].relative_time(); for (auto& trajectory_point : trajectory_points) { trajectory_point.set_relative_time(trajectory_point.relative_time() - zero_time); } // check if the trajectory has enough points; // if not, append the last points multiple times and // adjust their corresponding time stamps. while (trajectory_points.size() < static_cast<std::size_t>(FLAGS_rtk_trajectory_forward)) { const auto& last_point = trajectory_points.rbegin(); auto new_point = last_point; new_point->set_relative_time(new_point->relative_time() + FLAGS_trajectory_resolution); trajectory_points.push_back(*new_point); } reference_line_info->SetTrajectory(DiscretizedTrajectory(trajectory_points)); return Status::OK(); } void RTKReplayPlanner::ReadTrajectoryFile(const std::string& filename) { if (!complete_rtk_trajectory_.empty()) { complete_rtk_trajectory_.clear(); } std::ifstream file_in(filename.c_str()); if (!file_in.is_open()) { AERROR << "RTKReplayPlanner cannot open trajectory file: " << filename; return; } std::string line; // skip the header line. getline(file_in, line); while (true) { getline(file_in, line); if (line == "") { break; } auto tokens = apollo::common::util::StringTokenizer::Split(line, "\t "); if (tokens.size() < 11) { AERROR << "RTKReplayPlanner parse line failed; the data dimension does " "not match."; AERROR << line; continue; } TrajectoryPoint point; point.mutable_path_point()->set_x(std::stod(tokens[0])); point.mutable_path_point()->set_y(std::stod(tokens[1])); point.mutable_path_point()->set_z(std::stod(tokens[2])); point.set_v(std::stod(tokens[3])); point.set_a(std::stod(tokens[4])); point.mutable_path_point()->set_kappa(std::stod(tokens[5])); point.mutable_path_point()->set_dkappa(std::stod(tokens[6])); point.set_relative_time(std::stod(tokens[7])); point.mutable_path_point()->set_theta(std::stod(tokens[8])); point.mutable_path_point()->set_s(std::stod(tokens[10])); complete_rtk_trajectory_.push_back(std::move(point)); } file_in.close(); } std::uint32_t RTKReplayPlanner::QueryPositionMatchedPoint( const TrajectoryPoint& start_point, const std::vector<TrajectoryPoint>& trajectory) const { auto func_distance_square = [](const TrajectoryPoint& point, const double x, const double y) { double dx = point.path_point().x() - x; double dy = point.path_point().y() - y; return dx * dx + dy * dy; }; double d_min = func_distance_square(trajectory.front(), start_point.path_point().x(), start_point.path_point().y()); std::uint32_t index_min = 0; for (std::uint32_t i = 1; i < trajectory.size(); ++i) { double d_temp = func_distance_square(trajectory[i], start_point.path_point().x(), start_point.path_point().y()); if (d_temp < d_min) { d_min = d_temp; index_min = i; } } return index_min; } } // namespace planning } // namespace apollo
34.921212
80
0.669386
[ "vector" ]
f5961dcf1f36fd815f7b3ffbaac86ab3c701fc81
1,117
hpp
C++
c++/muse/algorithms/sorting/MergeSort.hpp
networkhermit/algorithm
5c7221b12fac2de947a7c75ee40ff4ff519b443f
[ "MIT" ]
null
null
null
c++/muse/algorithms/sorting/MergeSort.hpp
networkhermit/algorithm
5c7221b12fac2de947a7c75ee40ff4ff519b443f
[ "MIT" ]
null
null
null
c++/muse/algorithms/sorting/MergeSort.hpp
networkhermit/algorithm
5c7221b12fac2de947a7c75ee40ff4ff519b443f
[ "MIT" ]
null
null
null
#ifndef MUSE_ALGORITHMS_SORTING_MERGE_SORT_HPP #define MUSE_ALGORITHMS_SORTING_MERGE_SORT_HPP 1 #include <cstddef> #include <vector> namespace MergeSort { template <typename T> void merge(std::vector<T> &arr, std::size_t lo, std::size_t mid, std::size_t hi) { if (lo == mid) { return; } merge(arr, lo, (lo + mid) >> 1, mid); merge(arr, mid, (mid + hi) >> 1, hi); std::size_t m = lo; std::size_t n = mid; T *sorted = new T[hi - lo]; for (std::size_t i = 0, length = hi - lo; i < length; i++) { if (m != mid && (n == hi || arr[m] < arr[n])) { sorted[i] = arr[m]; m++; } else { sorted[i] = arr[n]; n++; } } std::size_t cursor = 0; for (std::size_t i = lo; i < hi; i++) { arr[i] = sorted[cursor]; cursor++; } delete[] sorted; } template <typename T> void sort(std::vector<T> &arr) { merge(arr, 0, arr.size() >> 1, arr.size()); } } #endif
22.795918
86
0.457475
[ "vector" ]
60d0ca698275454088400be97e071ef8ce516989
6,408
cpp
C++
device/plugins/api/src/command_poller.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
device/plugins/api/src/command_poller.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
null
null
null
device/plugins/api/src/command_poller.cpp
openharmony-gitee-mirror/developtools_profiler
89bdc094fc84c40accb8c0e82dc8bbc7e85f0387
[ "Apache-2.0" ]
1
2021-09-13T11:17:44.000Z
2021-09-13T11:17:44.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "command_poller.h" #include "buffer_writer.h" #include "plugin_manager.h" #include "socket_context.h" #include <fcntl.h> #include <unistd.h> namespace { constexpr int SLEEP_TIME = 10; } CommandPoller::CommandPoller(const ManagerInterfacePtr& p) : requestIdAutoIncrease_(1), pluginManager_(p) { Connect(DEFAULT_UNIX_SOCKET_PATH); } CommandPoller::~CommandPoller() {} uint32_t CommandPoller::GetRequestId() { return requestIdAutoIncrease_++; } bool CommandPoller::OnCreateSessionCmd(const CreateSessionCmd& cmd, SocketContext& context) const { HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd PROC"); uint32_t bufferSize = cmd.buffer_sizes(0); ProfilerPluginConfig config = cmd.plugin_configs(0); std::vector<ProfilerPluginConfig> configVec; configVec.push_back(config); auto pluginManager = pluginManager_.lock(); // promote to shared_ptr CHECK_NOTNULL(pluginManager, false, "promote FAILED!"); if (!pluginManager->LoadPlugin(config.name())) { HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd FAIL 1"); return false; } int smbFd = -1; int eventFd = -1; if (bufferSize != 0) { HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd bufferSize = %d", bufferSize); smbFd = context.ReceiveFileDiscriptor(); eventFd = context.ReceiveFileDiscriptor(); int flags = fcntl(eventFd, F_GETFL); HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd smbFd = %d, eventFd = %d", smbFd, eventFd); HILOG_DEBUG(LOG_CORE, "eventFd flags = %X", flags); } if (!pluginManager->CreateWriter(config.name(), bufferSize, smbFd, eventFd)) { HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd CreateWriter FAIL"); return false; } if (!pluginManager->CreatePluginSession(configVec)) { HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd CreatePluginSession FAIL"); return false; } HILOG_DEBUG(LOG_CORE, "OnCreateSessionCmd OK"); return true; } bool CommandPoller::OnDestroySessionCmd(const DestroySessionCmd& cmd) const { HILOG_DEBUG(LOG_CORE, "OnDestroySessionCmd PROC"); uint32_t pluginId = cmd.plugin_ids(0); std::vector<uint32_t> pluginIdVec; pluginIdVec.push_back(pluginId); auto pluginManager = pluginManager_.lock(); // promote to shared_ptr CHECK_NOTNULL(pluginManager, false, "promote FAILED!"); if (!pluginManager->DestroyPluginSession(pluginIdVec)) { HILOG_DEBUG(LOG_CORE, "OnDestroySessionCmd DestroyPluginSession FAIL"); return false; } if (!pluginManager->ResetWriter(pluginId)) { HILOG_DEBUG(LOG_CORE, "OnDestroySessionCmd ResetWriter FAIL"); return false; } if (!pluginManager->UnloadPlugin(pluginId)) { HILOG_DEBUG(LOG_CORE, "OnDestroySessionCmd UnloadPlugin FAIL"); return false; } HILOG_DEBUG(LOG_CORE, "OnDestroySessionCmd OK"); return true; } bool CommandPoller::OnStartSessionCmd(const StartSessionCmd& cmd) const { HILOG_DEBUG(LOG_CORE, "OnStartSessionCmd PROC"); std::vector<uint32_t> pluginIds; pluginIds.push_back(cmd.plugin_ids(0)); std::vector<ProfilerPluginConfig> configVec; configVec.push_back(cmd.plugin_configs(0)); auto pluginManager = pluginManager_.lock(); // promote to shared_ptr CHECK_NOTNULL(pluginManager, false, "promote FAILED!"); if (!pluginManager->StartPluginSession(pluginIds, configVec)) { HILOG_DEBUG(LOG_CORE, "OnStartSessionCmd FAIL"); return false; } HILOG_DEBUG(LOG_CORE, "OnStartSessionCmd OK"); return true; } bool CommandPoller::OnStopSessionCmd(const StopSessionCmd& cmd) const { HILOG_DEBUG(LOG_CORE, "OnStopSessionCmd PROC"); std::vector<uint32_t> pluginIds; pluginIds.push_back(cmd.plugin_ids(0)); auto pluginManager = pluginManager_.lock(); // promote to shared_ptr CHECK_NOTNULL(pluginManager, false, "promote FAILED!"); if (!pluginManager->StopPluginSession(pluginIds)) { HILOG_DEBUG(LOG_CORE, "OnStopSessionCmd FAIL"); return false; } HILOG_DEBUG(LOG_CORE, "OnStopSessionCmd OK"); return true; } bool CommandPoller::OnGetCommandResponse(SocketContext& context, ::GetCommandResponse& response) { HILOG_DEBUG(LOG_CORE, "OnGetCommandResponse"); std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME)); NotifyResultRequest nrr; nrr.set_request_id(1); nrr.set_command_id(response.command_id()); PluginResult* pr = nrr.add_result(); ProfilerPluginState* status = pr->mutable_status(); if (response.has_create_session_cmd()) { if (OnCreateSessionCmd(response.create_session_cmd(), context)) { status->set_state(ProfilerPluginState::LOADED); } else { status->set_state(ProfilerPluginState::REGISTERED); } } else if (response.has_destroy_session_cmd()) { if (OnDestroySessionCmd(response.destroy_session_cmd())) { status->set_state(ProfilerPluginState::REGISTERED); } else { status->set_state(ProfilerPluginState::LOADED); } } else if (response.has_start_session_cmd()) { if (OnStartSessionCmd(response.start_session_cmd())) { status->set_state(ProfilerPluginState::IN_SESSION); } else { status->set_state(ProfilerPluginState::LOADED); } } else if (response.has_stop_session_cmd()) { if (OnStopSessionCmd(response.stop_session_cmd())) { status->set_state(ProfilerPluginState::LOADED); } else { status->set_state(ProfilerPluginState::IN_SESSION); } } else { HILOG_DEBUG(LOG_CORE, "OnGetCommandResponse FAIL"); return false; } HILOG_DEBUG(LOG_CORE, "OnGetCommandResponse OK %d", nrr.command_id()); NotifyResult(nrr); return true; }
35.6
105
0.700999
[ "vector" ]
60d44a2188457602416d0df7bd90359b4c24dc61
1,298
cpp
C++
BashuOJ-Code/2922.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2922.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2922.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<iomanip> #include<algorithm> #include<queue> #include<stack> #include<limits> #include<vector> #define ri register int #define ll long long using namespace std; const int MAXN=55; int n,m,t,map[MAXN][MAXN],Outd[MAXN]; double p[MAXN][MAXN],f[505][55][55]; inline int getint() { int num=0,bj=1; char c=getchar(); while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar(); return num*bj; } int main() { n=getint(),m=getint(),t=getint(); for(ri i=1;i<=m;i++) { int x=getint(),y=getint(); map[x][y]=1,Outd[x]++; } for(ri i=1;i<=n;i++) for(ri j=1;j<=n;j++) { if(map[i][j]&&map[j][i])p[i][j]=1/(double)Outd[j]; else p[i][j]=1/(double)(Outd[j]+1); } int now=0,past; f[now][0][1]=100,map[0][1]=1,p[0][1]=1/(double)(Outd[1]+1); for(ri i=1;i<=t;i++) { past=now,now^=1; memset(f[now],0,sizeof(f[now])); for(ri j=0;j<=n;j++) for(ri k=0;k<=n;k++) { if(!map[j][k])continue; f[now][j][k]=f[past][j][k]*p[j][k]; for(ri w=0;w<=n;w++) if(map[w][j]&&w!=k) f[now][j][k]+=f[past][w][j]*p[w][j]; } } for(ri i=1;i<=n;i++) { double Ans=0; for(ri j=0;j<=n;j++)Ans+=f[now][j][i]; printf("%.3lf\n",Ans); } return 0; }
20.28125
60
0.546995
[ "vector" ]
60d6973624674d30c54f3d987a690f639af732d9
13,674
cpp
C++
src/ui/account-view.cpp
fakuivan/seafile-client
d79c883c8b85e65c1b4cd2e98560859a4c81a63f
[ "Apache-2.0" ]
null
null
null
src/ui/account-view.cpp
fakuivan/seafile-client
d79c883c8b85e65c1b4cd2e98560859a4c81a63f
[ "Apache-2.0" ]
null
null
null
src/ui/account-view.cpp
fakuivan/seafile-client
d79c883c8b85e65c1b4cd2e98560859a4c81a63f
[ "Apache-2.0" ]
1
2020-10-02T01:07:07.000Z
2020-10-02T01:07:07.000Z
#include <QMenu> #include <QAction> #include <QToolButton> #include <QScopedPointer> #include <QPainter> #include <QStringList> #include <QDesktopServices> #include <QMouseEvent> #include <QUrl> #include <QUrlQuery> #include <QThreadPool> #include "account.h" #include "seafile-applet.h" #include "account-mgr.h" #include "login-dialog.h" #include "settings-mgr.h" #ifdef HAVE_SHIBBOLETH_SUPPORT #include "shib/shib-login-dialog.h" #endif // HAVE_SHIBBOLETH_SUPPORT #include "account-settings-dialog.h" #include "rpc/rpc-client.h" #include "main-window.h" #include "init-vdrive-dialog.h" #include "auto-login-service.h" #include "avatar-service.h" #include "utils/paint-utils.h" #include "filebrowser/file-browser-manager.h" #include "api/api-error.h" #include "api/requests.h" #include "filebrowser/auto-update-mgr.h" #include "repo-service.h" #include "account-view.h" namespace { } // namespace AccountView::AccountView(QWidget *parent) : QWidget(parent) { setupUi(this); // Init account drop down menu account_menu_ = new QMenu; mAccountBtn->setMenu(account_menu_); mAccountBtn->setPopupMode(QToolButton::InstantPopup); mAccountBtn->setFixedSize(QSize(AvatarService::kAvatarSize, AvatarService::kAvatarSize)); onAccountChanged(); connect(AvatarService::instance(), SIGNAL(avatarUpdated(const QString&, const QImage&)), this, SLOT(updateAvatar())); mAccountBtn->setCursor(Qt::PointingHandCursor); mAccountBtn->installEventFilter(this); account_menu_->installEventFilter(this); connect(seafApplet->accountManager(), SIGNAL(requireAddAccount()), this, SLOT(showAddAccountDialog())); connect(mServerAddr, SIGNAL(linkActivated(const QString&)), this, SLOT(visitServerInBrowser(const QString&))); // Must get the pixmap from QIcon because QIcon would load the 2x version // automatically. mRefreshLabel->setPixmap(QIcon(":/images/toolbar/refresh-new.png").pixmap(20)); mRefreshLabel->installEventFilter(this); } void AccountView::showAddAccountDialog() { LoginDialog dialog(this); // Show InitVirtualDriveDialog for the first account added AccountManager *account_mgr = seafApplet->accountManager(); if (dialog.exec() == QDialog::Accepted && account_mgr->accounts().size() == 1) { InitVirtualDriveDialog dialog(account_mgr->currentAccount(), seafApplet->mainWindow()); #if defined(Q_OS_WIN32) dialog.exec(); #endif } } void AccountView::deleteAccount() { QAction *action = qobject_cast<QAction*>(sender()); if (!action) return; Account account = qvariant_cast<Account>(action->data()); // QString question = tr("Are you sure to remove account from \"%1\"?<br>" // "<b>Warning: All libraries of this account would be unsynced!</b>").arg(account.serverUrl.toString()); QString question = tr("Are you sure you want to remove account %1?<br><br>" "The account will be removed locally. All syncing " "configuration will be removed too. The account at " "the server will not be affected.") .arg(account.username); if (seafApplet->yesOrNoBox(question, this, false)) { FileBrowserManager::getInstance()->closeAllDialogByAccount(account); QString error; QUrl server_url = account.serverUrl; server_url.setPath("/"); if (seafApplet->rpcClient()->unsyncReposByAccount(server_url, account.username, &error) < 0) { seafApplet->warningBox( tr("Failed to unsync libraries of this account: %1").arg(error), this); } seafApplet->accountManager()->removeAccount(account); } } void AccountView::editAccountSettings() { QAction *action = qobject_cast<QAction*>(sender()); if (!action) return; Account account = qvariant_cast<Account>(action->data()); AccountSettingsDialog dialog(account, this); dialog.exec(); } void AccountView::updateAccountInfoDisplay() { if (seafApplet->accountManager()->hasAccount()) { const Account account = seafApplet->accountManager()->currentAccount(); if (!account.accountInfo.name.isEmpty()) { mEmail->setText(account.accountInfo.name); } else { mEmail->setText(account.username); } // mServerAddr->setOpenExternalLinks(true); mServerAddr->setToolTip(tr("click to open the website")); QString host = account.serverUrl.host(); QString href = account.serverUrl.toString(); QString text = QString("<a style=" "\"color:#A4A4A4; text-decoration: none;\" " "href=\"%1\">%2</a>").arg(href).arg(host); mServerAddr->setText(account.isPro() ? QString("%1 <small>%2<small>").arg(text).arg(tr("pro version")) : text); } else { mEmail->setText(tr("No account")); mServerAddr->setText(QString()); } updateAvatar(); } /** * Update the account menu when accounts changed */ void AccountView::onAccountChanged() { const std::vector<Account>& accounts = seafApplet->accountManager()->accounts(); // Remove all menu items account_menu_->clear(); if (!accounts.empty()) { for (size_t i = 0, n = accounts.size(); i < n; i++) { const Account &account = accounts[i]; QString text_name = account.accountInfo.name.isEmpty() ? account.username : account.accountInfo.name; QString text = text_name + " (" + account.serverUrl.host() + ")"; if (!account.isValid()) { text += ", " + tr("not logged in"); } QMenu *submenu = new QMenu(text, account_menu_); if (i == 0) { submenu->setIcon(QIcon(":/images/account-checked.png")); } else { submenu->setIcon(QIcon(":/images/account-else.png")); } QAction *submenu_action = submenu->menuAction(); submenu_action->setData(QVariant::fromValue(account)); connect(submenu_action, SIGNAL(triggered()), this, SLOT(onAccountItemClicked())); QAction *action = new QAction(tr("Choose"), submenu); action->setIcon(QIcon(":/images/account-checked.png")); action->setIconVisibleInMenu(true); action->setData(QVariant::fromValue(account)); connect(action, SIGNAL(triggered()), this, SLOT(onAccountItemClicked())); submenu->addAction(action); submenu->setDefaultAction(action); QAction *account_settings_action = new QAction(tr("Account settings"), this); account_settings_action->setIcon(QIcon(":/images/account-settings.png")); account_settings_action->setIconVisibleInMenu(true); account_settings_action->setData(QVariant::fromValue(account)); connect(account_settings_action, SIGNAL(triggered()), this, SLOT(editAccountSettings())); submenu->addAction(account_settings_action); QAction *toggle_action = new QAction(this); toggle_action->setIcon(QIcon(":/images/logout.png")); toggle_action->setIconVisibleInMenu(true); toggle_action->setData(QVariant::fromValue(account)); connect(toggle_action, SIGNAL(triggered()), this, SLOT(toggleAccount())); if (account.isValid()) toggle_action->setText(tr("Logout")); else toggle_action->setText(tr("Login")); submenu->addAction(toggle_action); QAction *delete_account_action = new QAction(tr("Delete"), this); delete_account_action->setIcon(QIcon(":/images/delete-account.png")); delete_account_action->setIconVisibleInMenu(true); delete_account_action->setData(QVariant::fromValue(account)); connect(delete_account_action, SIGNAL(triggered()), this, SLOT(deleteAccount())); submenu->addAction(delete_account_action); account_menu_->addMenu(submenu); } account_menu_->addSeparator(); } add_account_action_ = new QAction(tr("Add an account"), this); add_account_action_->setIcon(QIcon(":/images/add-account.png")); add_account_action_->setIconVisibleInMenu(true); connect(add_account_action_, SIGNAL(triggered()), this, SLOT(showAddAccountDialog())); account_menu_->addAction(add_account_action_); updateAccountInfoDisplay(); } QAction* AccountView::makeAccountAction(const Account& account) { QString text = account.username + "(" + account.serverUrl.host() + ")"; if (!account.isValid()) { text += ", " + tr("not logged in"); } QAction *action = new QAction(text, account_menu_); action->setData(QVariant::fromValue(account)); // action->setCheckable(true); // QMenu won't display tooltip for menu item // action->setToolTip(account.serverUrl.host()); connect(action, SIGNAL(triggered()), this, SLOT(onAccountItemClicked())); return action; } // Switch to the clicked account in the account menu void AccountView::onAccountItemClicked() { QAction *action = (QAction *)(sender()); Account account = qvariant_cast<Account>(action->data()); if (!account.isValid()) { seafApplet->accountManager()->reloginAccount(account); } else { seafApplet->accountManager()->setCurrentAccount(account); } } void AccountView::updateAvatar() { mAccountBtn->setIconSize(QSize(AvatarService::kAvatarSize, AvatarService::kAvatarSize)); const Account account = seafApplet->accountManager()->currentAccount(); if (!account.isValid()) { mAccountBtn->setIcon(QIcon(":/images/account.png")); return; } AvatarService *service = AvatarService::instance(); QIcon avatar = QPixmap::fromImage(service->getAvatar(account.username)); mAccountBtn->setIcon(QIcon(avatar)); } bool AccountView::eventFilter(QObject *obj, QEvent *event) { if (obj == account_menu_ && event->type() == QEvent::MouseButtonRelease) { QMouseEvent *ev = (QMouseEvent*)event; QAction *action = account_menu_->actionAt(ev->pos()); if (action) { action->trigger(); } } if (obj == mAccountBtn && event->type() == QEvent::Paint) { QRect rect(0, 0, AvatarService::kAvatarSize, AvatarService::kAvatarSize); QPainter painter(mAccountBtn); painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::HighQualityAntialiasing); // get the device pixel radio from current painter device double scale_factor = globalDevicePixelRatio(); QPixmap image(mAccountBtn->icon().pixmap(rect.size()).scaled(scale_factor * rect.size())); QRect actualRect(QPoint(0, 0), QSize(AvatarService::kAvatarSize * scale_factor, AvatarService::kAvatarSize * scale_factor)); QImage masked_image(actualRect.size(), QImage::Format_ARGB32_Premultiplied); masked_image.fill(Qt::transparent); QPainter mask_painter; mask_painter.begin(&masked_image); mask_painter.setRenderHint(QPainter::Antialiasing); mask_painter.setRenderHint(QPainter::HighQualityAntialiasing); mask_painter.setCompositionMode(QPainter::CompositionMode_SourceOver); mask_painter.setPen(Qt::NoPen); mask_painter.setBrush(Qt::white); mask_painter.drawEllipse(actualRect); mask_painter.setCompositionMode(QPainter::CompositionMode_SourceIn); mask_painter.drawPixmap(actualRect, image); mask_painter.setCompositionMode(QPainter::CompositionMode_DestinationOver); mask_painter.fillRect(actualRect, Qt::transparent); mask_painter.end(); masked_image.setDevicePixelRatio(scale_factor); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage(QPoint(0,0), masked_image); return true; } if (obj == mRefreshLabel) { if (event->type() == QEvent::MouseButtonPress) { emit refresh(); return true; } else if (event->type() == QEvent::Enter) { mRefreshLabel->setPixmap(QIcon(":/images/toolbar/refresh-orange.png").pixmap(20)); return true; } else if (event->type() == QEvent::Leave) { mRefreshLabel->setPixmap(QIcon(":/images/toolbar/refresh-new.png").pixmap(20)); return true; } } return QObject::eventFilter(obj, event); } /** * Only remove the api token of the account. The accout would still be shown * in the account list. */ void AccountView::toggleAccount() { QAction *action = qobject_cast<QAction*>(sender()); if (!action) return; Account account = qvariant_cast<Account>(action->data()); if (!account.isValid()) { seafApplet->accountManager()->reloginAccount(account); return; } qWarning("Logging out current account %s", account.username.toUtf8().data()); AutoUpdateManager::instance()->cleanCachedFile(); // logout Account FileBrowserManager::getInstance()->closeAllDialogByAccount(account); seafApplet->accountManager()->logoutDevice(account); } void AccountView::visitServerInBrowser(const QString& link) { AutoLoginService::instance()->startAutoLogin("/"); }
37.157609
131
0.643484
[ "vector" ]
60d80e67d79aa32f79bee180acd33b11e4bf73b6
6,303
cpp
C++
AVSCommon/Utils/test/UUIDGenerationTest.cpp
skrowten-hermit/avs-device-sdk
1255f3398b9c9bdd92d8fcde89c90f19f49eb21d
[ "Apache-2.0" ]
8
2018-05-10T09:02:44.000Z
2021-03-28T00:37:36.000Z
AVSCommon/Utils/test/UUIDGenerationTest.cpp
skrowten-hermit/avs-device-sdk
1255f3398b9c9bdd92d8fcde89c90f19f49eb21d
[ "Apache-2.0" ]
6
2019-03-26T10:30:43.000Z
2019-09-04T10:53:28.000Z
AVSCommon/Utils/test/UUIDGenerationTest.cpp
skrowten-hermit/avs-device-sdk
1255f3398b9c9bdd92d8fcde89c90f19f49eb21d
[ "Apache-2.0" ]
16
2019-02-12T12:09:54.000Z
2020-05-06T19:33:35.000Z
/* * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 <string> #include <future> #include <vector> #include <unordered_set> #include <cctype> #include <random> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "AVSCommon/Utils/UUIDGeneration/UUIDGeneration.h" namespace alexaClientSDK { namespace avsCommon { namespace test { using namespace testing; using namespace avsCommon::utils::uuidGeneration; /// The version of the UUID generated. static const std::string UUID_VERSION("4"); /// The variant of the UUID generated. static const unsigned int UUID_VARIANT(8); /// The offset of the UUID version in the string. static const unsigned int UUID_VERSION_OFFSET(14); /// The offset of the UUID variant in the string. static const unsigned int UUID_VARIANT_OFFSET(19); /// Hyphen. static const std::string HYPHEN("-"); /// Position of first hyphen. static const unsigned int HYPHEN1_POSITION(8); /// Position of second hyphen. static const unsigned int HYPHEN2_POSITION(13); /// Position of third hyphen. static const unsigned int HYPHEN3_POSITION(18); /// Position of fourth hyphen. static const unsigned int HYPHEN4_POSITION(23); /// The length of the UUID string - 32 hexadecimal digits and 4 hyphens. static const unsigned int UUID_LENGTH(36); /// The maximum UUIDs to generate to test for uniqueness. static const unsigned int MAX_UUIDS_TO_GENERATE(100); /// The maximum threads to test with. static const unsigned int MAX_TEST_THREADS(10); /// The maximum number of retries. static const unsigned int MAX_RETRIES(20); class UUIDGenerationTest : public ::testing::Test {}; /** * Call @c generateUUID and expect a string of length @c UUID_LENGTH. */ TEST_F(UUIDGenerationTest, testUUIDStringLength) { ASSERT_EQ(UUID_LENGTH, generateUUID().length()); } /** * Call @c generateUUID and expect a string of length @c UUID_LENGTH. Check that each character in the string * is a hexedecimal number except for the hyphens. */ TEST_F(UUIDGenerationTest, testUUIDContainsOnlyHexCharacters) { auto uuid = generateUUID(); ASSERT_EQ(UUID_LENGTH, uuid.length()); for (unsigned int i = 0; i < uuid.length(); i++) { if (i == HYPHEN1_POSITION || i == HYPHEN2_POSITION || i == HYPHEN3_POSITION || i == HYPHEN4_POSITION) { ASSERT_EQ(HYPHEN, uuid.substr(i, 1)); } else { ASSERT_TRUE(isxdigit(uuid[i])); } } } /** * Call @c generateUUID and check that the version is set correctly. */ TEST_F(UUIDGenerationTest, testUUIDVersion) { ASSERT_EQ(UUID_VERSION, generateUUID().substr(UUID_VERSION_OFFSET, 1)); } /** * Call @c generateUUID and check the variant is set correctly. */ TEST_F(UUIDGenerationTest, testUUIDVariant) { ASSERT_EQ(UUID_VARIANT, strtoul(generateUUID().substr(UUID_VARIANT_OFFSET, 1).c_str(), nullptr, 16) & UUID_VARIANT); } /** * Call @c generateUUID and check that the hyphens are in the right positions. */ TEST_F(UUIDGenerationTest, testUUIDHyphens) { std::string uuid = generateUUID(); ASSERT_EQ(HYPHEN, uuid.substr(HYPHEN1_POSITION, 1)); ASSERT_EQ(HYPHEN, uuid.substr(HYPHEN2_POSITION, 1)); ASSERT_EQ(HYPHEN, uuid.substr(HYPHEN3_POSITION, 1)); ASSERT_EQ(HYPHEN, uuid.substr(HYPHEN4_POSITION, 1)); } /** * Call @c generateUUID multiple times and check the version and variant are set correctly. * Check for uniqueness of the UUIDs generated. */ TEST_F(UUIDGenerationTest, testMultipleRequests) { std::unordered_set<std::string> uuidsGenerated; for (unsigned int i = 0; i < MAX_UUIDS_TO_GENERATE; ++i) { unsigned int prevSizeOfSet = uuidsGenerated.size(); auto uuid = generateUUID(); uuidsGenerated.insert(uuid); ASSERT_EQ(UUID_LENGTH, uuid.length()); ASSERT_EQ(UUID_VERSION, uuid.substr(UUID_VERSION_OFFSET, 1)); ASSERT_EQ(UUID_VARIANT, strtoul(uuid.substr(UUID_VARIANT_OFFSET, 1).c_str(), nullptr, 16) & UUID_VARIANT); ASSERT_EQ(prevSizeOfSet + 1, uuidsGenerated.size()); } } /** * Call @c generateUUID from multiple threads and check the version and variant are set correctly. * Check for uniqueness of the UUIDs generated. */ TEST_F(UUIDGenerationTest, testMultipleConcurrentRequests) { int no_of_threads = MAX_TEST_THREADS; std::vector<std::future<std::string>> uuidRequesters; std::unordered_set<std::string> uuidsGenerated; for (int i = 0; i < no_of_threads; ++i) { auto future = std::async(std::launch::async, []() { return generateUUID(); }); uuidRequesters.push_back(std::move(future)); } for (auto& future : uuidRequesters) { unsigned int prevSizeOfSet = uuidsGenerated.size(); auto uuid = future.get(); uuidsGenerated.insert(uuid); ASSERT_EQ(UUID_LENGTH, uuid.length()); ASSERT_EQ(UUID_VERSION, uuid.substr(UUID_VERSION_OFFSET, 1)); ASSERT_EQ(UUID_VARIANT, strtoul(uuid.substr(UUID_VARIANT_OFFSET, 1).c_str(), nullptr, 16) & UUID_VARIANT); ASSERT_EQ(prevSizeOfSet + 1, uuidsGenerated.size()); } } /** * Call @c generateUUID and ensure all hex values are generated. Will retry @c MAX_RETRIES times. */ TEST_F(UUIDGenerationTest, testAllHexValuesGenerated) { std::unordered_set<char> hexCharacters = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; for (unsigned int retry = 0; retry < MAX_RETRIES && !hexCharacters.empty(); retry++) { std::string uuid = generateUUID(); for (const char& digit : uuid) { hexCharacters.erase(digit); if (hexCharacters.empty()) { break; } } } ASSERT_TRUE(hexCharacters.empty()); } } // namespace test } // namespace avsCommon } // namespace alexaClientSDK
33.349206
120
0.699191
[ "vector" ]
60d8c101aef5f43c54c93ba9a1d2f9dfc4823b75
21,153
cpp
C++
Script/maxent.cpp
accurat-toolkit/maxent_DFKI_v3
a4e72f88dd318a40d108af06f52640d8064e39c5
[ "BSD-2-Clause" ]
1
2017-10-26T20:23:29.000Z
2017-10-26T20:23:29.000Z
Script/maxent.cpp
accurat-toolkit/maxent_DFKI_v3
a4e72f88dd318a40d108af06f52640d8064e39c5
[ "BSD-2-Clause" ]
null
null
null
Script/maxent.cpp
accurat-toolkit/maxent_DFKI_v3
a4e72f88dd318a40d108af06f52640d8064e39c5
[ "BSD-2-Clause" ]
null
null
null
/* * $Id: maxent.cpp,v 1.28 2006/08/21 17:30:38 tsuruoka Exp $ */ #include "maxent.h" #include <cmath> #include <cstdio> using namespace std; int ME_Model::BLMVMFunctionGradient(double *x, double *f, double *g, int n) { const int nf = _fb.Size(); if (_inequality_width > 0) { assert(nf == n/2); for (int i = 0; i < nf; i++) { _va[i] = x[i]; _vb[i] = x[i + nf]; _vl[i] = _va[i] - _vb[i]; } } else { assert(nf == n); for (int i = 0; i < n; i++) { _vl[i] = x[i]; } } double score = update_model_expectation(); if (_inequality_width > 0) { for (int i = 0; i < nf; i++) { g[i] = -(_vee[i] - _vme[i] - _inequality_width); g[i + nf] = -(_vme[i] - _vee[i] - _inequality_width); } } else { if (_sigma == 0) { for (int i = 0; i < n; i++) { g[i] = -(_vee[i] - _vme[i]); } } else { const double c = 1 / (_sigma * _sigma); for (int i = 0; i < n; i++) { g[i] = -(_vee[i] - _vme[i] - c * _vl[i]); } } } *f = -score; return 0; } int ME_Model::BLMVMLowerAndUpperBounds(double *xl,double *xu,int n) { if (_inequality_width > 0) { for (int i = 0; i < n; i++){ xl[i] = 0; xu[i] = 10000.0; } return 0; } for (int i = 0; i < n; i++){ xl[i] = -10000.0; xu[i] = 10000.0; } return 0; } int ME_Model::perform_GIS(int C) { cerr << "C = " << C << endl; C = 1; cerr << "performing AGIS" << endl; vector<double> pre_v; double pre_logl = -999999; for (int iter = 0; iter < 200; iter++) { double logl = update_model_expectation(); fprintf(stderr, "iter = %2d C = %d f = %10.7f train_err = %7.5f", iter, C, logl, _train_error); if (_heldout.size() > 0) { double hlogl = heldout_likelihood(); fprintf(stderr, " heldout_logl(err) = %f (%6.4f)", hlogl, _heldout_error); } cerr << endl; if (logl < pre_logl) { C += 1; _vl = pre_v; iter--; continue; } if (C > 1 && iter % 10 == 0) C--; pre_logl = logl; pre_v = _vl; for (int i = 0; i < _fb.Size(); i++) { double coef = _vee[i] / _vme[i]; _vl[i] += log(coef) / C; } } cerr << endl; } int ME_Model::perform_LMVM() { cerr << "performing LMVM" << endl; if (_inequality_width > 0) { int nvars = _fb.Size() * 2; double *x = (double*)malloc(nvars*sizeof(double)); // INITIAL POINT for (int i = 0; i < nvars / 2; i++) { x[i] = _va[i]; x[i + _fb.Size()] = _vb[i]; } int info = BLMVMSolve(x, nvars); for (int i = 0; i < nvars / 2; i++) { _va[i] = x[i]; _vb[i] = x[i + _fb.Size()]; _vl[i] = _va[i] - _vb[i]; } free(x); return 0; } int nvars = _fb.Size(); double *x = (double*)malloc(nvars*sizeof(double)); // INITIAL POINT for (int i = 0; i < nvars; i++) { x[i] = _vl[i]; } int info = BLMVMSolve(x, nvars); for (int i = 0; i < nvars; i++) { _vl[i] = x[i]; } free(x); return 0; } int ME_Model::conditional_probability(const Sample & s, std::vector<double> & membp) const { int num_classes = membp.size(); double sum = 0, maxpow = 0; int max_label = -1; double maxp = 0; vector<double> powv(_num_classes, 0.0); for (vector<int>::const_iterator j = s.positive_features.begin(); j != s.positive_features.end(); j++){ for (vector<int>::const_iterator k = _feature2mef[*j].begin(); k != _feature2mef[*j].end(); k++) { powv[_fb.Feature(*k).label()] += _vl[*k]; } } for (vector<pair<int, double> >::const_iterator j = s.rvfeatures.begin(); j != s.rvfeatures.end(); j++) { for (vector<int>::const_iterator k = _feature2mef[j->first].begin(); k != _feature2mef[j->first].end(); k++) { powv[_fb.Feature(*k).label()] += _vl[*k] * j->second; } } std::vector<double>::const_iterator pmax = max_element(powv.begin(), powv.end()); double offset = max(0.0, *pmax - 700); // to avoid overflow for (int label = 0; label < _num_classes; label++) { double pow = powv[label] - offset; double prod = exp(pow); // cout << pow << " " << prod << ", "; // if (_ref_modelp != NULL) prod *= _train_refpd[n][label]; if (_ref_modelp != NULL) prod *= s.ref_pd[label]; assert(prod != 0); membp[label] = prod; sum += prod; } for (int label = 0; label < _num_classes; label++) { membp[label] /= sum; if (membp[label] > membp[max_label]) max_label = label; } assert(max_label >= 0); return max_label; } int ME_Model::make_feature_bag(const int cutoff) { int max_num_features = 0; // count the occurrences of features #ifdef USE_HASH_MAP typedef __gnu_cxx::hash_map<unsigned int, int> map_type; #else typedef std::map<unsigned int, int> map_type; #endif map_type count; if (cutoff > 0) { for (std::vector<Sample>::const_iterator i = _vs.begin(); i != _vs.end(); i++) { for (std::vector<int>::const_iterator j = i->positive_features.begin(); j != i->positive_features.end(); j++) { count[ME_Feature(i->label, *j).body()]++; } for (std::vector<pair<int, double> >::const_iterator j = i->rvfeatures.begin(); j != i->rvfeatures.end(); j++) { count[ME_Feature(i->label, j->first).body()]++; } } } int n = 0; for (std::vector<Sample>::const_iterator i = _vs.begin(); i != _vs.end(); i++, n++) { max_num_features = max(max_num_features, (int)(i->positive_features.size())); for (std::vector<int>::const_iterator j = i->positive_features.begin(); j != i->positive_features.end(); j++) { const ME_Feature feature(i->label, *j); if (cutoff > 0 && count[feature.body()] < cutoff) continue; int id = _fb.Put(feature); // cout << i->label << "\t" << *j << "\t" << id << endl; // feature2sample[id].push_back(n); } for (std::vector<pair<int, double> >::const_iterator j = i->rvfeatures.begin(); j != i->rvfeatures.end(); j++) { const ME_Feature feature(i->label, j->first); // if (cutoff > 0 && count[feature.body()] < cutoff) continue; if (cutoff > 0 && count[feature.body()] <= cutoff) continue; int id = _fb.Put(feature); } } count.clear(); // cerr << "num_classes = " << _num_classes << endl; // cerr << "max_num_features = " << max_num_features << endl; int c = 0; init_feature2mef(); return max_num_features; } double ME_Model::heldout_likelihood() { double logl = 0; int ncorrect = 0; for (std::vector<Sample>::const_iterator i = _heldout.begin(); i != _heldout.end(); i++) { vector<double> membp(_num_classes); int l = classify(*i, membp); logl += log(membp[i->label]); if (l == i->label) ncorrect++; } _heldout_error = 1 - (double)ncorrect / _heldout.size(); return logl /= _heldout.size(); } double ME_Model::update_model_expectation() { double logl = 0; int ncorrect = 0; _vme.resize(_fb.Size()); for (int i = 0; i < _fb.Size(); i++) _vme[i] = 0; int n = 0; for (vector<Sample>::const_iterator i = _vs.begin(); i != _vs.end(); i++, n++) { vector<double> membp(_num_classes); int max_label = conditional_probability(*i, membp); logl += log(membp[i->label]); // cout << membp[*i] << " " << logl << " "; if (max_label == i->label) ncorrect++; // model_expectation for (vector<int>::const_iterator j = i->positive_features.begin(); j != i->positive_features.end(); j++){ for (vector<int>::const_iterator k = _feature2mef[*j].begin(); k != _feature2mef[*j].end(); k++) { _vme[*k] += membp[_fb.Feature(*k).label()]; } } for (vector<pair<int, double> >::const_iterator j = i->rvfeatures.begin(); j != i->rvfeatures.end(); j++) { for (vector<int>::const_iterator k = _feature2mef[j->first].begin(); k != _feature2mef[j->first].end(); k++) { _vme[*k] += membp[_fb.Feature(*k).label()] * j->second; } } } for (int i = 0; i < _fb.Size(); i++) { _vme[i] /= _vs.size(); } _train_error = 1 - (double)ncorrect / _vs.size(); logl /= _vs.size(); if (_inequality_width > 0) { for (int i = 0; i < _fb.Size(); i++) { logl -= (_va[i] + _vb[i]) * _inequality_width; } } else { if (_sigma > 0) { const double c = 1/(2*_sigma*_sigma); for (int i = 0; i < _fb.Size(); i++) { logl -= _vl[i] * _vl[i] * c; } } } //logl /= _vs.size(); // fprintf(stderr, "iter =%3d logl = %10.7f train_acc = %7.5f\n", iter, logl, (double)ncorrect/train.size()); // fprintf(stderr, "logl = %10.7f train_acc = %7.5f\n", logl, (double)ncorrect/_train.size()); return logl; } int ME_Model::train(const vector<ME_Sample> & vms, const int cutoff, const double sigma, const double widthfactor) { // convert ME_Sample to Sample // vector<Sample> vs; _vs.clear(); for (vector<ME_Sample>::const_iterator i = vms.begin(); i != vms.end(); i++) { add_training_sample(*i); } return train(cutoff, sigma, widthfactor); } void ME_Model::add_training_sample(const ME_Sample & mes) { Sample s; s.label = _label_bag.Put(mes.label); if (s.label > ME_Feature::MAX_LABEL_TYPES) { cerr << "error: too many types of labels." << endl; exit(1); } for (vector<string>::const_iterator j = mes.features.begin(); j != mes.features.end(); j++) { s.positive_features.push_back(_featurename_bag.Put(*j)); } for (vector<pair<string, double> >::const_iterator j = mes.rvfeatures.begin(); j != mes.rvfeatures.end(); j++) { s.rvfeatures.push_back(pair<int, double>(_featurename_bag.Put(j->first), j->second)); } if (_ref_modelp != NULL) { ME_Sample tmp = mes;; s.ref_pd = _ref_modelp->classify(tmp); } // cout << s.label << "\t"; // for (vector<int>::const_iterator j = s.positive_features.begin(); j != s.positive_features.end(); j++){ // cout << *j << " "; // } // cout << endl; _vs.push_back(s); } int ME_Model::train(const int cutoff, const double sigma, const double widthfactor) { if (sigma > 0 && widthfactor > 0) { cerr << "error: Gausian prior and inequality modeling cannot be used together." << endl; return 0; } if (_vs.size() == 0) { cerr << "error: no training data." << endl; return 0; } if (_nheldout >= _vs.size()) { cerr << "error: too much heldout data. no training data is available." << endl; return 0; } // if (_nheldout > 0) random_shuffle(_vs.begin(), _vs.end()); int max_label = 0; for (std::vector<Sample>::const_iterator i = _vs.begin(); i != _vs.end(); i++) { max_label = max(max_label, i->label); } _num_classes = max_label + 1; if (_num_classes != _label_bag.Size()) { cerr << "warning: _num_class != _label_bag.Size()" << endl; } if (_ref_modelp != NULL) { cerr << "setting reference distribution..."; for (int i = 0; i < _ref_modelp->num_classes(); i++) { _label_bag.Put(_ref_modelp->get_class_label(i)); } _num_classes = _label_bag.Size(); for (vector<Sample>::iterator i = _vs.begin(); i != _vs.end(); i++) { set_ref_dist(*i); } cerr << "done" << endl; } for (int i = 0; i < _nheldout; i++) { _heldout.push_back(_vs.back()); _vs.pop_back(); } // for (std::vector<Sample>::iterator i = _vs.begin(); i != _vs.end(); i++) { // sort(i->positive_features.begin(), i->positive_features.end()); // } sort(_vs.begin(), _vs.end()); // for (std::vector<Sample>::const_iterator i = _vs.begin(); i != _vs.end(); i++) { // for (vector<int>::const_iterator j = i->positive_features.begin(); j != i->positive_features.end(); j++){ // cout << *j << " "; // } // cout << endl; // } // _sigma = sqrt(Nsigma2 / (double)_train.size()); _sigma = sigma; _inequality_width = widthfactor / _vs.size(); if (cutoff > 0) cerr << "cutoff threshold = " << cutoff << endl; if (_sigma > 0) cerr << "Gaussian prior sigma = " << _sigma << endl; // cerr << "N*sigma^2 = " << Nsigma2 << " sigma = " << _sigma << endl; if (widthfactor > 0) cerr << "widthfactor = " << widthfactor << endl; cerr << "preparing for estimation..."; int C = make_feature_bag(cutoff); // _vs.clear(); cerr << "done" << endl; cerr << "number of samples = " << _vs.size() << endl; cerr << "number of features = " << _fb.Size() << endl; cerr << "calculating empirical expectation..."; _vee.resize(_fb.Size()); for (int i = 0; i < _fb.Size(); i++) { _vee[i] = 0; } for (int n = 0; n < (int)_vs.size(); n++) { const Sample * i = &_vs[n]; for (vector<int>::const_iterator j = i->positive_features.begin(); j != i->positive_features.end(); j++){ for (vector<int>::const_iterator k = _feature2mef[*j].begin(); k != _feature2mef[*j].end(); k++) { if (_fb.Feature(*k).label() == i->label) _vee[*k] += 1.0; } } for (vector<pair<int, double> >::const_iterator j = i->rvfeatures.begin(); j != i->rvfeatures.end(); j++) { for (vector<int>::const_iterator k = _feature2mef[j->first].begin(); k != _feature2mef[j->first].end(); k++) { if (_fb.Feature(*k).label() == i->label) _vee[*k] += j->second; } } } for (int i = 0; i < _fb.Size(); i++) { _vee[i] /= _vs.size(); } cerr << "done" << endl; _vl.resize(_fb.Size()); for (int i = 0; i < _fb.Size(); i++) _vl[i] = 0.0; if (_inequality_width > 0) { _va.resize(_fb.Size()); _vb.resize(_fb.Size()); for (int i = 0; i < _fb.Size(); i++) { _va[i] = 0.0; _vb[i] = 0.0; } } //perform_GIS(C); perform_LMVM(); if (_inequality_width > 0) { int sum = 0; for (int i = 0; i < _fb.Size(); i++) { if (_vl[i] != 0) sum++; } cerr << "number of active features = " << sum << endl; } } void ME_Model::get_features(list< pair< pair<string, string>, double> > & fl) { fl.clear(); // for (int i = 0; i < _fb.Size(); i++) { // ME_Feature f = _fb.Feature(i); // fl.push_back( make_pair(make_pair(_label_bag.Str(f.label()), _featurename_bag.Str(f.feature())), _vl[i])); // } for (MiniStringBag::map_type::const_iterator i = _featurename_bag.begin(); i != _featurename_bag.end(); i++) { for (int j = 0; j < _label_bag.Size(); j++) { string label = _label_bag.Str(j); string history = i->first; int id = _fb.Id(ME_Feature(j, i->second)); if (id < 0) continue; fl.push_back( make_pair(make_pair(label, history), _vl[id]) ); } } } bool ME_Model::load_from_file(const string & filename) { FILE * fp = fopen(filename.c_str(), "r"); if (!fp) { cerr << "error: cannot open " << filename << "!" << endl; return false; } _vl.clear(); _label_bag.Clear(); _featurename_bag.Clear(); _fb.Clear(); char buf[1024]; while(fgets(buf, 1024, fp)) { string line(buf); string::size_type t1 = line.find_first_of('\t'); string::size_type t2 = line.find_last_of('\t'); string classname = line.substr(0, t1); string featurename = line.substr(t1 + 1, t2 - (t1 + 1) ); float lambda; string w = line.substr(t2+1); sscanf(w.c_str(), "%f", &lambda); int label = _label_bag.Put(classname); int feature = _featurename_bag.Put(featurename); _fb.Put(ME_Feature(label, feature)); _vl.push_back(lambda); } _num_classes = _label_bag.Size(); init_feature2mef(); fclose(fp); return true; } void ME_Model::init_feature2mef() { _feature2mef.clear(); for (int i = 0; i < _featurename_bag.Size(); i++) { vector<int> vi; for (int k = 0; k < _num_classes; k++) { int id = _fb.Id(ME_Feature(k, i)); if (id >= 0) vi.push_back(id); } _feature2mef.push_back(vi); } } bool ME_Model::load_from_array(const ME_Model_Data data[]) { _vl.clear(); for (int i = 0;; i++) { if (string(data[i].label) == "///") break; int label = _label_bag.Put(data[i].label); int feature = _featurename_bag.Put(data[i].feature); _fb.Put(ME_Feature(label, feature)); _vl.push_back(data[i].weight); } _num_classes = _label_bag.Size(); init_feature2mef(); return true; } bool ME_Model::save_to_file(const string & filename) const { FILE * fp = fopen(filename.c_str(), "w"); if (!fp) { cerr << "error: cannot open " << filename << "!" << endl; return false; } // for (int i = 0; i < _fb.Size(); i++) { // if (_vl[i] == 0) continue; // ignore zero-weight features // ME_Feature f = _fb.Feature(i); // fprintf(fp, "%s\t%s\t%f\n", _label_bag.Str(f.label()).c_str(), _featurename_bag.Str(f.feature()).c_str(), _vl[i]); // } for (MiniStringBag::map_type::const_iterator i = _featurename_bag.begin(); i != _featurename_bag.end(); i++) { for (int j = 0; j < _label_bag.Size(); j++) { string label = _label_bag.Str(j); string history = i->first; int id = _fb.Id(ME_Feature(j, i->second)); if (id < 0) continue; if (_vl[id] == 0) continue; // ignore zero-weight features fprintf(fp, "%s\t%s\t%f\n", label.c_str(), history.c_str(), _vl[id]); } } fclose(fp); return true; } void ME_Model::set_ref_dist(Sample & s) const { vector<double> v0 = s.ref_pd; vector<double> v(_num_classes); for (int i = 0; i < v.size(); i++) { v[i] = 0; string label = get_class_label(i); int id_ref = _ref_modelp->get_class_id(label); if (id_ref != -1) { v[i] = v0[id_ref]; } if (v[i] == 0) v[i] = 0.001; // to avoid -inf logl } s.ref_pd = v; } int ME_Model::classify(const Sample & nbs, vector<double> & membp) const { // vector<double> membp(_num_classes); assert(_num_classes == (int)membp.size()); conditional_probability(nbs, membp); int max_label = 0; double max = 0.0; for (int i = 0; i < (int)membp.size(); i++) { // cout << membp[i] << " "; if (membp[i] > max) { max_label = i; max = membp[i]; } } // cout << endl; return max_label; } vector<double> ME_Model::classify(ME_Sample & mes) const { Sample s; for (vector<string>::const_iterator j = mes.features.begin(); j != mes.features.end(); j++) { int id = _featurename_bag.Id(*j); if (id >= 0) s.positive_features.push_back(id); } for (vector<pair<string, double> >::const_iterator j = mes.rvfeatures.begin(); j != mes.rvfeatures.end(); j++) { int id = _featurename_bag.Id(j->first); if (id >= 0) { s.rvfeatures.push_back(pair<int, double>(id, j->second)); } } if (_ref_modelp != NULL) { s.ref_pd = _ref_modelp->classify(mes); set_ref_dist(s); } vector<double> vp(_num_classes); int label = classify(s, vp); mes.label = get_class_label(label); return vp; } /* * $Log: maxent.cpp,v $ * Revision 1.28 2006/08/21 17:30:38 tsuruoka * use MAX_LABEL_TYPES * * Revision 1.27 2006/07/25 13:19:53 tsuruoka * sort _vs[] * * Revision 1.26 2006/07/18 11:13:15 tsuruoka * modify comments * * Revision 1.25 2006/07/18 10:02:15 tsuruoka * remove sample2feature[] * speed up conditional_probability() * * Revision 1.24 2006/07/18 05:10:51 tsuruoka * add ref_dist * * Revision 1.23 2005/12/24 07:05:32 tsuruoka * modify conditional_probability() to avoid overflow * * Revision 1.22 2005/12/24 07:01:25 tsuruoka * add cutoff for real-valued features * * Revision 1.21 2005/12/23 10:33:02 tsuruoka * support real-valued features * * Revision 1.20 2005/12/23 09:15:29 tsuruoka * modify _train to reduce memory consumption * * Revision 1.19 2005/10/28 13:10:14 tsuruoka * fix for overflow (thanks to Ming Li) * * Revision 1.18 2005/10/28 13:03:07 tsuruoka * add progress_bar * * Revision 1.17 2005/09/12 13:51:16 tsuruoka * Sample: list -> vector * * Revision 1.16 2005/09/12 13:27:10 tsuruoka * add add_training_sample() * * Revision 1.15 2005/04/27 11:22:27 tsuruoka * bugfix * ME_Sample: list -> vector * * Revision 1.14 2005/04/27 10:00:42 tsuruoka * remove tmpfb * * Revision 1.13 2005/04/26 14:25:53 tsuruoka * add MiniStringBag, USE_HASH_MAP * * Revision 1.12 2005/02/11 10:20:08 tsuruoka * modify cutoff * * Revision 1.11 2004/10/04 05:50:25 tsuruoka * add Clear() * * Revision 1.10 2004/08/26 16:52:26 tsuruoka * fix load_from_file() * * Revision 1.9 2004/08/09 12:27:21 tsuruoka * change messages * * Revision 1.8 2004/08/04 13:55:18 tsuruoka * modify _sample2feature * * Revision 1.7 2004/07/28 13:42:58 tsuruoka * add AGIS * * Revision 1.6 2004/07/28 05:54:13 tsuruoka * get_class_name() -> get_class_label() * ME_Feature: bugfix * * Revision 1.5 2004/07/27 16:58:47 tsuruoka * modify the interface of classify() * * Revision 1.4 2004/07/26 17:23:46 tsuruoka * _sample2feature: list -> vector * * Revision 1.3 2004/07/26 15:49:23 tsuruoka * modify ME_Feature * * Revision 1.2 2004/07/26 13:52:18 tsuruoka * modify cutoff * * Revision 1.1 2004/07/26 13:10:55 tsuruoka * add files * * Revision 1.20 2004/07/22 08:34:45 tsuruoka * modify _sample2feature[] * * Revision 1.19 2004/07/21 16:33:01 tsuruoka * remove some comments * */
27.578879
122
0.577554
[ "vector", "3d" ]
60d95ede8282793cd2fc303d6f39509ac891cff9
4,214
cpp
C++
09-LambertianPlusShadows/Passes/LambertianPlusShadowPass.cpp
OnionStark/Raytracing-Renderer
7dc0986bde15a764eaebacf2bfb6c3182533fb3a
[ "BSD-3-Clause" ]
559
2018-09-20T13:42:00.000Z
2022-03-28T04:54:44.000Z
09-LambertianPlusShadows/Passes/LambertianPlusShadowPass.cpp
OnionStark/Raytracing-Renderer
7dc0986bde15a764eaebacf2bfb6c3182533fb3a
[ "BSD-3-Clause" ]
13
2018-10-09T18:48:25.000Z
2021-12-07T09:59:38.000Z
09-LambertianPlusShadows/Passes/LambertianPlusShadowPass.cpp
OnionStark/Raytracing-Renderer
7dc0986bde15a764eaebacf2bfb6c3182533fb3a
[ "BSD-3-Clause" ]
87
2018-10-04T08:14:35.000Z
2022-03-08T01:55:26.000Z
/********************************************************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. 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 code must retain the copyright notice, this list of conditions and the following disclaimer. # * Neither the name of NVIDIA CORPORATION 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 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************************************************/ #include "LambertianPlusShadowPass.h" // Some global vars, used to simplify changing shader location & entry points namespace { // Where is our shader located? const char* kFileRayTrace = "Tutorial09\\lambertianPlusShadows.rt.hlsl"; // What are the entry points in that shader for various ray tracing shaders? const char* kEntryPointRayGen = "LambertShadowsRayGen"; const char* kEntryPointMiss0 = "ShadowMiss"; const char* kEntryAoAnyHit = "ShadowAnyHit"; const char* kEntryAoClosestHit = "ShadowClosestHit"; }; bool LambertianPlusShadowPass::initialize(RenderContext* pRenderContext, ResourceManager::SharedPtr pResManager) { // Keep a copy of our resource manager; request needed buffer resources mpResManager = pResManager; mpResManager->requestTextureResources({ "WorldPosition", "WorldNormal", "MaterialDiffuse" }); mpResManager->requestTextureResource(ResourceManager::kOutputChannel); // Set the default scene to load mpResManager->setDefaultSceneName("Data/pink_room/pink_room.fscene"); // Create our wrapper around a ray tracing pass. Tell it where our shaders are, then compile/link the program mpRays = RayLaunch::create(kFileRayTrace, kEntryPointRayGen); mpRays->addMissShader(kFileRayTrace, kEntryPointMiss0); mpRays->addHitShader(kFileRayTrace, kEntryAoClosestHit, kEntryAoAnyHit); mpRays->compileRayProgram(); if (mpScene) mpRays->setScene(mpScene); return true; } void LambertianPlusShadowPass::initScene(RenderContext* pRenderContext, Scene::SharedPtr pScene) { // Stash a copy of the scene and pass it to our ray tracer (if initialized) mpScene = std::dynamic_pointer_cast<RtScene>(pScene); if (mpRays) mpRays->setScene(mpScene); } void LambertianPlusShadowPass::execute(RenderContext* pRenderContext) { // Get the output buffer we're writing into; clear it to black. Texture::SharedPtr pDstTex = mpResManager->getClearedTexture(ResourceManager::kOutputChannel, vec4(0.0f, 0.0f, 0.0f, 0.0f)); // Do we have all the resources we need to render? If not, return if (!pDstTex || !mpRays || !mpRays->readyToRender()) return; // Set our ray tracing shader variables auto rayGenVars = mpRays->getRayGenVars(); rayGenVars["RayGenCB"]["gMinT"] = mpResManager->getMinTDist(); // Pass our G-buffer textures down to the HLSL so we can shade rayGenVars["gPos"] = mpResManager->getTexture("WorldPosition"); rayGenVars["gNorm"] = mpResManager->getTexture("WorldNormal"); rayGenVars["gDiffuseMatl"] = mpResManager->getTexture("MaterialDiffuse"); rayGenVars["gOutput"] = pDstTex; // Shoot our rays and shade our primary hit points mpRays->execute( pRenderContext, mpResManager->getScreenSize() ); }
51.390244
125
0.726863
[ "render" ]
60dc2599fbf49238a4a7ca025a21a630dc1b4a63
11,958
cpp
C++
hpc/L2/src/sw/mlp/api_fcn_multiInstr.cpp
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
4
2021-08-16T18:25:48.000Z
2022-03-22T08:49:43.000Z
mlp/gemm_based_fcn_designs/sw/src/api_fcn_multiInstr.cpp
Xilinx/HPC
c5d11c41f98a6ce8fc4a3fc9e7f5a133a09a9af3
[ "Apache-2.0" ]
null
null
null
mlp/gemm_based_fcn_designs/sw/src/api_fcn_multiInstr.cpp
Xilinx/HPC
c5d11c41f98a6ce8fc4a3fc9e7f5a133a09a9af3
[ "Apache-2.0" ]
1
2021-04-28T05:58:38.000Z
2021-04-28T05:58:38.000Z
/* * Copyright 2019 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <string> #include <fstream> #include <iostream> #include <sstream> #include <vector> #include <iomanip> #include <chrono> #include <stdio.h> // fgets for popen #include "gen_fcn.hpp" #include "fcn_api_test.hpp" int main(int argc, char** argv) { //############ UI and FCN problem size ############ if (argc < 6) { std::cerr << "Usage:\n" << " mlp_api_fcn_multiInstr.exe <path/mlp.xclbin> [M K N LdA LdB LdC LdX postScaleVal " "postScaleShift PReluScale PReluAlpha HandleA HandleB HandleC HandleX]\n" << " mlp_api_fcn_multiInstr.exe <path/mlp.xclbin> [M K N matAFile matBFile matXFile HandleA " "HandleB HandleC HandleX] \n"; exit(2); } unsigned int l_argIdx = 1; std::string l_xclbinFile(argv[l_argIdx]); unsigned int l_instrCount = 0; bool readFromFiles = 0; if ((argc - 2) % 10 == 0) { readFromFiles = 1; l_instrCount = ((argc - 2) / 10 > 1) ? ((argc - 2) / 10) : 1; // number of instructions } else if ((argc - 2) % 15 == 0) { l_instrCount = ((argc - 2) / 15 > 1) ? ((argc - 2) / 15) : 1; // number of instructions } else { std::cerr << " For each instruction, [M K N LdA LdB LdC LdX postScaleVal postScaleShift PReluScale " "PReluAlpha HandleA HandleB HandleC HandleX] or [M K N matAFile matBFile matXFile HandleA HandleB " "HandleC HandleX] could not be missing\n"; exit(2); } if (l_instrCount > 15) { std::cerr << " Too many instructions at same time\n"; exit(2); } unsigned int l_m[l_instrCount]; unsigned int l_k[l_instrCount]; unsigned int l_n[l_instrCount]; unsigned int l_lda[l_instrCount]; unsigned int l_ldb[l_instrCount]; unsigned int l_ldc[l_instrCount]; unsigned int l_ldx[l_instrCount]; int32_t l_postScaleVal; int32_t l_postScaleShift; int32_t l_postScale[l_instrCount]; int16_t l_PReluScale; int16_t l_PReluAlpha; int16_t l_PReluVal[l_instrCount]; std::string l_handleA[l_instrCount]; std::string l_handleB[l_instrCount]; std::string l_handleC[l_instrCount]; std::string l_handleX[l_instrCount]; std::string l_insFileName[l_instrCount]; std::string l_matAFileName[l_instrCount]; std::string l_matBFileName[l_instrCount]; std::string l_matXFileName[l_instrCount]; std::cout << "FCN C++ API example using accelerator image " << l_xclbinFile << std::endl; ProgramType l_program[BLAS_numKernels]; ProgramType l_program_golden; GenFcn l_fcn; // unsigned long int l_Ops[l_instrCount]; //operations carried out by each kernel for (int i = 0; i < BLAS_numKernels; i++) { l_argIdx = 2; for (unsigned int index = 0; index < l_instrCount; index++) { if (readFromFiles) { l_m[index] = atoi(argv[l_argIdx++]); l_k[index] = atoi(argv[l_argIdx++]); l_n[index] = atoi(argv[l_argIdx++]); l_matAFileName[index] = argv[l_argIdx++]; l_matBFileName[index] = argv[l_argIdx++]; l_matXFileName[index] = argv[l_argIdx++]; if (l_matAFileName[index] == "null") { l_matAFileName[index] = ""; } l_handleA[index] = argv[l_argIdx++]; l_handleB[index] = argv[l_argIdx++]; l_handleC[index] = argv[l_argIdx++]; l_handleX[index] = argv[l_argIdx++]; l_fcn.addInstrFromPython(l_program[i], l_m[index], l_k[index], l_n[index], l_matAFileName[index], l_matBFileName[index], l_matXFileName[index], l_handleA[index], l_handleB[index], l_handleC[index], l_handleX[index], false); } else { l_m[index] = atoi(argv[l_argIdx++]); l_k[index] = atoi(argv[l_argIdx++]); l_n[index] = atoi(argv[l_argIdx++]); l_lda[index] = atoi(argv[l_argIdx++]); l_ldb[index] = atoi(argv[l_argIdx++]); l_ldc[index] = atoi(argv[l_argIdx++]); l_ldx[index] = atoi(argv[l_argIdx++]); l_postScaleVal = atoi(argv[l_argIdx++]); l_postScaleShift = atoi(argv[l_argIdx++]); l_postScale[index] = (l_postScaleVal << 8) | (l_postScaleShift & 0x000000ff); l_PReluScale = atoi(argv[l_argIdx++]); l_PReluAlpha = atoi(argv[l_argIdx++]); l_PReluVal[index] = (l_PReluScale << 6) | (l_PReluAlpha & 0x003f); l_handleA[index] = argv[l_argIdx++]; l_handleB[index] = argv[l_argIdx++]; l_handleC[index] = argv[l_argIdx++]; l_handleX[index] = argv[l_argIdx++]; if (!l_fcn.check(l_m[index], l_k[index], l_n[index], l_lda[index], l_ldb[index], l_ldc[index], l_ldx[index])) { return EXIT_FAILURE; } l_fcn.addInstr(l_program[i], l_m[index], l_k[index], l_n[index], l_lda[index], l_ldb[index], l_ldc[index], l_ldx[index], l_postScale[index], l_PReluVal[index], l_handleA[index], l_handleB[index], l_handleC[index], l_handleX[index], false); } } } // golden program l_argIdx = 2; std::cout << "Calculate golden result on host, for large matrix size, this will take long time.\n" << std::endl; if (!getenv("SKIPPED_GOLD_CAL")) { for (unsigned int index = 0; index < l_instrCount; index++) { if (readFromFiles) { l_fcn.addInstrFromPython(l_program_golden, l_m[index], l_k[index], l_n[index], l_matAFileName[index], l_matBFileName[index], l_matXFileName[index], l_handleA[index], l_handleB[index], l_handleC[index], l_handleX[index], true); } else { l_fcn.addInstr(l_program_golden, l_m[index], l_k[index], l_n[index], l_lda[index], l_ldb[index], l_ldc[index], l_ldx[index], l_postScale[index], l_PReluVal[index], l_handleA[index], l_handleB[index], l_handleC[index], l_handleX[index], true); } } } std::string kernelNames[BLAS_numKernels]; xf::blas::MemDesc l_memDesc[BLAS_numKernels]; for (int i = 0; i < BLAS_numKernels; ++i) { l_memDesc[i] = l_program[i].getMemDesc(); } //############ Run FPGA accelerator ############ double l_timeApiInMs = run_hw_test(l_xclbinFile, l_program); //############ Get the exact kernel time from HW cycle counters on the accelerator ############ float l_boardFreqMHz = getBoardFreqMHz(l_xclbinFile); // unsigned long int l_Ops = 2ull * l_m * l_n * l_k * 2; //operations carried out by each kernel KargsType l_kargsRes[BLAS_numKernels]; KargsOpType l_op; xf::blas::InstrResArgs l_instrRes; unsigned long int l_cycleCount; unsigned long int l_maxCycleCount[l_instrCount] = {0}; double l_timeKernelInMs; double l_maxTimeKernelInMs[l_instrCount] = {0}; double l_perfKernelInTops[l_instrCount]; double l_perfApiInTops; double l_timeMsAt100pctEff; double l_timeMsAt100pctEffKernel; double l_effKernelPct; double l_effApiPct; unsigned long int l_total_Op[l_instrCount]; unsigned long int l_total_Ops = 0; unsigned long int l_total_parallel_Op[l_instrCount]; unsigned long int l_total_parallel_Ops = 0; for (unsigned int j = 0; j < l_instrCount; ++j) { l_total_Op[j] = 2ull * l_m[j] * l_n[j] * l_k[j] + l_m[j] * l_n[j] * 3; l_total_Ops += 2ull * l_m[j] * l_n[j] * l_k[j] + l_m[j] * l_n[j] * 3; l_total_parallel_Op[j] = 2ull * l_m[j] * l_k[j] * l_n[j]; l_total_parallel_Ops += 2ull * l_m[j] * l_k[j] * l_n[j]; } for (int i = 0; i < BLAS_numKernels; ++i) { for (unsigned int j = 0; j < l_instrCount; ++j) { // number of instructions l_op = l_kargsRes[i].load(l_program[i].getBaseResAddr(), j * l_kargsRes[i].getInstrWidth()); assert(l_op == KargsType::OpResult); l_instrRes = l_kargsRes[i].getInstrResArgs(); l_cycleCount = l_instrRes.getDuration(); std::cout << std::string("cycles in kernel ") << i << " " << l_cycleCount << std::endl; l_maxCycleCount[j] = (l_cycleCount > l_maxCycleCount[j]) ? l_cycleCount : l_maxCycleCount[j]; l_timeKernelInMs = l_maxCycleCount[j] / (l_boardFreqMHz * 1e6) * 1e3; l_maxTimeKernelInMs[j] = (l_timeKernelInMs > l_maxTimeKernelInMs[j]) ? l_timeKernelInMs : l_maxTimeKernelInMs[j]; l_perfKernelInTops[j] = l_total_Op[j] / (l_maxTimeKernelInMs[j] * 1e-3) / 1e12; } } // Show time, Tops in csv format if (readFromFiles) { std::cout << std::string("DATA_CSV:,DdrWidth,Freq,") + "Ops,KernelCycles," + "TimeKernelMs,TimeApiMs," + "EffKernelPct,EffApiPct," + "PerfKernelTops,PerfApiTops\n"; for (unsigned int i = 0; i < l_instrCount; ++i) { std::cout << "DATA_CSV:," << BLAS_ddrWidth << "," << l_boardFreqMHz << "," << l_maxCycleCount[i] << "," << l_maxTimeKernelInMs[i] << "," << l_timeApiInMs << std::endl; } } else { std::cout << std::string("DATA_CSV:,DdrWidth,Freq,M,K,N,") + "Ops,KernelCycles," + "TimeKernelMs,TimeApiMs," + "EffKernelPct,EffApiPct," + "PerfKernelTops,PerfApiTops\n"; for (unsigned int i = 0; i < l_instrCount; ++i) { l_perfApiInTops = (l_total_Ops * BLAS_numKernels) / (l_timeApiInMs * 1e-3) / 1e12; l_timeMsAt100pctEff = (l_total_parallel_Ops * BLAS_numKernels) / 2 / BLAS_ddrWidth / BLAS_ddrWidth / (l_boardFreqMHz * 1e6) * 1e3; l_timeMsAt100pctEffKernel = l_total_parallel_Op[i] / 2 / BLAS_ddrWidth / BLAS_ddrWidth / (l_boardFreqMHz * 1e6) * 1e3; l_effKernelPct = 100 * l_timeMsAt100pctEffKernel / l_maxTimeKernelInMs[i]; l_effApiPct = 100 * l_timeMsAt100pctEff / l_timeApiInMs; std::cout << "DATA_CSV:," << BLAS_ddrWidth << "," << l_boardFreqMHz << "," << l_m[i] << "," << l_k[i] << "," << l_n[i] << "," << l_total_Op[i] << "," << l_maxCycleCount[i] << "," << l_maxTimeKernelInMs[i] << "," << l_timeApiInMs << "," << l_effKernelPct << "," << l_effApiPct << "," << l_perfKernelInTops[i] << "," << l_perfApiInTops << std::endl; } } //############ Compare tha FPGA results with the reference results ############ // Calculate reference C = A * B // Since the reference is not needed on the acclerator allocate memory in any way if (!getenv("SKIPPED_GOLD_CAL")) { float l_TolRel = 1e-3, l_TolAbs = 1e-5; compareMultiInstrs(l_TolRel, l_TolAbs, l_program_golden, l_program[0]); } else { std::cout << "INFO: skipped gold calculation on host since it may take too long\n" << std::endl; } return EXIT_SUCCESS; }
47.452381
120
0.585215
[ "vector" ]
60dffabc508c4462d212c75e9ade66e6242df436
172
cpp
C++
tests/dump_files_for_tests/test_it_quaternion_addition_3.cpp
unl-nimbus-lab/phriky-units
16c8cdd91de0899411b139e5a94fcb4ea8104ad2
[ "MIT" ]
22
2017-07-18T09:39:34.000Z
2021-09-16T09:41:03.000Z
tests/dump_files_for_tests/test_it_quaternion_addition_3.cpp
unl-nimbus-lab/phriky-units
16c8cdd91de0899411b139e5a94fcb4ea8104ad2
[ "MIT" ]
9
2016-09-04T13:33:15.000Z
2018-01-05T22:39:03.000Z
tests/dump_files_for_tests/test_it_quaternion_addition_3.cpp
unl-nimbus-lab/phriky-units
16c8cdd91de0899411b139e5a94fcb4ea8104ad2
[ "MIT" ]
4
2016-12-07T16:34:57.000Z
2019-04-03T06:51:55.000Z
#include <ros/ros.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> int main(int argc, char **argv) { tf2::Transform tf; float f = 42.0 + tf.getRotation().getW(); }
19.111111
48
0.686047
[ "transform" ]
60e3a07164412213d3625bfa463d052d32084060
4,411
hpp
C++
Sources/VectorSpaces/vector_space.hpp
j042/SplineLib
db92df816b9af44f2d4f4275897f9ed3341a6646
[ "MIT" ]
null
null
null
Sources/VectorSpaces/vector_space.hpp
j042/SplineLib
db92df816b9af44f2d4f4275897f9ed3341a6646
[ "MIT" ]
null
null
null
Sources/VectorSpaces/vector_space.hpp
j042/SplineLib
db92df816b9af44f2d4f4275897f9ed3341a6646
[ "MIT" ]
null
null
null
/* Copyright (c) 2018–2021 SplineLib Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SOURCES_VECTORSPACES_VECTOR_SPACE_HPP_ #define SOURCES_VECTORSPACES_VECTOR_SPACE_HPP_ #include <algorithm> #include <array> #include <functional> #include <tuple> #include <utility> #include <vector> #include "Sources/Utilities/error_handling.hpp" #include "Sources/Utilities/named_type.hpp" #include "Sources/Utilities/numeric_operations.hpp" #include "Sources/Utilities/std_container_operations.hpp" #include "Sources/Utilities/string_operations.hpp" namespace splinelib::sources::vector_spaces { template<int dimensionality> class VectorSpace; template<int dimensionality> bool IsEqual(VectorSpace<dimensionality> const &lhs, VectorSpace<dimensionality> const &rhs, Tolerance const &tolerance = kEpsilon); template<int dimensionality> bool operator==(VectorSpace<dimensionality> const &lhs, VectorSpace<dimensionality> const &rhs); // VectorSpaces group coordinates. // // Example: // using VectorSpace3d = VectorSpace<3>; // using Coordinate = VectorSpace3d::Coordinate_; // using ScalarCoordinate = Coordinate::value_type; // ScalarCoordinate const k0_0{}, k1_0{1.0}; // VectorSpace3d const vector_space{{{k0_0, k0_0, k0_0}, {k1_0, k0_0, k0_0}, {k0_0, k1_0, k0_0}, {k1_0, k1_0, k0_0}}}; // int const &four = vector_space.GetNumberOfCoordinates(); // Coordinate const &coordinate = vector_space[Index{1}]; // Coordinate P_1 = {1.0, 0.0, 0.0}. // ScalarCoordinate const &one_point_zero = vector_space.DetermineMaximumDistanceFromOrigin(); template<int dimensionality> class VectorSpace { private: template<typename Type, size_t size> using Array_ = std::array<Type, size>; template<typename Type> using Vector_ = std::vector<Type>; public: using Coordinate_ = Array_<Coordinate, dimensionality>; using Coordinates_ = Vector_<Coordinate_>; using OutputInformation_ = std::tuple<Vector_<StringArray<dimensionality>>>; VectorSpace() = default; explicit VectorSpace(Coordinates_ coordinates); VectorSpace(VectorSpace const &other) = default; VectorSpace(VectorSpace &&other) noexcept = default; VectorSpace & operator=(VectorSpace const &rhs) = default; VectorSpace & operator=(VectorSpace &&rhs) noexcept = default; virtual ~VectorSpace() = default; // Comparison based on tolerance. friend bool IsEqual<dimensionality>(VectorSpace const &lhs, VectorSpace const &rhs, Tolerance const &tolerance); // Comparison based on numeric_operations::GetEpsilon<Tolerance>(). friend bool operator==<dimensionality>(VectorSpace const &lhs, VectorSpace const &rhs); virtual Coordinate_ const & operator[](Index const &coordinate) const; virtual int GetNumberOfCoordinates() const; virtual void Replace(Index const &coordinate_index, Coordinate_ coordinate); virtual void Insert(Index const &coordinate_index, Coordinate_ coordinate); virtual void Erase(Index const &coordinate_index); virtual Coordinate DetermineMaximumDistanceFromOrigin(Tolerance const &tolerance = kEpsilon) const; virtual OutputInformation_ Write(Precision const &precision = kPrecision) const; protected: Coordinates_ coordinates_; private: #ifndef NDEBUG void ThrowIfIndexIsInvalid(Index const &coordinate) const; #endif }; #include "Sources/VectorSpaces/vector_space.inc" } // namespace splinelib::sources::vector_spaces #endif // SOURCES_VECTORSPACES_VECTOR_SPACE_HPP_
43.245098
120
0.781002
[ "vector" ]
60e3e9466094e8e429ee4d4718fb53d8ee8ebd25
257
cpp
C++
casbin/ip_parser/parser/allFF.cpp
PDLdeLange/casbin-cpp
b84ed3495258c7a4777e5ade958546ac19706750
[ "Apache-2.0" ]
null
null
null
casbin/ip_parser/parser/allFF.cpp
PDLdeLange/casbin-cpp
b84ed3495258c7a4777e5ade958546ac19706750
[ "Apache-2.0" ]
null
null
null
casbin/ip_parser/parser/allFF.cpp
PDLdeLange/casbin-cpp
b84ed3495258c7a4777e5ade958546ac19706750
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #ifndef ALLFF_CPP #define ALLFF_CPP #include "./allFF.h" bool allFF(vector<byte> b) { for(int i = 0 ; i < b.size() ; i++){ if(b[i] != 0xff) { return false; } } return true; } #endif // ALLFF_CPP
13.526316
40
0.513619
[ "vector" ]
60e41e56dfa2629eec0f17fd4290924b81b49adb
12,556
cpp
C++
chess_md2.cpp
matthiascy/Chess3D
c1e323fd90c300085849b00c81eb4699059becf7
[ "MIT" ]
1
2015-09-06T15:29:41.000Z
2015-09-06T15:29:41.000Z
chess_md2.cpp
matthiascy/Chess3D
c1e323fd90c300085849b00c81eb4699059becf7
[ "MIT" ]
null
null
null
chess_md2.cpp
matthiascy/Chess3D
c1e323fd90c300085849b00c81eb4699059becf7
[ "MIT" ]
null
null
null
#include "chess_md2.h" #include <cstdio> #include <cmath> #include <cfloat> const float SPHERE_PADDING = 10.0; typedef struct { int numVerts; int numTris; int numFrames; GLfloat minY; Sphere boundingSphere; } ModelInfo; bool loadModel(char *filename, Vertex* &verts, Mesh* &tris, TexCoord* &texCoords, ModelInfo &info, GLfloat scale); void CalculateBoundingSphere(Sphere &sphere, GLfloat miny, GLfloat maxy); MD2Instance::MD2Instance() { currentFrame = 0; // current keyframe nextFrame = 1; // next keyframe interpolation = 0.0; // interpolation percent currentVerts = NULL; aniState = IDLE; rotateAngle = 0.0; data = NULL; numWeaponVertices = 0; numVertices = 0; } MD2Instance::~MD2Instance() { unload(); } void MD2Instance::setAnimation(int state, int nextState) { switch (state) { case RUN: { startFrame = 40; endFrame = 45; } break; case ATTACK: { startFrame = 46; endFrame = 53; } break; case PAIN1: { startFrame = 54; endFrame = 57; } break; case PAIN2: { startFrame = 58; endFrame = 61; } break; case PAIN3: { startFrame = 62; endFrame = 65; } break; case JUMP: { startFrame = 66; endFrame = 71; } break; case FLIPOFF: { startFrame = 72; endFrame = 83; } break; case SAULTE: { startFrame = 84; endFrame = 94; } break; case TAUNT: { startFrame = 95; endFrame = 111; } break; case WAVE: { startFrame = 112; endFrame = 122; } break; case POINT: { startFrame = 123; endFrame = 134; } break; case CROUCH_IDLE: { startFrame = 135; endFrame = 153; } break; case CROUCH_WALK: { startFrame = 154; endFrame = 159; } break; case CROUCH_ATTACK: { startFrame = 160; endFrame = 168; } break; case CROUCH_PAIN: { startFrame = 169; endFrame = 172; } break; case CROUCH_DEATH: { startFrame = 173; endFrame = 177; } break; case DEATH1: { startFrame = 178; endFrame = 183; } break; case DEATH2: { startFrame = 184; endFrame = 189; } break; case DEATH3: { startFrame = 190; endFrame = 197; } break; case IDLE: { startFrame = 0; endFrame = 39; } break; default: return; } if (aniState != state) { currentFrame = startFrame; nextFrame = startFrame + 1; } aniState = state; nextAniState = nextState; } void MD2Instance::setAnimationCustom(int start, int end) { if (start < 0) start = 0; if (start >= numFrames) start = numFrames - 1; if (end < 0) end = 0; if (end >= numFrames) end = numFrames - 1; startFrame = start; endFrame = end; aniState = _CUSTOM; nextAniState = _CUSTOM; } void MD2Instance::animate(float seconds) { if (startFrame > currentFrame) currentFrame = startFrame; if (startFrame < 0 || endFrame < 0) return; if (startFrame >= numFrames || endFrame >= numFrames) return; // increase percentage of interpolation between frames interpolation += KEYFRAMES_PER_S * seconds; if (interpolation >= 1.0) { interpolation = 0.0f; currentFrame++; nextFrame = currentFrame + 1; if (currentFrame > endFrame) { if (nextAniState == _REPEAT || aniState == _CUSTOM) { currentFrame = startFrame; nextFrame = currentFrame + 1; } else if (nextAniState == _STATIC) { currentFrame = nextFrame = startFrame = endFrame; aniState = _STATIC; } else { setAnimation(nextAniState, _REPEAT); } } if (nextFrame > endFrame) nextFrame = startFrame; } if ((nextAniState == _STATIC) && (nextFrame == startFrame)) nextFrame = endFrame; data->animate(currentVerts, weaponVerts, currentFrame, nextFrame, interpolation); } void MD2Instance::render() { glPushMatrix(); glTranslatef(pos.x, pos.y, pos.z); glRotatef(rotateAngle, 0, 1, 0); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_FLOAT, 0, currentVerts); glTexCoordPointer(2, GL_FLOAT, 0, data->texCoords); glBindTexture(GL_TEXTURE_2D, data->texID); glDrawArrays(GL_TRIANGLES, 0, numVertices); if (weaponVerts) { glVertexPointer(3, GL_FLOAT, 0, weaponVerts); glTexCoordPointer(2, GL_FLOAT, 0, data->weaponTexCoords); glBindTexture(GL_TEXTURE_2D, data->weaponTexID); glDrawArrays(GL_TRIANGLES, 0, numWeaponVertices); } glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glPopMatrix(); } // unload() // desc: unloads model data from memory void MD2Instance::unload() { delete [] currentVerts; currentVerts = NULL; delete [] weaponVerts; weaponVerts = NULL; } void MD2Instance::move(GLfloat x, GLfloat y, GLfloat z) { pos.x = x; pos.y = y - miny; pos.z = z; boundingSphere.center.x = x; boundingSphere.center.y = y + boundingSphere.radius - SPHERE_PADDING; boundingSphere.center.z = z; } // MD2Data constructor MD2Data::MD2Data() { tris = NULL; // triangle indices texCoords = NULL; // texture coordinate indices verts = NULL; // vertices texID = 0; // skin/texture numVerts = 0; numTris = 0; numFrames = 0; weaponTris = NULL; weaponTexCoords = NULL; weaponVerts = NULL; numWeaponVerts = 0; numWeaponTris = 0; weaponTexID = 0; } // MD2Data destructor MD2Data::~MD2Data() { unload(); } // MD2Data::load() // access: public // desc: loads model and skin bool MD2Data::load(char *modelFile, char *skinFile, char *weaponFile, char *weaponSkin, float scale) { ModelInfo info; loadModel(modelFile, verts, tris, texCoords, info, scale); numVerts = info.numVerts; numTris = info.numTris; numFrames = info.numFrames; miny = info.minY; boundingSphere = info.boundingSphere; if (weaponFile) { loadModel(weaponFile, weaponVerts, weaponTris, weaponTexCoords, info, scale); numWeaponVerts = info.numVerts; numWeaponTris = info.numTris; } TargaImage image; image.load(skinFile); glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_2D, texID); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, image.getWidth(), image.getHeight(), GL_RGB, GL_UNSIGNED_BYTE, image.getImage()); image.release(); if (weaponSkin) { image.load(weaponSkin); glGenTextures(1, &weaponTexID); glBindTexture(GL_TEXTURE_2D, weaponTexID); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, image.getWidth(), image.getHeight(), GL_RGB, GL_UNSIGNED_BYTE, image.getImage()); image.release(); } return true; } MD2Instance* MD2Data::getInstance() { MD2Instance *instance = new MD2Instance(); instance->currentVerts = new Vertex[numTris * 3]; instance->weaponVerts = new Vertex[numWeaponTris * 3]; instance->currentFrame = 0; instance->nextFrame = 1; instance->interpolation = 0.0; instance->numFrames = numFrames; instance->numVertices = numTris * 3; instance->numWeaponVertices = numWeaponTris * 3; instance->data = this; instance->boundingSphere = boundingSphere; instance->miny = miny; // animate at least one frame to make sure that currentVerts gets initialized instance->setAnimation(MD2Instance::IDLE); instance->animate(0); return instance; } void MD2Data::animate(Vertex *pVerts, Vertex *pWeaponVerts, int curFrame, int nextFrame, float interpol) { Vertex *vList; // current frame vertices Vertex *nextVList; // next frame vertices int i; // index counter float x1, y1, z1; // current frame point values float x2, y2, z2; // next frame point values vList = &verts[numVerts * curFrame]; nextVList = &verts[numVerts * nextFrame]; for (i = 0; i < numTris * 3; i++) { Vertex &vertex = pVerts[i]; // get first points of each frame x1 = vList[tris[i/3].meshIndex[i%3]].x; y1 = vList[tris[i/3].meshIndex[i%3]].y; z1 = vList[tris[i/3].meshIndex[i%3]].z; x2 = nextVList[tris[i/3].meshIndex[i%3]].x; y2 = nextVList[tris[i/3].meshIndex[i%3]].y; z2 = nextVList[tris[i/3].meshIndex[i%3]].z; // store first interpolated vertex of triangle vertex.x = x1 + interpol * (x2 - x1); vertex.y = y1 + interpol * (y2 - y1); vertex.z = z1 + interpol * (z2 - z1); } if (weaponVerts) { vList = &weaponVerts[numWeaponVerts * curFrame]; nextVList = &weaponVerts[numWeaponVerts * nextFrame]; for (i = 0; i < numWeaponTris * 3; i++) { Vertex &vertex = pWeaponVerts[i]; // get first points of each frame x1 = vList[weaponTris[i/3].meshIndex[i%3]].x; y1 = vList[weaponTris[i/3].meshIndex[i%3]].y; z1 = vList[weaponTris[i/3].meshIndex[i%3]].z; x2 = nextVList[weaponTris[i/3].meshIndex[i%3]].x; y2 = nextVList[weaponTris[i/3].meshIndex[i%3]].y; z2 = nextVList[weaponTris[i/3].meshIndex[i%3]].z; // store first interpolated vertex of triangle vertex.x = x1 + interpol * (x2 - x1); vertex.y = y1 + interpol * (y2 - y1); vertex.z = z1 + interpol * (z2 - z1); } } } // unload() // desc: unloads model data from memory void MD2Data::unload() { delete [] tris; tris = NULL; delete [] verts; verts = NULL; delete [] texCoords; texCoords = NULL; delete [] weaponTris; weaponTris = NULL; delete [] weaponVerts; weaponVerts = NULL; delete [] weaponTexCoords; weaponTexCoords = NULL; glDeleteTextures(1, &texID); } bool loadModel(char *filename, Vertex* &verts, Mesh* &tris, TexCoord* &texCoords, ModelInfo &info, GLfloat scale) { // open the model file FILE *file = fopen(filename, "rb"); if (file == NULL) return false; ModelHeader header; fread(&header, sizeof(ModelHeader), 1, file); verts = new Vertex[header.numVerts * header.numFrames]; info.numVerts = header.numVerts; info.numTris = header.numTris; info.numFrames = header.numFrames; char *buffer = new char[header.numFrames * header.framesize]; fseek(file, header.offsetFrames, SEEK_SET); fread(buffer, header.numFrames, header.framesize, file); int i, j; Frame *frame; Vertex *pVerts; info.minY = FLT_MAX; GLfloat maxy = FLT_MIN; for (j = 0; j < header.numFrames; ++j) { frame = (Frame*)&buffer[header.framesize * j]; pVerts = (Vertex*)&verts[header.numVerts * j]; for (i = 0; i < header.numVerts; i++) { pVerts[i].x = scale * (frame->scale[0] * frame->fp[i].v[0] + frame->translate[0]); pVerts[i].z = scale * (frame->scale[1] * frame->fp[i].v[1] + frame->translate[1]); pVerts[i].y = scale * (frame->scale[2] * frame->fp[i].v[2] + frame->translate[2]); if (j == 0) { if (pVerts[i].y < info.minY) info.minY = pVerts[i].y; if (pVerts[i].y > maxy) maxy = pVerts[i].y; } } } CalculateBoundingSphere(info.boundingSphere, info.minY, maxy); tris = new Mesh[header.numTris]; fseek(file, header.offsetTris, SEEK_SET); fread(tris, header.numTris, sizeof(Mesh), file); TexCoordIdx *stTemp = new TexCoordIdx[header.numTex]; texCoords = new TexCoord[header.numTris * 3]; fseek(file, header.offsetTex, SEEK_SET); fread(stTemp, header.numTex, sizeof(TexCoordIdx), file); int index = 0; for (i = 0; i < header.numTris; i++) { texCoords[index].s = (float)stTemp[tris[i].texIndex[0]].s / header.skinwidth; texCoords[index++].t = 1.0f - (float)stTemp[tris[i].texIndex[0]].t / header.skinheight; texCoords[index].s = (float)stTemp[tris[i].texIndex[1]].s / header.skinwidth; texCoords[index++].t = 1.0f - (float)stTemp[tris[i].texIndex[1]].t / header.skinheight; texCoords[index].s = (float)stTemp[tris[i].texIndex[2]].s / header.skinwidth; texCoords[index++].t = 1.0f - (float)stTemp[tris[i].texIndex[2]].t / header.skinheight; } // close file and free memory fclose(file); delete[] buffer; return true; } // this is a bit of a hack, since the sphere isn't guaranteed to completely // surround the model. However, the results for this demo are satisfactory void CalculateBoundingSphere(Sphere &sphere, GLfloat miny, GLfloat maxy) { sphere.center.x = 0; sphere.center.y = (maxy + miny) / 2.0f; sphere.center.z = 0; sphere.radius = maxy - sphere.center.y + SPHERE_PADDING; }
24.667976
91
0.633402
[ "mesh", "render", "model" ]
60e58f9b26b1625cccd793721bd56856b0424a7c
3,592
cc
C++
src/input/pointcloud_helpers.cc
ut-amrl/nautilus
d7c1f5b03e7bea54be87565da2a8845b044a28b5
[ "MIT" ]
1
2021-07-31T19:17:15.000Z
2021-07-31T19:17:15.000Z
src/input/pointcloud_helpers.cc
ut-amrl/nautilus
d7c1f5b03e7bea54be87565da2a8845b044a28b5
[ "MIT" ]
9
2020-08-27T20:49:50.000Z
2020-10-25T22:40:49.000Z
src/input/pointcloud_helpers.cc
ut-amrl/nautilus
d7c1f5b03e7bea54be87565da2a8845b044a28b5
[ "MIT" ]
null
null
null
// // Created by jack on 9/15/19. // #include "./pointcloud_helpers.h" #include <glog/logging.h> #include <numeric> #include "../util/kdtree.h" #include "../util/math_util.h" #include "eigen3/Eigen/Dense" #include "ros/package.h" #include "sensor_msgs/PointCloud2.h" namespace nautilus { using Eigen::Matrix2f; using Eigen::Rotation2D; using Eigen::Vector2f; using math_util::NormalsSimilar; using ros::Publisher; using sensor_msgs::PointCloud2; using std::pair; using std::vector; vector<Vector2f> LaserScanToPointCloud(const sensor_msgs::LaserScan &laser_scan, double max_range) { vector<Vector2f> pointcloud; float angle_offset = laser_scan.range_min; for (size_t index = 0; index < laser_scan.ranges.size(); index++) { float range = laser_scan.ranges[index]; if (range >= laser_scan.range_min && range <= max_range) { // Only accept valid ranges. // Then we must rotate the point by the specified angle at that distance. Vector2f point(range, 0.0); Matrix2f rot_matrix = Rotation2D<float>(laser_scan.angle_min + (laser_scan.angle_increment * index)) .toRotationMatrix(); point = rot_matrix * point; pointcloud.emplace_back(point); } angle_offset += laser_scan.angle_increment; } return pointcloud; } void InitPointcloud(PointCloud2 *point) { CHECK_NOTNULL(point); std::string arr[3] = {"x", "y", "z"}; point->header.seq = 1; point->header.stamp = ros::Time::now(); point->header.frame_id = "map"; sensor_msgs::PointField field; int offset = 0; field.datatype = 7; field.count = 1; for (std::string type : arr) { field.offset = offset; field.name = type; point->fields.push_back(field); offset += 4; } point->height = 1; point->width = 0; point->is_bigendian = false; point->point_step = 12; point->row_step = 0; point->is_dense = true; } void PushBackBytes(float val, sensor_msgs::PointCloud2 *ptr) { CHECK_NOTNULL(ptr); uint8_t *data_ptr = reinterpret_cast<uint8_t *>(&val); for (int i = 0; i < 4; i++) { ptr->data.push_back(data_ptr[i]); } } void PublishPointcloud(const vector<Vector2f> &points, PointCloud2 *point_cloud, const Publisher &pub) { CHECK_NOTNULL(point_cloud); for (uint64_t i = 0; i < points.size(); i++) { Vector2f vec = points[i]; PushBackBytes(vec[0], point_cloud); PushBackBytes(vec[1], point_cloud); PushBackBytes(0.0f, point_cloud); } point_cloud->width = points.size(); pub.publish(*point_cloud); point_cloud->width = 0; point_cloud->data.clear(); } PointCloud2 EigenPointcloudToRos(const vector<Vector2f> &pointcloud) { PointCloud2 point_msg; InitPointcloud(&point_msg); for (uint64_t i = 0; i < pointcloud.size(); i++) { Vector2f vec = pointcloud[i]; PushBackBytes(vec[0], &point_msg); PushBackBytes(vec[1], &point_msg); PushBackBytes(0.0f, &point_msg); } point_msg.height = 1; point_msg.width = pointcloud.size(); return point_msg; } std::vector<Vector2f> normalizePointCloud(const vector<Vector2f> &pointcloud, double range) { std::vector<Vector2f> normalized(pointcloud.size()); Vector2f mean = std::accumulate(pointcloud.begin(), pointcloud.end(), Vector2f(0.0f, 0.0f)) / pointcloud.size(); for (uint64_t i = 0; i < pointcloud.size(); i++) { normalized[i] = (pointcloud[i] - mean) / range; } return normalized; } } // namespace nautilus
28.736
80
0.64755
[ "vector" ]
60e652ec7a1fcc0d3844f0254fa6ff6072a861ce
7,189
cc
C++
tensorflow/lite/tools/optimize/calibration/calibrator_test.cc
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
36
2016-12-17T15:25:25.000Z
2022-01-29T21:50:53.000Z
tensorflow/lite/tools/optimize/calibration/calibrator_test.cc
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
59
2019-06-17T09:37:49.000Z
2022-01-19T01:21:34.000Z
tensorflow/lite/tools/optimize/calibration/calibrator_test.cc
PaulWang1905/tensorflow
ebf12d22b4801fb8dab5034cc94562bf7cc33fa0
[ "Apache-2.0" ]
36
2017-07-27T21:12:40.000Z
2022-02-03T16:45:56.000Z
/* Copyright 2018 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 <cstring> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/lite/kernels/register.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/tools/optimize/calibration/calibrator.h" namespace { tensorflow::string* g_test_model_file = nullptr; } // namespace namespace tflite { namespace optimize { namespace calibration { namespace { std::unique_ptr<FlatBufferModel> ReadModel() { if (g_test_model_file) { return FlatBufferModel::BuildFromFile(g_test_model_file->c_str()); } return nullptr; } TEST(CalibratorTest, CalibrationStatsAreCollected) { auto model = ReadModel(); ASSERT_TRUE(model); std::unique_ptr<Interpreter> interpreter; std::unique_ptr<CalibrationReader> reader; auto status = BuildLoggingInterpreter( *model, ops::builtin::BuiltinOpResolver{}, &interpreter, &reader); EXPECT_EQ(kTfLiteOk, status); ASSERT_TRUE(interpreter); ASSERT_TRUE(reader); std::unordered_map<int, CalibrationReader::CalibrationStats> stats; status = reader->GetTensorStatsAsMap(&stats); EXPECT_EQ(kTfLiteOk, status); EXPECT_TRUE(stats.empty()); status = interpreter->AllocateTensors(); ASSERT_EQ(kTfLiteOk, status); // Model does the following: // 0 1 2 3 // | |__ ____| | // | | | // | Add(tensor:4) | // |____ ______|______ ______| // | | // Add Add // | | // Output:5 Output:6 const size_t tensor_size = 1 * 8 * 8 * 3; std::vector<float> ones(tensor_size, 1.0f); // Fill input tensor i with i+1, i.e. input[0] = 1.0f, input[1] = 2.0f, // input[2] = 3.0f for (size_t i = 0; i < interpreter->inputs().size(); i++) { int input_tensor_idx = interpreter->inputs()[i]; TfLiteTensor* tensor = interpreter->tensor(input_tensor_idx); ASSERT_EQ(tensor->bytes, tensor_size * sizeof(float)); for (size_t j = 0; j < tensor_size; j++) { tensor->data.f[j] = i + 1; } } status = interpreter->Invoke(); ASSERT_EQ(kTfLiteOk, status); const float eps = 1e-6f; // Verify that tensor 5: is 6 // Verify that tensor 6: is 9 TfLiteTensor* tensor = interpreter->tensor(interpreter->outputs()[0]); for (size_t i = 0; i < tensor_size; i++) { EXPECT_NEAR(tensor->data.f[i], 6.0f, eps); } tensor = interpreter->tensor(interpreter->outputs()[1]); for (size_t i = 0; i < tensor_size; i++) { EXPECT_NEAR(tensor->data.f[i], 9.0f, eps); } // Verify that min max of tensors. status = reader->GetTensorStatsAsMap(&stats); EXPECT_EQ(kTfLiteOk, status); EXPECT_EQ(7, stats.size()); // Check inputs for (int tensor_idx = 0; tensor_idx < 4; tensor_idx++) { EXPECT_NEAR(stats.at(tensor_idx).min, tensor_idx + 1, eps); EXPECT_NEAR(stats.at(tensor_idx).max, tensor_idx + 1, eps); } // Check tensor 4 max. EXPECT_NEAR(stats.at(4).min, 5, eps); EXPECT_NEAR(stats.at(4).max, 5, eps); // Check outputs EXPECT_NEAR(stats.at(5).min, 6, eps); EXPECT_NEAR(stats.at(5).max, 6, eps); EXPECT_NEAR(stats.at(6).min, 9, eps); EXPECT_NEAR(stats.at(6).max, 9, eps); } TEST(CalibratorTest, MultipleInvokes) { auto model = ReadModel(); ASSERT_TRUE(model); std::unique_ptr<Interpreter> interpreter; std::unique_ptr<CalibrationReader> reader; auto status = BuildLoggingInterpreter( *model, ops::builtin::BuiltinOpResolver{}, &interpreter, &reader); EXPECT_EQ(kTfLiteOk, status); ASSERT_TRUE(interpreter); ASSERT_TRUE(reader); status = interpreter->AllocateTensors(); EXPECT_EQ(kTfLiteOk, status); const size_t tensor_size = 1 * 8 * 8 * 3; // Fill input tensor i with i+1, i.e. input[0] = 1.0f, input[1] = 2.0f, // input[2] = 3.0f for (size_t i = 0; i < interpreter->inputs().size(); i++) { int input_tensor_idx = interpreter->inputs()[i]; TfLiteTensor* tensor = interpreter->tensor(input_tensor_idx); ASSERT_EQ(tensor->bytes, tensor_size * sizeof(float)); for (size_t j = 0; j < tensor_size; j++) { tensor->data.f[j] = i + 1; } } status = interpreter->Invoke(); ASSERT_EQ(kTfLiteOk, status); const float eps = 1e-6f; // Verify that min max of tensors. std::unordered_map<int, CalibrationReader::CalibrationStats> stats; status = reader->GetTensorStatsAsMap(&stats); EXPECT_EQ(kTfLiteOk, status); EXPECT_EQ(7, stats.size()); const float expected_values[7] = { 1.0f, // input 0 2.0f, // input 1 3.0f, // input 2 4.0f, // input 3 5.0f, // Add(1, 2) 6.0f, // Output 5: Add(0, Add(1,2)) 9.0f, // Output 6: Add(Add(1,2), 3) }; for (int tensor_idx = 0; tensor_idx < 7; tensor_idx++) { EXPECT_NEAR(stats.at(tensor_idx).min, expected_values[tensor_idx], eps); EXPECT_NEAR(stats.at(tensor_idx).max, expected_values[tensor_idx], eps); } // Set input[0][0] = 1.5 and input[0][1] = 0.5 this should change the values // only for input[0] and tensor 4 and ouputs 5, 6. TfLiteTensor* input0 = interpreter->tensor(0); input0->data.f[0] = 1.5f; input0->data.f[1] = 0.5f; status = interpreter->Invoke(); ASSERT_EQ(kTfLiteOk, status); status = reader->GetTensorStatsAsMap(&stats); EXPECT_EQ(kTfLiteOk, status); EXPECT_EQ(7, stats.size()); EXPECT_NEAR(stats.at(0).min, 0.5f, eps); EXPECT_NEAR(stats.at(0).max, 1.5f, eps); for (int tensor_idx = 1; tensor_idx < 5; tensor_idx++) { EXPECT_NEAR(stats.at(tensor_idx).min, expected_values[tensor_idx], eps); EXPECT_NEAR(stats.at(tensor_idx).max, expected_values[tensor_idx], eps); } EXPECT_NEAR(stats.at(5).min, 5.5f, eps); EXPECT_NEAR(stats.at(5).max, 6.5f, eps); EXPECT_NEAR(stats.at(6).min, 9.0f, eps); EXPECT_NEAR(stats.at(6).max, 9.0f, eps); } } // namespace } // namespace calibration } // namespace optimize } // namespace tflite int main(int argc, char** argv) { tensorflow::string model_file; const std::vector<tensorflow::Flag> flag_list = { tensorflow::Flag("test_model_file", &model_file, "Path to test tflite model file."), }; const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list); if (!parse_result) { std::cerr << "Required test_model_file\n"; std::abort(); } g_test_model_file = new tensorflow::string(model_file); ::tensorflow::port::InitMain(argv[0], &argc, &argv); return RUN_ALL_TESTS(); }
33.751174
80
0.658923
[ "vector", "model" ]
60e7241e290c4c5406a13f1dd075b27d9c5f6873
8,397
cpp
C++
lldb/source/Host/netbsd/HostNetBSD.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
lldb/source/Host/netbsd/HostNetBSD.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
lldb/source/Host/netbsd/HostNetBSD.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
//===-- source/Host/netbsd/HostNetBSD.cpp ---------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <cstdio> #include <dlfcn.h> #include <execinfo.h> #include <sys/proc.h> #include <sys/sysctl.h> #include <sys/types.h> #include <climits> #include <kvm.h> #include <sys/exec.h> #include <sys/ptrace.h> #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/LLDBLog.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/NameMatches.h" #include "lldb/Utility/ProcessInfo.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "llvm/Object/ELF.h" #include "llvm/Support/Host.h" extern "C" { extern char **environ; } using namespace lldb; using namespace lldb_private; namespace lldb_private { class ProcessLaunchInfo; } Environment Host::GetEnvironment() { return Environment(environ); } static bool GetNetBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr, ProcessInstanceInfo &process_info) { if (!process_info.ProcessIDIsValid()) return false; int pid = process_info.GetProcessID(); int mib[4] = {CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ARGV}; char arg_data[8192]; size_t arg_data_size = sizeof(arg_data); if (::sysctl(mib, 4, arg_data, &arg_data_size, NULL, 0) != 0) return false; DataExtractor data(arg_data, arg_data_size, endian::InlHostByteOrder(), sizeof(void *)); lldb::offset_t offset = 0; const char *cstr; cstr = data.GetCStr(&offset); if (!cstr) return false; process_info.GetExecutableFile().SetFile(cstr, FileSpec::Style::native); if (!(match_info_ptr == NULL || NameMatches(process_info.GetExecutableFile().GetFilename().GetCString(), match_info_ptr->GetNameMatchType(), match_info_ptr->GetProcessInfo().GetName()))) return false; process_info.SetArg0(cstr); Args &proc_args = process_info.GetArguments(); while (1) { const uint8_t *p = data.PeekData(offset, 1); while ((p != NULL) && (*p == '\0') && offset < arg_data_size) { ++offset; p = data.PeekData(offset, 1); } if (p == NULL || offset >= arg_data_size) break; cstr = data.GetCStr(&offset); if (!cstr) break; proc_args.AppendArgument(llvm::StringRef(cstr)); } return true; } static bool GetNetBSDProcessCPUType(ProcessInstanceInfo &process_info) { Log *log = GetLog(LLDBLog::Host); if (process_info.ProcessIDIsValid()) { auto buffer_sp = FileSystem::Instance().CreateDataBuffer( process_info.GetExecutableFile(), 0x20, 0); if (buffer_sp) { uint8_t exe_class = llvm::object::getElfArchType( {buffer_sp->GetChars(), size_t(buffer_sp->GetByteSize())}) .first; switch (exe_class) { case llvm::ELF::ELFCLASS32: process_info.GetArchitecture() = HostInfo::GetArchitecture(HostInfo::eArchKind32); return true; case llvm::ELF::ELFCLASS64: process_info.GetArchitecture() = HostInfo::GetArchitecture(HostInfo::eArchKind64); return true; default: LLDB_LOG(log, "Unknown elf class ({0}) in file {1}", exe_class, process_info.GetExecutableFile()); } } } process_info.GetArchitecture().Clear(); return false; } static bool GetNetBSDProcessUserAndGroup(ProcessInstanceInfo &process_info) { ::kvm_t *kdp; char errbuf[_POSIX2_LINE_MAX]; /* XXX: error string unused */ struct ::kinfo_proc2 *proc_kinfo; const int pid = process_info.GetProcessID(); int nproc; if (!process_info.ProcessIDIsValid()) goto error; if ((kdp = ::kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf)) == NULL) goto error; if ((proc_kinfo = ::kvm_getproc2(kdp, KERN_PROC_PID, pid, sizeof(struct ::kinfo_proc2), &nproc)) == NULL) { ::kvm_close(kdp); goto error; } if (nproc < 1) { ::kvm_close(kdp); /* XXX: we don't check for error here */ goto error; } process_info.SetParentProcessID(proc_kinfo->p_ppid); process_info.SetUserID(proc_kinfo->p_ruid); process_info.SetGroupID(proc_kinfo->p_rgid); process_info.SetEffectiveUserID(proc_kinfo->p_uid); process_info.SetEffectiveGroupID(proc_kinfo->p_gid); ::kvm_close(kdp); /* XXX: we don't check for error here */ return true; error: process_info.SetParentProcessID(LLDB_INVALID_PROCESS_ID); process_info.SetUserID(UINT32_MAX); process_info.SetGroupID(UINT32_MAX); process_info.SetEffectiveUserID(UINT32_MAX); process_info.SetEffectiveGroupID(UINT32_MAX); return false; } uint32_t Host::FindProcessesImpl(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) { const ::pid_t our_pid = ::getpid(); const ::uid_t our_uid = ::getuid(); const bool all_users = match_info.GetMatchAllUsers() || // Special case, if lldb is being run as root we can attach to anything (our_uid == 0); kvm_t *kdp; char errbuf[_POSIX2_LINE_MAX]; /* XXX: error string unused */ if ((kdp = ::kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf)) == NULL) return 0; struct ::kinfo_proc2 *proc_kinfo; int nproc; if ((proc_kinfo = ::kvm_getproc2(kdp, KERN_PROC_ALL, 0, sizeof(struct ::kinfo_proc2), &nproc)) == NULL) { ::kvm_close(kdp); return 0; } ProcessInstanceInfoMatch match_info_noname{match_info}; match_info_noname.SetNameMatchType(NameMatch::Ignore); for (int i = 0; i < nproc; i++) { if (proc_kinfo[i].p_pid < 1) continue; /* not valid */ /* Make sure the user is acceptable */ if (!all_users && proc_kinfo[i].p_ruid != our_uid) continue; if (proc_kinfo[i].p_pid == our_pid || // Skip this process proc_kinfo[i].p_pid == 0 || // Skip kernel (kernel pid is 0) proc_kinfo[i].p_stat == LSZOMB || // Zombies are bad proc_kinfo[i].p_flag & P_TRACED || // Being debugged? proc_kinfo[i].p_flag & P_WEXIT) // Working on exiting continue; // Every thread is a process in NetBSD, but all the threads of a single // process have the same pid. Do not store the process info in the result // list if a process with given identifier is already registered there. if (proc_kinfo[i].p_nlwps > 1) { bool already_registered = false; for (size_t pi = 0; pi < process_infos.size(); pi++) { if ((::pid_t)process_infos[pi].GetProcessID() == proc_kinfo[i].p_pid) { already_registered = true; break; } } if (already_registered) continue; } ProcessInstanceInfo process_info; process_info.SetProcessID(proc_kinfo[i].p_pid); process_info.SetParentProcessID(proc_kinfo[i].p_ppid); process_info.SetUserID(proc_kinfo[i].p_ruid); process_info.SetGroupID(proc_kinfo[i].p_rgid); process_info.SetEffectiveUserID(proc_kinfo[i].p_uid); process_info.SetEffectiveGroupID(proc_kinfo[i].p_gid); // Make sure our info matches before we go fetch the name and cpu type if (match_info_noname.Matches(process_info) && GetNetBSDProcessArgs(&match_info, process_info)) { GetNetBSDProcessCPUType(process_info); if (match_info.Matches(process_info)) process_infos.push_back(process_info); } } kvm_close(kdp); /* XXX: we don't check for error here */ return process_infos.size(); } bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) { process_info.SetProcessID(pid); if (GetNetBSDProcessArgs(NULL, process_info)) { GetNetBSDProcessCPUType(process_info); GetNetBSDProcessUserAndGroup(process_info); return true; } process_info.Clear(); return false; } Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { return Status("unimplemented"); }
30.758242
80
0.659164
[ "object" ]
60e7c89fdb3605b37f66fecb6ad4ce92f0cfd579
5,879
cpp
C++
udp-echo/test-udp-puncher/test-client.cpp
iexperiment-org/raspberry-jam
0981ba27ca4c599ae1e7f186643f9ad63bee8ec1
[ "MIT" ]
13
2020-04-15T22:52:31.000Z
2021-09-28T10:18:46.000Z
udp-echo/test-udp-puncher/test-client.cpp
iexperiment-org/raspberry-jam
0981ba27ca4c599ae1e7f186643f9ad63bee8ec1
[ "MIT" ]
28
2020-03-31T20:20:03.000Z
2021-07-13T23:13:09.000Z
udp-echo/test-udp-puncher/test-client.cpp
iexperiment-org/raspberry-jam
0981ba27ca4c599ae1e7f186643f9ad63bee8ec1
[ "MIT" ]
3
2020-07-25T19:49:36.000Z
2020-09-01T01:27:02.000Z
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <time.h> #define PORT 8080 #define MAXLINE 1024 #define REREGISTER_CLOCK 30 int serverIndex = 0; int nameIndex = 0; int portIndex = 0; int contactIndex = 0; char name[128] = "client"; char contact[128] = "contact"; char serverAddress[128] = "127.0.0.1"; int serverPort = 8080; void printUsage(char *prog) { printf("Usage: \r\n"); printf("\t%s -s <server address> -p <server port> -n <my name> -c <name to contact>\n", prog); printf("where:\r\n"); printf("\t <server address> is the STAGE MANAGER server to connect to\r\n"); printf("\t <server port> is the STAGE MANAGER port to connect to\r\n"); printf("\t <name> is a text string to send to the server\r\n"); printf("example:\r\n\t(alice would do this, if she is trying to reach bob)\r\n"); printf("\t%s -s 127.0.0.1 -p 8080 -n alice -c bob\r\n", prog); printf("\t(bob would do this, if he is trying to reach alice)\r\n"); printf("\t%s -s 127.0.0.1 -p 8080 -n bob -c alice\r\n", prog); } int processArgs(int argc, char **argv) { int i; if (argc < 9) { printUsage(argv[0]); return -1; } for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-h") == 0) { printUsage(argv[0]); return -1; } if (strcmp(argv[i], "-p") == 0) { i++; portIndex = i; serverPort = atoi(argv[i]); } if (strcmp(argv[i], "-s") == 0) { i++; serverIndex = i; strcpy(serverAddress, argv[i]); } if (strcmp(argv[i], "-n") == 0) { i++; nameIndex = i; strcpy(name, argv[i]); } if (strcmp(argv[i], "-c") == 0) { i++; contactIndex = i; strcpy(contact, argv[i]); } } if (portIndex == 0 || nameIndex == 0 || serverIndex == 0 || contactIndex == 0) { printUsage(argv[0]); return -1; } return 0; } void stageManagerHandler() { int sockfd; struct sockaddr_in servaddr, cliaddr, contactaddr; struct timeval timeout; char buffer[MAXLINE]; int reregister_clock = REREGISTER_CLOCK; // Creating socket file descriptor if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } timeout.tv_sec = 1; // set the read timeout to a seconds so we can keep alive connections timeout.tv_usec = 0; setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (struct timeval *)&timeout, sizeof(struct timeval)); memset(&servaddr, 0, sizeof(servaddr)); memset(&contactaddr, 0, sizeof(contactaddr)); // Filling server information servaddr.sin_family = AF_INET; inet_pton(AF_INET, serverAddress, &servaddr.sin_addr); servaddr.sin_port = htons(serverPort); socklen_t len; int n; char ipaddr[INET_ADDRSTRLEN]; while (1) { puts("Registering with Stage Manager."); sendto(sockfd, name, strlen(name), 0, (const struct sockaddr *)&servaddr, sizeof(servaddr)); puts("Retrieving incoming messages."); while (1) { n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr *)&cliaddr, &len); printf("."); fflush(stdout); reregister_clock--; if (reregister_clock <= 0) { reregister_clock = REREGISTER_CLOCK; break; } if (n < 0) continue; // just wait some more buffer[n] = '\0'; // check who it was that just sent the message inet_ntop(AF_INET, &(cliaddr.sin_addr), ipaddr, INET_ADDRSTRLEN); // This is not really a solid test, but should be good enough in most cases if (strcmp(ipaddr, serverAddress) == 0 && cliaddr.sin_port == servaddr.sin_port) { printf("Stage Manager sent us a Phonebook entry: %s", buffer); char delims[8] = ",\n\r "; int slotnum = atoi(strtok(buffer, delims)); int nslots = atoi(strtok(NULL, delims)); char peer_name[256]; strncpy(peer_name, strtok(NULL, delims), 256); char peer_addr[256]; strncpy(peer_addr, strtok(NULL, delims), 256); int peer_port = atoi(strtok(NULL, delims)); printf("Peer: %d/%d %s@%s:%d\n", slotnum, nslots, peer_name, peer_addr, peer_port); if (strcmp(peer_name, contact) == 0) { // we found the contact we are looking for! printf("Located %s!\n", peer_name); // Filling the contact server information contactaddr.sin_family = AF_INET; inet_pton(AF_INET, peer_addr, &contactaddr.sin_addr); contactaddr.sin_port = htons(peer_port); } } else { printf("We received a peer message of len %d from %s:%d ->>\n%s\n", n, ipaddr, cliaddr.sin_port, buffer); } if (contactaddr.sin_port != 0) { // We have contact info, so keep trying to talk to them :-) sleep(1); // just to slow things down a bit sprintf(buffer, "This is a direct P2P message from %s to %s", name, contact); sendto(sockfd, buffer, strlen(buffer), 0, (const struct sockaddr *)&contactaddr, sizeof(contactaddr)); } } } } int main(int argc, char **argv) { if (processArgs(argc, argv) != 0) { return -1; } printf("Stage Manager Server address: %s\r\n", serverAddress); printf("My Name: %s\r\n", name); stageManagerHandler(); // never returns return 0; }
28.400966
117
0.559959
[ "solid" ]
60eb322ef4ca9fa055784d91e809ad56b89556b3
31,959
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/MessageQueue2/cpp/class1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/MessageQueue2/cpp/class1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/MessageQueue2/cpp/class1.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
#using <System.dll> #using <System.Messaging.dll> using namespace System; using namespace System::Messaging; // Creates a new queue. static void CreateQueue(String^ queuePath, bool transactional) { if (!MessageQueue::Exists(queuePath)) { MessageQueue^ queue = MessageQueue::Create(queuePath, transactional); queue->Close(); } else { Console::WriteLine("{0} already exists.", queuePath); } } void SendObjectString() { // <snippet1> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label"); queue->Close(); // </snippet1> } void SendObjectTransactionType() { // <snippet2> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, MessageQueueTransactionType::Single); queue->Close(); // </snippet2> } void SendObjectStringTransactionType() { // <snippet3> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label", MessageQueueTransactionType::Single); queue->Close(); // </snippet3> } void SendObjectStringTransaction() { // <snippet4> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Create a message queuing transaction. MessageQueueTransaction^ transaction = gcnew MessageQueueTransaction(); try { // Begin a transaction. transaction->Begin(); // Send the message to the queue. queue->Send(msg, "Example Message Label", transaction); // Commit the transaction. transaction->Commit(); } catch (Exception^ ex) { // Cancel the transaction. transaction->Abort(); // Propagate the exception. throw ex; } finally { // Dispose of the transaction object. delete transaction; queue->Close(); } // </snippet4> } void PeekByCorrelationIdStringTimespan() { // <snippet5> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Designate a queue to receive the acknowledgement message for this // message. msg->AdministrationQueue = gcnew MessageQueue(".\\exampleAdminQueue"); // Set the message to generate an acknowledgement message upon its // arrival. msg->AcknowledgeType = AcknowledgeTypes::PositiveArrival; // Send the message. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0)); // Connect to the admin queue. MessageQueue^ adminQueue = gcnew MessageQueue(".\\exampleAdminQueue"); // Set the admin queue's MessageReadPropertyFilter property to ensure // that the acknowledgement message includes the desired properties. adminQueue->MessageReadPropertyFilter->Acknowledgment = true; adminQueue->MessageReadPropertyFilter->CorrelationId = true; // Peek at the acknowledgement message. Message^ ackMsg = adminQueue->PeekByCorrelationId(id, TimeSpan::FromSeconds(10.0)); // Display the acknowledgement message's property values. Console::WriteLine("Message.Label: {0}", ackMsg->Label); Console::WriteLine("Message.Acknowledgment: {0}", ackMsg->Acknowledgment); Console::WriteLine("Message.CorrelationId: {0}", ackMsg->CorrelationId); adminQueue->Close(); queue->Close(); // </snippet5> } void PeekByIdString() { // <snippet6> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Simulate doing other work so the message has time to arrive. System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0)); // Peek at the message. msg = queue->PeekById(id); queue->Close(); // </snippet6> } void PeekByIdStringTimespan() { // <snippet7> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Peek at the message. msg = queue->PeekById(id, TimeSpan::FromSeconds(10.0)); queue->Close(); // </snippet7> } void ReceiveTimespanTransactionType() { // <snippet8> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, MessageQueueTransactionType::Single); // Set the formatter to indicate the message body contains a String. queue->Formatter = gcnew XmlMessageFormatter( gcnew array<Type^>{String::typeid}); // Receive the message from the queue. Because the Id of the message // is not specified, it might not be the message just sent. msg = queue->Receive(TimeSpan::FromSeconds(10.0), MessageQueueTransactionType::Single); queue->Close(); // </snippet8> } void ReceiveTransactionType() { // <snippet9> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, MessageQueueTransactionType::Single); // Simulate doing other work so the message has time to arrive. System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0)); // Set the formatter to indicate the message body contains a String. queue->Formatter = gcnew XmlMessageFormatter( gcnew array<Type^>{String::typeid}); // Receive the message from the queue. Because the Id of the message // , it might not be the message just sent. msg = queue->Receive(MessageQueueTransactionType::Single); queue->Close(); // </snippet9> } void ReceiveByCorrelationIdStringTimespan() { // <snippet10> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Designate a queue to receive the acknowledgement message for this // message. msg->AdministrationQueue = gcnew MessageQueue(".\\exampleAdminQueue"); // Set the message to generate an acknowledgement message upon its // arrival. msg->AcknowledgeType = AcknowledgeTypes::PositiveArrival; // Send the message. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0)); // Connect to the admin queue. MessageQueue^ adminQueue = gcnew MessageQueue(".\\exampleAdminQueue"); // Set the admin queue's MessageReadPropertyFilter property to ensure // that the acknowledgement message includes the desired properties. adminQueue->MessageReadPropertyFilter->Acknowledgment = true; adminQueue->MessageReadPropertyFilter->CorrelationId = true; // Receive the acknowledgement message from the admin queue. Message^ ackMsg = adminQueue->ReceiveByCorrelationId(id, TimeSpan::FromSeconds(10.0)); // Display the acknowledgement message's property values. Console::WriteLine("Message.Label: {0}", ackMsg->Label); Console::WriteLine("Message.Acknowledgment: {0}", ackMsg->Acknowledgment); Console::WriteLine("Message.CorrelationId: {0}", ackMsg->CorrelationId); adminQueue->Close(); queue->Close(); // </snippet10> } void ReceiveByCorrelationIdStringTransactionType() { // <snippet11> // Connect to a nontransactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message to the nontransactional queue. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the nontransactional queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0)); // Connect to a transactional queue on the local computer. MessageQueue^ transQueue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message in response to the original message. Message^ responseMsg = gcnew Message("Example Response Message Body"); // Set the response message's CorrelationId property value to the Id // property value of the original message. responseMsg->CorrelationId = id; // Send the response message to the transactional queue. transQueue->Send(responseMsg, "Example Response Message Label", MessageQueueTransactionType::Single); // Simulate doing other work so the message has time to arrive. System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0)); // Set the transactional queue's MessageReadPropertyFilter property to // ensure that the response message includes the desired properties. transQueue->MessageReadPropertyFilter->CorrelationId = true; // Receive the response message from the transactional queue. responseMsg = transQueue->ReceiveByCorrelationId(id, MessageQueueTransactionType::Single); // Display the response message's property values. Console::WriteLine("Message.Label: {0}", responseMsg->Label); Console::WriteLine("Message.CorrelationId: {0}", responseMsg->CorrelationId); transQueue->Close(); queue->Close(); // </snippet11> } void ReceiveByCorrelationIdStringTimespanTransactionType() { // <snippet12> // Connect to a nontransactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message to the nontransactional queue. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the nontransactional queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0)); // Connect to a transactional queue on the local computer. MessageQueue^ transQueue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message in response to the original message. Message^ responseMsg = gcnew Message("Example Response Message Body"); // Set the response message's CorrelationId property value to the Id // property value of the original message. responseMsg->CorrelationId = id; // Send the response message to the transactional queue. transQueue->Send(responseMsg, "Example Response Message Label", MessageQueueTransactionType::Single); // Set the transactional queue's MessageReadPropertyFilter property to // ensure that the response message includes the desired properties. transQueue->MessageReadPropertyFilter->CorrelationId = true; // Receive the response message from the transactional queue. responseMsg = transQueue->ReceiveByCorrelationId(id, TimeSpan::FromSeconds(10.0), MessageQueueTransactionType::Single); // Display the response message's property values. Console::WriteLine("Message.Label: {0}", responseMsg->Label); Console::WriteLine("Message.CorrelationId: {0}", responseMsg->CorrelationId); transQueue->Close(); queue->Close(); // </snippet12> } void ReceiveByCorrelationIdStringTimespanTransaction() { // <snippet13> // Connect to a nontransactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message to the nontransactional queue. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the nontransactional queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0)); // Connect to a transactional queue on the local computer. MessageQueue^ transQueue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message in response to the original message. Message^ responseMsg = gcnew Message("Example Response Message Body"); // Set the response message's CorrelationId property value to the Id // property value of the original message. responseMsg->CorrelationId = id; // Send the response message to the transactional queue. transQueue->Send(responseMsg, "Example Response Message Label", MessageQueueTransactionType::Single); // Set the transactional queue's MessageReadPropertyFilter property to // ensure that the response message includes the desired properties. transQueue->MessageReadPropertyFilter->CorrelationId = true; // Create a message queuing transaction. MessageQueueTransaction^ transaction = gcnew MessageQueueTransaction(); try { // Begin a transaction. transaction->Begin(); // Receive the response message from the transactional queue. responseMsg = transQueue->ReceiveByCorrelationId(id, TimeSpan::FromSeconds(10.0), transaction); // Commit the transaction. transaction->Commit(); } catch (Exception^ ex) { // Cancel the transaction. transaction->Abort(); // Propagate the exception. throw ex; } finally { // Dispose of the transaction object. delete transaction; transQueue->Close(); queue->Close(); } // Display the response message's property values. Console::WriteLine("Message.Label: {0}", responseMsg->Label); Console::WriteLine("Message.CorrelationId: {0}", responseMsg->CorrelationId); // </snippet13> } void ReceiveByCorrelationIdStringTransaction() { // <snippet14> // Connect to a nontransactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message to the nontransactional queue. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the nontransactional queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0)); // Connect to a transactional queue on the local computer. MessageQueue^ transQueue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message in response to the original message. Message^ responseMsg = gcnew Message("Example Response Message Body"); // Set the response message's CorrelationId property value to the Id // property value of the original message. responseMsg->CorrelationId = id; // Send the response message to the transactional queue. transQueue->Send(responseMsg, "Example Response Message Label", MessageQueueTransactionType::Single); // Simulate doing other work so the message has time to arrive. System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0)); // Set the transactional queue's MessageReadPropertyFilter property to // ensure that the response message includes the desired properties. transQueue->MessageReadPropertyFilter->CorrelationId = true; // Create a message queuing transaction. MessageQueueTransaction^ transaction = gcnew MessageQueueTransaction(); try { // Begin a transaction. transaction->Begin(); // Receive the response message from the transactional queue. responseMsg = transQueue->ReceiveByCorrelationId(id, transaction); // Commit the transaction. transaction->Commit(); } catch (Exception^ ex) { // Cancel the transaction. transaction->Abort(); // Propagate the exception. throw ex; } finally { // Dispose of the transaction object. delete transaction; transQueue->Close(); queue->Close(); } // Display the response message's property values. Console::WriteLine("Message.Label: {0}", responseMsg->Label); Console::WriteLine("Message.CorrelationId: {0}", responseMsg->CorrelationId); // </snippet14> } void ReceiveByIdStringTransactionType() { // <snippet15> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label", MessageQueueTransactionType::Single); // Get the message's Id property value. String^ id = msg->Id; // Simulate doing other work so the message has time to arrive. System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0)); // Receive the message from the queue. msg = queue->ReceiveById(id, MessageQueueTransactionType::Single); queue->Close(); // </snippet15> } void ReceiveByIdString() { // <snippet16> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Simulate doing other work so the message has time to arrive. System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0)); // Receive the message from the queue. msg = queue->ReceiveById(id); queue->Close(); // </snippet16> } void ReceiveByIdStringTransaction() { // <snippet17> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label", MessageQueueTransactionType::Single); // Get the message's Id property value. String^ id = msg->Id; // Simulate doing other work so the message has time to arrive. System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0)); // Create a message queuing transaction. MessageQueueTransaction^ transaction = gcnew MessageQueueTransaction(); try { // Begin a transaction. transaction->Begin(); // Receive the message from the queue. msg = queue->ReceiveById(id, transaction); // Commit the transaction. transaction->Commit(); } catch (Exception^ ex) { // Cancel the transaction. transaction->Abort(); // Propagate the exception. throw ex; } finally { // Dispose of the transaction object. delete transaction; queue->Close(); } // </snippet17> } void ReceiveByIdStringTimespanTransaction() { // <snippet18> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label", MessageQueueTransactionType::Single); // Get the message's Id property value. String^ id = msg->Id; // Create a message queuing transaction. MessageQueueTransaction^ transaction = gcnew MessageQueueTransaction(); try { // Begin a transaction. transaction->Begin(); // Receive the message from the queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0), transaction); // Commit the transaction. transaction->Commit(); } catch (Exception^ ex) { // Cancel the transaction. transaction->Abort(); // Propagate the exception. throw ex; } finally { // Dispose of the transaction object. delete transaction; queue->Close(); } // </snippet18> } void ReceiveByIdStringTimespanTransactionType() { // <snippet19> // Connect to a transactional queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleTransQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label", MessageQueueTransactionType::Single); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0), MessageQueueTransactionType::Single); queue->Close(); // </snippet19> } void ReceiveByIdStringTimespan() { // <snippet20> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new message. Message^ msg = gcnew Message("Example Message Body"); // Send the message. queue->Send(msg, "Example Message Label"); // Get the message's Id property value. String^ id = msg->Id; // Receive the message from the queue. msg = queue->ReceiveById(id, TimeSpan::FromSeconds(10.0)); queue->Close(); // </snippet20> } void GetAllMessages() { // <snippet21> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Populate an array with copies of all the messages in the queue. array<Message^>^ msgs = queue->GetAllMessages(); // Loop through the messages. for each(Message^ msg in msgs) { // Display the label of each message. Console::WriteLine(msg->Label); } queue->Close(); // </snippet21> } void GetEnumerator() { // <snippet22> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Get an IEnumerator object. System::Collections::IEnumerator^ enumerator = queue->GetMessageEnumerator2(); // Use the IEnumerator object to loop through the messages. while(enumerator->MoveNext()) { // Get a message from the enumerator. Message^ msg = (Message^)enumerator->Current; // Display the label of the message. Console::WriteLine(msg->Label); } queue->Close(); // </snippet22> } void SetPermissionsStringAccessRights() { // <snippet23> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Grant all users in the "Everyone" user group the right to receive // messages from the queue. queue->SetPermissions("Everyone", MessageQueueAccessRights::ReceiveMessage); queue->Close(); // </snippet23> } void SetPermissionsAccessControlEntry() { // <snippet24> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create a new trustee to represent the "Everyone" user group. Trustee^ tr = gcnew Trustee("Everyone"); // Create a MessageQueueAccessControlEntry, granting the trustee the // right to receive messages from the queue. MessageQueueAccessControlEntry^ entry = gcnew MessageQueueAccessControlEntry( tr, MessageQueueAccessRights::ReceiveMessage, AccessControlEntryType::Allow); // Apply the MessageQueueAccessControlEntry to the queue. queue->SetPermissions(entry); queue->Close(); // </snippet24> } void SetPermissionsStringAccessRightsAccessControlEntryType() { // <snippet25> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Grant all users in the "Everyone" user group the right to receive // messages from the queue. queue->SetPermissions("Everyone", MessageQueueAccessRights::ReceiveMessage, AccessControlEntryType::Allow); queue->Close(); // </snippet25> } void SetPermissionsAccessControlList() { // <snippet26> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Create an AccessControlList. AccessControlList^ list = gcnew AccessControlList(); // Create a new trustee to represent the "Everyone" user group. Trustee^ tr = gcnew Trustee("Everyone"); // Create an AccessControlEntry, granting the trustee read access to // the queue. AccessControlEntry^ entry = gcnew AccessControlEntry( tr, GenericAccessRights::Read, StandardAccessRights::Read, AccessControlEntryType::Allow); // Add the AccessControlEntry to the AccessControlList. list->Add(entry); // Apply the AccessControlList to the queue. queue->SetPermissions(list); queue->Close(); // </snippet26> } void ResetPermissions() { // <snippet27> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Reset the queue's permission list to its default values. queue->ResetPermissions(); queue->Close(); // </snippet27> } void Refresh() { // <snippet28> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Refresh the queue's property values to obtain its current state. queue->Refresh(); queue->Close(); // </snippet28> } void Purge() { // <snippet29> // Connect to a queue on the local computer. MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue"); // Delete all messages from the queue. queue->Purge(); queue->Close(); // </snippet29> } void main() { try { // Create a nontransactional queue on the local computer. // Note that the queue might not be immediately accessible, and // therefore this example might throw an exception of type // System.Messaging.MessageQueueException when trying to send a // message to the newly created queue. CreateQueue(".\\exampleQueue", false); // Create a nontransactional queue on the local computer. This // queue will be used to receive acknowledgement messages. CreateQueue(".\\exampleAdminQueue", false); // Create a transactional queue on the local computer. CreateQueue(".\\exampleTransQueue", true); // Send a message to a queue. SendObjectString(); // Send a message to a transactional queue. SendObjectTransactionType(); // Send a message to a transactional queue. SendObjectStringTransactionType(); // Send a message to a transactional queue. SendObjectStringTransaction(); // Demonstrate PeekById. PeekByIdString(); // Demonstrate PeekById. PeekByIdStringTimespan(); // Demonstrate PeekByCorrelationId. PeekByCorrelationIdStringTimespan(); // Receive a message from a transactional queue. ReceiveTimespanTransactionType(); // Receive a message from a transactional queue. ReceiveTransactionType(); // Demonstrate ReceiveByCorrelationId. ReceiveByCorrelationIdStringTimespan(); // Demonstrate ReceiveByCorrelationId. ReceiveByCorrelationIdStringTransactionType(); // Demonstrate ReceiveByCorrelationId. ReceiveByCorrelationIdStringTimespanTransactionType(); // Demonstrate ReceiveByCorrelationId. ReceiveByCorrelationIdStringTimespanTransaction(); // Demonstrate ReceiveByCorrelationId. ReceiveByCorrelationIdStringTransaction(); // Demonstrate ReceiveById. ReceiveByIdStringTransactionType(); // Demonstrate ReceiveById. ReceiveByIdString(); // Demonstrate ReceiveById. ReceiveByIdStringTransaction(); // Demonstrate ReceiveById. ReceiveByIdStringTimespanTransaction(); // Demonstrate ReceiveById. ReceiveByIdStringTimespanTransactionType(); // Demonstrate ReceiveById. ReceiveByIdStringTimespan(); // Demonstrate GetAllMessages. GetAllMessages(); // Demonstrate GetEnumerator. GetEnumerator(); // Demonstrate SetPermissions. SetPermissionsStringAccessRights(); // Demonstrate SetPermissions. SetPermissionsAccessControlEntry(); // Demonstrate SetPermissions. SetPermissionsStringAccessRightsAccessControlEntryType(); // Demonstrate SetPermissions. SetPermissionsAccessControlList(); // Demonstrate ResetPermissions. ResetPermissions(); // Demonstrate Refresh. Refresh(); // Demonstrate Purge. Purge(); } catch (InvalidOperationException^) { Console::WriteLine("Please install Message Queuing."); } catch (MessageQueueException^ ex) { // Write the exception information to the console. Console::WriteLine(ex->Message); } }
29.027248
78
0.64298
[ "object" ]
60ebfadb424da8a3df86842052576d430095205e
7,903
cpp
C++
TP2/AlgorithmLocal.cpp
GuillaumeArruda/INF4705
134f965045514066133b19d0206f99e34f3e2947
[ "BSD-3-Clause" ]
null
null
null
TP2/AlgorithmLocal.cpp
GuillaumeArruda/INF4705
134f965045514066133b19d0206f99e34f3e2947
[ "BSD-3-Clause" ]
null
null
null
TP2/AlgorithmLocal.cpp
GuillaumeArruda/INF4705
134f965045514066133b19d0206f99e34f3e2947
[ "BSD-3-Clause" ]
null
null
null
#include "AlgorithmLocal.h" #include "AlgorithmVorace.h" #include <algorithm> #include <iostream> AlgorithmLocal::AlgorithmLocal() { } AlgorithmLocal::~AlgorithmLocal() { } Solution AlgorithmLocal::concreteSolve(const Problem& problem) { AlgorithmVorace vorace; Solution solution(problem); solution = vorace.solve(problem, false, false); bool bestSolutionReached = false; std::vector<Location> locationNotInSolution(problem.locations.size()); std::sort(solution.locations.begin(), solution.locations.end()); auto it = std::set_difference(problem.locations.begin(), problem.locations.end(), solution.locations.begin(), solution.locations.end(), locationNotInSolution.begin()); locationNotInSolution.resize(it - locationNotInSolution.begin()); while (!bestSolutionReached) { int solutionTotalIncome = solution.totalIncome(); int solutionTotalConsommation = solution.totalConsommation(); int bestIncome = solutionTotalIncome; int removeIndex[2]; removeIndex[0] = -1; removeIndex[1] = -1; int addIndex[2]; addIndex[0] = -1; addIndex[1] = -1; //One replace one for (size_t i = 0; i < solution.locations.size(); ++i) { int currentIncome = solutionTotalIncome - solution.locations[i].income; int currentConsommation = solutionTotalConsommation - solution.locations[i].chickenConsommation; for (size_t j = 0; j < locationNotInSolution.size(); ++j) { if (currentConsommation + locationNotInSolution[j].chickenConsommation < problem.totalChickenProduction) { int newIncome = currentIncome + locationNotInSolution[j].income; if (newIncome > bestIncome) { bestIncome = newIncome; removeIndex[0] = i; removeIndex[1] = -1; addIndex[0] = j; addIndex[1] = -1; } } } } //One replace two for(size_t i = 0; i < solution.locations.size(); ++i)\ { int incomeWithoutFistLocation = solutionTotalIncome - solution.locations[i].income; int consommationWithoutFirstLocation = solutionTotalConsommation - solution.locations[i].chickenConsommation; for(size_t j = i + 1; j < solution.locations.size(); ++j) { int currentIncome = incomeWithoutFistLocation - solution.locations[j].income; int currentConsommation = consommationWithoutFirstLocation - solution.locations[j].chickenConsommation; for(size_t k = 0; k < locationNotInSolution.size(); ++k) { if(currentConsommation + locationNotInSolution[k].chickenConsommation < problem.totalChickenProduction) { int newIncome = currentIncome + locationNotInSolution[k].income; if(newIncome > bestIncome) { bestIncome = newIncome; removeIndex[0] = i; removeIndex[1] = j; addIndex[0] = k; addIndex[1] = -1; } } } } } //Two replace one for(size_t i = 0; i < solution.locations.size(); ++i)\ { int incomeWithoutFistLocation = solutionTotalIncome - solution.locations[i].income; int consommationWithoutFirstLocation = solutionTotalConsommation - solution.locations[i].chickenConsommation; for(size_t j = 0; j < locationNotInSolution.size(); ++j) { int currentIncome = incomeWithoutFistLocation +locationNotInSolution[j].income; int currentConsommation = consommationWithoutFirstLocation + locationNotInSolution[j].chickenConsommation; if(currentConsommation < problem.totalChickenProduction) { for(size_t k = j + 1; k < locationNotInSolution.size(); ++k) { if(currentConsommation + locationNotInSolution[k].chickenConsommation < problem.totalChickenProduction) { int newIncome = currentIncome + locationNotInSolution[k].income; if(newIncome > bestIncome) { bestIncome = newIncome; removeIndex[0] = i; removeIndex[1] = -1; addIndex[0] = j; addIndex[1] = k; } } } } } } //Two replace two for(size_t i = 0; i < solution.locations.size(); ++i)\ { int incomeWithoutFistLocation = solutionTotalIncome - solution.locations[i].income; int consommationWithoutFirstLocation = solutionTotalConsommation - solution.locations[i].chickenConsommation; for(size_t j = i + 1; j <solution.locations.size(); ++j) { int incomeWithoutTwoLocation = incomeWithoutFistLocation - solution.locations[j].income; int consommationWithoutTwoLocation = consommationWithoutFirstLocation - solution.locations[j].chickenConsommation; for(size_t k = 0; k < locationNotInSolution.size(); ++k) { int currentIncome = incomeWithoutTwoLocation + locationNotInSolution[k].income; int currentConsommation = consommationWithoutTwoLocation + locationNotInSolution[k].chickenConsommation; if(currentConsommation < problem.totalChickenProduction) { for(size_t l = k + 1; l < locationNotInSolution.size(); ++l) { if(currentConsommation + locationNotInSolution[l].chickenConsommation < problem.totalChickenProduction) { int newIncome = currentIncome + locationNotInSolution[l].income; if(newIncome > bestIncome) { bestIncome = newIncome; removeIndex[0] = i; removeIndex[1] = j; addIndex[0] = k; addIndex[1] = l; } } } } } } } if (removeIndex[0] != -1 && addIndex[0] != -1) { if(addIndex[1] != -1) { solution.locations.push_back(locationNotInSolution[addIndex[1]]); locationNotInSolution.erase(locationNotInSolution.begin() + addIndex[1]); } if(removeIndex[1] != -1) { locationNotInSolution.push_back(solution.locations[removeIndex[1]]); solution.locations.erase(solution.locations.begin() + removeIndex[1]); } solution.locations.push_back(locationNotInSolution[addIndex[0]]); locationNotInSolution.erase(locationNotInSolution.begin() + addIndex[0]); locationNotInSolution.push_back(solution.locations[removeIndex[0]]); solution.locations.erase(solution.locations.begin() + removeIndex[0]); } else { bestSolutionReached = true; } } return solution; }
45.947674
171
0.52904
[ "vector" ]
60ec9f8acae490633147c13a7de4593b3a67fad9
18,845
cpp
C++
src/drivers/pwm_esc/pwm_esc.cpp
aravindraja93/px4-firmware
2de89b19a554cca6edbba1d41b267ef675f9920b
[ "BSD-3-Clause" ]
null
null
null
src/drivers/pwm_esc/pwm_esc.cpp
aravindraja93/px4-firmware
2de89b19a554cca6edbba1d41b267ef675f9920b
[ "BSD-3-Clause" ]
34
2020-11-19T06:19:56.000Z
2022-03-25T08:54:11.000Z
src/drivers/pwm_esc/pwm_esc.cpp
aravindraja93/px4-firmware
2de89b19a554cca6edbba1d41b267ef675f9920b
[ "BSD-3-Clause" ]
7
2020-11-18T16:51:32.000Z
2022-01-12T08:46:09.000Z
/**************************************************************************** * * Copyright (c) 2021 Technology Innovation Institute. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file pwm_esc.cpp * Driver for the NuttX PWM driver controleed escs * */ #include <px4_platform_common/px4_config.h> #include <px4_platform_common/tasks.h> #include <px4_platform_common/sem.hpp> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <assert.h> #include <debug.h> #include <time.h> #include <queue.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <math.h> #include <drivers/device/device.h> #include <drivers/drv_pwm_output.h> #include <drivers/drv_hrt.h> #include <drivers/drv_mixer.h> #include <lib/mixer_module/mixer_module.hpp> #include <perf/perf_counter.h> #include <systemlib/err.h> #include <parameters/param.h> #include <uORB/Subscription.hpp> #include <uORB/topics/actuator_armed.h> #include <uORB/topics/parameter_update.h> #include <nuttx/timers/pwm.h> #include <debug.h> #ifndef PWMESC_OUT_PATH #define PWMESC_OUT_PATH "/dev/pwmX"; #endif #ifndef PWMESC_MAX_DEVICES #define PWMESC_MAX_DEVICES 2 #endif #ifndef PWMESC_MAX_CHANNELS #define PWMESC_MAX_CHANNELS 8 #endif #ifndef PWM_DEFAULT_RATE #define PWM_DEFAULT_RATE 400 #endif //using namespace time_literals; /** * The PWMESC class. * */ class PWMESC : public cdev::CDev, public OutputModuleInterface { public: /** * Constructor. * * Initialize all class variables. */ PWMESC(); /** * Destructor. * * Wait for worker thread to terminate. */ virtual ~PWMESC(); /** * Initialize the PWMESC class. * * Retrieve relevant initial system parameters. Connect to PWM device * * @param hitl_mode set to suppress publication of actuator_outputs */ int init(bool hitl_mode); /** * Get the singleton instance */ static inline PWMESC *getInstance() {return _instance;} /** * IO Control handler. * * Handle all IOCTL calls to the PWMESC file descriptor. * * @param[in] filp file handle (not used). This function is always called directly through object reference * @param[in] cmd the IOCTL command * @param[in] the IOCTL command parameter (optional) */ virtual int ioctl(file *filp, int cmd, unsigned long arg); /** * updateOutputs * * Sets the actual PWM outputs. See OutputModuleInterface * */ bool updateOutputs(bool stop_motors, uint16_t outputs[MAX_ACTUATORS], unsigned num_outputs, unsigned num_control_groups_updated) override; /** * Don't allow more channels than MAX_ACTUATORS */ static_assert(PWMESC_MAX_CHANNELS <= MAX_ACTUATORS, "Increase MAX_ACTUATORS if this fails"); private: bool _initialized{false}; volatile int _task; ///< worker task id volatile bool _task_should_exit; ///< worker terminate flag px4_sem_t _update_sem; perf_counter_t _perf_update; ///< local performance counter for PWM updates /* subscribed topics */ int _actuator_armed_sub{-1}; ///< system armed control topic MixingOutput _mixing_output{PWMESC_MAX_CHANNELS, *this, MixingOutput::SchedulingPolicy::Auto, true}; uORB::SubscriptionInterval _parameter_update_sub{ORB_ID(parameter_update), 1000000}; /* advertised topics */ uORB::PublicationMulti<actuator_outputs_s> _actuator_outputs_pub{ORB_ID(actuator_outputs)}; actuator_armed_s _actuator_armed; bool _hitl_mode; ///< Hardware-in-the-loop simulation mode - don't publish actuator_outputs int _pwm_fd[PWMESC_MAX_DEVICES]; int32_t _pwm_min_default; int32_t _pwm_max_default; int32_t _pwm_disarmed_default; uint16_t _pwm_min[MAX_ACTUATORS]; uint16_t _pwm_max[MAX_ACTUATORS]; uint16_t _pwm_disarmed[MAX_ACTUATORS]; uint16_t _pwm_fail[MAX_ACTUATORS]; int32_t _pwm_rate{PWM_DEFAULT_RATE}; int init_pwm_outputs(); /* Singleton pointer */ static PWMESC *_instance; /** * Trampoline to the worker task */ static int task_main_trampoline(int argc, char *argv[]); /** * worker task */ void task_main(); /** * Callback for mixer subscriptions */ void Run() override; void update_params(); /* No copy constructor */ PWMESC(const PWMESC &); PWMESC operator=(const PWMESC &); }; PWMESC *PWMESC::_instance = nullptr; PWMESC::PWMESC() : CDev(PWM_OUTPUT0_DEVICE_PATH), OutputModuleInterface(MODULE_NAME, px4::wq_configurations::hp_default), _task(-1), _task_should_exit(false), _perf_update(perf_alloc(PC_ELAPSED, "pwm update")), _actuator_armed_sub(-1), _hitl_mode(false) { /* initialize tick semaphores */ px4_sem_init(&_update_sem, 0, 0); px4_sem_setprotocol(&_update_sem, SEM_PRIO_NONE); /* we need this potentially before it could be set in task_main */ _instance = this; } PWMESC::~PWMESC() { /* tell the task we want it to go away */ _task_should_exit = true; /* spin waiting for the task to stop */ for (unsigned i = 0; (i < 10) && (_task != -1); i++) { /* give it another 100ms */ px4_usleep(100000); } /* well, kill it anyway, though this will probably crash */ if (_task != -1) { task_delete(_task); } /* deallocate perfs */ perf_free(_perf_update); px4_sem_destroy(&_update_sem); _instance = nullptr; } int PWMESC::init(bool hitl_mode) { int ret; _hitl_mode = hitl_mode; /* do regular cdev init */ ret = CDev::init(); if (ret != OK) { return ret; } /* start the main task */ _task = px4_task_spawn_cmd("pwm_esc", SCHED_DEFAULT, SCHED_PRIORITY_ACTUATOR_OUTPUTS, 3048, (px4_main_t)&PWMESC::task_main_trampoline, nullptr); if (_task < 0) { PX4_ERR("task start failed: %d", errno); return -errno; } /* schedule workqueue */ ScheduleNow(); return OK; } int PWMESC::task_main_trampoline(int argc, char *argv[]) { _instance->task_main(); return 0; } bool PWMESC::updateOutputs(bool stop_motors, uint16_t outputs[MAX_ACTUATORS], unsigned num_outputs, unsigned num_control_groups_updated) { bool ret = true; struct pwm_info_s pwm; memset(&pwm, 0, sizeof(struct pwm_info_s)); pwm.frequency = _pwm_rate; for (unsigned i = 0; i < num_outputs; i++) { // TODO: channel to proper pwm device map. // this is now just quick hack for one pwm device, direct map of channels uint16_t pwm_val = outputs[i]; pwm.channels[i].duty = ((((uint32_t)pwm_val) << 16) / (1000000 / _pwm_rate)); pwm.channels[i].channel = i + 1; } /* Only publish if not in hitl */ if (!_hitl_mode && ::ioctl(_pwm_fd[0], PWMIOC_SETCHARACTERISTICS, (unsigned long)((uintptr_t)&pwm)) < 0) { PX4_ERR("PWMIOC_SETCHARACTERISTICS) failed: %d\n", errno); ret = false; } return ret; } int PWMESC::init_pwm_outputs() { int ret; /* Update parameters initially to get pwm min/max etc */ update_params(); _mixing_output.setIgnoreLockdown(_hitl_mode); _mixing_output.setMaxNumOutputs(PWMESC_MAX_CHANNELS); const int update_interval_in_us = math::constrain(1000000 / (_pwm_rate * 2), 500, 100000); _mixing_output.setMaxTopicUpdateRate(update_interval_in_us); /* Open the PWM devnode */ // TODO: loop through the devices, open all fd:s char pwm_device_name[] = PWMESC_OUT_PATH; int n_pwm_devices = 1; for (int i = 0; i < 1 && i < n_pwm_devices; i++) { pwm_device_name[sizeof(pwm_device_name) - 2] = '0' + i; _pwm_fd[i] = ::open(pwm_device_name, O_RDONLY); if (_pwm_fd[i] < 0) { PX4_ERR("pwm_main: open %s failed: %d\n", pwm_device_name, errno); return -ENODEV; } /* Configure PWM to default rate, disarmed pulse and start */ struct pwm_info_s pwm; memset(&pwm, 0, sizeof(struct pwm_info_s)); pwm.frequency = _pwm_rate; for (int j = 0; j < PWMESC_MAX_CHANNELS; j++) { pwm.channels[j].duty = ((((uint32_t)_pwm_disarmed[j]) << 16) / 2500); pwm.channels[j].channel = j + 1; } ret = ::ioctl(_pwm_fd[i], PWMIOC_SETCHARACTERISTICS, (unsigned long)((uintptr_t)&pwm)); if (ret < 0) { PX4_ERR("PWMIOC_SETCHARACTERISTICS) failed: %d\n", errno); } ret = ::ioctl(_pwm_fd[i], PWMIOC_START, 0); if (ret < 0) { PX4_ERR("PWMIOC_START failed: %d\n", errno); return -ENODEV; } } return 0; } void PWMESC::Run() { /* Just trigger the main task */ px4_sem_post(&_update_sem); } void PWMESC::task_main() { bool first = true; /* Wait for system to be initialized fully */ while (!_initialized) { usleep(10000); } _actuator_armed_sub = orb_subscribe(ORB_ID(actuator_armed)); if (_actuator_armed_sub < 0) { PX4_ERR("arming status subscription failed"); _task_should_exit = true; } while (!_task_should_exit) { /* Get the armed status */ orb_copy(ORB_ID(actuator_armed), _actuator_armed_sub, &_actuator_armed); /* Initialize PWM outputs on first execution */ if (first) { first = false; if (init_pwm_outputs() != 0) { _task_should_exit = true; } } /* sleep waiting for mixer update */ px4_sem_wait(&_update_sem); perf_begin(_perf_update); _mixing_output.update(); // check for parameter updates if (_parameter_update_sub.updated()) { // clear update parameter_update_s pupdate; _parameter_update_sub.copy(&pupdate); } _mixing_output.updateSubscriptions(true); perf_end(_perf_update); } PX4_DEBUG("exiting"); /* tell the dtor that we are exiting */ _task = -1; _exit(0); } void PWMESC::update_params() { // skip update when armed if (_actuator_armed.armed) { return; } /* Call MixingOutput::updateParams */ updateParams(); _pwm_min_default = PWM_DEFAULT_MIN; _pwm_max_default = PWM_DEFAULT_MAX; _pwm_disarmed_default = PWM_MOTOR_OFF; const char *prefix = "PWM_MAIN"; param_get(param_find("PWM_MAIN_MIN"), &_pwm_min_default); param_get(param_find("PWM_MAIN_MAX"), &_pwm_max_default); param_get(param_find("PWM_MAIN_DISARM"), &_pwm_disarmed_default); param_get(param_find("PWM_MAIN_RATE"), &_pwm_rate); char str[17]; // PWM_MAIN_MINx { for (unsigned i = 0; i < PWMESC_MAX_CHANNELS; i++) { sprintf(str, "%s_MIN%u", prefix, i + 1); int32_t pwm_min = -1; if (param_get(param_find(str), &pwm_min) == PX4_OK) { if (pwm_min >= 0) { _pwm_min[i] = math::constrain(pwm_min, static_cast<int32_t>(PWM_LOWEST_MIN), static_cast<int32_t>(PWM_HIGHEST_MIN)); if (pwm_min != _pwm_min[i]) { int32_t pwm_min_new = _pwm_min[i]; param_set(param_find(str), &pwm_min_new); } } else { _pwm_min[i] = _pwm_min_default; } } else { _pwm_min[i] = 0; } _mixing_output.minValue(i) = _pwm_min[i]; } } // PWM_MAIN_MAXx { for (unsigned i = 0; i < PWMESC_MAX_CHANNELS; i++) { sprintf(str, "%s_MAX%u", prefix, i + 1); int32_t pwm_max = -1; if (param_get(param_find(str), &pwm_max) == PX4_OK) { if (pwm_max >= 0) { _pwm_max[i] = math::constrain(pwm_max, static_cast<int32_t>(PWM_LOWEST_MAX), static_cast<int32_t>(PWM_HIGHEST_MAX)); if (pwm_max != _pwm_max[i]) { int32_t pwm_max_new = _pwm_max[i]; param_set(param_find(str), &pwm_max_new); } } else { _pwm_max[i] = _pwm_max_default; } } else { _pwm_max[i] = 0; } _mixing_output.maxValue(i) = _pwm_max[i]; } } // PWM_MAIN_FAILx { for (unsigned i = 0; i < PWMESC_MAX_CHANNELS; i++) { sprintf(str, "%s_FAIL%u", prefix, i + 1); int32_t pwm_fail = -1; if (param_get(param_find(str), &pwm_fail) == PX4_OK) { if (pwm_fail >= 0) { _pwm_fail[i] = math::constrain(pwm_fail, static_cast<int32_t>(0), static_cast<int32_t>(PWM_HIGHEST_MAX)); if (pwm_fail != _pwm_fail[i]) { int32_t pwm_fail_new = _pwm_fail[i]; param_set(param_find(str), &pwm_fail_new); } } else { _pwm_fail[i] = -1; } } else { _pwm_fail[i] = 0; } _mixing_output.failsafeValue(i) = _pwm_fail[i]; } } // PWM_MAIN_DISx { for (unsigned i = 0; i < PWMESC_MAX_CHANNELS; i++) { sprintf(str, "%s_DIS%u", prefix, i + 1); int32_t pwm_dis = -1; if (param_get(param_find(str), &pwm_dis) == PX4_OK) { if (pwm_dis >= 0) { _pwm_disarmed[i] = math::constrain(pwm_dis, static_cast<int32_t>(0), static_cast<int32_t>(PWM_HIGHEST_MAX)); if (pwm_dis != _pwm_disarmed[i]) { int32_t pwm_dis_new = _pwm_disarmed[i]; param_set(param_find(str), &pwm_dis_new); } } else { _pwm_disarmed[i] = _pwm_disarmed_default; } } else { _pwm_disarmed[i] = 0; } _mixing_output.disarmedValue(i) = _pwm_disarmed[i]; } } } int PWMESC::ioctl(file *filep, int cmd, unsigned long arg) { int ret = OK; switch (cmd) { case PWM_SERVO_ARM: /* set the 'armed' bit */ _alert("PWM_SERVO_ARM\n"); break; case PWM_SERVO_SET_ARM_OK: /* set the 'OK to arm' bit */ _alert("PWM_SERVO_SET_ARM_OK\n"); break; case PWM_SERVO_CLEAR_ARM_OK: /* clear the 'OK to arm' bit */ _alert("PWM_SERVO_CLEAR_ARM_OK\n"); break; case PWM_SERVO_DISARM: /* clear the 'armed' bit */ _alert("PWM_SERVO_DISARM\n"); break; case PWM_SERVO_GET_DEFAULT_UPDATE_RATE: /* get the default update rate */ _alert("PWM_SERVO_GET_DEFAULT_UPDATE_RATE\n"); break; case PWM_SERVO_SET_UPDATE_RATE: /* set the requested alternate rate */ _alert("PWM_SERVO_SET_UPDATE_RATE\n"); break; case PWM_SERVO_GET_UPDATE_RATE: /* get the alternative update rate */ _alert("PWM_SERVO_GET_UPDATE_RATE\n"); break; case PWM_SERVO_SET_SELECT_UPDATE_RATE: _alert("PWM_SERVO_SET_SELECT_UPDATE_RATE\n"); break; case PWM_SERVO_GET_SELECT_UPDATE_RATE: _alert("PWM_SERVO_GET_SELECT_UPDATE_RATE\n"); break; case PWM_SERVO_SET_FAILSAFE_PWM: _alert("PWM_SERVO_SET_FAILSAFE_PWM\n"); break; case PWM_SERVO_GET_FAILSAFE_PWM: _alert("PWM_SERVO_GET_FAILSAFE_PWM\n"); break; case PWM_SERVO_SET_DISARMED_PWM: _alert("PWM_SERVO_SET_DISARMED_PWM\n"); break; case PWM_SERVO_GET_DISARMED_PWM: _alert("PWM_SERVO_GET_DISARMED_PWM\n"); break; case PWM_SERVO_SET_MIN_PWM: { _alert("PWM_SERVO_SET_MIN_PWM\n"); struct pwm_output_values *pwm = (struct pwm_output_values *)arg; for (unsigned i = 0; i < pwm->channel_count; i++) { if (i < MAX_ACTUATORS) { _mixing_output.minValue(i) = pwm->values[i]; } } break; } case PWM_SERVO_GET_MIN_PWM: _alert("PWM_SERVO_GET_MIN_PWM\n"); break; case PWM_SERVO_SET_MAX_PWM: { _alert("PWM_SERVO_SET_MAX_PWM\n"); struct pwm_output_values *pwm = (struct pwm_output_values *)arg; for (unsigned i = 0; i < pwm->channel_count; i++) { if (i < MAX_ACTUATORS) { _mixing_output.maxValue(i) = pwm->values[i]; } } break; } case PWM_SERVO_GET_MAX_PWM: _alert("PWM_SERVO_GET_MAX_PWM\n"); break; case PWM_SERVO_GET_TRIM_PWM: _alert("PWM_SERVO_GET_TRIM_PWM\n"); break; case PWM_SERVO_GET_COUNT: _alert("PWM_SERVO_GET_COUNT\n"); break; case PWM_SERVO_SET_DISABLE_LOCKDOWN: _alert("PWM_SERVO_SET_DISABLE_LOCKDOWN\n"); break; case PWM_SERVO_GET_DISABLE_LOCKDOWN: _alert("PWM_SERVO_GET_DISABLE_LOCKDOWN\n"); break; case PWM_SERVO_SET_FORCE_SAFETY_OFF: _alert("PWM_SERVO_SET_FORCE_SAFETY_OFF\n"); break; case PWM_SERVO_SET_FORCE_SAFETY_ON: _alert("PWM_SERVO_SET_FORCE_SAFETY_ON\n"); break; case PWM_SERVO_SET_FORCE_FAILSAFE: _alert("PWM_SERVO_SET_FORCE_FAILSAFE\n"); break; case PWM_SERVO_SET_TERMINATION_FAILSAFE: _alert("PWM_SERVO_SET_TERMINATION_FAILSAFE\n"); break; case PWM_SERVO_SET(0) ... PWM_SERVO_SET(PWM_OUTPUT_MAX_CHANNELS - 1): _alert("PWM_SERVO_SET\n"); break; case PWM_SERVO_GET(0) ... PWM_SERVO_GET(PWM_OUTPUT_MAX_CHANNELS - 1): _alert("PWM_SERVO_GET\n"); break; case PWM_SERVO_GET_RATEGROUP(0) ... PWM_SERVO_GET_RATEGROUP(PWM_OUTPUT_MAX_CHANNELS - 1): _alert("PWM_SERVO_GET_RATEGROUP\n"); break; case PWM_SERVO_SET_MODE: _alert("PWM_SERVO_SET_MODE\n"); break; case MIXERIOCRESET: _alert("MIXERIOCRESET\n"); /* Can start the main thread now */ _initialized = true; _mixing_output.resetMixerThreadSafe(); break; case MIXERIOCLOADBUF: { _alert("MIXERIOCLOADBUF\n"); const char *buf = (const char *)arg; unsigned buflen = strlen(buf); ret = _mixing_output.loadMixerThreadSafe(buf, buflen); break; } default: /* see if the parent class can make any use of it */ ret = CDev::ioctl(filep, cmd, arg); break; } return ret; } extern "C" __EXPORT int pwm_esc_main(int argc, char *argv[]); namespace { void start(int argc, char *argv[]) { if (PWMESC::getInstance() != nullptr) { errx(0, "already loaded"); } /* create the driver */ (void)new PWMESC(); if (PWMESC::getInstance == nullptr) { errx(1, "driver allocation failed"); } bool hitl_mode = false; /* Check if started in hil mode */ for (int extra_args = 1; extra_args < argc; extra_args++) { if (!strcmp(argv[extra_args], "hil")) { hitl_mode = true; } else if (argv[extra_args][0] != '\0') { PX4_WARN("unknown argument: %s", argv[extra_args]); } } if (OK != PWMESC::getInstance()->init(hitl_mode)) { delete PWMESC::getInstance(); errx(1, "driver init failed"); } exit(0); } } /* namespace */ int pwm_esc_main(int argc, char *argv[]) { /* check for sufficient number of arguments */ if (argc < 2) { goto out; } if (!strcmp(argv[1], "start")) { start(argc - 1, argv + 1); } out: errx(1, "need a command, try 'start'"); }
22.732207
121
0.688936
[ "object" ]
60edeef91e72313784b9a4d5760d38f68f4c532d
1,060
cpp
C++
Star.cpp
caudate-julie/OrbitalArcadeGame
ca8061dd20ea235cc926e7bbf3dde3ceab8d0eef
[ "Zlib" ]
1
2020-08-30T15:36:35.000Z
2020-08-30T15:36:35.000Z
Star.cpp
caudate-julie/OrbitalArcadeGame
ca8061dd20ea235cc926e7bbf3dde3ceab8d0eef
[ "Zlib" ]
null
null
null
Star.cpp
caudate-julie/OrbitalArcadeGame
ca8061dd20ea235cc926e7bbf3dde3ceab8d0eef
[ "Zlib" ]
null
null
null
#include "Star.h" #include "Configuration.h" #include "auxiliary.h" extern Configuration* config; /**------------------------------------------------------------ Constructor - given position, makes random size and (once) size-based or random type. -----------------------------------------------------------*/ Star::Star() { position = Point(0, 0); size = pow(d_random(sqrt(config->STAR_MIN_SIZE), sqrt(config->STAR_MAX_SIZE)), 2); type = 'W'; } /**------------------------------------------------------------ void destructor. -----------------------------------------------------------*/ Star::~Star(void) {} /**------------------------------------------------------------ Makes class with info about the object to pass outside Game class (mainly to graphics class). -----------------------------------------------------------*/ GalaxyObject Star::info() const { GalaxyObject my_info; my_info.position = position; my_info.direction = Point(); my_info.type = star; my_info.subtype = regular; my_info.size = size; return my_info; }
30.285714
83
0.457547
[ "object" ]
60ee723ab2c5f22ef52abfbe20f8e8d00952e2d4
5,561
cpp
C++
admin/darwin/src/buildtools/mkerrtbl/mkerrtbl.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/darwin/src/buildtools/mkerrtbl/mkerrtbl.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/darwin/src/buildtools/mkerrtbl/mkerrtbl.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1995 - 1999 // // File: mkerrtbl.cpp // //-------------------------------------------------------------------------- #include "common.h" // to allow use of precompiled headers for windows.h //#define WIN32_LEAN_AND_MEAN // omit stuff we don't need, to make builds fast //#define INC_OLE2 // IUnknown //#pragma warning(disable : 4201) // unnamed struct/unions, in Win32 headers //#pragma warning(disable : 4514) // inline function not used, no possible to fix //#include <windows.h> #undef IError #define IError(a,b,c) { (b), c, #a }, // override normal error definition #include <msidefs.h> struct MsiErrorEntry { int iErr; const char* szFmt; const char* szName; }; #define ERRORTABLE // read only IError(...) lines MsiErrorEntry rgErrors[] = { {0,0,0}, #include "services.h" // includes: database.h, path.h, regkey.h #include "iconfig.h" #include "engine.h" #include "handler.h" }; int cErrors = sizeof(rgErrors)/sizeof(MsiErrorEntry); char szTxtHeader[] = "Windows installer Error and Debug Messages\r\n\r\n"; char szTxtFormat[] = "%4i %-30s %s\r\n"; char szTxtFooter[] = ""; char szIdtHeader[] = "Error\tMessage\r\n" "i2\tL255\r\n" "Error\tError\r\n"; char szIdtFormat[] = "%i\t%s\r\n"; char szIdtFooter[] = ""; char szRcHeader[] = "/* Auto-generated error strings, DO NOT EDIT! */\nSTRINGTABLE {\r\n"; char szRcFormat[] = "\t%i, \"%s\"\r\n"; char szRcFooter[] = "}\r\n"; char szRHeader[] = "/* Auto-generated error strings, DO NOT EDIT! */\r\n"; char szRFormat[] = "resource 'STR ' (%i) {\"%s\"};\r\n"; char szRFooter[] = ""; char szRtfHeader[] = "{\\rtf1\\ansi {\\fonttbl{\\f0\\fswiss Helv;}" "{\\f1\\fmodern Courier New;}} {\\colortbl;} \\fs20\r\n" "#{\\footnote Msi_Errors}\r\n${\\footnote Msi Errors}\r\n" "\\pard\\f0\\cf1\\sb90{\\li-150\\fi150\\brdrb\\fs24\\b\r\n" "Windows installer Errors\r\n\\par}\\li180\r\n" "\\trowd\\trgaph108\\trleft108 \\cellx1200\\cellx4400\\cellx9030\r\n" "\\intbl{\\b Error #\\cell Constant\\cell Message\\cell }\\row\r\n"; char szRtfFormat[] = "\\intbl %4i \\cell %-30s \\cell %s \\cell \\row\r\n"; char szRtfFooter[] = "\\page}"; char szInfoHeader[] = "PropertyId Value\r\n" "i2 l255\r\n" "_SummaryInformation PropertyId\r\n" "1 1252\r\n" "2 Debug Error table transform\r\n" "4 Microsoft Corporation\r\n" "5 Installer,MSI,Transform\r\n" "6 Replaces ship messages with debug messages\r\n" "7 ;1033\r\n" "14 100\r\n" // minimum version - means minimum version of debug error transform will always be 100 "16 49\r\n" "18 Windows installer\r\n" "19 2\r\n"; char szError[] = "Must specify a target file name, either *.txt, *.idt, *.rc, *.r, or *.rtf\n"; int _cdecl main(int argc, char *argv[]) { char* szExt = ""; char* szHeader; char* szFormat; char* szFooter; Bool fName = fFalse; int iLimit = idbgBase; DWORD cbWrite; HANDLE hFile; if (argc >= 2) szExt = argv[1]; int cbArg = lstrlenA(szExt); szExt += cbArg; while (cbArg-- && *(--szExt) != '.') ; if (lstrcmpi(szExt, ".txt") == 0) { fName = fTrue; iLimit = 9999; szHeader = szTxtHeader; szFormat = szTxtFormat; szFooter = szTxtFooter; } else if (lstrcmpi(szExt, ".idt") == 0) // Error.idt { szHeader = szIdtHeader; szFormat = szIdtFormat; szFooter = szIdtFooter; if ((szExt[-1] | 32) == 'i') // ErrorSI.idt { szHeader = szInfoHeader; cErrors = 0; } if ((szExt[-1] | 32) == 'd') // ErrorD.idt iLimit = 9999; } else if (lstrcmpi(szExt, ".rc") == 0) { szHeader = szRcHeader; szFormat = szRcFormat; szFooter = szRcFooter; } else if (lstrcmpi(szExt, ".r") == 0) { szHeader = szRHeader; szFormat = szRFormat; szFooter = szRFooter; } else if (lstrcmpi(szExt, ".rtf") == 0) { fName = fTrue; iLimit = 9999; szHeader = szRtfHeader; szFormat = szRtfFormat; szFooter = szRtfFooter; } else { hFile = ::GetStdHandle(STD_OUTPUT_HANDLE); ::WriteFile(hFile, szError, sizeof(szError), &cbWrite, 0); return 1; } hFile = ::CreateFile(argv[1], GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); ::WriteFile(hFile, szHeader, lstrlenA(szHeader), &cbWrite, 0); for(int iError = 2; iError < cErrors; iError++) // sort by error code for (int i = iError; i && rgErrors[i].iErr < rgErrors[i-1].iErr; i--) { rgErrors[0].iErr = rgErrors[i].iErr; rgErrors[0].szFmt = rgErrors[i].szFmt; rgErrors[0].szName = rgErrors[i].szName; rgErrors[i].iErr = rgErrors[i-1].iErr; rgErrors[i].szFmt = rgErrors[i-1].szFmt; rgErrors[i].szName = rgErrors[i-1].szName; rgErrors[i-1].iErr = rgErrors[0].iErr; rgErrors[i-1].szFmt = rgErrors[0].szFmt; rgErrors[i-1].szName = rgErrors[0].szName; } for(int c=1; c < cErrors; c++) { char szBuf[1024]; int iError = rgErrors[c].iErr; if (iError >= iLimit) break; if (fName) cbWrite = wsprintf(szBuf, szFormat, iError, rgErrors[c].szName, rgErrors[c].szFmt); else cbWrite = wsprintf(szBuf, szFormat, iError, rgErrors[c].szFmt); ::WriteFile(hFile, szBuf, cbWrite, &cbWrite, 0); } ::WriteFile(hFile, szFooter, lstrlenA(szFooter), &cbWrite, 0); ::CloseHandle(hFile); return 0; }
32.520468
100
0.59198
[ "transform" ]
60f1311992bab047f59718bc2f117d3a137f04c6
4,702
cpp
C++
src/Kripke/Kernel/SweepSubdomain.cpp
brandonneth/Kripke
9604d8f4e81fd18bf351c2a8578829053addb357
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
1
2019-11-20T21:46:39.000Z
2019-11-20T21:46:39.000Z
src/Kripke/Kernel/SweepSubdomain.cpp
brandonneth/Kripke
9604d8f4e81fd18bf351c2a8578829053addb357
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
src/Kripke/Kernel/SweepSubdomain.cpp
brandonneth/Kripke
9604d8f4e81fd18bf351c2a8578829053addb357
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2014-19, Lawrence Livermore National Security, LLC // and Kripke project contributors. See the COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) // #include <Kripke/Kernel.h> #include <Kripke.h> #include <Kripke/Arch/SweepSubdomains.h> #include <Kripke/Timing.h> #include <Kripke/VarTypes.h> using namespace Kripke; using namespace Kripke::Core; struct SweepSdom { static const std::string KernelName; template<typename AL> RAJA_INLINE void operator()(AL al, Kripke::Core::DataStore &data_store, Kripke::SdomId sdom_id) const { using ExecPolicy = typename Kripke::Arch::Policy_SweepSubdomains<AL>::ExecPolicy; auto sdom_al = getSdomAL(al, sdom_id); int num_directions = data_store.getVariable<Set>("Set/Direction").size(sdom_id); int num_groups = data_store.getVariable<Set>("Set/Group").size(sdom_id); int local_imax = data_store.getVariable<Set>("Set/ZoneI").size(sdom_id); int local_jmax = data_store.getVariable<Set>("Set/ZoneJ").size(sdom_id); int local_kmax = data_store.getVariable<Set>("Set/ZoneK").size(sdom_id); auto xcos = sdom_al.getView(data_store.getVariable<Field_Direction2Double>("quadrature/xcos")); auto ycos = sdom_al.getView(data_store.getVariable<Field_Direction2Double>("quadrature/ycos")); auto zcos = sdom_al.getView(data_store.getVariable<Field_Direction2Double>("quadrature/zcos")); auto view_id = data_store.getVariable<Field_Direction2Int>("quadrature/id").getView(sdom_id); auto view_jd = data_store.getVariable<Field_Direction2Int>("quadrature/jd").getView(sdom_id); auto view_kd = data_store.getVariable<Field_Direction2Int>("quadrature/kd").getView(sdom_id); auto dx = sdom_al.getView(data_store.getVariable<Field_ZoneI2Double>("dx")); auto dy = sdom_al.getView(data_store.getVariable<Field_ZoneJ2Double>("dy")); auto dz = sdom_al.getView(data_store.getVariable<Field_ZoneK2Double>("dz")); auto sigt = sdom_al.getView(data_store.getVariable<Kripke::Field_SigmaTZonal>("sigt_zonal")); auto psi = sdom_al.getView(data_store.getVariable<Kripke::Field_Flux>("psi")); auto rhs = sdom_al.getView(data_store.getVariable<Kripke::Field_Flux>("rhs")); auto psi_lf = sdom_al.getView(data_store.getVariable<Field_IPlane>("i_plane")); auto psi_fr = sdom_al.getView(data_store.getVariable<Field_JPlane>("j_plane")); auto psi_bo = sdom_al.getView(data_store.getVariable<Field_KPlane>("k_plane")); // Assumption: all directions in this sdom have same mesh traversal Direction d0{0}; int id = view_id(d0); int jd = view_jd(d0); int kd = view_kd(d0); ZoneI start_i((id>0) ? 0 : local_imax-1); ZoneJ start_j((jd>0) ? 0 : local_jmax-1); ZoneK start_k((kd>0) ? 0 : local_kmax-1); ZoneI end_i((id>0) ? local_imax : -1); ZoneJ end_j((jd>0) ? local_jmax : -1); ZoneK end_k((kd>0) ? local_kmax : -1); auto zone_layout = data_store.getVariable<ProductSet<3>>("Set/Zone").getLayout(sdom_id); RAJA::kernel<ExecPolicy>( camp::make_tuple( RAJA::TypedRangeSegment<Direction>(0, num_directions), RAJA::TypedRangeSegment<Group>(0, num_groups), RAJA::TypedRangeStrideSegment<ZoneK>(*start_k, *end_k, kd), RAJA::TypedRangeStrideSegment<ZoneJ>(*start_j, *end_j, jd), RAJA::TypedRangeStrideSegment<ZoneI>(*start_i, *end_i, id) ), KRIPKE_LAMBDA (Direction d, Group g, ZoneK k, ZoneJ j, ZoneI i) { double xcos_dxi = 2.0 * xcos(d) / dx(i); double ycos_dyj = 2.0 * ycos(d) / dy(j); double zcos_dzk = 2.0 * zcos(d) / dz(k); Zone z(zone_layout(*k, *j, *i)); /* Calculate new zonal flux */ double psi_d_g_z = (rhs(d,g,z) + psi_lf(d, g, j, k) * xcos_dxi + psi_fr(d, g, i, k) * ycos_dyj + psi_bo(d, g, i, j) * zcos_dzk) / (xcos_dxi + ycos_dyj + zcos_dzk + sigt(g, z)); psi(d, g, z) = psi_d_g_z; /* Apply diamond-difference relationships */ psi_lf(d, g, j, k) = 2.0 * psi_d_g_z - psi_lf(d, g, j, k); psi_fr(d, g, i, k) = 2.0 * psi_d_g_z - psi_fr(d, g, i, k); psi_bo(d, g, i, j) = 2.0 * psi_d_g_z - psi_bo(d, g, i, j); } ); } }; const std::string SweepSdom::KernelName = "sweepSubdomain"; void Kripke::Kernel::sweepSubdomain(Kripke::Core::DataStore &data_store, Kripke::SdomId sdom_id) { KRIPKE_TIMER(data_store, SweepSubdomain); ArchLayoutV al_v = data_store.getVariable<ArchLayout>("al").al_v; Kripke::dispatch(al_v, SweepSdom{}, data_store, sdom_id); }
37.616
99
0.661421
[ "mesh" ]
60f1e2bc24196d202b73fc589cb75b3bab38e5f4
9,990
cc
C++
third_party/blink/renderer/core/css/affected_by_pseudo_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
third_party/blink/renderer/core/css/affected_by_pseudo_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/core/css/affected_by_pseudo_test.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// 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 <memory> #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/css/style_engine.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/element_traversal.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/frame/local_frame_view.h" #include "third_party/blink/renderer/core/html/html_element.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" namespace blink { class AffectedByPseudoTest : public PageTestBase { protected: struct ElementResult { const blink::HTMLQualifiedName tag; bool children_or_siblings_affected_by; }; void SetHtmlInnerHTML(const char* html_content); void CheckElementsForFocus(ElementResult expected[], unsigned expected_count) const; }; void AffectedByPseudoTest::SetHtmlInnerHTML(const char* html_content) { GetDocument().documentElement()->setInnerHTML(String::FromUTF8(html_content)); UpdateAllLifecyclePhasesForTest(); } void AffectedByPseudoTest::CheckElementsForFocus( ElementResult expected[], unsigned expected_count) const { unsigned i = 0; HTMLElement* element = GetDocument().body(); for (; element && i < expected_count; element = Traversal<HTMLElement>::Next(*element), ++i) { ASSERT_TRUE(element->HasTagName(expected[i].tag)); DCHECK(element->GetComputedStyle()); ASSERT_EQ(expected[i].children_or_siblings_affected_by, element->ChildrenOrSiblingsAffectedByFocus()); } DCHECK(!element); DCHECK_EQ(i, expected_count); } // ":focus div" will mark ascendants of all divs with // childrenOrSiblingsAffectedByFocus. TEST_F(AffectedByPseudoTest, FocusedAscendant) { ElementResult expected[] = {{html_names::kBodyTag, true}, {html_names::kDivTag, true}, {html_names::kDivTag, false}, {html_names::kDivTag, false}, {html_names::kSpanTag, false}}; SetHtmlInnerHTML(R"HTML( <head> <style>:focus div { background-color: pink }</style> </head> <body> <div><div></div></div> <div><span></span></div> </body> )HTML"); CheckElementsForFocus(expected, sizeof(expected) / sizeof(ElementResult)); } // "body:focus div" will mark the body element with // childrenOrSiblingsAffectedByFocus. TEST_F(AffectedByPseudoTest, FocusedAscendantWithType) { ElementResult expected[] = {{html_names::kBodyTag, true}, {html_names::kDivTag, false}, {html_names::kDivTag, false}, {html_names::kDivTag, false}, {html_names::kSpanTag, false}}; SetHtmlInnerHTML(R"HTML( <head> <style>body:focus div { background-color: pink }</style> </head> <body> <div><div></div></div> <div><span></span></div> </body> )HTML"); CheckElementsForFocus(expected, sizeof(expected) / sizeof(ElementResult)); } // ":not(body):focus div" should not mark the body element with // childrenOrSiblingsAffectedByFocus. // Note that currently ":focus:not(body)" does not do the same. Then the :focus // is checked and the childrenOrSiblingsAffectedByFocus flag set before the // negated type selector is found. TEST_F(AffectedByPseudoTest, FocusedAscendantWithNegatedType) { ElementResult expected[] = {{html_names::kBodyTag, false}, {html_names::kDivTag, true}, {html_names::kDivTag, false}, {html_names::kDivTag, false}, {html_names::kSpanTag, false}}; SetHtmlInnerHTML(R"HTML( <head> <style>:not(body):focus div { background-color: pink }</style> </head> <body> <div><div></div></div> <div><span></span></div> </body> )HTML"); CheckElementsForFocus(expected, sizeof(expected) / sizeof(ElementResult)); } // Checking current behavior for ":focus + div", but this is a BUG or at best // sub-optimal. The focused element will also in this case get // childrenOrSiblingsAffectedByFocus even if it's really a sibling. Effectively, // the whole sub-tree of the focused element will have styles recalculated even // though none of the children are affected. There are other mechanisms that // makes sure the sibling also gets its styles recalculated. TEST_F(AffectedByPseudoTest, FocusedSibling) { ElementResult expected[] = {{html_names::kBodyTag, false}, {html_names::kDivTag, true}, {html_names::kSpanTag, false}, {html_names::kDivTag, false}}; SetHtmlInnerHTML(R"HTML( <head> <style>:focus + div { background-color: pink }</style> </head> <body> <div> <span></span> </div> <div></div> </body> )HTML"); CheckElementsForFocus(expected, sizeof(expected) / sizeof(ElementResult)); } TEST_F(AffectedByPseudoTest, AffectedByFocusUpdate) { // Check that when focussing the outer div in the document below, you only // get a single element style recalc. SetHtmlInnerHTML(R"HTML( <style>:focus { border: 1px solid lime; }</style> <div id=d tabIndex=1> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> )HTML"); UpdateAllLifecyclePhasesForTest(); unsigned start_count = GetStyleEngine().StyleForElementCount(); GetElementById("d")->focus(); UpdateAllLifecyclePhasesForTest(); unsigned element_count = GetStyleEngine().StyleForElementCount() - start_count; ASSERT_EQ(1U, element_count); } TEST_F(AffectedByPseudoTest, ChildrenOrSiblingsAffectedByFocusUpdate) { // Check that when focussing the outer div in the document below, you get a // style recalc for the whole subtree. SetHtmlInnerHTML(R"HTML( <style>:focus div { border: 1px solid lime; }</style> <div id=d tabIndex=1> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> )HTML"); UpdateAllLifecyclePhasesForTest(); unsigned start_count = GetStyleEngine().StyleForElementCount(); GetElementById("d")->focus(); UpdateAllLifecyclePhasesForTest(); unsigned element_count = GetStyleEngine().StyleForElementCount() - start_count; ASSERT_EQ(11U, element_count); } TEST_F(AffectedByPseudoTest, InvalidationSetFocusUpdate) { // Check that when focussing the outer div in the document below, you get a // style recalc for the outer div and the class=a div only. SetHtmlInnerHTML(R"HTML( <style>:focus .a { border: 1px solid lime; }</style> <div id=d tabIndex=1> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div class='a'></div> </div> )HTML"); UpdateAllLifecyclePhasesForTest(); unsigned start_count = GetStyleEngine().StyleForElementCount(); GetElementById("d")->focus(); UpdateAllLifecyclePhasesForTest(); unsigned element_count = GetStyleEngine().StyleForElementCount() - start_count; ASSERT_EQ(2U, element_count); } TEST_F(AffectedByPseudoTest, NoInvalidationSetFocusUpdate) { // Check that when focussing the outer div in the document below, you get a // style recalc for the outer div only. The invalidation set for :focus will // include 'a', but the id=d div should be affectedByFocus, not // childrenOrSiblingsAffectedByFocus. SetHtmlInnerHTML(R"HTML( <style>#nomatch:focus .a { border: 1px solid lime; }</style> <div id=d tabIndex=1> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div class='a'></div> </div> )HTML"); UpdateAllLifecyclePhasesForTest(); unsigned start_count = GetStyleEngine().StyleForElementCount(); GetElementById("d")->focus(); UpdateAllLifecyclePhasesForTest(); unsigned element_count = GetStyleEngine().StyleForElementCount() - start_count; ASSERT_EQ(1U, element_count); } TEST_F(AffectedByPseudoTest, FocusWithinCommonAncestor) { // Check that when changing the focus between 2 elements we don't need a style // recalc for all the ancestors affected by ":focus-within". SetHtmlInnerHTML(R"HTML( <style>div:focus-within { background-color: lime; }</style> <div> <div> <div id=focusme1 tabIndex=1></div> <div id=focusme2 tabIndex=2></div> <div> </div> )HTML"); UpdateAllLifecyclePhasesForTest(); unsigned start_count = GetStyleEngine().StyleForElementCount(); GetElementById("focusme1")->focus(); UpdateAllLifecyclePhasesForTest(); unsigned element_count = GetStyleEngine().StyleForElementCount() - start_count; EXPECT_EQ(3U, element_count); start_count += element_count; GetElementById("focusme2")->focus(); UpdateAllLifecyclePhasesForTest(); element_count = GetStyleEngine().StyleForElementCount() - start_count; // Only "focusme1" & "focusme2" elements need a recalc thanks to the common // ancestor strategy. EXPECT_EQ(2U, element_count); } TEST_F(AffectedByPseudoTest, HoverScrollbar) { SetHtmlInnerHTML( "<style>div::-webkit-scrollbar:hover { color: pink; }</style>" "<div id=div1></div>"); UpdateAllLifecyclePhasesForTest(); EXPECT_FALSE(GetElementById("div1")->GetComputedStyle()->AffectedByHover()); } } // namespace blink
30.090361
80
0.667267
[ "solid" ]
60f6773fb0cb499d315c326042482cb34888e84d
7,947
cpp
C++
test/arrayproperty.cpp
16tons/camp
3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8
[ "MIT" ]
1
2018-08-07T22:32:55.000Z
2018-08-07T22:32:55.000Z
test/arrayproperty.cpp
16tons/camp
3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8
[ "MIT" ]
null
null
null
test/arrayproperty.cpp
16tons/camp
3edae6d6a06036bac5faf4e7b9e7b5dd8e463af8
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2014 TEGESO/TEGESOFT and/or its subsidiary(-ies) and mother company. ** Contact: Tegesoft Information (contact@tegesoft.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 "arrayproperty.hpp" #include <camp/classget.hpp> #include <camp/arrayproperty.hpp> #include <boost/test/unit_test.hpp> using namespace ArrayPropertyTest; //----------------------------------------------------------------------------- struct ArrayPropertyFixture { ArrayPropertyFixture() { const camp::Class& metaclass = camp::classByType<MyClass>(); bools = &static_cast<const camp::ArrayProperty&>(metaclass.getPropertyById("bools")); ints = &static_cast<const camp::ArrayProperty&>(metaclass.getPropertyById("ints")); strings = &static_cast<const camp::ArrayProperty&>(metaclass.getPropertyById("strings")); objects = &static_cast<const camp::ArrayProperty&>(metaclass.getPropertyById("objects")); } const camp::ArrayProperty* bools; const camp::ArrayProperty* ints; const camp::ArrayProperty* strings; const camp::ArrayProperty* objects; MyClass object; }; //----------------------------------------------------------------------------- // Tests for camp::ArrayProperty //----------------------------------------------------------------------------- BOOST_FIXTURE_TEST_SUITE(ARRAYPROPERTY, ArrayPropertyFixture) //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(type) { BOOST_CHECK_EQUAL(bools->type(), camp::arrayType); BOOST_CHECK_EQUAL(ints->type(), camp::arrayType); BOOST_CHECK_EQUAL(strings->type(), camp::arrayType); BOOST_CHECK_EQUAL(objects->type(), camp::arrayType); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(elementType) { BOOST_CHECK_EQUAL(bools->elementType(), camp::boolType); BOOST_CHECK_EQUAL(ints->elementType(), camp::intType); BOOST_CHECK_EQUAL(strings->elementType(), camp::stringType); BOOST_CHECK_EQUAL(objects->elementType(), camp::userType); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(dynamic) { BOOST_CHECK_EQUAL(bools->dynamic(), false); BOOST_CHECK_EQUAL(ints->dynamic(), false); BOOST_CHECK_EQUAL(strings->dynamic(), true); BOOST_CHECK_EQUAL(objects->dynamic(), true); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(size) { BOOST_CHECK_EQUAL(bools->size(object), boost::size(object.bools)); BOOST_CHECK_EQUAL(ints->size(object), object.ints.size()); BOOST_CHECK_EQUAL(strings->size(object), object.strings.size()); BOOST_CHECK_EQUAL(objects->size(object), object.objects.size()); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(get) { BOOST_CHECK_EQUAL(bools->get(object, 0), camp::Value(object.bools[0])); BOOST_CHECK_EQUAL(bools->get(object, 1), camp::Value(object.bools[1])); BOOST_CHECK_THROW(bools->get(object, 2), camp::OutOfRange); BOOST_CHECK_EQUAL(ints->get(object, 0), camp::Value(object.ints[0])); BOOST_CHECK_EQUAL(ints->get(object, 1), camp::Value(object.ints[1])); BOOST_CHECK_EQUAL(ints->get(object, 2), camp::Value(object.ints[2])); BOOST_CHECK_THROW(ints->get(object, 3), camp::OutOfRange); BOOST_CHECK_EQUAL(strings->get(object, 0), camp::Value(object.strings[0])); BOOST_CHECK_EQUAL(strings->get(object, 1), camp::Value(object.strings[1])); BOOST_CHECK_EQUAL(strings->get(object, 2), camp::Value(object.strings[2])); BOOST_CHECK_EQUAL(strings->get(object, 3), camp::Value(object.strings[3])); BOOST_CHECK_THROW(strings->get(object, 4), camp::OutOfRange); std::list<MyType>::const_iterator it = object.objects.begin(); BOOST_CHECK_EQUAL(objects->get(object, 0), camp::Value(*boost::next(it, 0))); BOOST_CHECK_EQUAL(objects->get(object, 1), camp::Value(*boost::next(it, 1))); BOOST_CHECK_EQUAL(objects->get(object, 2), camp::Value(*boost::next(it, 2))); BOOST_CHECK_EQUAL(objects->get(object, 3), camp::Value(*boost::next(it, 3))); BOOST_CHECK_EQUAL(objects->get(object, 4), camp::Value(*boost::next(it, 4))); BOOST_CHECK_THROW(objects->get(object, 5), camp::OutOfRange); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(set) { bools->set(object, 1, true); ints->set(object, 1, 20); strings->set(object, 1, "hello"); objects->set(object, 1, MyType(8)); BOOST_CHECK_EQUAL(object.bools[1], true); BOOST_CHECK_EQUAL(object.ints[1], 20); BOOST_CHECK_EQUAL(object.strings[1], "hello"); BOOST_CHECK(*boost::next(object.objects.begin(), 1) == MyType(8)); BOOST_CHECK_THROW(bools->set(object, 10, true), camp::OutOfRange); BOOST_CHECK_THROW(ints->set(object, 10, 1), camp::OutOfRange); BOOST_CHECK_THROW(strings->set(object, 10, "hi"), camp::OutOfRange); BOOST_CHECK_THROW(objects->set(object, 10, MyType(9)), camp::OutOfRange); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(insert) { BOOST_CHECK_THROW(bools->insert(object, 0, true), camp::ForbiddenWrite); BOOST_CHECK_THROW(ints->insert(object, 0, true), camp::ForbiddenWrite); std::size_t stringsSize = object.strings.size(); std::size_t objectsSize = object.objects.size(); strings->insert(object, 1, "bonjour"); objects->insert(object, 1, MyType(10)); BOOST_CHECK_EQUAL(object.strings.size(), stringsSize + 1); BOOST_CHECK_EQUAL(object.objects.size(), objectsSize + 1); BOOST_CHECK_EQUAL(object.strings[1], "bonjour"); BOOST_CHECK(*boost::next(object.objects.begin(), 1) == MyType(10)); } //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(remove) { BOOST_CHECK_THROW(bools->remove(object, 0), camp::ForbiddenWrite); BOOST_CHECK_THROW(ints->remove(object, 0), camp::ForbiddenWrite); std::string string1 = object.strings[1]; MyType object1 = *boost::next(object.objects.begin(), 1); std::size_t stringsSize = object.strings.size(); std::size_t objectsSize = object.objects.size(); strings->remove(object, 0); objects->remove(object, 0); BOOST_CHECK_EQUAL(object.strings.size(), stringsSize - 1); BOOST_CHECK_EQUAL(object.objects.size(), objectsSize - 1); BOOST_CHECK(object.strings.front() == string1); BOOST_CHECK(object.objects.front() == object1); } BOOST_AUTO_TEST_SUITE_END()
42.956757
97
0.615956
[ "object" ]
8801826f551e4299ba4364a6d90094ab17ecac79
8,457
cpp
C++
CrescentEngine/Core/Defunct/Primitive.cpp
xRiveria/Crescent-Engine
b6512b6a8dab2d27cf542c562ccc28f21bf2345d
[ "Apache-2.0" ]
2
2020-12-18T03:43:07.000Z
2020-12-23T12:20:00.000Z
CrescentEngine/Core/Defunct/Primitive.cpp
xRiveria/Crescent-Engine
b6512b6a8dab2d27cf542c562ccc28f21bf2345d
[ "Apache-2.0" ]
null
null
null
CrescentEngine/Core/Defunct/Primitive.cpp
xRiveria/Crescent-Engine
b6512b6a8dab2d27cf542c562ccc28f21bf2345d
[ "Apache-2.0" ]
null
null
null
#include "CrescentPCH.h" /* #include "Primitive.h" #include <imgui/imgui.h> #include <sstream> #include <glm/gtc/type_ptr.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm/gtx/quaternion.hpp> static int temporaryUUID = 0; float planeVertices[] = { // positions // normals // texcoords 25.0f, -0.5f, 25.0f, 0.0f, 1.0f, 0.0f, 25.0f, 0.0f, -25.0f, -0.5f, 25.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -25.0f, -0.5f, -25.0f, 0.0f, 1.0f, 0.0f, 0.0f, 25.0f, 25.0f, -0.5f, 25.0f, 0.0f, 1.0f, 0.0f, 25.0f, 0.0f, -25.0f, -0.5f, -25.0f, 0.0f, 1.0f, 0.0f, 0.0f, 25.0f, 25.0f, -0.5f, -25.0f, 0.0f, 1.0f, 0.0f, 25.0f, 25.0f }; float cubeVertices[] = { //Positions //Normals //Texture Coordinates -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; namespace Crescent { Primitive::Primitive(const PrimitiveShape& primitiveShape) { SetupPrimitiveBuffers(primitiveShape); } void Primitive::SetupPrimitiveBuffers(const PrimitiveShape& primitiveShape) { m_PrimitiveShape = primitiveShape; m_PrimitiveObjectID = temporaryUUID++; glGenVertexArrays(1, &m_VertexArrayID); glGenBuffers(1, &m_VertexBufferID); glBindVertexArray(m_VertexArrayID); glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferID); switch (primitiveShape) { case PrimitiveShape::PlanePrimitive: { glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW); break; } case PrimitiveShape::CubePrimitive: { glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW); break; } case PrimitiveShape::QuadPrimitive: { break; } } glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); glBindVertexArray(0); } void Primitive::BindPrimitiveVertexArray() const { glBindVertexArray(m_VertexArrayID); } void Primitive::DrawPrimitive(Shader& shader) { shader.UseShader(); glBindVertexArray(m_VertexArrayID); glm::mat4 rotation = glm::toMat4(glm::quat(m_PrimitiveRotation)); glm::mat4 modelMatrix = glm::translate(glm::mat4(1.0f), m_PrimitivePosition) * rotation * glm::scale(glm::mat4(1.0f), m_PrimitiveScale); shader.SetUniformMat4("model", modelMatrix); switch (m_PrimitiveShape) { case PrimitiveShape::CubePrimitive: { glDrawArrays(GL_TRIANGLES, 0, 36); break; } case PrimitiveShape::PlanePrimitive: { glDrawArrays(GL_TRIANGLES, 0, 6); break; } case PrimitiveShape::QuadPrimitive: { break; } } glBindVertexArray(0); } void Primitive::DrawEditorSettings() { ImGui::Begin((ConvertPrimitiveEnumToString() + ConvertUUIDToChar()).c_str()); ImGui::DragFloat3((std::string("Position##") + ConvertUUIDToChar()).c_str(), glm::value_ptr(m_PrimitivePosition), 0.05f); ImGui::DragFloat3((std::string("Rotation##") + ConvertUUIDToChar()).c_str(), glm::value_ptr(m_PrimitiveRotation), 0.05f); ImGui::DragFloat3((std::string("Scale##") + ConvertUUIDToChar()).c_str(), glm::value_ptr(m_PrimitiveScale)); ImGui::End(); } std::string Primitive::ConvertUUIDToChar() const { std::string result; std::stringstream convert; convert << m_PrimitiveObjectID; result = convert.str(); return convert.str(); } std::string Primitive::ConvertPrimitiveEnumToString() const //For use with ImGui, { switch (m_PrimitiveShape) { case PrimitiveShape::PlanePrimitive: { return "Plane##"; } case PrimitiveShape::CubePrimitive: { return "Cube##"; } case PrimitiveShape::QuadPrimitive: { return "Quad##"; } } } void TransparentQuad::SetupTransparentQuadBuffers() { float transparentVertices[] = { //Positions //Texture Coordinates 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.0f, 1.0f, 0.0f }; glGenVertexArrays(1, &m_VertexArrayID); glGenBuffers(1, &m_VertexBufferID); glBindVertexArray(m_VertexArrayID); glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferID); glBufferData(GL_ARRAY_BUFFER, sizeof(transparentVertices), transparentVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glBindVertexArray(0); } void TransparentQuad::DrawTransparentQuad(Shader& shader, glm::mat4& modelMatrix) { shader.UseShader(); glBindVertexArray(m_VertexArrayID); shader.SetUniformMat4("model", modelMatrix); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); } void TransparentQuad::DrawTransparentQuad(Shader& shader, glm::mat4& modelMatrix, Texture2D& texture) { shader.UseShader(); glBindVertexArray(m_VertexArrayID); texture.BindTexture(); shader.SetUniformMat4("model", modelMatrix); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); } } */
34.518367
144
0.531631
[ "model" ]
880258f85245cd9b2fe50e0cd2fa9e38f3c531ff
1,900
cpp
C++
marlin-firmware/Marlin/src/feature/leds/tempstat.cpp
voicevon/gogame_bot
a1d91f4a1b2537d00b5cd5ed78d429a9c1aad3d1
[ "MIT" ]
6
2020-12-04T21:55:04.000Z
2022-02-02T20:49:45.000Z
marlin-firmware/Marlin/src/feature/leds/tempstat.cpp
voicevon/gogame_bot
a1d91f4a1b2537d00b5cd5ed78d429a9c1aad3d1
[ "MIT" ]
24
2020-12-25T05:00:51.000Z
2021-04-20T00:56:50.000Z
marlin-firmware/Marlin/src/feature/leds/tempstat.cpp
voicevon/gogame_bot
a1d91f4a1b2537d00b5cd5ed78d429a9c1aad3d1
[ "MIT" ]
3
2021-05-01T15:13:41.000Z
2022-02-11T01:15:30.000Z
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ /** * Marlin RGB LED general support */ #include "../../inc/MarlinConfig.h" #if ENABLED(TEMP_STAT_LEDS) #include "tempstat.h" #include "../../module/temperature.h" void handle_status_leds() { static int8_t old_red = -1; // Invalid value to force LED initialization static millis_t next_status_led_update_ms = 0; if (ELAPSED(millis(), next_status_led_update_ms)) { next_status_led_update_ms += 500; // Update every 0.5s float max_temp = TERN0(HAS_HEATED_BED, _MAX(thermalManager.degTargetBed(), thermalManager.degBed())); HOTEND_LOOP() max_temp = _MAX(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e)); const int8_t new_red = (max_temp > 55.0) ? HIGH : (max_temp < 54.0 || old_red < 0) ? LOW : old_red; if (new_red != old_red) { old_red = new_red; #if PIN_EXISTS(STAT_LED_RED) WRITE(STAT_LED_RED_PIN, new_red); #endif #if PIN_EXISTS(STAT_LED_BLUE) WRITE(STAT_LED_BLUE_PIN, !new_red); #endif } } } #endif // TEMP_STAT_LEDS
33.928571
105
0.706316
[ "3d" ]
8802a7546dc06dcbb6a4d55b8ecc60239c0ea5b1
3,626
cxx
C++
Libs/Core/Code/m3doFolder.cxx
midasplatform/MidasClient
728d4a5969691b54b7d0efd2dbad5a4df85d1a0e
[ "Apache-2.0" ]
null
null
null
Libs/Core/Code/m3doFolder.cxx
midasplatform/MidasClient
728d4a5969691b54b7d0efd2dbad5a4df85d1a0e
[ "Apache-2.0" ]
null
null
null
Libs/Core/Code/m3doFolder.cxx
midasplatform/MidasClient
728d4a5969691b54b7d0efd2dbad5a4df85d1a0e
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2011 Kitware Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "m3doFolder.h" #include "m3doItem.h" #include "midasStandardIncludes.h" #include <QString> namespace m3do { Folder::Folder() { m_Id = 0; m_BitstreamCount = 0; m_ParentFolder = NULL; } // copy constructor Folder::Folder(Folder* other) { m_Id = other->GetId(); m_Uuid = other->GetUuid(); m_ParentFolder = other->GetParentFolder(); m_Path = other->GetPath(); m_Name = other->GetName(); m_Description = other->GetDescription(); m_Folders = other->GetFolders(); m_Items = other->GetItems(); } Folder::~Folder() { // Delete the subtree std::vector<Folder *>::iterator itF = m_Folders.begin(); while( itF != m_Folders.end() ) { Folder* f = *itF; itF++; delete f; } std::vector<Item *>::iterator itI = m_Items.begin(); while( itI != m_Items.end() ) { Item* i = *itI; itI++; delete i; } } void Folder::AddFolder(Folder* folder) { m_Folders.push_back(folder); } void Folder::AddItem(Item* item) { m_Items.push_back(item); } void Folder::Clear() { this->m_Name = ""; this->m_Description = ""; this->m_Uuid = ""; this->m_HasAgreement = ""; this->m_Size = ""; } void Folder::SetName(const char* name) { m_Name = name; } std::string & Folder::GetName() { return m_Name; } // Set/Get description void Folder::SetDescription(const char* description) { m_Description = description; } std::string & Folder::GetDescription() { return m_Description; } // Get the list of child folders std::vector<Folder *> & Folder::GetFolders() { return m_Folders; } std::vector<Item *> & Folder::GetItems() { return m_Items; } std::string Folder::GetTypeName() { return "Folder"; } int Folder::GetResourceType() { return midas3ResourceType::FOLDER; } void Folder::SetBitstreamCount(unsigned int count) { m_BitstreamCount = count; } unsigned int Folder::GetBitstreamCount() { return m_BitstreamCount; } void Folder::SetParentFolder(Folder* folder) { m_ParentFolder = folder; } Folder * Folder::GetParentFolder() { return m_ParentFolder; } void Folder::SetPath(const std::string& path) { m_Path = path; } std::string & Folder::GetPath() { return m_Path; } /** Load */ bool Folder::Load() { return m_Proxy->Load(); } /** Fill the full tree with Folder and collection */ bool Folder::LoadTree() { return m_Proxy->LoadTree(); } bool Folder::SetValue(std::string key, std::string value, bool append) { QString keyStr = key.c_str(); keyStr = keyStr.toUpper(); key = keyStr.toStdString(); if( key == "NAME" ) { if( append ) { m_Name += value; } else { m_Name = value; } return true; } if( key == "DESCRIPTION" ) { if( append ) { m_Description += value; } else { m_Description = value; } return true; } return false; } } // end namespace
17.687805
79
0.61914
[ "vector" ]
880938a8decfb79741e84ff3c4df5eeb91f85236
984
cpp
C++
mr.Sadman/Classes/GameAct/Objects/Shared/Fire/Fire.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
mr.Sadman/Classes/GameAct/Objects/Shared/Fire/Fire.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
mr.Sadman/Classes/GameAct/Objects/Shared/Fire/Fire.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
#include "Fire.hpp" #include "Resources/Cache/Cache.hpp" namespace GameAct { namespace Shared { void Fire::initialize() { Stream::initialize(); _particle->setStartColor( cocos2d::Color4F::RED ); _particle->setEndColor( cocos2d::Color4F::RED ); } std::string Fire::getResourcesName() const { return "Radiation"; } void Fire::setSize( cocos2d::Size size ) { // configuration _particle->setStartSize( 5.0f ); _particle->setEndSize( 5.0f ); _particle->setStartSizeVar( 0.0f ); _particle->setEndSizeVar( 0.0f ); _particle->setRadialAccel( size.width * size.width / 500.0f ); _particle->setLife( 0.7f ); _particle->setLifeVar( 0.2f ); _particle->setEmissionRate( 80.0f ); float delta = 2.0f * size.width; float x = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); float y = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); _particle->setGravity( cocos2d::Vec2( x, y ) ); Object::setSize( size ); } } }
20.5
67
0.660569
[ "object" ]
880c7cf4fa8159d49d3d93afc67d8ff658a68aef
15,803
cpp
C++
Modules/Tools/Sources/Tools/AssetCache/Private/AssetCacheClient.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-11-14T10:18:24.000Z
2020-11-14T10:18:24.000Z
Modules/Tools/Sources/Tools/AssetCache/Private/AssetCacheClient.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
null
null
null
Modules/Tools/Sources/Tools/AssetCache/Private/AssetCacheClient.cpp
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-09-05T21:16:17.000Z
2020-09-05T21:16:17.000Z
#include "Tools/AssetCache/AssetCacheClient.h" #include "Tools/AssetCache/ChunkSplitter.h" #include <FileSystem/FileSystem.h> #include <Concurrency/LockGuard.h> #include <Concurrency/Thread.h> #include <FileSystem/DynamicMemoryFile.h> #include <Preferences/PreferencesRegistrator.h> #include <Time/SystemTimer.h> #include <Utils/StringFormat.h> #include <Logger/Logger.h> #include <Network/NetCore.h> namespace DAVA { namespace AssetCacheClientDetail { InspInfoRegistrator inspInfoRegistrator(AssetCacheClient::ConnectionParams::TypeInfo(), { PREF_ARG("ip", DAVA::AssetCache::GetLocalHost()), PREF_ARG("port", DAVA::AssetCache::ASSET_SERVER_PORT), PREF_ARG("timeoutms", DAVA::uint64(10 * 1000)) }); }; AssetCacheClient::AssetCacheClient() : dispatcher([](const Function<void()>& fn) { fn(); }) , client(&dispatcher) , isActive(false) { dispatcher.LinkToCurrentThread(); client.AddListener(this); } AssetCacheClient::~AssetCacheClient() { client.RemoveListener(this); DVASSERT(isActive == false); } AssetCache::Error AssetCacheClient::ConnectSynchronously(const ConnectionParams& connectionParams) { isActive = true; timeoutMs = connectionParams.timeoutms; client.Connect(connectionParams.ip, AssetCache::ASSET_SERVER_PORT); { LockGuard<Mutex> guard(connectEstablishLocker); uint64 startTime = SystemTimer::GetMs(); while (client.ChannelIsOpened() == false) { ProcessNetwork(); if (!isActive) { return AssetCache::Error::CANNOT_CONNECT; } uint64 deltaTime = SystemTimer::GetMs() - startTime; if (((timeoutMs > 0) && (deltaTime > timeoutMs)) && (client.ChannelIsOpened() == false)) { Logger::Error("Timeout on connecting to asset cache %s (%lld ms)", connectionParams.ip.c_str(), timeoutMs); isActive = false; return AssetCache::Error::OPERATION_TIMEOUT; } } } return CheckStatusSynchronously(); } void AssetCacheClient::Disconnect() { isActive = false; { // wait for connection establishing loop is finished LockGuard<Mutex> guard(connectEstablishLocker); } client.DisconnectBlocked(); } AssetCache::Error AssetCacheClient::CheckStatusSynchronously() { { LockGuard<Mutex> guard(requestLocker); request = Request(); request.requestID = AssetCache::ePacketID::PACKET_STATUS_REQUEST; } AssetCache::Error resultCode = AssetCache::Error::CANNOT_SEND_REQUEST; bool requestSent = client.RequestServerStatus(); if (requestSent) { resultCode = WaitRequest(); } { LockGuard<Mutex> guard(requestLocker); request.Reset(); } return resultCode; } AssetCache::Error AssetCacheClient::AddToCacheSynchronously(const AssetCache::CacheItemKey& key, const AssetCache::CachedItemValue& value) { uint64 dataSizeOverall = 0; uint32 chunksOverall = 0; { LockGuard<Mutex> guard(requestLocker); request = Request(AssetCache::PACKET_ADD_CHUNK_REQUEST, key); addFilesRequest.Reset(); value.Serialize(addFilesRequest.serializedData); dataSizeOverall = addFilesRequest.serializedData->GetSize(); chunksOverall = AssetCache::ChunkSplitter::GetNumberOfChunks(dataSizeOverall); addFilesRequest.chunksSent = 0; } AssetCache::Error resultCode = AssetCache::Error::CANNOT_SEND_REQUEST; for (uint32 currentChunk = 0; currentChunk < chunksOverall; ++currentChunk) { Vector<uint8> chunkData; { LockGuard<Mutex> guard(requestLocker); request = Request(AssetCache::PACKET_ADD_CHUNK_REQUEST, key); chunkData = AssetCache::ChunkSplitter::GetChunk(addFilesRequest.serializedData->GetDataVector(), currentChunk); } resultCode = AssetCache::Error::CANNOT_SEND_REQUEST; bool requestSent = client.RequestAddNextChunk(key, dataSizeOverall, chunksOverall, currentChunk, chunkData); if (requestSent) { resultCode = WaitRequest(); } { LockGuard<Mutex> guard(requestLocker); request.Reset(); } if (resultCode != AssetCache::Error::NO_ERRORS) { break; } } return resultCode; } AssetCache::Error AssetCacheClient::RequestFromCacheSynchronously(const AssetCache::CacheItemKey& key, AssetCache::CachedItemValue* value) { DVASSERT(value != nullptr); { LockGuard<Mutex> guard(requestLocker); request = Request(AssetCache::PACKET_GET_CHUNK_REQUEST, key); getFilesRequest.Reset(); } AssetCache::Error resultCode = AssetCache::Error::CANNOT_SEND_REQUEST; bool requestSent = client.RequestGetNextChunk(key, 0); if (requestSent) { resultCode = WaitRequest(); } uint32 chunksOverall = 0; { LockGuard<Mutex> guard(requestLocker); request.Reset(); chunksOverall = getFilesRequest.chunksOverall; } if (resultCode == AssetCache::Error::NO_ERRORS) { DVASSERT(chunksOverall > 0); for (uint32 currentChunk = 1; currentChunk < chunksOverall; ++currentChunk) { { LockGuard<Mutex> guard(requestLocker); request = Request(AssetCache::PACKET_GET_CHUNK_REQUEST, key); } resultCode = AssetCache::Error::CANNOT_SEND_REQUEST; bool requestSent = client.RequestGetNextChunk(key, currentChunk); if (requestSent) { resultCode = WaitRequest(); } { LockGuard<Mutex> guard(requestLocker); request.Reset(); } if (resultCode != AssetCache::Error::NO_ERRORS) { break; } } if (resultCode == AssetCache::Error::NO_ERRORS) { LockGuard<Mutex> guard(requestLocker); if (getFilesRequest.chunksReceived == getFilesRequest.chunksOverall && getFilesRequest.bytesRemaining == 0) { ScopedPtr<DynamicMemoryFile> f(DynamicMemoryFile::Create(std::move(getFilesRequest.receivedData), File::OPEN | File::READ, "receivedData")); value->Deserialize(f); const AssetCache::CachedItemValue::Description& description = value->GetDescription(); Logger::Info("Data got from cache. Generated %s on machine %s (%s)", description.creationDate.c_str(), description.machineName.c_str(), description.comment.c_str()); } else { Logger::Error("Packet was not completely transferred. Chunks %u/%u, bytes remaining: %u", getFilesRequest.chunksReceived, getFilesRequest.chunksOverall, getFilesRequest.bytesRemaining); resultCode = AssetCache::Error::CORRUPTED_DATA; } } } return resultCode; } AssetCache::Error AssetCacheClient::RemoveFromCacheSynchronously(const AssetCache::CacheItemKey& key) { { LockGuard<Mutex> guard(requestLocker); request = Request(AssetCache::PACKET_REMOVE_REQUEST, key); } AssetCache::Error resultCode = AssetCache::Error::CANNOT_SEND_REQUEST; bool requestSent = client.RequestRemoveData(key); if (requestSent) { resultCode = WaitRequest(); } { LockGuard<Mutex> guard(requestLocker); request.Reset(); } return resultCode; } AssetCache::Error AssetCacheClient::ClearCacheSynchronously() { { LockGuard<Mutex> guard(requestLocker); request = Request(AssetCache::PACKET_CLEAR_REQUEST); } AssetCache::Error resultCode = AssetCache::Error::CANNOT_SEND_REQUEST; bool requestSent = client.RequestClearCache(); if (requestSent) { resultCode = WaitRequest(); } { LockGuard<Mutex> guard(requestLocker); request.Reset(); } return resultCode; } AssetCache::Error AssetCacheClient::WaitRequest() { uint64 startTime = SystemTimer::GetMs(); Request currentRequest; { LockGuard<Mutex> guard(requestLocker); currentRequest = request; } while (currentRequest.recieved == false) { ProcessNetwork(); if (!isActive) { return AssetCache::Error::OPERATION_TIMEOUT; } { LockGuard<Mutex> guard(requestLocker); currentRequest = request; } uint64 deltaTime = SystemTimer::GetMs() - startTime; if (((timeoutMs > 0) && (deltaTime > timeoutMs)) && (currentRequest.recieved == false) && (currentRequest.processingRequest == false)) { Logger::FrameworkDebug("Operation timeout: (%lld ms)", timeoutMs); return AssetCache::Error::OPERATION_TIMEOUT; } } if (currentRequest.result == AssetCache::Error::NO_ERRORS) { while (currentRequest.processingRequest) { ProcessNetwork(); LockGuard<Mutex> guard(requestLocker); currentRequest = request; } } return currentRequest.result; } void AssetCacheClient::OnServerStatusReceived() { LockGuard<Mutex> guard(requestLocker); if (request.requestID == AssetCache::PACKET_STATUS_REQUEST) { request.result = AssetCache::Error::NO_ERRORS; request.recieved = true; request.processingRequest = false; } else { //skip this request, because it was canceled by timeout } } void AssetCacheClient::OnAddedToCache(const AssetCache::CacheItemKey& key, bool added) { LockGuard<Mutex> guard(requestLocker); if ((request.requestID == AssetCache::PACKET_ADD_CHUNK_REQUEST) && request.key == key) { request.result = (added) ? AssetCache::Error::NO_ERRORS : AssetCache::Error::SERVER_ERROR; request.recieved = true; request.processingRequest = false; } else { //skip this request, because it was canceled by timeout } } void AssetCacheClient::OnReceivedFromCache(const AssetCache::CacheItemKey& key, uint64 dataSize, uint32 numOfChunks, uint32 chunkNumber, const Vector<uint8>& chunkData) { LockGuard<Mutex> guard(requestLocker); if (request.requestID == AssetCache::PACKET_GET_CHUNK_REQUEST && request.key == key) { if (getFilesRequest.chunksReceived == 0) { if (dataSize == 0 || numOfChunks == 0) { request.result = AssetCache::Error::NOT_FOUND_ON_SERVER; request.recieved = true; request.processingRequest = false; return; } else { request.result = AssetCache::Error::NO_ERRORS; getFilesRequest.chunksOverall = numOfChunks; getFilesRequest.bytesRemaining = static_cast<size_t>(dataSize); getFilesRequest.receivedData.resize(getFilesRequest.bytesRemaining); Logger::FrameworkDebug("Received info: %u bytes, %u chunks", dataSize, numOfChunks); } } if (chunkData.empty()) { request.result = AssetCache::Error::NOT_FOUND_ON_SERVER; } else if (chunkNumber != getFilesRequest.chunksReceived) { Logger::Error("Wrong chunk: expected #%u, received #%u", getFilesRequest.chunksReceived, chunkNumber); request.result = AssetCache::Error::WRONG_CHUNK; } else if (getFilesRequest.bytesRemaining < chunkData.size()) { Logger::Error("Chunk #%u size is too big. Remaining bytes: %u, received chunk size: ", chunkNumber, getFilesRequest.bytesRemaining, chunkData.size()); request.result = AssetCache::Error::WRONG_CHUNK; } else { request.result = AssetCache::Error::NO_ERRORS; Memcpy(getFilesRequest.receivedData.data() + getFilesRequest.bytesReceived, chunkData.data(), chunkData.size()); getFilesRequest.bytesReceived += chunkData.size(); getFilesRequest.bytesRemaining -= chunkData.size(); ++(getFilesRequest.chunksReceived); Logger::FrameworkDebug("Chunk #%u received: %u bytes. Overall received %u, remaining %u", chunkNumber, chunkData.size(), getFilesRequest.bytesReceived, getFilesRequest.bytesRemaining); } request.recieved = true; request.processingRequest = false; } else { //skip this request, because it was canceled by timeout } } void AssetCacheClient::OnRemovedFromCache(const AssetCache::CacheItemKey& key, bool removed) { LockGuard<Mutex> guard(requestLocker); if (request.requestID == AssetCache::PACKET_REMOVE_REQUEST && request.key == key) { request.result = (removed) ? AssetCache::Error::NO_ERRORS : AssetCache::Error::SERVER_ERROR; request.recieved = true; request.processingRequest = false; } else { //skip this request, because it was canceled by timeout } } void AssetCacheClient::OnCacheCleared(bool cleared) { LockGuard<Mutex> guard(requestLocker); if (request.requestID == AssetCache::PACKET_CLEAR_REQUEST) { request.result = (cleared) ? AssetCache::Error::NO_ERRORS : AssetCache::Error::SERVER_ERROR; request.recieved = true; request.processingRequest = false; } else { //skip this request, because it was canceled by timeout } } void AssetCacheClient::OnIncorrectPacketReceived(AssetCache::IncorrectPacketType type) { LockGuard<Mutex> guard(requestLocker); request.recieved = true; request.processingRequest = false; switch (type) { case AssetCache::IncorrectPacketType::UNDEFINED_DATA: request.result = AssetCache::Error::CORRUPTED_DATA; break; case AssetCache::IncorrectPacketType::UNSUPPORTED_VERSION: request.result = AssetCache::Error::UNSUPPORTED_VERSION; break; case AssetCache::IncorrectPacketType::UNEXPECTED_PACKET: request.result = AssetCache::Error::UNEXPECTED_PACKET; break; default: DVASSERT(false, Format("Unexpected incorrect packet type: %d", type).c_str()); request.result = AssetCache::Error::CORRUPTED_DATA; break; } } void AssetCacheClient::OnClientProxyStateChanged() { if (client.ChannelIsOpened() == false) { isActive = false; LockGuard<Mutex> guard(requestLocker); request.recieved = true; request.processingRequest = false; request.result = AssetCache::Error::CANNOT_CONNECT; } } bool AssetCacheClient::IsConnected() const { return client.ChannelIsOpened(); } void AssetCacheClient::ProcessNetwork() { Net::NetCore::Instance()->Update(); if (dispatcher.HasEvents()) { dispatcher.ProcessEvents(); } } AssetCacheClient::ConnectionParams::ConnectionParams() { PreferencesStorage::Instance()->RegisterPreferences(this); } AssetCacheClient::ConnectionParams::~ConnectionParams() { PreferencesStorage::Instance()->UnregisterPreferences(this); } } //END of DAVA
31.108268
196
0.62292
[ "vector" ]
880ed6c727d5679fbf8e0368f90f5cd06cade0a4
18,897
cpp
C++
src/Server.cpp
AndreVuillemot160/cuberite
a7076b5ac1d4de9fef54a3cae215b9b848c28daf
[ "Apache-2.0" ]
null
null
null
src/Server.cpp
AndreVuillemot160/cuberite
a7076b5ac1d4de9fef54a3cae215b9b848c28daf
[ "Apache-2.0" ]
null
null
null
src/Server.cpp
AndreVuillemot160/cuberite
a7076b5ac1d4de9fef54a3cae215b9b848c28daf
[ "Apache-2.0" ]
null
null
null
// ReDucTor is an awesome guy who helped me a lot #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "Server.h" #include "ClientHandle.h" #include "Mobs/Monster.h" #include "Root.h" #include "World.h" #include "Bindings/PluginManager.h" #include "ChatColor.h" #include "Entities/Player.h" #include "Inventory.h" #include "Item.h" #include "FurnaceRecipe.h" #include "WebAdmin.h" #include "Protocol/ProtocolRecognizer.h" #include "CommandOutput.h" #include "FastRandom.h" #include "IniFile.h" #include <fstream> #include <sstream> #include <iostream> //////////////////////////////////////////////////////////////////////////////// // cServerListenCallbacks: class cServerListenCallbacks: public cNetwork::cListenCallbacks { cServer & m_Server; UInt16 m_Port; virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort) override { return m_Server.OnConnectionAccepted(a_RemoteIPAddress); } virtual void OnAccepted(cTCPLink & a_Link) override {} virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override { LOGWARNING("Cannot listen on port %d: %d (%s).", m_Port, a_ErrorCode, a_ErrorMsg.c_str()); } public: cServerListenCallbacks(cServer & a_Server, UInt16 a_Port): m_Server(a_Server), m_Port(a_Port) { } }; //////////////////////////////////////////////////////////////////////////////// // cServer::cTickThread: cServer::cTickThread::cTickThread(cServer & a_Server) : Super("Server Ticker"), m_Server(a_Server) { } void cServer::cTickThread::Execute(void) { auto LastTime = std::chrono::steady_clock::now(); static const auto msPerTick = std::chrono::milliseconds(50); while (!m_ShouldTerminate) { auto NowTime = std::chrono::steady_clock::now(); auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(NowTime - LastTime).count(); m_Server.Tick(static_cast<float>(msec)); auto TickTime = std::chrono::steady_clock::now() - NowTime; if (TickTime < msPerTick) { // Stretch tick time until it's at least msPerTick std::this_thread::sleep_for(msPerTick - TickTime); } LastTime = NowTime; } } //////////////////////////////////////////////////////////////////////////////// // cServer: cServer::cServer(void) : m_PlayerCount(0), m_ClientViewDistance(0), m_bIsConnected(false), m_RCONServer(*this), m_MaxPlayers(0), m_bIsHardcore(false), m_TickThread(*this), m_ShouldAuthenticate(false), m_UpTime(0) { // Initialize the LuaStateTracker singleton before the app goes multithreaded: cLuaStateTracker::GetStats(); } void cServer::ClientMovedToWorld(const cClientHandle * a_Client) { cCSLock Lock(m_CSClients); m_ClientsToRemove.push_back(const_cast<cClientHandle *>(a_Client)); } void cServer::PlayerCreated() { m_PlayerCount++; } void cServer::PlayerDestroyed() { m_PlayerCount--; } bool cServer::InitServer(cSettingsRepositoryInterface & a_Settings, bool a_ShouldAuth) { m_Description = a_Settings.GetValueSet("Server", "Description", "Cuberite - in C++!"); m_ShutdownMessage = a_Settings.GetValueSet("Server", "ShutdownMessage", "Server shutdown"); m_MaxPlayers = static_cast<size_t>(a_Settings.GetValueSetI("Server", "MaxPlayers", 100)); m_bIsHardcore = a_Settings.GetValueSetB("Server", "HardcoreEnabled", false); m_bAllowMultiLogin = a_Settings.GetValueSetB("Server", "AllowMultiLogin", false); m_ResourcePackUrl = a_Settings.GetValueSet("Server", "ResourcePackUrl", ""); m_CustomRedirectUrl = a_Settings.GetValueSet("Server", "CustomRedirectUrl", "https://youtu.be/dQw4w9WgXcQ"); m_FaviconData = Base64Encode(cFile::ReadWholeFile(AString("favicon.png"))); // Will return empty string if file nonexistant; client doesn't mind if (m_bIsConnected) { LOGERROR("ERROR: Trying to initialize server while server is already running!"); return false; } LOGINFO("Compatible clients: %s", MCS_CLIENT_VERSIONS); LOGD("Compatible protocol versions %s", MCS_PROTOCOL_VERSIONS); m_Ports = ReadUpgradeIniPorts(a_Settings, "Server", "Ports", "Port", "PortsIPv6", "25565"); m_RCONServer.Initialize(a_Settings); m_bIsConnected = true; m_ServerID = "-"; m_ShouldAuthenticate = a_ShouldAuth; if (m_ShouldAuthenticate) { auto & rand = GetRandomProvider(); unsigned int r1 = rand.RandInt<unsigned int>(1000000000U, 0x7fffffffU); unsigned int r2 = rand.RandInt<unsigned int>(1000000000U, 0x7fffffffU); std::ostringstream sid; sid << std::hex << r1; sid << std::hex << r2; m_ServerID = sid.str(); m_ServerID.resize(16, '0'); } // Check if both BungeeCord and online mode are on, if so, warn the admin: m_ShouldAllowBungeeCord = a_Settings.GetValueSetB("Authentication", "AllowBungeeCord", false); m_OnlyAllowBungeeCord = a_Settings.GetValueSetB("Authentication", "OnlyAllowBungeeCord", false); m_ProxySharedSecret = a_Settings.GetValueSet("Authentication", "ProxySharedSecret", ""); if (m_ShouldAllowBungeeCord && m_ShouldAuthenticate) { LOGWARNING("WARNING: BungeeCord is allowed and server set to online mode. This is unsafe and will not work properly. Disable either authentication or BungeeCord in settings.ini."); } if (m_ShouldAllowBungeeCord && m_ProxySharedSecret.empty()) { LOGWARNING("WARNING: There is not a Proxy Forward Secret set up, and any proxy server can forward a player to this server unless closed from the internet."); } m_ShouldAllowMultiWorldTabCompletion = a_Settings.GetValueSetB("Server", "AllowMultiWorldTabCompletion", true); m_ShouldLimitPlayerBlockChanges = a_Settings.GetValueSetB("AntiCheat", "LimitPlayerBlockChanges", true); const auto ClientViewDistance = a_Settings.GetValueSetI("Server", "DefaultViewDistance", cClientHandle::DEFAULT_VIEW_DISTANCE); if (ClientViewDistance < cClientHandle::MIN_VIEW_DISTANCE) { m_ClientViewDistance = cClientHandle::MIN_VIEW_DISTANCE; LOGINFO("Setting default view distance to the minimum of %d", m_ClientViewDistance); } else if (ClientViewDistance > cClientHandle::MAX_VIEW_DISTANCE) { m_ClientViewDistance = cClientHandle::MAX_VIEW_DISTANCE; LOGINFO("Setting default view distance to the maximum of %d", m_ClientViewDistance); } else { m_ClientViewDistance = ClientViewDistance; } PrepareKeys(); return true; } bool cServer::RegisterForgeMod(const AString & a_ModName, const AString & a_ModVersion, UInt32 a_ProtocolVersionNumber) { auto & Mods = RegisteredForgeMods(a_ProtocolVersionNumber); return Mods.insert({a_ModName, a_ModVersion}).second; } void cServer::UnregisterForgeMod(const AString & a_ModName, UInt32 a_ProtocolVersionNumber) { auto & Mods = RegisteredForgeMods(a_ProtocolVersionNumber); auto it = Mods.find(a_ModName); if (it != Mods.end()) { Mods.erase(it); } } AStringMap & cServer::RegisteredForgeMods(const UInt32 a_Protocol) { auto it = m_ForgeModsByVersion.find(a_Protocol); if (it == m_ForgeModsByVersion.end()) { AStringMap mods; m_ForgeModsByVersion.insert({a_Protocol, mods}); return m_ForgeModsByVersion.find(a_Protocol)->second; } return it->second; } const AStringMap & cServer::GetRegisteredForgeMods(const UInt32 a_Protocol) { return RegisteredForgeMods(a_Protocol); } bool cServer::IsPlayerInQueue(const AString & a_Username) { cCSLock Lock(m_CSClients); for (const auto & client : m_Clients) { if ((client->GetUsername()).compare(a_Username) == 0) { return true; } } return false; } void cServer::PrepareKeys(void) { LOGD("Generating protocol encryption keypair..."); VERIFY(m_PrivateKey.Generate(1024)); m_PublicKeyDER = m_PrivateKey.GetPubKeyDER(); } cTCPLink::cCallbacksPtr cServer::OnConnectionAccepted(const AString & a_RemoteIPAddress) { LOGD("Client \"%s\" connected!", a_RemoteIPAddress.c_str()); cClientHandlePtr NewHandle = std::make_shared<cClientHandle>(a_RemoteIPAddress, m_ClientViewDistance); cCSLock Lock(m_CSClients); m_Clients.push_back(NewHandle); return NewHandle; } void cServer::Tick(float a_Dt) { // Update server uptime m_UpTime++; // Send the tick to the plugins, as well as let the plugin manager reload, if asked to (issue #102): cPluginManager::Get()->Tick(a_Dt); // Process all the queued commands: TickCommands(); // Tick all clients not yet assigned to a world: TickClients(a_Dt); // Process all queued tasks TickQueuedTasks(); } void cServer::TickClients(float a_Dt) { cClientHandlePtrs RemoveClients; { cCSLock Lock(m_CSClients); // Remove clients that have moved to a world (the world will be ticking them from now on) for (auto itr = m_ClientsToRemove.begin(), end = m_ClientsToRemove.end(); itr != end; ++itr) { for (auto itrC = m_Clients.begin(), endC = m_Clients.end(); itrC != endC; ++itrC) { if (itrC->get() == *itr) { m_Clients.erase(itrC); break; } } } // for itr - m_ClientsToRemove[] m_ClientsToRemove.clear(); // Tick the remaining clients, take out those that have been destroyed into RemoveClients for (auto itr = m_Clients.begin(); itr != m_Clients.end();) { auto & Client = *itr; Client->ServerTick(a_Dt); if (Client->IsDestroyed()) { // Delete the client later, when CS is not held, to avoid deadlock: https://forum.cuberite.org/thread-374.html RemoveClients.push_back(std::move(Client)); itr = m_Clients.erase(itr); continue; } ++itr; } // for itr - m_Clients[] } // Delete the clients that have been destroyed RemoveClients.clear(); } bool cServer::Start(void) { for (const auto & port: m_Ports) { UInt16 PortNum; if (!StringToInteger(port, PortNum)) { LOGWARNING("Invalid port specified for server: \"%s\". Ignoring.", port.c_str()); continue; } auto Handle = cNetwork::Listen(PortNum, std::make_shared<cServerListenCallbacks>(*this, PortNum)); if (Handle->IsListening()) { m_ServerHandles.push_back(Handle); } } // for port - Ports[] if (m_ServerHandles.empty()) { LOGERROR("Couldn't open any ports. Aborting the server"); return false; } m_TickThread.Start(); return true; } bool cServer::Command(cClientHandle & a_Client, AString & a_Cmd) { bool Res = cRoot::Get()->DoWithPlayerByUUID( a_Client.GetUUID(), [&](cPlayer & a_Player) { return cRoot::Get()->GetPluginManager()->CallHookChat(a_Player, a_Cmd); } ); return Res; } void cServer::QueueExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output) { // Put the command into a queue (Alleviates FS #363): cCSLock Lock(m_CSPendingCommands); m_PendingCommands.emplace_back(a_Cmd, &a_Output); } void cServer::ScheduleTask(cTickTime a_DelayTicks, std::function<void(cServer &)> a_Task) { const auto TargetTick = a_DelayTicks + m_UpTime; // Insert the task into the list of scheduled tasks { cCSLock Lock(m_CSTasks); m_Tasks.emplace_back(TargetTick, std::move(a_Task)); } } void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output) { AStringVector split = StringSplit(a_Cmd, " "); if (split.empty()) { return; } // "stop" and "restart" are handled in cRoot::ExecuteConsoleCommand, our caller, due to its access to controlling variables // "help" and "reload" are to be handled by Cuberite, so that they work no matter what if (split[0] == "help") { PrintHelp(split, a_Output); a_Output.Finished(); return; } else if (split[0] == "reload") { if (split.size() > 1) { cPluginManager::Get()->ReloadPlugin(split[1]); a_Output.Out("Plugin reload scheduled"); } else { cPluginManager::Get()->ReloadPlugins(); } a_Output.Finished(); return; } else if (split[0] == "reloadplugins") { cPluginManager::Get()->ReloadPlugins(); a_Output.Out("Plugins reloaded"); a_Output.Finished(); return; } else if (split[0] == "reloadweb") { cRoot::Get()->GetWebAdmin()->Reload(); a_Output.Out("WebAdmin configuration reloaded"); a_Output.Finished(); return; } else if (split[0] == "load") { if (split.size() > 1) { cPluginManager::Get()->RefreshPluginList(); // Refresh the plugin list, so that if the plugin was added just now, it is loadable a_Output.Out(cPluginManager::Get()->LoadPlugin(split[1]) ? "Plugin loaded" : "Error occurred loading plugin"); } else { a_Output.Out("Usage: load <PluginFolder>"); } a_Output.Finished(); return; } else if (split[0] == "unload") { if (split.size() > 1) { cPluginManager::Get()->UnloadPlugin(split[1]); a_Output.Out("Plugin unload scheduled"); } else { a_Output.Out("Usage: unload <PluginFolder>"); } a_Output.Finished(); return; } if (split[0] == "destroyentities") { cRoot::Get()->ForEachWorld([](cWorld & a_World) { a_World.ForEachEntity([](cEntity & a_Entity) { if (!a_Entity.IsPlayer()) { a_Entity.Destroy(); } return false; } ); return false; } ); a_Output.Out("Destroyed all entities"); a_Output.Finished(); return; } // There is currently no way a plugin can do these (and probably won't ever be): else if (split[0].compare("chunkstats") == 0) { cRoot::Get()->LogChunkStats(a_Output); a_Output.Finished(); return; } else if (split[0].compare("luastats") == 0) { a_Output.Out(cLuaStateTracker::GetStats()); a_Output.Finished(); return; } else if (cPluginManager::Get()->ExecuteConsoleCommand(split, a_Output, a_Cmd)) { a_Output.Finished(); return; } a_Output.Out("Unknown command, type 'help' for all commands."); a_Output.Finished(); } void cServer::PrintHelp(const AStringVector & a_Split, cCommandOutputCallback & a_Output) { UNUSED(a_Split); typedef std::pair<AString, AString> AStringPair; typedef std::vector<AStringPair> AStringPairs; class cCallback : public cPluginManager::cCommandEnumCallback { public: cCallback(void) : m_MaxLen(0) {} virtual bool Command(const AString & a_Command, const cPlugin * a_Plugin, const AString & a_Permission, const AString & a_HelpString) override { UNUSED(a_Plugin); UNUSED(a_Permission); if (!a_HelpString.empty()) { m_Commands.push_back(AStringPair(a_Command, a_HelpString)); if (m_MaxLen < a_Command.length()) { m_MaxLen = a_Command.length(); } } return false; } AStringPairs m_Commands; size_t m_MaxLen; } Callback; cPluginManager::Get()->ForEachConsoleCommand(Callback); std::sort(Callback.m_Commands.begin(), Callback.m_Commands.end()); for (AStringPairs::const_iterator itr = Callback.m_Commands.begin(), end = Callback.m_Commands.end(); itr != end; ++itr) { const AStringPair & cmd = *itr; a_Output.Out(Printf("%-*s - %s\n", static_cast<int>(Callback.m_MaxLen), cmd.first.c_str(), cmd.second.c_str())); } // for itr - Callback.m_Commands[] } void cServer::BindBuiltInConsoleCommands(void) { // Create an empty handler - the actual handling for the commands is performed before they are handed off to cPluginManager class cEmptyHandler: public cPluginManager::cCommandHandler { virtual bool ExecuteCommand( const AStringVector & a_Split, cPlayer * a_Player, const AString & a_Command, cCommandOutputCallback * a_Output = nullptr ) override { return false; } }; auto handler = std::make_shared<cEmptyHandler>(); // Register internal commands: cPluginManager * PlgMgr = cPluginManager::Get(); PlgMgr->BindConsoleCommand("help", nullptr, handler, "Shows the available commands"); PlgMgr->BindConsoleCommand("reload", nullptr, handler, "Reloads all plugins"); PlgMgr->BindConsoleCommand("reloadweb", nullptr, handler, "Reloads the webadmin configuration"); PlgMgr->BindConsoleCommand("restart", nullptr, handler, "Restarts the server cleanly"); PlgMgr->BindConsoleCommand("stop", nullptr, handler, "Stops the server cleanly"); PlgMgr->BindConsoleCommand("chunkstats", nullptr, handler, "Displays detailed chunk memory statistics"); PlgMgr->BindConsoleCommand("load", nullptr, handler, "Adds and enables the specified plugin"); PlgMgr->BindConsoleCommand("unload", nullptr, handler, "Disables the specified plugin"); PlgMgr->BindConsoleCommand("destroyentities", nullptr, handler, "Destroys all entities in all worlds"); } void cServer::Shutdown(void) { // Stop listening on all sockets: for (const auto & srv: m_ServerHandles) { srv->Close(); } m_ServerHandles.clear(); // Notify the tick thread and wait for it to terminate: m_TickThread.Stop(); // Save all chunks in all worlds, wait for chunks to be sent to the ChunkStorage queue for each world: cRoot::Get()->SaveAllChunksNow(); // Remove all clients: cCSLock Lock(m_CSClients); for (auto itr = m_Clients.begin(); itr != m_Clients.end(); ++itr) { (*itr)->Destroy(); } m_Clients.clear(); } void cServer::KickUser(int a_ClientID, const AString & a_Reason) { cCSLock Lock(m_CSClients); for (auto itr = m_Clients.begin(); itr != m_Clients.end(); ++itr) { if ((*itr)->GetUniqueID() == a_ClientID) { (*itr)->Kick(a_Reason); } } // for itr - m_Clients[] } void cServer::AuthenticateUser(int a_ClientID, AString && a_Username, const cUUID & a_UUID, Json::Value && a_Properties) { cCSLock Lock(m_CSClients); // Check max players condition within lock (expect server and authenticator thread to both call here) if (GetNumPlayers() >= GetMaxPlayers()) { KickUser(a_ClientID, "The server is currently full :(" "\n" "Try again later?"); return; } for (const auto & Client : m_Clients) { if (Client->GetUniqueID() == a_ClientID) { Client->Authenticate(std::move(a_Username), a_UUID, std::move(a_Properties)); return; } } } void cServer::TickCommands(void) { decltype(m_PendingCommands) PendingCommands; { cCSLock Lock(m_CSPendingCommands); std::swap(PendingCommands, m_PendingCommands); } // Execute any pending commands: for (const auto & Command : PendingCommands) { ExecuteConsoleCommand(Command.first, *Command.second); } } void cServer::TickQueuedTasks(void) { // Move the tasks to be executed to a seperate vector to avoid deadlocks on // accessing m_Tasks decltype(m_Tasks) Tasks; { cCSLock Lock(m_CSTasks); if (m_Tasks.empty()) { return; } // Partition everything to be executed by returning false to move to end // of list if time reached auto MoveBeginIterator = std::partition( m_Tasks.begin(), m_Tasks.end(), [this](const decltype(m_Tasks)::value_type & a_Task) { return a_Task.first >= m_UpTime; }); // Cut all the due tasks from m_Tasks into Tasks: Tasks.insert( Tasks.end(), std::make_move_iterator(MoveBeginIterator), std::make_move_iterator(m_Tasks.end())); m_Tasks.erase(MoveBeginIterator, m_Tasks.end()); } // Execute each task: for (const auto & Task : Tasks) { Task.second(*this); } // for itr - m_Tasks[] }
23.890013
182
0.70154
[ "vector" ]
88140a5a8f9fc8871ed678f25856d3cb76ae8082
64,251
hpp
C++
legion/engine/core/math/glm/gtc/type_precision.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
legion/engine/core/math/glm/gtc/type_precision.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
legion/engine/core/math/glm/gtc/type_precision.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
/// @ref gtc_type_precision /// @file glm/gtc/type_precision.hpp /// /// @see core (dependence) /// @see gtc_quaternion (dependence) /// /// @defgroup gtc_type_precision GLM_GTC_type_precision /// @ingroup gtc /// /// Include <glm/gtc/type_precision.hpp> to use the features of this extension. /// /// Defines specific C++-based qualifier types. #pragma once // Dependency: #include "../gtc/quaternion.hpp" #include "../gtc/vec1.hpp" #include "../ext/vector_int1_sized.hpp" #include "../ext/vector_int2_sized.hpp" #include "../ext/vector_int3_sized.hpp" #include "../ext/vector_int4_sized.hpp" #include "../ext/scalar_int_sized.hpp" #include "../ext/vector_uint1_sized.hpp" #include "../ext/vector_uint2_sized.hpp" #include "../ext/vector_uint3_sized.hpp" #include "../ext/vector_uint4_sized.hpp" #include "../ext/scalar_uint_sized.hpp" #include "../detail/type_vec2.hpp" #include "../detail/type_vec3.hpp" #include "../detail/type_vec4.hpp" #include "../detail/type_mat2x2.hpp" #include "../detail/type_mat2x3.hpp" #include "../detail/type_mat2x4.hpp" #include "../detail/type_mat3x2.hpp" #include "../detail/type_mat3x3.hpp" #include "../detail/type_mat3x4.hpp" #include "../detail/type_mat4x2.hpp" #include "../detail/type_mat4x3.hpp" #include "../detail/type_mat4x4.hpp" #if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED) # pragma message("GLM: GLM_GTC_type_precision extension included") #endif namespace legion::core::math { /////////////////////////// // Signed int vector types /// @addtogroup gtc_type_precision /// @{ /// Low qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 lowp_int8; /// Low qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 lowp_int16; /// Low qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 lowp_int32; /// Low qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 lowp_int64; /// Low qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 lowp_int8_t; /// Low qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 lowp_int16_t; /// Low qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 lowp_int32_t; /// Low qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 lowp_int64_t; /// Low qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 lowp_i8; /// Low qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 lowp_i16; /// Low qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 lowp_i32; /// Low qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 lowp_i64; /// Medium qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 mediump_int8; /// Medium qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 mediump_int16; /// Medium qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 mediump_int32; /// Medium qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 mediump_int64; /// Medium qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 mediump_int8_t; /// Medium qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 mediump_int16_t; /// Medium qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 mediump_int32_t; /// Medium qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 mediump_int64_t; /// Medium qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 mediump_i8; /// Medium qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 mediump_i16; /// Medium qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 mediump_i32; /// Medium qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 mediump_i64; /// High qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 highp_int8; /// High qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 highp_int16; /// High qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 highp_int32; /// High qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 highp_int64; /// High qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 highp_int8_t; /// High qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 highp_int16_t; /// 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 highp_int32_t; /// High qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 highp_int64_t; /// High qualifier 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 highp_i8; /// High qualifier 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 highp_i16; /// High qualifier 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 highp_i32; /// High qualifier 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 highp_i64; #if GLM_HAS_EXTENDED_INTEGER_TYPE using std::int8_t; using std::int16_t; using std::int32_t; using std::int64_t; #else /// 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 int8_t; /// 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 int16_t; /// 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 int32_t; /// 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 int64_t; #endif /// 8 bit signed integer type. /// @see gtc_type_precision typedef detail::int8 i8; /// 16 bit signed integer type. /// @see gtc_type_precision typedef detail::int16 i16; /// 32 bit signed integer type. /// @see gtc_type_precision typedef detail::int32 i32; /// 64 bit signed integer type. /// @see gtc_type_precision typedef detail::int64 i64; ///////////////////////////// // Unsigned int vector types /// Low qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 lowp_uint8; /// Low qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 lowp_uint16; /// Low qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 lowp_uint32; /// Low qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 lowp_uint64; /// Low qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 lowp_uint8_t; /// Low qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 lowp_uint16_t; /// Low qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 lowp_uint32_t; /// Low qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 lowp_uint64_t; /// Low qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 lowp_u8; /// Low qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 lowp_u16; /// Low qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 lowp_u32; /// Low qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 lowp_u64; /// Medium qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 mediump_uint8; /// Medium qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 mediump_uint16; /// Medium qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 mediump_uint32; /// Medium qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 mediump_uint64; /// Medium qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 mediump_uint8_t; /// Medium qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 mediump_uint16_t; /// Medium qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 mediump_uint32_t; /// Medium qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 mediump_uint64_t; /// Medium qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 mediump_u8; /// Medium qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 mediump_u16; /// Medium qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 mediump_u32; /// Medium qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 mediump_u64; /// High qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 highp_uint8; /// High qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 highp_uint16; /// High qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 highp_uint32; /// High qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 highp_uint64; /// High qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 highp_uint8_t; /// High qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 highp_uint16_t; /// High qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 highp_uint32_t; /// High qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 highp_uint64_t; /// High qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 highp_u8; /// High qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 highp_u16; /// High qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 highp_u32; /// High qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 highp_u64; #if GLM_HAS_EXTENDED_INTEGER_TYPE using std::uint8_t; using std::uint16_t; using std::uint32_t; using std::uint64_t; #else /// Default qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 uint8_t; /// Default qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 uint16_t; /// Default qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 uint32_t; /// Default qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 uint64_t; #endif /// Default qualifier 8 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint8 u8; /// Default qualifier 16 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint16 u16; /// Default qualifier 32 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint32 u32; /// Default qualifier 64 bit unsigned integer type. /// @see gtc_type_precision typedef detail::uint64 u64; ////////////////////// // Float vector types /// Single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float float32; /// Double-qualifier floating-point scalar. /// @see gtc_type_precision typedef double float64; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_float32; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_float64; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_float32_t; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_float64_t; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_f32; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_f64; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_float32; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_float64; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_float32_t; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_float64_t; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_f32; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_f64; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_float32; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_float64; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_float32_t; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_float64_t; /// Low 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 lowp_f32; /// Low 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 lowp_f64; /// Medium 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 mediump_float32; /// Medium 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 mediump_float64; /// Medium 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 mediump_float32_t; /// Medium 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 mediump_float64_t; /// Medium 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 mediump_f32; /// Medium 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 mediump_f64; /// High 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 highp_float32; /// High 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 highp_float64; /// High 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 highp_float32_t; /// High 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 highp_float64_t; /// High 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 highp_f32; /// High 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 highp_f64; #if(defined(GLM_PRECISION_LOWP_FLOAT)) /// Default 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef lowp_float32_t float32_t; /// Default 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef lowp_float64_t float64_t; /// Default 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef lowp_f32 f32; /// Default 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef lowp_f64 f64; #elif(defined(GLM_PRECISION_MEDIUMP_FLOAT)) /// Default 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef mediump_float32 float32_t; /// Default 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef mediump_float64 float64_t; /// Default 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef mediump_float32 f32; /// Default 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef mediump_float64 f64; #else//(defined(GLM_PRECISION_HIGHP_FLOAT)) /// Default 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef highp_float32_t float32_t; /// Default 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef highp_float64_t float64_t; /// Default 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef highp_float32_t f32; /// Default 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef highp_float64_t f64; #endif /// Low single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, float, lowp> lowp_fvec1; /// Low single-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, float, lowp> lowp_fvec2; /// Low single-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, float, lowp> lowp_fvec3; /// Low single-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, float, lowp> lowp_fvec4; /// Medium single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, float, mediump> mediump_fvec1; /// Medium Single-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, float, mediump> mediump_fvec2; /// Medium Single-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, float, mediump> mediump_fvec3; /// Medium Single-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, float, mediump> mediump_fvec4; /// High single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, float, highp> highp_fvec1; /// High Single-qualifier floating-point vector of 2 components. /// @see core_precision typedef vec<2, float, highp> highp_fvec2; /// High Single-qualifier floating-point vector of 3 components. /// @see core_precision typedef vec<3, float, highp> highp_fvec3; /// High Single-qualifier floating-point vector of 4 components. /// @see core_precision typedef vec<4, float, highp> highp_fvec4; /// Low single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f32, lowp> lowp_f32vec1; /// Low single-qualifier floating-point vector of 2 components. /// @see core_precision typedef vec<2, f32, lowp> lowp_f32vec2; /// Low single-qualifier floating-point vector of 3 components. /// @see core_precision typedef vec<3, f32, lowp> lowp_f32vec3; /// Low single-qualifier floating-point vector of 4 components. /// @see core_precision typedef vec<4, f32, lowp> lowp_f32vec4; /// Medium single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f32, mediump> mediump_f32vec1; /// Medium single-qualifier floating-point vector of 2 components. /// @see core_precision typedef vec<2, f32, mediump> mediump_f32vec2; /// Medium single-qualifier floating-point vector of 3 components. /// @see core_precision typedef vec<3, f32, mediump> mediump_f32vec3; /// Medium single-qualifier floating-point vector of 4 components. /// @see core_precision typedef vec<4, f32, mediump> mediump_f32vec4; /// High single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f32, highp> highp_f32vec1; /// High single-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, f32, highp> highp_f32vec2; /// High single-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, f32, highp> highp_f32vec3; /// High single-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, f32, highp> highp_f32vec4; /// Low double-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f64, lowp> lowp_f64vec1; /// Low double-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, f64, lowp> lowp_f64vec2; /// Low double-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, f64, lowp> lowp_f64vec3; /// Low double-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, f64, lowp> lowp_f64vec4; /// Medium double-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f64, mediump> mediump_f64vec1; /// Medium double-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, f64, mediump> mediump_f64vec2; /// Medium double-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, f64, mediump> mediump_f64vec3; /// Medium double-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, f64, mediump> mediump_f64vec4; /// High double-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f64, highp> highp_f64vec1; /// High double-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, f64, highp> highp_f64vec2; /// High double-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, f64, highp> highp_f64vec3; /// High double-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, f64, highp> highp_f64vec4; ////////////////////// // Float matrix types /// Low single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef lowp_f32 lowp_fmat1x1; /// Low single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, lowp> lowp_fmat2x2; /// Low single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, lowp> lowp_fmat2x3; /// Low single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, lowp> lowp_fmat2x4; /// Low single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, lowp> lowp_fmat3x2; /// Low single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, lowp> lowp_fmat3x3; /// Low single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, lowp> lowp_fmat3x4; /// Low single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, lowp> lowp_fmat4x2; /// Low single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, lowp> lowp_fmat4x3; /// Low single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, lowp> lowp_fmat4x4; /// Low single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef lowp_fmat1x1 lowp_fmat1; /// Low single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef lowp_fmat2x2 lowp_fmat2; /// Low single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef lowp_fmat3x3 lowp_fmat3; /// Low single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef lowp_fmat4x4 lowp_fmat4; /// Medium single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef mediump_f32 mediump_fmat1x1; /// Medium single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, mediump> mediump_fmat2x2; /// Medium single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, mediump> mediump_fmat2x3; /// Medium single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, mediump> mediump_fmat2x4; /// Medium single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, mediump> mediump_fmat3x2; /// Medium single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, mediump> mediump_fmat3x3; /// Medium single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, mediump> mediump_fmat3x4; /// Medium single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, mediump> mediump_fmat4x2; /// Medium single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, mediump> mediump_fmat4x3; /// Medium single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, mediump> mediump_fmat4x4; /// Medium single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef mediump_fmat1x1 mediump_fmat1; /// Medium single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mediump_fmat2x2 mediump_fmat2; /// Medium single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mediump_fmat3x3 mediump_fmat3; /// Medium single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mediump_fmat4x4 mediump_fmat4; /// High single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef highp_f32 highp_fmat1x1; /// High single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, highp> highp_fmat2x2; /// High single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, highp> highp_fmat2x3; /// High single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, highp> highp_fmat2x4; /// High single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, highp> highp_fmat3x2; /// High single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, highp> highp_fmat3x3; /// High single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, highp> highp_fmat3x4; /// High single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, highp> highp_fmat4x2; /// High single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, highp> highp_fmat4x3; /// High single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, highp> highp_fmat4x4; /// High single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef highp_fmat1x1 highp_fmat1; /// High single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef highp_fmat2x2 highp_fmat2; /// High single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef highp_fmat3x3 highp_fmat3; /// High single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef highp_fmat4x4 highp_fmat4; /// Low single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f32 lowp_f32mat1x1; /// Low single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, lowp> lowp_f32mat2x2; /// Low single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, lowp> lowp_f32mat2x3; /// Low single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, lowp> lowp_f32mat2x4; /// Low single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, lowp> lowp_f32mat3x2; /// Low single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, lowp> lowp_f32mat3x3; /// Low single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, lowp> lowp_f32mat3x4; /// Low single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, lowp> lowp_f32mat4x2; /// Low single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, lowp> lowp_f32mat4x3; /// Low single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, lowp> lowp_f32mat4x4; /// Low single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef detail::tmat1x1<f32, lowp> lowp_f32mat1; /// Low single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef lowp_f32mat2x2 lowp_f32mat2; /// Low single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef lowp_f32mat3x3 lowp_f32mat3; /// Low single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef lowp_f32mat4x4 lowp_f32mat4; /// High single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f32 mediump_f32mat1x1; /// Low single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, mediump> mediump_f32mat2x2; /// Medium single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, mediump> mediump_f32mat2x3; /// Medium single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, mediump> mediump_f32mat2x4; /// Medium single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, mediump> mediump_f32mat3x2; /// Medium single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, mediump> mediump_f32mat3x3; /// Medium single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, mediump> mediump_f32mat3x4; /// Medium single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, mediump> mediump_f32mat4x2; /// Medium single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, mediump> mediump_f32mat4x3; /// Medium single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, mediump> mediump_f32mat4x4; /// Medium single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef detail::tmat1x1<f32, mediump> f32mat1; /// Medium single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mediump_f32mat2x2 mediump_f32mat2; /// Medium single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mediump_f32mat3x3 mediump_f32mat3; /// Medium single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mediump_f32mat4x4 mediump_f32mat4; /// High single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f32 highp_f32mat1x1; /// High single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, highp> highp_f32mat2x2; /// High single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, highp> highp_f32mat2x3; /// High single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, highp> highp_f32mat2x4; /// High single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, highp> highp_f32mat3x2; /// High single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, highp> highp_f32mat3x3; /// High single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, highp> highp_f32mat3x4; /// High single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, highp> highp_f32mat4x2; /// High single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, highp> highp_f32mat4x3; /// High single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, highp> highp_f32mat4x4; /// High single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef detail::tmat1x1<f32, highp> f32mat1; /// High single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef highp_f32mat2x2 highp_f32mat2; /// High single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef highp_f32mat3x3 highp_f32mat3; /// High single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef highp_f32mat4x4 highp_f32mat4; /// Low double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f64 lowp_f64mat1x1; /// Low double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f64, lowp> lowp_f64mat2x2; /// Low double-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f64, lowp> lowp_f64mat2x3; /// Low double-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f64, lowp> lowp_f64mat2x4; /// Low double-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f64, lowp> lowp_f64mat3x2; /// Low double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f64, lowp> lowp_f64mat3x3; /// Low double-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f64, lowp> lowp_f64mat3x4; /// Low double-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f64, lowp> lowp_f64mat4x2; /// Low double-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f64, lowp> lowp_f64mat4x3; /// Low double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f64, lowp> lowp_f64mat4x4; /// Low double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef lowp_f64mat1x1 lowp_f64mat1; /// Low double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef lowp_f64mat2x2 lowp_f64mat2; /// Low double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef lowp_f64mat3x3 lowp_f64mat3; /// Low double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef lowp_f64mat4x4 lowp_f64mat4; /// Medium double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f64 Highp_f64mat1x1; /// Medium double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f64, mediump> mediump_f64mat2x2; /// Medium double-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f64, mediump> mediump_f64mat2x3; /// Medium double-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f64, mediump> mediump_f64mat2x4; /// Medium double-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f64, mediump> mediump_f64mat3x2; /// Medium double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f64, mediump> mediump_f64mat3x3; /// Medium double-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f64, mediump> mediump_f64mat3x4; /// Medium double-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f64, mediump> mediump_f64mat4x2; /// Medium double-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f64, mediump> mediump_f64mat4x3; /// Medium double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f64, mediump> mediump_f64mat4x4; /// Medium double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef mediump_f64mat1x1 mediump_f64mat1; /// Medium double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mediump_f64mat2x2 mediump_f64mat2; /// Medium double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mediump_f64mat3x3 mediump_f64mat3; /// Medium double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mediump_f64mat4x4 mediump_f64mat4; /// High double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f64 highp_f64mat1x1; /// High double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f64, highp> highp_f64mat2x2; /// High double-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f64, highp> highp_f64mat2x3; /// High double-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f64, highp> highp_f64mat2x4; /// High double-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f64, highp> highp_f64mat3x2; /// High double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f64, highp> highp_f64mat3x3; /// High double-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f64, highp> highp_f64mat3x4; /// High double-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f64, highp> highp_f64mat4x2; /// High double-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f64, highp> highp_f64mat4x3; /// High double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f64, highp> highp_f64mat4x4; /// High double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef highp_f64mat1x1 highp_f64mat1; /// High double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef highp_f64mat2x2 highp_f64mat2; /// High double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef highp_f64mat3x3 highp_f64mat3; /// High double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef highp_f64mat4x4 highp_f64mat4; ///////////////////////////// // Signed int vector types /// Low qualifier signed integer vector of 1 component type. /// @see gtc_type_precision typedef vec<1, int, lowp> lowp_ivec1; /// Low qualifier signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, int, lowp> lowp_ivec2; /// Low qualifier signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, int, lowp> lowp_ivec3; /// Low qualifier signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, int, lowp> lowp_ivec4; /// Medium qualifier signed integer vector of 1 component type. /// @see gtc_type_precision typedef vec<1, int, mediump> mediump_ivec1; /// Medium qualifier signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, int, mediump> mediump_ivec2; /// Medium qualifier signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, int, mediump> mediump_ivec3; /// Medium qualifier signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, int, mediump> mediump_ivec4; /// High qualifier signed integer vector of 1 component type. /// @see gtc_type_precision typedef vec<1, int, highp> highp_ivec1; /// High qualifier signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, int, highp> highp_ivec2; /// High qualifier signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, int, highp> highp_ivec3; /// High qualifier signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, int, highp> highp_ivec4; /// Low qualifier 8 bit signed integer vector of 1 component type. /// @see gtc_type_precision typedef vec<1, i8, lowp> lowp_i8vec1; /// Low qualifier 8 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i8, lowp> lowp_i8vec2; /// Low qualifier 8 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i8, lowp> lowp_i8vec3; /// Low qualifier 8 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i8, lowp> lowp_i8vec4; /// Medium qualifier 8 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i8, mediump> mediump_i8vec1; /// Medium qualifier 8 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i8, mediump> mediump_i8vec2; /// Medium qualifier 8 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i8, mediump> mediump_i8vec3; /// Medium qualifier 8 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i8, mediump> mediump_i8vec4; /// High qualifier 8 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i8, highp> highp_i8vec1; /// High qualifier 8 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i8, highp> highp_i8vec2; /// High qualifier 8 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i8, highp> highp_i8vec3; /// High qualifier 8 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i8, highp> highp_i8vec4; /// Low qualifier 16 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i16, lowp> lowp_i16vec1; /// Low qualifier 16 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i16, lowp> lowp_i16vec2; /// Low qualifier 16 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i16, lowp> lowp_i16vec3; /// Low qualifier 16 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i16, lowp> lowp_i16vec4; /// Medium qualifier 16 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i16, mediump> mediump_i16vec1; /// Medium qualifier 16 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i16, mediump> mediump_i16vec2; /// Medium qualifier 16 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i16, mediump> mediump_i16vec3; /// Medium qualifier 16 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i16, mediump> mediump_i16vec4; /// High qualifier 16 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i16, highp> highp_i16vec1; /// High qualifier 16 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i16, highp> highp_i16vec2; /// High qualifier 16 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i16, highp> highp_i16vec3; /// High qualifier 16 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i16, highp> highp_i16vec4; /// Low qualifier 32 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i32, lowp> lowp_i32vec1; /// Low qualifier 32 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i32, lowp> lowp_i32vec2; /// Low qualifier 32 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i32, lowp> lowp_i32vec3; /// Low qualifier 32 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i32, lowp> lowp_i32vec4; /// Medium qualifier 32 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i32, mediump> mediump_i32vec1; /// Medium qualifier 32 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i32, mediump> mediump_i32vec2; /// Medium qualifier 32 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i32, mediump> mediump_i32vec3; /// Medium qualifier 32 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i32, mediump> mediump_i32vec4; /// High qualifier 32 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i32, highp> highp_i32vec1; /// High qualifier 32 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i32, highp> highp_i32vec2; /// High qualifier 32 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i32, highp> highp_i32vec3; /// High qualifier 32 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i32, highp> highp_i32vec4; /// Low qualifier 64 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i64, lowp> lowp_i64vec1; /// Low qualifier 64 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i64, lowp> lowp_i64vec2; /// Low qualifier 64 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i64, lowp> lowp_i64vec3; /// Low qualifier 64 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i64, lowp> lowp_i64vec4; /// Medium qualifier 64 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i64, mediump> mediump_i64vec1; /// Medium qualifier 64 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i64, mediump> mediump_i64vec2; /// Medium qualifier 64 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i64, mediump> mediump_i64vec3; /// Medium qualifier 64 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i64, mediump> mediump_i64vec4; /// High qualifier 64 bit signed integer scalar type. /// @see gtc_type_precision typedef vec<1, i64, highp> highp_i64vec1; /// High qualifier 64 bit signed integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, i64, highp> highp_i64vec2; /// High qualifier 64 bit signed integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, i64, highp> highp_i64vec3; /// High qualifier 64 bit signed integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, i64, highp> highp_i64vec4; ///////////////////////////// // Unsigned int vector types /// Low qualifier unsigned integer vector of 1 component type. /// @see gtc_type_precision typedef vec<1, uint, lowp> lowp_uvec1; /// Low qualifier unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, uint, lowp> lowp_uvec2; /// Low qualifier unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, uint, lowp> lowp_uvec3; /// Low qualifier unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, uint, lowp> lowp_uvec4; /// Medium qualifier unsigned integer vector of 1 component type. /// @see gtc_type_precision typedef vec<1, uint, mediump> mediump_uvec1; /// Medium qualifier unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, uint, mediump> mediump_uvec2; /// Medium qualifier unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, uint, mediump> mediump_uvec3; /// Medium qualifier unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, uint, mediump> mediump_uvec4; /// High qualifier unsigned integer vector of 1 component type. /// @see gtc_type_precision typedef vec<1, uint, highp> highp_uvec1; /// High qualifier unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, uint, highp> highp_uvec2; /// High qualifier unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, uint, highp> highp_uvec3; /// High qualifier unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, uint, highp> highp_uvec4; /// Low qualifier 8 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u8, lowp> lowp_u8vec1; /// Low qualifier 8 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u8, lowp> lowp_u8vec2; /// Low qualifier 8 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u8, lowp> lowp_u8vec3; /// Low qualifier 8 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u8, lowp> lowp_u8vec4; /// Medium qualifier 8 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u8, mediump> mediump_u8vec1; /// Medium qualifier 8 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u8, mediump> mediump_u8vec2; /// Medium qualifier 8 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u8, mediump> mediump_u8vec3; /// Medium qualifier 8 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u8, mediump> mediump_u8vec4; /// High qualifier 8 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u8, highp> highp_u8vec1; /// High qualifier 8 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u8, highp> highp_u8vec2; /// High qualifier 8 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u8, highp> highp_u8vec3; /// High qualifier 8 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u8, highp> highp_u8vec4; /// Low qualifier 16 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u16, lowp> lowp_u16vec1; /// Low qualifier 16 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u16, lowp> lowp_u16vec2; /// Low qualifier 16 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u16, lowp> lowp_u16vec3; /// Low qualifier 16 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u16, lowp> lowp_u16vec4; /// Medium qualifier 16 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u16, mediump> mediump_u16vec1; /// Medium qualifier 16 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u16, mediump> mediump_u16vec2; /// Medium qualifier 16 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u16, mediump> mediump_u16vec3; /// Medium qualifier 16 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u16, mediump> mediump_u16vec4; /// High qualifier 16 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u16, highp> highp_u16vec1; /// High qualifier 16 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u16, highp> highp_u16vec2; /// High qualifier 16 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u16, highp> highp_u16vec3; /// High qualifier 16 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u16, highp> highp_u16vec4; /// Low qualifier 32 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u32, lowp> lowp_u32vec1; /// Low qualifier 32 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u32, lowp> lowp_u32vec2; /// Low qualifier 32 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u32, lowp> lowp_u32vec3; /// Low qualifier 32 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u32, lowp> lowp_u32vec4; /// Medium qualifier 32 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u32, mediump> mediump_u32vec1; /// Medium qualifier 32 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u32, mediump> mediump_u32vec2; /// Medium qualifier 32 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u32, mediump> mediump_u32vec3; /// Medium qualifier 32 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u32, mediump> mediump_u32vec4; /// High qualifier 32 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u32, highp> highp_u32vec1; /// High qualifier 32 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u32, highp> highp_u32vec2; /// High qualifier 32 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u32, highp> highp_u32vec3; /// High qualifier 32 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u32, highp> highp_u32vec4; /// Low qualifier 64 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u64, lowp> lowp_u64vec1; /// Low qualifier 64 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u64, lowp> lowp_u64vec2; /// Low qualifier 64 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u64, lowp> lowp_u64vec3; /// Low qualifier 64 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u64, lowp> lowp_u64vec4; /// Medium qualifier 64 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u64, mediump> mediump_u64vec1; /// Medium qualifier 64 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u64, mediump> mediump_u64vec2; /// Medium qualifier 64 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u64, mediump> mediump_u64vec3; /// Medium qualifier 64 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u64, mediump> mediump_u64vec4; /// High qualifier 64 bit unsigned integer scalar type. /// @see gtc_type_precision typedef vec<1, u64, highp> highp_u64vec1; /// High qualifier 64 bit unsigned integer vector of 2 components type. /// @see gtc_type_precision typedef vec<2, u64, highp> highp_u64vec2; /// High qualifier 64 bit unsigned integer vector of 3 components type. /// @see gtc_type_precision typedef vec<3, u64, highp> highp_u64vec3; /// High qualifier 64 bit unsigned integer vector of 4 components type. /// @see gtc_type_precision typedef vec<4, u64, highp> highp_u64vec4; ////////////////////// // Float vector types /// 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 float32_t; /// 32 bit single-qualifier floating-point scalar. /// @see gtc_type_precision typedef float32 f32; # ifndef GLM_FORCE_SINGLE_ONLY /// 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 float64_t; /// 64 bit double-qualifier floating-point scalar. /// @see gtc_type_precision typedef float64 f64; # endif//GLM_FORCE_SINGLE_ONLY /// Single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, float, defaultp> fvec1; /// Single-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, float, defaultp> fvec2; /// Single-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, float, defaultp> fvec3; /// Single-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, float, defaultp> fvec4; /// Single-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f32, defaultp> f32vec1; /// Single-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, f32, defaultp> f32vec2; /// Single-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, f32, defaultp> f32vec3; /// Single-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, f32, defaultp> f32vec4; # ifndef GLM_FORCE_SINGLE_ONLY /// Double-qualifier floating-point vector of 1 component. /// @see gtc_type_precision typedef vec<1, f64, defaultp> f64vec1; /// Double-qualifier floating-point vector of 2 components. /// @see gtc_type_precision typedef vec<2, f64, defaultp> f64vec2; /// Double-qualifier floating-point vector of 3 components. /// @see gtc_type_precision typedef vec<3, f64, defaultp> f64vec3; /// Double-qualifier floating-point vector of 4 components. /// @see gtc_type_precision typedef vec<4, f64, defaultp> f64vec4; # endif//GLM_FORCE_SINGLE_ONLY ////////////////////// // Float matrix types /// Single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef detail::tmat1x1<f32> fmat1; /// Single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, defaultp> fmat2; /// Single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, defaultp> fmat3; /// Single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, defaultp> fmat4; /// Single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f32 fmat1x1; /// Single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, defaultp> fmat2x2; /// Single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, defaultp> fmat2x3; /// Single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, defaultp> fmat2x4; /// Single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, defaultp> fmat3x2; /// Single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, defaultp> fmat3x3; /// Single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, defaultp> fmat3x4; /// Single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, defaultp> fmat4x2; /// Single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, defaultp> fmat4x3; /// Single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, defaultp> fmat4x4; /// Single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef detail::tmat1x1<f32, defaultp> f32mat1; /// Single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, defaultp> f32mat2; /// Single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, defaultp> f32mat3; /// Single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, defaultp> f32mat4; /// Single-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f32 f32mat1x1; /// Single-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f32, defaultp> f32mat2x2; /// Single-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f32, defaultp> f32mat2x3; /// Single-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f32, defaultp> f32mat2x4; /// Single-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f32, defaultp> f32mat3x2; /// Single-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f32, defaultp> f32mat3x3; /// Single-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f32, defaultp> f32mat3x4; /// Single-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f32, defaultp> f32mat4x2; /// Single-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f32, defaultp> f32mat4x3; /// Single-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f32, defaultp> f32mat4x4; # ifndef GLM_FORCE_SINGLE_ONLY /// Double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef detail::tmat1x1<f64, defaultp> f64mat1; /// Double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f64, defaultp> f64mat2; /// Double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f64, defaultp> f64mat3; /// Double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f64, defaultp> f64mat4; /// Double-qualifier floating-point 1x1 matrix. /// @see gtc_type_precision //typedef f64 f64mat1x1; /// Double-qualifier floating-point 2x2 matrix. /// @see gtc_type_precision typedef mat<2, 2, f64, defaultp> f64mat2x2; /// Double-qualifier floating-point 2x3 matrix. /// @see gtc_type_precision typedef mat<2, 3, f64, defaultp> f64mat2x3; /// Double-qualifier floating-point 2x4 matrix. /// @see gtc_type_precision typedef mat<2, 4, f64, defaultp> f64mat2x4; /// Double-qualifier floating-point 3x2 matrix. /// @see gtc_type_precision typedef mat<3, 2, f64, defaultp> f64mat3x2; /// Double-qualifier floating-point 3x3 matrix. /// @see gtc_type_precision typedef mat<3, 3, f64, defaultp> f64mat3x3; /// Double-qualifier floating-point 3x4 matrix. /// @see gtc_type_precision typedef mat<3, 4, f64, defaultp> f64mat3x4; /// Double-qualifier floating-point 4x2 matrix. /// @see gtc_type_precision typedef mat<4, 2, f64, defaultp> f64mat4x2; /// Double-qualifier floating-point 4x3 matrix. /// @see gtc_type_precision typedef mat<4, 3, f64, defaultp> f64mat4x3; /// Double-qualifier floating-point 4x4 matrix. /// @see gtc_type_precision typedef mat<4, 4, f64, defaultp> f64mat4x4; # endif//GLM_FORCE_SINGLE_ONLY ////////////////////////// // Quaternion types /// Single-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f32, defaultp> f32quat; /// Low single-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f32, lowp> lowp_f32quat; /// Low double-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f64, lowp> lowp_f64quat; /// Medium single-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f32, mediump> mediump_f32quat; # ifndef GLM_FORCE_SINGLE_ONLY /// Medium double-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f64, mediump> mediump_f64quat; /// High single-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f32, highp> highp_f32quat; /// High double-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f64, highp> highp_f64quat; /// Double-qualifier floating-point quaternion. /// @see gtc_type_precision typedef qua<f64, defaultp> f64quat; # endif//GLM_FORCE_SINGLE_ONLY /// @} }//namespace legion::core::math #include "type_precision.inl"
30.668735
79
0.740829
[ "vector" ]
881b0d16fa119304ef099406cbd1da88d0ba8c1d
659
hpp
C++
platform/glfw/test_writer.hpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
4,234
2015-01-09T08:10:16.000Z
2022-03-30T14:13:55.000Z
platform/glfw/test_writer.hpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
12,771
2015-01-01T20:27:42.000Z
2022-03-24T18:14:44.000Z
platform/glfw/test_writer.hpp
roblabs/maplibre-gl-native
d62ff400c6f75750d71b563344b1ca1e07b9b576
[ "BSD-2-Clause", "BSD-3-Clause" ]
1,571
2015-01-08T08:24:53.000Z
2022-03-28T06:30:53.000Z
#pragma once #include <mbgl/map/camera.hpp> #include <mbgl/style/style.hpp> #include <mbgl/util/size.hpp> #include <memory> #include <string> #include <vector> class TestOperationSerializer; class TestWriter final { public: TestWriter(); ~TestWriter(); TestWriter& withCameraOptions(const mbgl::CameraOptions&); TestWriter& withStyle(const mbgl::style::Style&); TestWriter& withInitialSize(const mbgl::Size&); bool write(const std::string& dir) const; private: std::string serialize() const; std::vector<std::unique_ptr<TestOperationSerializer>> operations; std::unique_ptr<TestOperationSerializer> initialSize; };
21.966667
69
0.728376
[ "vector" ]
88219332a01572b8a33545ff6320c7971fd8f0d9
5,910
cpp
C++
ThirdParty/poco/Foundation/src/Process.cpp
gregmedlock/roadrunnerwork
11f18f78ef3e381bc59c546a8d5e3ed46d8ab596
[ "Apache-2.0" ]
1
2021-11-29T08:30:19.000Z
2021-11-29T08:30:19.000Z
ThirdParty/poco/Foundation/src/Process.cpp
gregmedlock/roadrunnerwork
11f18f78ef3e381bc59c546a8d5e3ed46d8ab596
[ "Apache-2.0" ]
null
null
null
ThirdParty/poco/Foundation/src/Process.cpp
gregmedlock/roadrunnerwork
11f18f78ef3e381bc59c546a8d5e3ed46d8ab596
[ "Apache-2.0" ]
6
2016-06-04T08:15:01.000Z
2022-01-17T07:54:46.000Z
// // Process.cpp // // $Id: //poco/1.4/Foundation/src/Process.cpp#4 $ // // Library: Foundation // Package: Processes // Module: Process // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/Process.h" #include "Poco/Environment.h" namespace { std::vector<char> getEnvironmentVariablesBuffer(const Poco::Process::Env& env) { std::vector<char> envbuf; std::size_t pos = 0; for (Poco::Process::Env::const_iterator it = env.begin(); it != env.end(); ++it) { std::size_t envlen = it->first.length() + it->second.length() + 1; envbuf.resize(pos + envlen + 1); std::copy(it->first.begin(), it->first.end(), &envbuf[pos]); pos += it->first.length(); envbuf[pos] = '='; ++pos; std::copy(it->second.begin(), it->second.end(), &envbuf[pos]); pos += it->second.length(); envbuf[pos] = '\0'; ++pos; } envbuf.resize(pos + 1); envbuf[pos] = '\0'; return envbuf; } void setEnvironmentVariables(const Poco::Process::Env& env) { for (Poco::Process::Env::const_iterator it = env.begin(); it != env.end(); ++it) { Poco::Environment::set(it->first, it->second); } } } #if defined(POCO_OS_FAMILY_WINDOWS) && defined(POCO_WIN32_UTF8) #if defined(_WIN32_WCE) #include "Process_WINCE.cpp" #else #include "Process_WIN32U.cpp" #endif #elif defined(POCO_OS_FAMILY_WINDOWS) #include "Process_WIN32.cpp" #elif defined(POCO_VXWORKS) #include "Process_VX.cpp" #elif defined(POCO_OS_FAMILY_UNIX) #include "Process_UNIX.cpp" #else #include "Process_VMS.cpp" #endif namespace Poco { // // ProcessHandle // ProcessHandle::ProcessHandle(const ProcessHandle& handle): _pImpl(handle._pImpl) { _pImpl->duplicate(); } ProcessHandle::~ProcessHandle() { _pImpl->release(); } ProcessHandle::ProcessHandle(ProcessHandleImpl* pImpl): _pImpl(pImpl) { poco_check_ptr (_pImpl); } ProcessHandle& ProcessHandle::operator = (const ProcessHandle& handle) { if (&handle != this) { _pImpl->release(); _pImpl = handle._pImpl; _pImpl->duplicate(); } return *this; } ProcessHandle::PID ProcessHandle::id() const { return _pImpl->id(); } int ProcessHandle::wait() const { return _pImpl->wait(); } // // Process // ProcessHandle Process::launch(const std::string& command, const Args& args) { std::string initialDirectory; Env env; return ProcessHandle(launchImpl(command, args, initialDirectory, 0, 0, 0, env)); } ProcessHandle Process::launch(const std::string& command, const Args& args, const std::string& initialDirectory) { Env env; return ProcessHandle(launchImpl(command, args, initialDirectory, 0, 0, 0, env)); } ProcessHandle Process::launch(const std::string& command, const Args& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) { poco_assert (inPipe == 0 || (inPipe != outPipe && inPipe != errPipe)); std::string initialDirectory; Env env; return ProcessHandle(launchImpl(command, args, initialDirectory, inPipe, outPipe, errPipe, env)); } ProcessHandle Process::launch(const std::string& command, const Args& args, const std::string& initialDirectory, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe) { poco_assert (inPipe == 0 || (inPipe != outPipe && inPipe != errPipe)); Env env; return ProcessHandle(launchImpl(command, args, initialDirectory, inPipe, outPipe, errPipe, env)); } ProcessHandle Process::launch(const std::string& command, const Args& args, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe, const Env& env) { poco_assert (inPipe == 0 || (inPipe != outPipe && inPipe != errPipe)); std::string initialDirectory; return ProcessHandle(launchImpl(command, args, initialDirectory, inPipe, outPipe, errPipe, env)); } ProcessHandle Process::launch(const std::string& command, const Args& args, const std::string& initialDirectory, Pipe* inPipe, Pipe* outPipe, Pipe* errPipe, const Env& env) { poco_assert (inPipe == 0 || (inPipe != outPipe && inPipe != errPipe)); return ProcessHandle(launchImpl(command, args, initialDirectory, inPipe, outPipe, errPipe, env)); } int Process::wait(const ProcessHandle& handle) { return handle.wait(); } void Process::kill(const ProcessHandle& handle) { killImpl(*handle._pImpl); } void Process::kill(PID pid) { killImpl(pid); } void Process::requestTermination(PID pid) { requestTerminationImpl(pid); } } // namespace Poco
26.621622
173
0.687479
[ "object", "vector" ]
882277bb01558d4d5e0f9c54460f4ac1944ba79e
34,345
cpp
C++
src/chrono_multicore/physics/ChFluidContainer.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
1
2021-12-09T05:24:42.000Z
2021-12-09T05:24:42.000Z
src/chrono_multicore/physics/ChFluidContainer.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
7
2021-10-20T04:43:35.000Z
2021-12-24T08:44:31.000Z
src/chrono_multicore/physics/ChFluidContainer.cpp
Ruochun/chrono
7b0f09242ef540ae56cfc8add3a5dc7985c654d2
[ "BSD-3-Clause" ]
2
2021-12-09T05:32:31.000Z
2021-12-12T17:31:18.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2016 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: Hammad Mazhar // ============================================================================= #include <algorithm> #include <cmath> #include "chrono_multicore/ChDataManager.h" #include "chrono_multicore/physics/ChSystemMulticore.h" #include "chrono_multicore/physics/Ch3DOFContainer.h" #include "chrono_multicore/physics/ChFluidKernels.h" #include "chrono_multicore/constraints/ChConstraintUtils.h" #include "chrono_multicore/collision/ChCollision.h" #include "chrono_multicore/math/other_types.h" // for uint, vec2, vec3 #include "chrono_multicore/math/real.h" // for real #include "chrono_multicore/math/real2.h" // for real2 #include "chrono_multicore/math/real3.h" // for real3 #include "chrono_multicore/math/real4.h" // for quaternion, real4 #include "chrono_multicore/math/matrix.h" // for quaternion, real4 #ifdef CHRONO_MULTICORE_USE_CUDA #include "chrono_multicore/physics/ChMPM.cuh" #endif namespace chrono { using namespace collision; using namespace geometry; ChFluidContainer::ChFluidContainer() { body_offset = 0; epsilon = 1e-3; tau = 4 * .001; rho = 1000; mass = 1; viscosity = 0; artificial_pressure = false; artificial_pressure_k = 0.01; artificial_pressure_dq = .2 * kernel_radius; artificial_pressure_n = 4; enable_viscosity = false; mpm_iterations = 0; nu = .2; youngs_modulus = 1.4e5; hardening_coefficient = 10; lame_lambda = youngs_modulus * nu / ((1. + nu) * (1. - 2. * nu)); lame_mu = youngs_modulus / (2. * (1. + nu)); theta_s = 7.5e-3; theta_c = 2.5e-2; alpha_flip = .95; mpm_init = false; } void ChFluidContainer::AddBodies(const std::vector<real3>& positions, const std::vector<real3>& velocities) { custom_vector<real3>& pos_fluid = data_manager->host_data.pos_3dof; custom_vector<real3>& vel_fluid = data_manager->host_data.vel_3dof; pos_fluid.insert(pos_fluid.end(), positions.begin(), positions.end()); vel_fluid.insert(vel_fluid.end(), velocities.begin(), velocities.end()); // In case the number of velocities provided were not enough, resize to the number of fluid bodies vel_fluid.resize(pos_fluid.size()); data_manager->num_fluid_bodies = (int)pos_fluid.size(); } void ChFluidContainer::Update(double ChTime) { uint num_fluid_bodies = data_manager->num_fluid_bodies; uint num_rigid_bodies = data_manager->num_rigid_bodies; uint num_shafts = data_manager->num_shafts; uint num_motors = data_manager->num_motors; custom_vector<real3>& pos_fluid = data_manager->host_data.pos_3dof; custom_vector<real3>& vel_fluid = data_manager->host_data.vel_3dof; real3 g_acc = data_manager->settings.gravity; real3 h_gravity = data_manager->settings.step_size * mass * g_acc; #ifdef CHRONO_MULTICORE_USE_CUDA if (mpm_init) { temp_settings.dt = (float)data_manager->settings.step_size; temp_settings.kernel_radius = (float)kernel_radius; temp_settings.inv_radius = float(1.0 / kernel_radius); temp_settings.bin_edge = float(kernel_radius * 2); temp_settings.inv_bin_edge = float(1.0 / (kernel_radius * 2.0)); temp_settings.max_velocity = (float)max_velocity; temp_settings.mu = (float)lame_mu; temp_settings.lambda = (float)lame_lambda; temp_settings.hardening_coefficient = (float)hardening_coefficient; temp_settings.theta_c = (float)theta_c; temp_settings.theta_s = (float)theta_s; temp_settings.alpha_flip = (float)alpha_flip; temp_settings.youngs_modulus = (float)youngs_modulus; temp_settings.poissons_ratio = (float)nu; temp_settings.num_mpm_markers = data_manager->num_fluid_bodies; temp_settings.mass = (float)mass; temp_settings.yield_stress = (float)yield_stress; temp_settings.num_iterations = mpm_iterations; if (mpm_iterations > 0) { mpm_pos.resize(data_manager->num_fluid_bodies * 3); mpm_vel.resize(data_manager->num_fluid_bodies * 3); mpm_jejp.resize(data_manager->num_fluid_bodies * 2); for (int i = 0; i < (signed)data_manager->num_fluid_bodies; i++) { mpm_pos[i * 3 + 0] = (float)data_manager->host_data.pos_3dof[i].x; mpm_pos[i * 3 + 1] = (float)data_manager->host_data.pos_3dof[i].y; mpm_pos[i * 3 + 2] = (float)data_manager->host_data.pos_3dof[i].z; } for (int i = 0; i < (signed)data_manager->num_fluid_bodies; i++) { mpm_vel[i * 3 + 0] = (float)data_manager->host_data.vel_3dof[i].x; mpm_vel[i * 3 + 1] = (float)data_manager->host_data.vel_3dof[i].y; mpm_vel[i * 3 + 2] = (float)data_manager->host_data.vel_3dof[i].z; } MPM_UpdateDeformationGradient(std::ref(temp_settings), std::ref(mpm_pos), std::ref(mpm_vel), std::ref(mpm_jejp)); mpm_thread = std::thread(MPM_Solve, std::ref(temp_settings), std::ref(mpm_pos), std::ref(mpm_vel)); for (int i = 0; i < (signed)data_manager->num_fluid_bodies; i++) { data_manager->host_data.vel_3dof[i].x = mpm_vel[i * 3 + 0]; data_manager->host_data.vel_3dof[i].y = mpm_vel[i * 3 + 1]; data_manager->host_data.vel_3dof[i].z = mpm_vel[i * 3 + 2]; } } } #endif uint offset = num_rigid_bodies * 6 + num_shafts + num_motors; #pragma omp parallel for for (int i = 0; i < (signed)num_fluid_bodies; i++) { // This was moved to after fluid collision detection // real3 vel = vel_fluid[i]; // data_manager->host_data.v[offset + i * 3 + 0] = vel.x; // data_manager->host_data.v[offset + i * 3 + 1] = vel.y; // data_manager->host_data.v[offset + i * 3 + 2] = vel.z; data_manager->host_data.hf[offset + i * 3 + 0] = h_gravity.x; data_manager->host_data.hf[offset + i * 3 + 1] = h_gravity.y; data_manager->host_data.hf[offset + i * 3 + 2] = h_gravity.z; } } void ChFluidContainer::UpdatePosition(double ChTime) { uint num_fluid_bodies = data_manager->num_fluid_bodies; uint num_rigid_bodies = data_manager->num_rigid_bodies; uint num_shafts = data_manager->num_shafts; uint num_motors = data_manager->num_motors; custom_vector<real3>& pos_fluid = data_manager->host_data.pos_3dof; custom_vector<real3>& vel_fluid = data_manager->host_data.vel_3dof; custom_vector<real3>& sorted_pos_fluid = data_manager->host_data.sorted_pos_3dof; uint offset = num_rigid_bodies * 6 + num_shafts + num_motors; #pragma omp parallel for for (int i = 0; i < (signed)num_fluid_bodies; i++) { real3 vel; int original_index = data_manager->host_data.particle_indices_3dof[i]; // these are sorted so we have to unsort them vel.x = data_manager->host_data.v[offset + i * 3 + 0]; vel.y = data_manager->host_data.v[offset + i * 3 + 1]; vel.z = data_manager->host_data.v[offset + i * 3 + 2]; real speed = Length(vel); if (speed > max_velocity) { vel = vel * max_velocity / speed; } vel_fluid[original_index] = vel; pos_fluid[original_index] += vel * data_manager->settings.step_size; // sorted_pos_fluid[i] = pos_fluid[original_index]; } // if (num_fluid_bodies != 0) { // data_manager->narrowphase->DispatchRigidFluid(); // // custom_vector<real3>& cpta = data_manager->host_data.cpta_rigid_fluid; // custom_vector<real3>& norm = data_manager->host_data.norm_rigid_fluid; // custom_vector<real>& dpth = data_manager->host_data.dpth_rigid_fluid; // custom_vector<int>& neighbor_rigid_fluid = data_manager->host_data.neighbor_rigid_fluid; // custom_vector<int>& contact_counts = data_manager->host_data.c_counts_rigid_fluid; // // This treats all rigid neighbors as fixed. This correction should usually be pretty small if the // // timestep // // isnt too large. // if (data_manager->num_rigid_fluid_contacts > 0) { //#pragma omp parallel for // for (int p = 0; p < num_fluid_bodies; p++) { // int start = contact_counts[p]; // int end = contact_counts[p + 1]; // real3 delta = real3(0); // real weight = 0; // for (int index = start; index < end; index++) { // int i = index - start; // // int rigid = neighbor_rigid_fluid[p * max_rigid_neighbors + i]; // // if (data_manager->host_data.active_rigid[rigid] == false) { // real3 U = norm[p * max_rigid_neighbors + i]; // real depth = dpth[p * max_rigid_neighbors + i]; // if (depth < 0) { // real w = 1.0; // mass / (mass + data_manager->host_data.mass_rigid[rigid]); // delta -= w * depth * U; // weight++; // } // //} // } // if (weight > 0) { // sorted_pos_fluid[p] = sorted_pos_fluid[p] + delta / weight; // } // } // } // real inv_dt = 1.0 / data_manager->settings.step_size; //#pragma omp parallel for // for (int p = 0; p < num_fluid_bodies; p++) { // int original_index = data_manager->host_data.particle_indices_3dof[p]; // real3 vv = real3((sorted_pos_fluid[p] - pos_fluid[original_index]) * inv_dt); // if (contact_counts[p + 1] - contact_counts[p] > 0) { // pos_fluid[original_index] = sorted_pos_fluid[p]; // vel_fluid[original_index] += vv; // } // } // } } int ChFluidContainer::GetNumConstraints() { int num_fluid_fluid = data_manager->num_fluid_bodies; if (contact_mu == 0) { num_fluid_fluid += data_manager->num_rigid_fluid_contacts; } else { num_fluid_fluid += data_manager->num_rigid_fluid_contacts * 3; } if (enable_viscosity) { num_fluid_fluid += data_manager->num_fluid_bodies * 3; } // printf("ChFluidContainer::GetNumConstraints() %d\n", num_fluid_fluid); return num_fluid_fluid; } int ChFluidContainer::GetNumNonZeros() { int nnz_fluid_fluid = data_manager->num_fluid_bodies * 6 * max_neighbors; if (contact_mu == 0) { nnz_fluid_fluid += 9 * data_manager->num_rigid_fluid_contacts; } else { nnz_fluid_fluid += 9 * 3 * data_manager->num_rigid_fluid_contacts; } if (enable_viscosity) { nnz_fluid_fluid += data_manager->num_fluid_bodies * 18 * max_neighbors; } // printf("ChFluidContainer::GetNumNonZeros() %d\n", nnz_fluid_fluid); return nnz_fluid_fluid; } void ChFluidContainer::ComputeInvMass(int offset) { CompressedMatrix<real>& M_inv = data_manager->host_data.M_inv; uint num_fluid_bodies = data_manager->num_fluid_bodies; real inv_mass = 1.0 / mass; for (int i = 0; i < (signed)num_fluid_bodies; i++) { M_inv.append(offset + i * 3 + 0, offset + i * 3 + 0, inv_mass); M_inv.finalize(offset + i * 3 + 0); M_inv.append(offset + i * 3 + 1, offset + i * 3 + 1, inv_mass); M_inv.finalize(offset + i * 3 + 1); M_inv.append(offset + i * 3 + 2, offset + i * 3 + 2, inv_mass); M_inv.finalize(offset + i * 3 + 2); } } void ChFluidContainer::ComputeMass(int offset) { CompressedMatrix<real>& M = data_manager->host_data.M; uint num_fluid_bodies = data_manager->num_fluid_bodies; real fluid_mass = mass; for (int i = 0; i < (signed)num_fluid_bodies; i++) { M.append(offset + i * 3 + 0, offset + i * 3 + 0, fluid_mass); M.finalize(offset + i * 3 + 0); M.append(offset + i * 3 + 1, offset + i * 3 + 1, fluid_mass); M.finalize(offset + i * 3 + 1); M.append(offset + i * 3 + 2, offset + i * 3 + 2, fluid_mass); M.finalize(offset + i * 3 + 2); } } void ChFluidContainer::Setup(int start_constraint) { Ch3DOFContainer::Setup(start_constraint); start_boundary = start_constraint; if (contact_mu == 0) { start_density = start_constraint + num_rigid_fluid_contacts; } else { start_density = start_constraint + num_rigid_fluid_contacts * 3; } start_viscous = start_density + num_fluid_bodies; body_offset = num_rigid_bodies * 6 + num_shafts + num_motors; } void ChFluidContainer::Initialize() { #ifdef CHRONO_MULTICORE_USE_CUDA temp_settings.dt = (float)data_manager->settings.step_size; temp_settings.kernel_radius = (float)kernel_radius; temp_settings.inv_radius = float(1.0 / kernel_radius); temp_settings.bin_edge = float(kernel_radius * 2); temp_settings.inv_bin_edge = float(1.0 / (kernel_radius * 2.0)); temp_settings.max_velocity = (float)max_velocity; temp_settings.mu = (float)lame_mu; temp_settings.lambda = (float)lame_lambda; temp_settings.hardening_coefficient = (float)hardening_coefficient; temp_settings.theta_c = (float)theta_c; temp_settings.theta_s = (float)theta_s; temp_settings.alpha_flip = (float)alpha_flip; temp_settings.youngs_modulus = (float)youngs_modulus; temp_settings.poissons_ratio = (float)nu; temp_settings.num_mpm_markers = data_manager->num_fluid_bodies; temp_settings.mass = (float)mass; temp_settings.yield_stress = (float)yield_stress; temp_settings.num_iterations = mpm_iterations; if (mpm_iterations > 0) { mpm_pos.resize(data_manager->num_fluid_bodies * 3); for (int i = 0; i < (signed)data_manager->num_fluid_bodies; i++) { mpm_pos[i * 3 + 0] = (float)data_manager->host_data.pos_3dof[i].x; mpm_pos[i * 3 + 1] = (float)data_manager->host_data.pos_3dof[i].y; mpm_pos[i * 3 + 2] = (float)data_manager->host_data.pos_3dof[i].z; } MPM_Initialize(temp_settings, mpm_pos); } mpm_init = true; #endif } void ChFluidContainer::Density_FluidMPM() { custom_vector<real3>& sorted_pos = data_manager->host_data.sorted_pos_3dof; real h = kernel_radius; real envel = data_manager->settings.collision.collision_envelope; real inv_density = 1.0 / rho; real mass_over_density = mass * inv_density; real eta = .01; CompressedMatrix<real>& D_T = data_manager->host_data.D_T; #pragma omp parallel for for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { real dens = 0; real3 dcon_diag = real3(0.0); real3 pos_p = sorted_pos[body_a]; int d_ind = 0; for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; if (body_a == body_b) { dens += mass * CPOLY6 * H6; d_ind = i; continue; } int column = body_offset + body_b * 3; real3 xij = pos_p - sorted_pos[body_b]; real dist = Length(xij); dens += mass * KPOLY6; } density[body_a] = dens; } #pragma omp parallel for for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { real dens = 0; real3 diag = real3(0); real3 pos_p = sorted_pos[body_a]; for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; if (body_a == body_b) { dens += mass / density[body_b] * CPOLY6 * H6; continue; } real3 xij = pos_p - sorted_pos[body_b]; real dist = Length(xij); dens += (mass / density[body_b]) * KPOLY6; } density[body_a] = density[body_a] / dens; } } void ChFluidContainer::DensityConstraint_FluidMPM() { custom_vector<real3>& sorted_pos = data_manager->host_data.sorted_pos_3dof; real h = kernel_radius; real envel = data_manager->settings.collision.collision_envelope; real inv_density = 1.0 / rho; real mass_over_density = mass * inv_density; real step_size = data_manager->settings.step_size; real eta = .01; CompressedMatrix<real>& D_T = data_manager->host_data.D_T; #pragma omp parallel for for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { real3 dcon_diag = real3(0.0); real3 pos_p = sorted_pos[body_a]; int d_ind = 0; for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; if (body_a == body_b) { d_ind = i; continue; } int column = body_offset + body_b * 3; real3 xij = pos_p - sorted_pos[body_b]; real dist = Length(xij); // printf("jpjp: %f d: %f\n", (mpm_jejp[body_b * 2 + 0] / mpm_jejp[body_b * 2 + 1]) * step_size, // mass_over_density); real3 kernel_xij = KGSPIKY * xij; real3 dcon_od = (mass / density[body_b]) * (mpm_jejp[body_b * 2 + 0] / mpm_jejp[body_b * 2 + 1]) * kernel_xij; // off diagonal dcon_diag -= dcon_od; // diagonal is sum // den_con_jac[body_a * max_neighbors + i] = dcon_od; SetRow3Check(D_T, start_density + body_a, body_offset + body_b * 3, dcon_od); } // den_con_jac[body_a * max_neighbors + d_ind] = dcon_diag; SetRow3Check(D_T, start_density + body_a, body_offset + body_a * 3, dcon_diag); } } void ChFluidContainer::Density_Fluid() { custom_vector<real3>& sorted_pos = data_manager->host_data.sorted_pos_3dof; real h = kernel_radius; real envel = data_manager->settings.collision.collision_envelope; real inv_density = 1.0 / rho; real mass_over_density = mass * inv_density; real eta = .01; CompressedMatrix<real>& D_T = data_manager->host_data.D_T; #pragma omp parallel for for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { real dens = 0; real3 dcon_diag = real3(0.0); real3 pos_p = sorted_pos[body_a]; int d_ind = 0; for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; if (body_a == body_b) { dens += mass * CPOLY6 * H6; d_ind = i; continue; } int column = body_offset + body_b * 3; real3 xij = pos_p - sorted_pos[body_b]; real dist = Length(xij); dens += mass * KPOLY6; real3 kernel_xij = KGSPIKY * xij; real3 dcon_od = mass_over_density * kernel_xij; // off diagonal dcon_diag -= dcon_od; // diagonal is sum // den_con_jac[body_a * max_neighbors + i] = dcon_od; SetRow3Check(D_T, start_density + body_a, body_offset + body_b * 3, dcon_od); } // den_con_jac[body_a * max_neighbors + d_ind] = dcon_diag; SetRow3Check(D_T, start_density + body_a, body_offset + body_a * 3, dcon_diag); density[body_a] = dens; } } void ChFluidContainer::Normalize_Density_Fluid() { real h = kernel_radius; custom_vector<real3>& pos = data_manager->host_data.pos_3dof; real inv_density = 1.0 / rho; real mass_over_density = mass * inv_density; custom_vector<real3>& sorted_pos = data_manager->host_data.sorted_pos_3dof; #pragma omp parallel for for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { real dens = 0; real3 diag = real3(0); real3 pos_p = sorted_pos[body_a]; for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; if (body_a == body_b) { dens += mass / density[body_b] * CPOLY6 * H6; continue; } real3 xij = pos_p - sorted_pos[body_b]; real dist = Length(xij); dens += (mass / density[body_b]) * KPOLY6; } density[body_a] = density[body_a] / dens; } } void ChFluidContainer::Build_D() { LOG(INFO) << "ChFluidContainer::Build_D"; CompressedMatrix<real>& D_T = data_manager->host_data.D_T; BuildRigidFluidBoundary(contact_mu, num_fluid_bodies, body_offset, start_boundary, data_manager); if (data_manager->num_fluid_contacts > 0) { LOG(INFO) << "ChFluidContainer::Build_D Fluid"; real h = kernel_radius; real envel = data_manager->settings.collision.collision_envelope; real inv_density = 1.0 / rho; real mass_over_density = mass * inv_density; real eta = .01; // custom_vector<real3>& vel = data_manager->host_data.vel_3dof; custom_vector<real3>& sorted_pos = data_manager->host_data.sorted_pos_3dof; //=======COMPUTE DENSITY OF FLUID density.resize(num_fluid_bodies); // if (mpm_iterations > 0) { // Density_FluidMPM(); // DensityConstraint_FluidMPM(); // } else { Density_Fluid(); Normalize_Density_Fluid(); //} real visca = viscosity; real viscb = viscosity; const real mass_2 = mass * mass; const real eta_2 = eta * eta; if (enable_viscosity) { #pragma omp parallel for for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { real3 pos_p = sorted_pos[body_a]; real3 vmat_row1(0); real3 vmat_row2(0); real3 vmat_row3(0); int d_ind = 0; for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; if (body_a == body_b) { d_ind = i; continue; } int column = body_offset + body_b * 3; real3 xij = pos_p - sorted_pos[body_b]; real dist = Length(xij); real3 kernel_xij = KGSPIKY * xij; // real density_a = density[body_a]; real density_b = density[body_b]; real part_a = (8.0 / (density_a + density_b)); real part_b = (visca + viscb); real part_c = 1.0 / (h * ((dist * dist / (H2)) + eta_2)); real scalar = -mass_2 * part_a * part_b * part_c; real3 r1 = xij[0] * kernel_xij * scalar; real3 r2 = xij[1] * kernel_xij * scalar; real3 r3 = xij[2] * kernel_xij * scalar; SetRow3Check(D_T, start_viscous + body_a * 3 + 0, body_offset + body_b * 3, r1); SetRow3Check(D_T, start_viscous + body_a * 3 + 1, body_offset + body_b * 3, r2); SetRow3Check(D_T, start_viscous + body_a * 3 + 2, body_offset + body_b * 3, r3); vmat_row1 -= r1; vmat_row2 -= r2; vmat_row3 -= r3; } SetRow3Check(D_T, start_viscous + body_a * 3 + 0, body_offset + body_a * 3, vmat_row1); SetRow3Check(D_T, start_viscous + body_a * 3 + 1, body_offset + body_a * 3, vmat_row2); SetRow3Check(D_T, start_viscous + body_a * 3 + 2, body_offset + body_a * 3, vmat_row3); } } } } void ChFluidContainer::Build_b() { real inv_h = 1 / data_manager->settings.step_size; real inv_hpa = 1.0 / (data_manager->settings.step_size + alpha); real inv_hhpa = inv_h * inv_hpa; real dt = data_manager->settings.step_size; real h = kernel_radius; real zeta = 1.0 / (1.0 + 4.0 * tau / h); DynamicVector<real>& b = data_manager->host_data.b; CorrectionRigidFluidBoundary(contact_mu, contact_cohesion, alpha, contact_recovery_speed, num_fluid_bodies, start_boundary, data_manager); if (num_fluid_bodies > 0) { // if (mpm_iterations > 0) { //#pragma omp parallel for // for (int index = 0; index < num_fluid_bodies; index++) { // b[start_density + index] = (1.0 / mpm_jejp[index * 2 + 1]) * (mpm_jejp[index * 2 + 0] - 1.0); // // printf("J:%f J:%f [%f,%f]\n", mpm_jejp[index * 2 + 0], mpm_jejp[index * 2 + 1], // b[start_density + // } // } else { #pragma omp parallel for for (int index = 0; index < (signed)num_fluid_bodies; index++) { b[start_density + index] = -(density[index] / rho - 1.0); } } } } void ChFluidContainer::Build_E() { DynamicVector<real>& E = data_manager->host_data.E; ComplianceRigidFluidBoundary(contact_mu, contact_compliance, alpha, start_boundary, data_manager); real step_size = data_manager->settings.step_size; real zeta = 1.0 / (1.0 + 4.0 * tau / step_size); real f_compliance = 4.0 / (step_size * step_size) * (epsilon * zeta); if (num_fluid_bodies > 0) { #pragma omp parallel for for (int index = 0; index < (signed)num_fluid_bodies; index++) { E[start_density + index] = f_compliance; if (enable_viscosity) { E[start_viscous + index * 3 + 0] = 0; E[start_viscous + index * 3 + 1] = 0; E[start_viscous + index * 3 + 2] = 0; } } } } void ChFluidContainer::Project(real* gamma) { ProjectRigidFluidBoundary(contact_mu, contact_cohesion, num_fluid_bodies, start_boundary, gamma, data_manager); } void ChFluidContainer::GenerateSparsity() { CompressedMatrix<real>& D_T = data_manager->host_data.D_T; LOG(INFO) << "ChFluidContainer::GenerateSparsity"; AppendRigidFluidBoundary(contact_mu, num_fluid_bodies, body_offset, start_boundary, data_manager); if (data_manager->num_fluid_contacts > 0) { for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; AppendRow3(D_T, start_density + body_a, body_offset + body_b * 3, 0); } D_T.finalize(start_density + body_a); } // Add more entries for viscosity // Code is repeated because there are three rows per viscosity constraint if (enable_viscosity) { for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; AppendRow3(D_T, start_viscous + body_a * 3 + 0, body_offset + body_b * 3, 0); } D_T.finalize(start_viscous + body_a * 3 + 0); // for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; AppendRow3(D_T, start_viscous + body_a * 3 + 1, body_offset + body_b * 3, 0); } D_T.finalize(start_viscous + body_a * 3 + 1); // for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; AppendRow3(D_T, start_viscous + body_a * 3 + 2, body_offset + body_b * 3, 0); } D_T.finalize(start_viscous + body_a * 3 + 2); } } } } void ChFluidContainer::PreSolve() { #ifdef CHRONO_MULTICORE_USE_CUDA if (mpm_thread.joinable()) { mpm_thread.join(); #pragma omp parallel for for (int p = 0; p < (signed)num_fluid_bodies; p++) { int index = data_manager->host_data.reverse_mapping_3dof[p]; data_manager->host_data.v[body_offset + index * 3 + 0] = mpm_vel[p * 3 + 0]; data_manager->host_data.v[body_offset + index * 3 + 1] = mpm_vel[p * 3 + 1]; data_manager->host_data.v[body_offset + index * 3 + 2] = mpm_vel[p * 3 + 2]; } } #endif if (gamma_old.size() > 0) { if (enable_viscosity) { if (gamma_old.size() == (num_fluid_bodies + num_fluid_bodies * 3)) { blaze::subvector(data_manager->host_data.gamma, start_density, num_fluid_bodies + num_fluid_bodies * 3) = gamma_old * .9; } } else { if (gamma_old.size() == num_fluid_bodies) { blaze::subvector(data_manager->host_data.gamma, start_density, num_fluid_bodies) = gamma_old * .9; } } } } void ChFluidContainer::PostSolve() { LOG(INFO) << "ChFluidContainer::PostSolve() "; if (num_fluid_bodies > 0) { if (enable_viscosity) { gamma_old.resize(num_fluid_bodies + num_fluid_bodies * 3); gamma_old = blaze::subvector(data_manager->host_data.gamma, start_density, num_fluid_bodies + num_fluid_bodies * 3); } else { gamma_old.resize(num_fluid_bodies); gamma_old = blaze::subvector(data_manager->host_data.gamma, start_density, num_fluid_bodies); } } if (artificial_pressure == false) { return; } LOG(INFO) << "ChFluidContainer::artificial_pressure() "; custom_vector<real3>& sorted_pos = data_manager->host_data.sorted_pos_3dof; custom_vector<real3>& sorted_vel = data_manager->host_data.sorted_vel_3dof; real inv_density = 1.0 / rho; real h = kernel_radius; real k = artificial_pressure_k; real dq = artificial_pressure_dq; real n = artificial_pressure_n; real dt = data_manager->settings.step_size; #pragma omp parallel for for (int body_a = 0; body_a < (signed)num_fluid_bodies; body_a++) { real corr = 0; real3 vorticity_grad(0); real3 pos_a = sorted_pos[body_a]; for (int i = 0; i < data_manager->host_data.c_counts_3dof_3dof[body_a]; i++) { int body_b = data_manager->host_data.neighbor_3dof_3dof[body_a * max_neighbors + i]; if (body_a == body_b) { continue; } real3 xij = (pos_a - sorted_pos[body_b]); real dist = Length(xij); corr += k * Pow(KERNEL(dist, h) / KERNEL(dq, h), n); } data_manager->host_data.gamma[start_density + body_a] += corr; } } void ChFluidContainer::CalculateContactForces() { uint num_contacts = data_manager->num_rigid_fluid_contacts; if (num_contacts <= 0) { return; } LOG(INFO) << "ChFluidContainer::CalculateContactForces() "; DynamicVector<real>& gamma = data_manager->host_data.gamma; SubVectorType gamma_n = subvector(gamma, start_boundary, _num_rf_c_); contact_forces = submatrix(data_manager->host_data.D, 0, start_boundary, _num_dof_, _num_rf_c_) * gamma_n / data_manager->settings.step_size; if (contact_mu != 0) { SubVectorType gamma_t = subvector(gamma, start_boundary + _num_rf_c_, 2 * _num_rf_c_); contact_forces += submatrix(data_manager->host_data.D, 0, start_boundary + _num_rf_c_, _num_dof_, 2 * _num_rf_c_) * gamma_t / data_manager->settings.step_size; } // contact_forces } real3 ChFluidContainer::GetBodyContactForce(uint body_id) { if (data_manager->num_rigid_fluid_contacts <= 0) { return real3(0); } return real3(contact_forces[body_id * 6 + 0], contact_forces[body_id * 6 + 1], contact_forces[body_id * 6 + 2]); } real3 ChFluidContainer::GetBodyContactTorque(uint body_id) { if (data_manager->num_rigid_fluid_contacts <= 0) { return real3(0); } return real3(contact_forces[body_id * 6 + 3], contact_forces[body_id * 6 + 4], contact_forces[body_id * 6 + 5]); } void ChFluidContainer::GetFluidDensity(custom_vector<real>& dens) { dens = density; } void ChFluidContainer::GetFluidPressure(custom_vector<real>& pres) { pres.resize(num_fluid_bodies); for (int i = 0; i < (signed)num_fluid_bodies; i++) { pres[i] = data_manager->host_data.gamma[start_density + i]; } } void ChFluidContainer::GetFluidForce(custom_vector<real3>& forc) { forc.resize(num_fluid_bodies); DynamicVector<real>& gamma = data_manager->host_data.gamma; SubVectorType gamma_n = subvector(gamma, start_density, num_fluid_bodies); DynamicVector<real> pressure_forces = submatrix(data_manager->host_data.D, body_offset, start_density, num_fluid_bodies * 3, num_fluid_bodies) * gamma_n / data_manager->settings.step_size; for (int i = 0; i < (signed)num_fluid_bodies; i++) { forc[i] = real3(pressure_forces[i * 3 + 0], pressure_forces[i * 3 + 1], pressure_forces[i * 3 + 2]); } } } // end namespace chrono
43.092848
120
0.603145
[ "geometry", "vector" ]
8823485d90f165c47f220f7eb96a4348d57712fe
1,099
cpp
C++
atcoder/abc104c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
atcoder/abc104c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
atcoder/abc104c.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // at most one type not take all. void solve() { int n, g; cin >> n >> g; g/=100; vector<int> p(n), c(n); for (int i = 0; i < n; i++) { cin >> p[i] >> c[i]; c[i]/=100; } const int MSK = 1<<n; int res = 1e6; for (int msk = 0; msk < MSK; msk++) { int sum = 0; int cnt = 0; for (int i = 0; i < n; i++) { if (msk & (1<<i)) { sum += p[i]*(i+1) + c[i]; cnt += p[i]; } } if (sum >= g) res = min(res, cnt); else { for (int i = n-1; i >= 0; i--) { if (!(msk & (1<<i))) { for (int j = 0; j < p[i]; j++) { sum += (i+1); cnt += 1; if (sum >= g) res = min(res, cnt); } break; } } } } cout << res; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
21.98
58
0.320291
[ "vector" ]
8825eeb856b01820ec62bad320ef4f29e3ea0e52
907
cpp
C++
16A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
16A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
16A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; int bawah,samping,x,y,z; char flag[111][111]; bool oke; int main() { scanf("%d %d",&bawah,&samping); for(x=0;x<bawah;x++) scanf("%s",flag[x]); oke=true; for(x=0;x<bawah;x++) if(!oke) break; else for(y=1;y<samping;y++) if(flag[x][y]!=flag[x][0]) oke=false; if(oke) for(x=1;x+1<bawah;x++) if((flag[x][0]==flag[x-1][0])||(flag[x][0]==flag[x+1][0])) oke=false; printf("%s\n",oke?"YES":"NO"); return 0; }
20.155556
72
0.619625
[ "vector" ]
8828b1446b769e1a09f45b747506807d116ca2da
330,472
cpp
C++
src/QtPhonemes/Phonemes/nSpeechTranslator.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nSpeechTranslator.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nSpeechTranslator.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
#include <qtphonemes.h> typedef struct { const char * name ; int offset ; unsigned short range_min ; unsigned short range_max ; int language ; int flags ; } nSpeakAlphabet ; extern nSpeakAlphabet * FromName(const char * name) ; extern nSpeakAlphabet * FromChar(int c ) ; #define L(c1,c2) (c1<<8)+c2 // combine two characters into an integer for translator name #define L_qa 0x716100 #define L_grc 0x677263 // grc Ancient Greek #define L_jbo 0x6a626f // jbo Lojban #define L_pap 0x706170 // pap Papiamento] #define L_qvi 0x717669 // qvi Kichwa #define L_shs 0x736873 // shs Shuswap / Secwepemctsin #define L_zhy 0x7a6879 // zhy #define REPLACED_E 'E' // 'e' replaced by silent e #define N_WORD_PHONEMES 200 // max phonemes in a word #define N_WORD_BYTES 160 // max bytes for the UTF8 characters in a word #define N_CLAUSE_WORDS 300 // max words in a clause #define N_RULE_GROUP2 120 // max num of two-letter rule chains #define N_HASH_DICT 1024 #define N_CHARSETS 20 #define N_LETTER_GROUPS 95 // maximum is 127-32 /* dictionary flags, word 1 */ // bits 0-3 stressed syllable, bit 6=unstressed #define FLAG_SKIPWORDS 0x80 #define FLAG_PREPAUSE 0x100 #define FLAG_STRESS_END 0x200 // full stress if at end of clause #define FLAG_STRESS_END2 0x400 // full stress if at end of clause, or only followed by unstressed #define FLAG_UNSTRESS_END 0x800 // reduce stress at end of clause #define FLAG_SPELLWORD 0x1000 // re-translate the word as individual letters, separated by spaces #define FLAG_ABBREV 0x2000 // spell as letters, even with a vowel, OR use specified pronunciation rather than split into letters #define FLAG_DOUBLING 0x4000 // doubles the following consonant #define BITNUM_FLAG_ALT 14 // bit number of FLAG_ALT_TRANS - 1 #define FLAG_ALT_TRANS 0x8000 // language specific #define FLAG_ALT2_TRANS 0x10000 // language specific #define FLAG_ALT3_TRANS 0x20000 // language specific #define FLAG_ALT4_TRANS 0x40000 // language specific #define FLAG_ALT5_TRANS 0x80000 // language specific #define FLAG_ALT6_TRANS 0x100000 // language specific #define FLAG_COMBINE 0x800000 // combine with the next word #define FLAG_ALLOW_DOT 0x01000000 // ignore '.' after word (abbreviation) #define FLAG_NEEDS_DOT 0x02000000 // only if the word is followed by a dot #define FLAG_WAS_UNPRONOUNCABLE 0x04000000 // the unpronounceable routine was used #define FLAG_MAX3 0x08000000 // limit to 3 repeats #define FLAG_PAUSE1 0x10000000 // shorter prepause #define FLAG_TEXTMODE 0x20000000 // word translates to replacement text, not phonemes #define BITNUM_FLAG_TEXTMODE 29 #define FLAG_FOUND_ATTRIBUTES 0x40000000 // word was found in the dictionary list (has attributes) #define FLAG_FOUND 0x80000000 // pronunciation was found in the dictionary list // dictionary flags, word 2 #define FLAG_VERBF 0x1 /* verb follows */ #define FLAG_VERBSF 0x2 /* verb follows, may have -s suffix */ #define FLAG_NOUNF 0x4 /* noun follows */ #define FLAG_PASTF 0x8 /* past tense follows */ #define FLAG_VERB 0x10 /* pronunciation for verb */ #define FLAG_NOUN 0x20 /* pronunciation for noun */ #define FLAG_PAST 0x40 /* pronunciation for past tense */ #define FLAG_VERB_EXT 0x100 /* extend the 'verb follows' */ #define FLAG_CAPITAL 0x200 /* pronunciation if initial letter is upper case */ #define FLAG_ALLCAPS 0x400 // only if the word is all capitals #define FLAG_ACCENT 0x800 // character name is base-character name + accent name #define FLAG_HYPHENATED 0x1000 // multiple-words, but needs hyphen between parts 1 and 2 #define FLAG_SENTENCE 0x2000 // only if the clause is a sentence #define FLAG_ONLY 0x4000 #define FLAG_ONLY_S 0x8000 #define FLAG_STEM 0x10000 // must have a suffix #define FLAG_ATEND 0x20000 // use this pronunciation if at end of clause #define FLAG_ATSTART 0x40000 // use this pronunciation if at start of clause #define FLAG_NATIVE 0x80000 // not if we've switched translators #define FLAG_LOOKUP_SYMBOL 0x40000000 // to indicate called from Lookup() #define BITNUM_FLAG_ALLCAPS 0x2a #define BITNUM_FLAG_HYPHENATED 0x2c #define BITNUM_FLAG_ONLY 0x2e #define BITNUM_FLAG_ONLY_S 0x2f // wordflags, flags in source word #define FLAG_ALL_UPPER 0x1 /* no lower case letters in the word */ #define FLAG_FIRST_UPPER 0x2 /* first letter is upper case */ #define FLAG_UPPERS 0x3 // FLAG_ALL_UPPER | FLAG_FIRST_UPPER #define FLAG_HAS_PLURAL 0x4 /* upper-case word with s or 's lower-case ending */ #define FLAG_PHONEMES 0x8 /* word is phonemes */ #define FLAG_LAST_WORD 0x10 /* last word in clause */ #define FLAG_EMBEDDED 0x40 /* word is preceded by embedded commands */ #define FLAG_HYPHEN 0x80 #define FLAG_NOSPACE 0x100 // word is not seperated from previous word by a space #define FLAG_FIRST_WORD 0x200 // first word in clause #define FLAG_FOCUS 0x400 // the focus word of a clause #define FLAG_EMPHASIZED 0x800 #define FLAG_EMPHASIZED2 0xc00 // FLAG_FOCUS | FLAG_EMPHASIZED #define FLAG_DONT_SWITCH_TRANSLATOR 0x1000 #define FLAG_SUFFIX_REMOVED 0x2000 #define FLAG_HYPHEN_AFTER 0x4000 #define FLAG_ORDINAL 0x8000 // passed to TranslateNumber() to indicate an ordinal number #define FLAG_HAS_DOT 0x10000 // dot after this word #define FLAG_COMMA_AFTER 0x20000 // comma after this word #define FLAG_MULTIPLE_SPACES 0x40000 // word is preceded by multiple spaces, newline, or tab #define FLAG_INDIVIDUAL_DIGITS 0x80000 // speak number as individual digits #define FLAG_DELETE_WORD 0x100000 // don't speak this word, it has been spoken as part of the previous word #define FLAG_CHAR_REPLACED 0x200000 // characters have been replaced by .replace in the *_rules #define FLAG_TRANSLATOR2 0x400000 // retranslating using a different language #define FLAG_SUFFIX_VOWEL 0x08000000 // remember an initial vowel from the suffix #define FLAG_NO_TRACE 0x10000000 // passed to TranslateRules() to suppress dictionary lookup printout #define FLAG_NO_PREFIX 0x20000000 #define FLAG_UNPRON_TEST 0x80000000 // do unpronounability test on the beginning of the word // prefix/suffix flags (bits 8 to 14, bits 16 to 22) don't use 0x8000, 0x800000 #define SUFX_E 0x0100 // e may have been added #define SUFX_I 0x0200 // y may have been changed to i #define SUFX_P 0x0400 // prefix #define SUFX_V 0x0800 // suffix means use the verb form pronunciation #define SUFX_D 0x1000 // previous letter may have been doubled #define SUFX_F 0x2000 // verb follows #define SUFX_Q 0x4000 // don't retranslate #define SUFX_T 0x10000 // don't affect the stress position in the stem #define SUFX_B 0x20000 // break, this character breaks the word into stem and suffix (used with SUFX_P) #define SUFX_A 0x40000 // remember that the suffix starts with a vowel #define SUFX_M 0x80000 // bit 19, allow multiple suffixes #define SUFX_UNPRON 0x8000 // used to return $unpron flag from *_rules #define FLAG_ALLOW_TEXTMODE 0x02 // allow dictionary to translate to text rather than phonemes #define FLAG_SUFX 0x04 #define FLAG_SUFX_S 0x08 #define FLAG_SUFX_E_ADDED 0x10 // codes in dictionary rules #define RULE_PRE 1 #define RULE_POST 2 #define RULE_PHONEMES 3 #define RULE_PH_COMMON 4 // At start of rule. Its phoneme string is used by subsequent rules #define RULE_CONDITION 5 // followed by condition number (byte) #define RULE_GROUP_START 6 #define RULE_GROUP_END 7 #define RULE_PRE_ATSTART 8 // as RULE_PRE but also match with 'start of word' #define RULE_LINENUM 9 // next 2 bytes give a line number, for debugging purposes #define RULE_SPACE 32 // ascii space #define RULE_SYLLABLE 21 // @ #define RULE_STRESSED 10 // & #define RULE_DOUBLE 11 // % #define RULE_INC_SCORE 12 // + #define RULE_DEL_FWD 13 // # #define RULE_ENDING 14 // S #define RULE_DIGIT 15 // D digit #define RULE_NONALPHA 16 // Z non-alpha #define RULE_LETTERGP 17 // A B C H F G Y letter group number #define RULE_LETTERGP2 18 // L + letter group number #define RULE_CAPITAL 19 // ! word starts with a capital letter #define RULE_REPLACEMENTS 20 // section for character replacements #define RULE_SKIPCHARS 23 // J #define RULE_NO_SUFFIX 24 // N #define RULE_NOTVOWEL 25 // K #define RULE_IFVERB 26 // V #define RULE_DOLLAR 28 // $ commands #define RULE_NOVOWELS 29 // X no vowels up to word boundary #define RULE_SPELLING 31 // W while spelling letter-by-letter #define RULE_LAST_RULE 31 #define LETTERGP_A 0 #define LETTERGP_B 1 #define LETTERGP_C 2 #define LETTERGP_H 3 #define LETTERGP_F 4 #define LETTERGP_G 5 #define LETTERGP_Y 6 #define LETTERGP_VOWEL2 7 #define N_LOPTS 21 #define LOPT_DIERESES 1 #define LOPT_IT_LENGTHEN 2 #define LOPT_PREFIXES 3 #define LOPT_REGRESSIVE_VOICING 4 #define LOPT_UNPRONOUNCABLE 5 #define LOPT_LENGTH_MODS 6 #define LOPT_SONORANT_MIN 7 #define LOPT_WORD_MERGE 8 #define LOPT_MAXAMP_EOC 9 #define LOPT_REDUCE 10 #define LOPT_COMBINE_WORDS 11 #define LOPT_REDUCE_T 12 #define LOPT_CAPS_IN_WORD 13 #define LOPT_IT_DOUBLING 14 #define LOPT_ALT 15 #define LOPT_BRACKET_PAUSE 16 #define LOPT_ANNOUNCE_PUNCT 17 #define LOPT_LONG_VOWEL_THRESHOLD 18 #define LOPT_SUFFIX 19 #define LOPT_APOSTROPHE 20 // stress_rule #define STRESSPOSN_1L 0 // 1st syllable #define STRESSPOSN_2L 1 // 2nd syllable #define STRESSPOSN_2R 2 // penultimate #define STRESSPOSN_1R 3 // final syllable #define STRESSPOSN_3R 4 // antipenultimate #define BREAK_THOUSANDS 0x49249248 #define NUM_THOUS_SPACE 0x4 #define NUM_DECIMAL_COMMA 0x8 #define NUM_SWAP_TENS 0x10 #define NUM_AND_UNITS 0x20 #define NUM_HUNDRED_AND 0x40 #define NUM_SINGLE_AND 0x80 #define NUM_SINGLE_STRESS 0x100 #define NUM_SINGLE_VOWEL 0x200 #define NUM_OMIT_1_HUNDRED 0x400 #define NUM_1900 0x800 #define NUM_ALLOW_SPACE 0x1000 #define NUM_DFRACTION_1 0x2000 #define NUM_DFRACTION_2 0x4000 #define NUM_DFRACTION_3 0x6000 #define NUM_DFRACTION_4 0x8000 #define NUM_DFRACTION_5 0xa000 #define NUM_DFRACTION_6 0xc000 #define NUM_DFRACTION_7 0xe000 // lang=si, alternative form of number for decimal fraction digits (except the last) #define NUM_ORDINAL_DOT 0x10000 #define NUM_NOPAUSE 0x20000 #define NUM_AND_HUNDRED 0x40000 #define NUM_THOUSAND_AND 0x80000 #define NUM_VIGESIMAL 0x100000 #define NUM_OMIT_1_THOUSAND 0x200000 #define NUM_ZERO_HUNDRED 0x400000 #define NUM_HUNDRED_AND_DIGIT 0x800000 #define NUM_ROMAN 0x1000000 #define NUM_ROMAN_CAPITALS 0x2000000 #define NUM_ROMAN_AFTER 0x4000000 #define NUM_ROMAN_ORDINAL 0x8000000 #define NUM_SINGLE_STRESS_L 0x10000000 #define NUM2_THOUSANDS_VAR1 0x40 #define NUM2_THOUSANDS_VAR2 0x80 #define NUM2_THOUSANDS_VAR3 0xc0 #define NUM2_THOUSANDS_VAR4 0x100 #define NUM2_THOUSANDS_VAR5 0x140 #define NUM2_ORDINAL_NO_AND 0x800 #define NUM2_MULTIPLE_ORDINAL 0x1000 #define NUM2_NO_TEEN_ORDINALS 0x2000 #define NUM2_MYRIADS 0x4000 #define NUM2_ENGLISH_NUMERALS 0x8000 #define NUM2_PERCENT_BEFORE 0x10000 #define PITCHfall 0 #define PITCHrise 2 #define PITCHfrise 4 // and 3 must be for the variant preceded by 'r' #define PITCHfrise2 6 // and 5 must be the 'r' variant #define PITCHrisefall 8 #define SYL_RISE 1 #define SYL_EMPHASIS 2 #define SYL_END_CLAUSE 4 // start of unicode pages for character sets #define OFFSET_GREEK 0x0380 #define OFFSET_CYRILLIC 0x0420 #define OFFSET_ARMENIAN 0x0530 #define OFFSET_HEBREW 0x0590 #define OFFSET_ARABIC 0x0600 #define OFFSET_THAANA 0x0780 // Divehi/Maldives #define OFFSET_DEVANAGARI 0x0900 #define OFFSET_BENGALI 0x0980 #define OFFSET_GURMUKHI 0x0a00 #define OFFSET_GUJARATI 0x0a80 #define OFFSET_ORIYA 0x0b00 #define OFFSET_TAMIL 0x0b80 #define OFFSET_TELUGU 0x0c00 #define OFFSET_KANNADA 0x0c80 #define OFFSET_MALAYALAM 0x0d00 #define OFFSET_SINHALA 0x0d80 #define OFFSET_THAI 0x0e00 #define OFFSET_LAO 0x0e80 #define OFFSET_TIBET 0x0f00 #define OFFSET_MYANMAR 0x1000 #define OFFSET_GEORGIAN 0x10a0 #define OFFSET_KOREAN 0x1100 #define OFFSET_ETHIOPIC 0x1200 #define OFFSET_BRAILLE 0x2800 #define OFFSET_JAPANESE 0x3040 #define OFFSET_CHINESE 0x3100 #define S_NO_DIM 0x02 #define S_FINAL_DIM 0x04 #define S_FINAL_DIM_ONLY 0x06 #define S_FINAL_NO_2 0x10 #define S_NO_AUTO_2 0x20 #define S_2_TO_HEAVY 0x40 #define S_FIRST_PRIMARY 0x80 #define S_FINAL_STRESS_C 0x100 #define S_FINAL_SPANISH 0x200 #define S_2_SYL_2 0x1000 #define S_INITIAL_2 0x2000 #define S_MID_DIM 0x10000 #define S_PRIORITY_STRESS 0x20000 #define S_EO_CLAUSE1 0x40000 #define S_FINAL_LONG 0x80000 #define S_HYPEN_UNSTRESS 0x100000 #define S_NO_EOC_LENGTHEN 0x200000 #define SFLAG_SEQCONTINUE 0x01 // a liquid or nasal after a vowel, but not followed by a vowel #define SFLAG_EMBEDDED 0x02 // there are embedded commands before this phoneme #define SFLAG_SYLLABLE 0x04 // vowel or syllabic consonant #define SFLAG_LENGTHEN 0x08 // lengthen symbol : included after this phoneme #define SFLAG_DICTIONARY 0x10 // the pronunciation of this word was listed in the xx_list dictionary #define SFLAG_SWITCHED_LANG 0x20 // this word uses phonemes from a different language #define SFLAG_PROMOTE_STRESS 0x40 // this unstressed word can be promoted to stressed #define SFLAG_PREV_PAUSE 0x1000 // consider previous phoneme as pause #define SFLAG_NEXT_PAUSE 0x2000 // consider next phoneme as pause #define CLAUSE_BIT_SENTENCE 0x80000 #define CLAUSE_BIT_CLAUSE 0x40000 #define CLAUSE_BIT_VOICE 0x20000 #define CLAUSE_BITS_INTONATION 0x7000 // embedded command numbers #define EMBED_P 1 // pitch #define EMBED_S 2 // speed (used in setlengths) #define EMBED_A 3 // amplitude/volume #define EMBED_R 4 // pitch range/expression #define EMBED_H 5 // echo/reverberation #define EMBED_T 6 // different tone for announcing punctuation (not used) #define EMBED_I 7 // sound icon #define EMBED_S2 8 // speed (used in synthesize) #define EMBED_Y 9 // say-as commands #define EMBED_M 10 // mark name #define EMBED_U 11 // audio uri #define EMBED_B 12 // break #define EMBED_F 13 // emphasis #define EMBED_C 14 // capital letter indication #define N_EMBEDDED_VALUES 15 #define N_REMOVE_ACCENT 0x25e // additional Latin characters beyond the ascii character set #define MAX_WALPHA 0x24f // indexed by character - 0x80 // 0=not alphabetic, 0xff=lower case, 0xfe=no case, 0xfd=use wchar_tolower // other=value to add to upper case to convert to lower case static unsigned char walpha_tab[MAX_WALPHA-0x7f] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 080 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 090 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xfe, 0, 0, 0, 0, 0, // 0a0 0, 0, 0, 0, 0, 0xff, 0, 0, 0, 0, 0xfe, 0, 0, 0, 0, 0, // 0b0 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, // 0c0 32, 32, 32, 32, 32, 32, 32, 0, 32, 32, 32, 32, 32, 32, 32, 0xff, // 0d0 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // 0e0 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // 0f0 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 100 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 110 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 120 0xfd, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 0xfe, 1, 0xff, 1, 0xff, 1, 0xff, 1, // 130 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 0xfe, 1, 0xff, 1, 0xff, 1, 0xff, // 140 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 150 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 160 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 0xfd, 1, 0xff, 1, 0xff, 1, 0xff, 0xff, // 170 0xff, 210, 1, 0xff, 1, 0xff, 206, 1, 0xff, 205, 205, 1, 0xff, 0xfe, 79, 202, // 180 203, 1, 0xff, 205, 207, 0xff, 211, 209, 1, 0xff, 0xff, 0xfe, 211, 213, 0xff, 214, // 190 1, 0xff, 1, 0xff, 1, 0xff, 218, 1, 0xff, 218, 0xfe, 0xfe, 1, 0xff, 218, 1, // 1a0 0xff, 217, 217, 1, 0xff, 1, 0xff, 219, 1, 0xff, 0xfe, 0xfe, 1, 0xff, 0xfe, 0xff, // 1b0 0xfe, 0xfe, 0xfe, 0xfe, 2, 0xff, 0xff, 2, 0xff, 0xff, 2, 0xff, 0xff, 1, 0xff, 1, // 1c0 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 0xff, 1, 0xff, // 1d0 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 1e0 0xfe, 2, 0xff, 0xff, 1, 0xff, 0xfd, 0xfd, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 1f0 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 200 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 210 0xfd, 0xfe, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, // 220 1, 0xff, 1, 0xff, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 1, 0xff, 0xfd, 0xfd, 0xfe, // 230 0xfe, 1, 0xff, 0xfd, 69, 71, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff, 1, 0xff}; // 240 static const short wchar_tolower[] = { 0x130, 0x069, 0x178, 0x0ff, 0x1f6, 0x195, 0x1f7, 0x1bf, 0x220, 0x19e, 0x23a, 0x2c65, 0x23d, 0x19a, 0x23e, 0x2c66, 0x243, 0x180, 0 ,0 }; static const short wchar_toupper[] = { 0x0b5, 0x39c, 0x0df, 0x0df, 0x0ff, 0x178, 0x131, 0x049, 0x17f, 0x053, 0x180, 0x243, 0x195, 0x1f6, 0x19a, 0x23d, 0x19e, 0x220, 0x1bf, 0x1f7, 0x1c6, 0x1c4, 0x1c9, 0x1c7, 0x1cc, 0x1ca, 0x1dd, 0x18e, 0x1f3, 0x1f1, 0 , 0 }; // brackets, also 0x2014 to 0x021f which don't need to be in this list static const unsigned short brackets[] = { '(',')','[',']','{','}','<','>','"','\'','`', 0xab,0xbb, // double angle brackets 0x300a,0x300b, // double angle brackets (ideograph) 0xe000+'<', // private usage area 0 }; // unicode ranges for non-ascii digits 0-9 static const int number_ranges[] = { 0x660, 0x6f0, // arabic 0x966, 0x9e6, 0xa66, 0xae6, 0xb66, 0xbe6, 0xc66, 0xce6, 0xd66, // indic 0xe50, 0xed0, 0xf20, 0x1040, 0x1090, 0 }; // these must be in ascending order static const char * UCase_ga[] = {"bp","bhf","dt","gc","hA","mb","nd","ng","ts","tA","nA",NULL}; static char stress_phonemes[] = { N::Speak::PcStressD , N::Speak::PcStressU , N::Speak::PcStress2 , N::Speak::PcStress3 , N::Speak::PcStressP , N::Speak::PcStressP2 , N::Speak::PcStressTonic } ; static char consonant_types [16] = {0,0,0,1,1,1,1,1,1,1,0,0,0,0, 0, 0} ; static char guess_ru [16] = {0,0,1,1,2,3,3,4,5,6,7,7,8,9,10,11} ; static char guess_ru_v [16] = {0,0,1,1,2,2,3,3,4,5,6,7,7,8, 9,10} ; // for final phoneme is a vowel static char guess_ru_t [16] = {0,0,1,2,3,3,3,4,5,6,7,7,7,8, 9,10} ; // for final phoneme is an unvoiced stop static unsigned char remove_accent[N_REMOVE_ACCENT] = { 'a','a','a','a','a','a','a','c','e','e','e','e','i','i','i','i', // 0c0 'd','n','o','o','o','o','o', 0, 'o','u','u','u','u','y','t','s', // 0d0 'a','a','a','a','a','a','a','c','e','e','e','e','i','i','i','i', // 0e0 'd','n','o','o','o','o','o', 0 ,'o','u','u','u','u','y','t','y', // 0f0 'a','a','a','a','a','a','c','c','c','c','c','c','c','c','d','d', // 100 'd','d','e','e','e','e','e','e','e','e','e','e','g','g','g','g', // 110 'g','g','g','g','h','h','h','h','i','i','i','i','i','i','i','i', // 120 'i','i','i','i','j','j','k','k','k','l','l','l','l','l','l','l', // 130 'l','l','l','n','n','n','n','n','n','n','n','n','o','o','o','o', // 140 'o','o','o','o','r','r','r','r','r','r','s','s','s','s','s','s', // 150 's','s','t','t','t','t','t','t','u','u','u','u','u','u','u','u', // 160 'u','u','u','u','w','w','y','y','y','z','z','z','z','z','z','s', // 170 'b','b','b','b', 0, 0, 'o','c','c','d','d','d','d','d','e','e', // 180 'e','f','f','g','g','h','i','i','k','k','l','l','m','n','n','o', // 190 'o','o','o','o','p','p','y', 0, 0, 's','s','t','t','t','t','u', // 1a0 'u','u','v','y','y','z','z','z','z','z','z','z', 0, 0, 0, 'w', // 1b0 't','t','t','k','d','d','d','l','l','l','n','n','n','a','a','i', // 1c0 'i','o','o','u','u','u','u','u','u','u','u','u','u','e','a','a', // 1d0 'a','a','a','a','g','g','g','g','k','k','o','o','o','o','z','z', // 1e0 'j','d','d','d','g','g','w','w','n','n','a','a','a','a','o','o', // 1f0 'a','a','a','a','e','e','e','e','i','i','i','i','o','o','o','o', // 200 'r','r','r','r','u','u','u','u','s','s','t','t','y','y','h','h', // 210 'n','d','o','o','z','z','a','a','e','e','o','o','o','o','o','o', // 220 'o','o','y','y','l','n','t','j','d','q','a','c','c','l','t','s', // 230 'z', 0, 0, 'b','u','v','e','e','j','j','q','q','r','r','y','y', // 240 'a','a','a','b','o','c','d','d','e','e','e','e','e','e' } ; // Translate character codes 0xA0 to 0xFF into their unicode values // ISO_8859_1 is set as default static const unsigned short ISO_8859_1[0x60] = { 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, // a0 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, // a8 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, // b0 0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, // b8 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, // c0 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, // c8 0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, // d0 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df, // d8 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, // e0 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, // e8 0x00f0, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, // f0 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x00fe, 0x00ff, // f8 }; static const unsigned short ISO_8859_2[0x60] = { 0x00a0, 0x0104, 0x02d8, 0x0141, 0x00a4, 0x013d, 0x015a, 0x00a7, // a0 0x00a8, 0x0160, 0x015e, 0x0164, 0x0179, 0x00ad, 0x017d, 0x017b, // a8 0x00b0, 0x0105, 0x02db, 0x0142, 0x00b4, 0x013e, 0x015b, 0x02c7, // b0 0x00b8, 0x0161, 0x015f, 0x0165, 0x017a, 0x02dd, 0x017e, 0x017c, // b8 0x0154, 0x00c1, 0x00c2, 0x0102, 0x00c4, 0x0139, 0x0106, 0x00c7, // c0 0x010c, 0x00c9, 0x0118, 0x00cb, 0x011a, 0x00cd, 0x00ce, 0x010e, // c8 0x0110, 0x0143, 0x0147, 0x00d3, 0x00d4, 0x0150, 0x00d6, 0x00d7, // d0 0x0158, 0x016e, 0x00da, 0x0170, 0x00dc, 0x00dd, 0x0162, 0x00df, // d8 0x0155, 0x00e1, 0x00e2, 0x0103, 0x00e4, 0x013a, 0x0107, 0x00e7, // e0 0x010d, 0x00e9, 0x0119, 0x00eb, 0x011b, 0x00ed, 0x00ee, 0x010f, // e8 0x0111, 0x0144, 0x0148, 0x00f3, 0x00f4, 0x0151, 0x00f6, 0x00f7, // f0 0x0159, 0x016f, 0x00fa, 0x0171, 0x00fc, 0x00fd, 0x0163, 0x02d9, // f8 }; static const unsigned short ISO_8859_3[0x60] = { 0x00a0, 0x0126, 0x02d8, 0x00a3, 0x00a4, 0x0000, 0x0124, 0x00a7, // a0 0x00a8, 0x0130, 0x015e, 0x011e, 0x0134, 0x00ad, 0x0000, 0x017b, // a8 0x00b0, 0x0127, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x0125, 0x00b7, // b0 0x00b8, 0x0131, 0x015f, 0x011f, 0x0135, 0x00bd, 0x0000, 0x017c, // b8 0x00c0, 0x00c1, 0x00c2, 0x0000, 0x00c4, 0x010a, 0x0108, 0x00c7, // c0 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, // c8 0x0000, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x0120, 0x00d6, 0x00d7, // d0 0x011c, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x016c, 0x015c, 0x00df, // d8 0x00e0, 0x00e1, 0x00e2, 0x0000, 0x00e4, 0x010b, 0x0109, 0x00e7, // e0 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, // e8 0x0000, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x0121, 0x00f6, 0x00f7, // f0 0x011d, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x016d, 0x015d, 0x02d9, // f8 }; static const unsigned short ISO_8859_4[0x60] = { 0x00a0, 0x0104, 0x0138, 0x0156, 0x00a4, 0x0128, 0x013b, 0x00a7, // a0 0x00a8, 0x0160, 0x0112, 0x0122, 0x0166, 0x00ad, 0x017d, 0x00af, // a8 0x00b0, 0x0105, 0x02db, 0x0157, 0x00b4, 0x0129, 0x013c, 0x02c7, // b0 0x00b8, 0x0161, 0x0113, 0x0123, 0x0167, 0x014a, 0x017e, 0x014b, // b8 0x0100, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x012e, // c0 0x010c, 0x00c9, 0x0118, 0x00cb, 0x0116, 0x00cd, 0x00ce, 0x012a, // c8 0x0110, 0x0145, 0x014c, 0x0136, 0x00d4, 0x00d5, 0x00d6, 0x00d7, // d0 0x00d8, 0x0172, 0x00da, 0x00db, 0x00dc, 0x0168, 0x016a, 0x00df, // d8 0x0101, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x012f, // e0 0x010d, 0x00e9, 0x0119, 0x00eb, 0x0117, 0x00ed, 0x00ee, 0x012b, // e8 0x0111, 0x0146, 0x014d, 0x0137, 0x00f4, 0x00f5, 0x00f6, 0x00f7, // f0 0x00f8, 0x0173, 0x00fa, 0x00fb, 0x00fc, 0x0169, 0x016b, 0x02d9, // f8 }; static const unsigned short ISO_8859_5[0x60] = { 0x00a0, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, // a0 Cyrillic 0x0408, 0x0409, 0x040a, 0x040b, 0x040c, 0x00ad, 0x040e, 0x040f, // a8 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, // b0 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f, // b8 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, // c0 0x0428, 0x0429, 0x042a, 0x042b, 0x042c, 0x042d, 0x042e, 0x042f, // c8 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, // d0 0x0438, 0x0439, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, 0x043f, // d8 0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, // e0 0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f, // e8 0x2116, 0x0451, 0x0452, 0x0453, 0x0454, 0x0455, 0x0456, 0x0457, // f0 0x0458, 0x0459, 0x045a, 0x045b, 0x045c, 0x00a7, 0x045e, 0x045f, // f8 }; static const unsigned short ISO_8859_7[0x60] = { 0x00a0, 0x2018, 0x2019, 0x00a3, 0x20ac, 0x20af, 0x00a6, 0x00a7, // a0 Greek 0x00a8, 0x00a9, 0x037a, 0x00ab, 0x00ac, 0x00ad, 0x0000, 0x2015, // a8 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x0384, 0x0385, 0x0386, 0x00b7, // b0 0x0388, 0x0389, 0x038a, 0x00bb, 0x038c, 0x00bd, 0x038e, 0x038f, // b8 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, // c0 0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e, 0x039f, // c8 0x03a0, 0x03a1, 0x0000, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7, // d0 0x03a8, 0x03a9, 0x03aa, 0x03ab, 0x03ac, 0x03ad, 0x03ae, 0x03af, // d8 0x03b0, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7, // e0 0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf, // e8 0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6, 0x03c7, // f0 0x03c8, 0x03c9, 0x03ca, 0x03cb, 0x03cc, 0x03cd, 0x03ce, 0x0000, // f8 }; static const unsigned short ISO_8859_9[0x60] = { 0x00a0, 0x00a1, 0x00a2, 0x00a3, 0x00a4, 0x00a5, 0x00a6, 0x00a7, // a0 0x00a8, 0x00a9, 0x00aa, 0x00ab, 0x00ac, 0x00ad, 0x00ae, 0x00af, // a8 0x00b0, 0x00b1, 0x00b2, 0x00b3, 0x00b4, 0x00b5, 0x00b6, 0x00b7, // b0 0x00b8, 0x00b9, 0x00ba, 0x00bb, 0x00bc, 0x00bd, 0x00be, 0x00bf, // b8 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, // c0 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, // c8 0x011e, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7, // d0 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x0130, 0x015e, 0x00df, // d8 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, // e0 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, // e8 0x011f, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x00f7, // f0 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x0131, 0x015f, 0x00ff, // f8 }; static const unsigned short ISO_8859_14[0x60] = { 0x00a0, 0x1e02, 0x1e03, 0x00a3, 0x010a, 0x010b, 0x1e0a, 0x00a7, // a0 Welsh 0x1e80, 0x00a9, 0x1e82, 0x1e0b, 0x1ef2, 0x00ad, 0x00ae, 0x0178, // a8 0x1e1e, 0x1e1f, 0x0120, 0x0121, 0x1e40, 0x1e41, 0x00b6, 0x1e56, // b0 0x1e81, 0x1e57, 0x1e83, 0x1e60, 0x1ef3, 0x1e84, 0x1e85, 0x1e61, // b8 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6, 0x00c7, // c0 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce, 0x00cf, // c8 0x0174, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x1e6a, // d0 0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x0176, 0x00df, // d8 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6, 0x00e7, // e0 0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef, // e8 0x0175, 0x00f1, 0x00f2, 0x00f3, 0x00f4, 0x00f5, 0x00f6, 0x1e6b, // f0 0x00f8, 0x00f9, 0x00fa, 0x00fb, 0x00fc, 0x00fd, 0x0177, 0x00ff, // f8 }; static const unsigned short KOI8_R[0x60] = { 0x2550, 0x2551, 0x2552, 0x0451, 0x2553, 0x2554, 0x2555, 0x2556, // a0 Russian 0x2557, 0x2558, 0x2559, 0x255a, 0x255b, 0x255c, 0x255d, 0x255e, // a8 0x255f, 0x2560, 0x2561, 0x0401, 0x2562, 0x2563, 0x2564, 0x2565, // b0 0x2566, 0x2567, 0x2568, 0x2569, 0x256a, 0x256b, 0x256c, 0x00a9, // b8 0x044e, 0x0430, 0x0431, 0x0446, 0x0434, 0x0435, 0x0444, 0x0433, // c0 0x0445, 0x0438, 0x0439, 0x043a, 0x043b, 0x043c, 0x043d, 0x043e, // c8 0x043f, 0x044f, 0x0440, 0x0441, 0x0442, 0x0443, 0x0436, 0x0432, // d0 0x044c, 0x044b, 0x0437, 0x0448, 0x044d, 0x0449, 0x0447, 0x044a, // d8 0x042e, 0x0410, 0x0411, 0x0426, 0x0414, 0x0415, 0x0424, 0x0413, // e0 0x0425, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, // e8 0x041f, 0x042f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0416, 0x0412, // f0 0x042c, 0x042b, 0x0417, 0x0428, 0x042d, 0x0429, 0x0427, 0x042a, // f8 }; static const unsigned short ISCII[0x60] = { 0x0020, 0x0901, 0x0902, 0x0903, 0x0905, 0x0906, 0x0907, 0x0908, // a0 0x0909, 0x090a, 0x090b, 0x090e, 0x090f, 0x0910, 0x090d, 0x0912, // a8 0x0913, 0x0914, 0x0911, 0x0915, 0x0916, 0x0917, 0x0918, 0x0919, // b0 0x091a, 0x091b, 0x091c, 0x091d, 0x091e, 0x091f, 0x0920, 0x0921, // b8 0x0922, 0x0923, 0x0924, 0x0925, 0x0926, 0x0927, 0x0928, 0x0929, // c0 0x092a, 0x092b, 0x092c, 0x092d, 0x092e, 0x092f, 0x095f, 0x0930, // c8 0x0931, 0x0932, 0x0933, 0x0934, 0x0935, 0x0936, 0x0937, 0x0938, // d0 0x0939, 0x0020, 0x093e, 0x093f, 0x0940, 0x0941, 0x0942, 0x0943, // d8 0x0946, 0x0947, 0x0948, 0x0945, 0x094a, 0x094b, 0x094c, 0x0949, // e0 0x094d, 0x093c, 0x0964, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, // e8 0x0020, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, // f0 0x0037, 0x0038, 0x0039, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020, // f8 } ; static const unsigned short * charsets [ N_CHARSETS ] = { ISO_8859_1 , ISO_8859_1 , ISO_8859_2 , ISO_8859_3 , ISO_8859_4 , ISO_8859_5 , ISO_8859_1 , ISO_8859_7 , ISO_8859_1 , ISO_8859_9 , ISO_8859_1 , ISO_8859_1 , ISO_8859_1 , ISO_8859_1 , ISO_8859_14 , ISO_8859_1 , ISO_8859_1 , ISO_8859_1 , KOI8_R , ISCII } ; // Tables of the relative lengths of vowels, depending on the // type of the two phonemes that follow // indexes are the "length_mod" value for the following phonemes // use this table if vowel is not the last in the word static unsigned char length_mods_en[100] = { /* a , t s n d z r N <- next */ 100,120,100,105,100,110,110,100, 95, 100, /* a <- next2 */ 105,120,105,110,125,130,135,115,125, 100, /* , */ 105,120, 75,100, 75,105,120, 85, 75, 100, /* t */ 105,120, 85,105, 95,115,120,100, 95, 100, /* s */ 110,120, 95,105,100,115,120,100,100, 100, /* n */ 105,120,100,105, 95,115,120,110, 95, 100, /* d */ 105,120,100,105,105,122,125,110,105, 100, /* z */ 105,120,100,105,105,122,125,110,105, 100, /* r */ 105,120, 95,105,100,115,120,110,100, 100, /* N */ 100,120,100,100,100,100,100,100,100, 100 }; // SPARE // as above, but for the last syllable in a word static unsigned char length_mods_en0[100] = { /* a , t s n d z r N <- next */ 100,150,100,105,110,115,110,110,110, 100, /* a <- next2 */ 105,150,105,110,125,135,140,115,135, 100, /* , */ 105,150, 90,105, 90,122,135,100, 90, 100, /* t */ 105,150,100,105,100,122,135,100,100, 100, /* s */ 105,150,100,105,105,115,135,110,105, 100, /* n */ 105,150,100,105,105,122,130,120,125, 100, /* d */ 105,150,100,105,110,122,125,115,110, 100, /* z */ 105,150,100,105,105,122,135,120,105, 100, /* r */ 105,150,100,105,105,115,135,110,105, 100, /* N */ 100,100,100,100,100,100,100,100,100, 100 }; // SPARE static unsigned char length_mods_equal[100] = { /* a , t s n d z r N <- next */ 110,120,100,110,110,110,110,110,110, 110, /* a <- next2 */ 110,120,100,110,110,110,110,110,110, 110, /* , */ 110,120,100,110,100,110,110,110,100, 110, /* t */ 110,120,100,110,110,110,110,110,110, 110, /* s */ 110,120,100,110,110,110,110,110,110, 110, /* n */ 110,120,100,110,110,110,110,110,110, 110, /* d */ 110,120,100,110,110,110,110,110,110, 110, /* z */ 110,120,100,110,110,110,110,110,110, 110, /* r */ 110,120,100,110,110,110,110,110,110, 110, /* N */ 110,120,100,110,110,110,110,110,110, 110 }; // SPARE static unsigned char * length_mod_tabs[6] = { length_mods_en , length_mods_en , // 1 length_mods_en0 , // 2 length_mods_equal , // 3 length_mods_equal , // 4 length_mods_equal // 5 } ; static const char transpose_map_latin [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27, 28, 29, 0, 0, 30, 31, 32, 33, 34, 35, 36, 0, 37, 38, 0, 0, 0, 0, 39, 0, 0, 40, 0, 41, 0, 42, 0, 43, 0, 0, 0, 0, 0, 0, 44, 0, 45, 0, 46, 0, 0, 0, 0, 0, 47, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 0, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 53, 0, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 55, 0, 56, 0, 57, 0 } ; static const unsigned char stress_amps2 [ ] = { 18, 18, 20, 20, 20, 22, 22, 20} ; static const short stress_lengths2 [8] = {182,140,220,220,220,240,260,280} ; static const wchar_t empty_wstring [1] = {0}; static const wchar_t punct_in_word [2] = {'\'', 0}; // allow hyphen within words static const unsigned char default_tunes [6] = { 0, 1, 2, 3, 0, 0}; static const short stress_lengths_equal[8] = {230,230,230,230, 0, 0,230,230} ; static const unsigned char stress_amps_equal [8] = { 18, 18, 18, 18, 18, 18, 18, 18} ; static const short stress_lengths_fr [8] = {190,170,190,200, 0, 0,190,240} ; static const unsigned char stress_amps_fr [8] = { 18, 16, 18, 18, 18, 18, 18, 18} ; static const unsigned char stress_amps_sk [8] = { 17, 16, 20, 20, 20, 22, 22, 21} ; static const short stress_lengths_sk [8] = {190,190,210,210, 0, 0,210,210} ; static const short stress_lengths_ta [8] = {200,200,210,210, 0, 0,230,230} ; static const short stress_lengths_ta2 [8] = {230,230,240,240, 0, 0,260,260} ; static const unsigned char stress_amps_ta [8] = { 18, 18, 18, 18, 20, 20, 22, 22} ; /* index by 0=. 1=, 2=?, 3=! 4=none, 5=emphasized */ static unsigned char punctuation_to_tone[8][6] = { { 0, 1, 2, 3, 0, 4} , { 0, 1, 2, 3, 0, 4} , { 5, 6, 2, 3, 0, 4} , { 5, 7, 1, 3, 0, 4} , { 8, 9,10, 3, 0, 0} , { 8, 8,10, 3, 0, 0} , {11,11,11,11, 0, 0} , {12,12,12,12, 0, 0} } ; // ignore these characters static const unsigned short chars_ignore_default[] = { 0x00ad , 1 , // soft hyphen 0x200c , 1 , // zero width non-joiner 0x200d , 1 , // zero width joiner 0 , 0 } ; // alternatively, ignore characters but allow zero-width-non-joiner (lang-fa) static const unsigned short chars_ignore_zwnj_hyphen[] = { 0x00ad , 1 , // soft hyphen 0x200c , '-' , // zero width non-joiner, replace with hyphen 0x200d , 1 , // zero width joiner 0 , 0 } ; // common letter pairs, encode these as a single byte // 2 bytes, using the transposed character codes static const short pairs_ru[] = { 0x010c, // ла 21052 0x23 0x010e, // на 18400 0x0113, // та 14254 0x0301, // ав 31083 0x030f, // ов 13420 0x060e, // не 21798 0x0611, // ре 19458 0x0903, // ви 16226 0x0b01, // ак 14456 0x0b0f, // ок 17836 0x0c01, // ал 13324 0x0c09, // ил 16877 0x0e01, // ан 15359 0x0e06, // ен 13543 0x30 0x0e09, // ин 17168 0x0e0e, // нн 15973 0x0e0f, // он 22373 0x0e1c, // ын 15052 0x0f03, // во 24947 0x0f11, // ро 13552 0x0f12, // со 16368 0x100f, // оп 19054 0x1011, // рп 17067 0x1101, // ар 23967 0x1106, // ер 18795 0x1109, // ир 13797 0x110f, // ор 21737 0x1213, // тс 25076 0x1220, // яс 14310 0x7fff}; //0x040f ог 12976 //0x1306 ет 12826 //0x0f0d мо 12688 static const unsigned int replace_cyrillic_latin[] = { 0x430 , 'a', 0x431 , 'b', 0x446 , 'c', 0x45b , 0x107, 0x447 , 0x10d, 0x45f , 'd'+(0x17e<<16), 0x455 , 'd'+('z'<<16), 0x434 , 'd', 0x452 , 0x111, 0x435 , 'e', 0x444 , 'f', 0x433 , 'g', 0x445 , 'h', 0x438 , 'i', 0x458 , 'j', 0x43a , 'k', 0x459 , 'l'+('j'<<16), 0x43b , 'l', 0x43c , 'm', 0x45a , 'n'+('j'<<16), 0x43d , 'n', 0x43e , 'o', 0x43f , 'p', 0x440 , 'r', 0x441 , 's', 0x448 , 0x161, 0x442 , 't', 0x443 , 'u', 0x432 , 'v', 0x437 , 'z', 0x436 , 0x17e, 0x453 , 0x111, 0x45c , 0x107, 0}; // ѓ ѕ ќ static const unsigned char ru_vowels [] = { 0x10,0x15,0x31,0x18,0x1e,0x23,0x2b,0x2d,0x2e,0x2f, 0xb9,0xc9,0x91,0x8f,0x36,0}; //also kazakh static const unsigned char ru_consonants [] = { 0x11,0x12,0x13,0x14,0x16,0x17,0x19,0x1a,0x1b,0x1c, 0x1d,0x1f,0x20,0x21,0x22,0x24,0x25,0x26,0x27,0x28, 0x29,0x2a,0x2c,0x73,0x7b,0x83,0x9b,0}; static const char ru_soft [] = {0x2c,0x19,0x27,0x29,0} ; // letter group B [k ts; s;] static const char ru_hard [] = {0x2a,0x16,0x26,0x28,0} ; // letter group H [S Z ts] static const char ru_nothard [] = { 0x11,0x12,0x13,0x14,0x17,0x19,0x1a,0x1b,0x1c,0x1d, 0x1f,0x20,0x21,0x22,0x24,0x25,0x27,0x29,0x2c,0}; static const char ru_voiced [] = {0x11,0x12,0x13,0x14,0x16,0x17,0} ; // letter group G (voiced obstruents) static const char ru_ivowels [] = {0x2c,0x2e,0x2f,0x31,0} ; // letter group Y (iotated vowels & soft-sign) static const short stress_lengths_zh[8] = {230,150,230,230,230, 0,240,250} ; // 1=tone5. end-of-sentence, 6=tone 1&4, 7=tone 2&3 static const unsigned char stress_amps_zh [ ] = { 22, 16, 22, 22, 22, 22, 22, 22} ; static const short stress_lengths_vi[8] = {150, 150, 180, 180, 210, 230, 230, 240}; static const unsigned char stress_amps_vi[] = {16,16, 16,16, 22,22, 22,22 }; static wchar_t vowels_vi[] = { 0x61, 0xe0, 0xe1, 0x1ea3, 0xe3, 0x1ea1, // a 0x103, 0x1eb1, 0x1eaf, 0x1eb3, 0x1eb5, 0x1eb7, // ă 0xe2, 0x1ea7, 0x1ea5, 0x1ea9, 0x1eab, 0x1ead, // â 0x65, 0xe8, 0xe9, 0x1ebb, 0x1ebd, 0x1eb9, // e 0xea, 0x1ec1, 0x1ebf, 0x1ec3, 0x1ec5, 0x1ec7, // i 0x69, 0xec, 0xed, 0x1ec9, 0x129, 0x1ecb, // i 0x6f, 0xf2, 0xf3, 0x1ecf, 0xf5, 0x1ecd, // o 0xf4, 0x1ed3, 0x1ed1, 0x1ed5, 0x1ed7, 0x1ed9, // ô 0x1a1, 0x1edd, 0x1edb, 0x1edf, 0x1ee1, 0x1ee3, // ơ 0x75, 0xf9, 0xfa, 0x1ee7, 0x169, 0x1ee5, // u 0x1b0, 0x1eeb, 0x1ee9, 0x1eed, 0x1eef, 0x1ef1, // ư 0x79, 0x1ef3, 0xfd, 0x1ef7, 0x1ef9, 0x1ef5, 0 }; // y static const unsigned char stress_amps_tr[8] = {18,16, 20,21, 20,21, 21,20 }; static const short stress_lengths_tr[8] = {190,180, 200,230, 0,0, 240,250}; static const short stress_lengths_th[8] = {230,150, 230,230, 230,0, 230,250}; static const unsigned char stress_amps_th[] = {22,16, 22,22, 22,22, 22,22 }; static const short stress_lengths_bn[8] = {180, 180, 210, 210, 0, 0, 230, 240}; static const unsigned char stress_amps_bn[8] = {18,18, 18,18, 20,20, 22,22 }; // Set letter types for Indic scripts, Devanagari, Tamill, etc static const char dev_consonants2[] = {0x02,0x03,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,0x7b,0x7c,0x7e,0x7f,0}; static const char dev_vowels2[] = {0x60,0x61, 0x55,0x56,0x57,0x62,0x63,0}; // non-consecutive vowels and vowel-signs static const short stress_lengths_cy[8] = {170,220, 180,180, 0, 0, 250,270}; static const unsigned char stress_amps_cy[8] = {17,15, 18,18, 0,0, 22,20 }; // 'diminished' is used to mark a quieter, final unstressed syllable static const short stress_lengths_da[8] = {160,140, 200,200, 0,0, 220,230}; static const short stress_lengths_de[8] = {150,130, 200,200, 0, 0, 270,270}; static const unsigned char stress_amps_de[] = {20,20, 20,20, 20,22, 22,20 }; static const short stress_lengths_sw[8] = {160, 170, 200, 200, 0, 0, 320, 340}; static const unsigned char stress_amps_sw[] = {16,12, 19,19, 20,22, 22,21 }; static const unsigned char stress_amps_sv[] = {16,16, 20,20, 20,22, 22,21 }; static const short stress_lengths_sv[8] = {160,135, 220,220, 0,0, 250,280}; static const short stress_lengths_sq[8] = {150, 150, 180, 180, 0, 0, 300, 300}; static const unsigned char stress_amps_sq[8] = {16,12, 16,16, 20,20, 21,19 }; static const char *sk_voiced = "bdgjlmnrvwzaeiouy"; static const unsigned char stress_amps_ru[] = {16,16, 18,18, 20,24, 24,22 }; static const short stress_lengths_ru[8] = {150,140, 220,220, 0,0, 260,280}; static const char ru_ivowels2[] = {0x2c,0x15,0x18,0x2e,0x2f,0}; // add more vowels to letter group Y (iotated vowels & soft-sign) static const short stress_lengths_en[8] = {182,140, 220,220, 0,0, 248,275}; static const short stress_lengths_el[8] = {155, 180, 210, 210, 0, 0, 270, 300}; static const unsigned char stress_amps_el[8] = {15,12, 20,20, 20,22, 22,21 }; // 'diminished' is used to mark a quieter, final unstressed syllable // character codes offset by 0x380 static const char el_vowels[] = {0x10,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x35,0x37,0x39,0x3f,0x45,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0}; static const char el_fvowels[] = {0x2d,0x2e,0x2f,0x35,0x37,0x39,0x45,0x4d,0}; // ε η ι υ έ ή ί ύ _ static const char el_voiceless[]= {0x38,0x3a,0x3e,0x40,0x42,0x43,0x44,0x46,0x47,0}; // θ κ ξ π ς σ τ φ χ _ static const char el_consonants[]={0x32,0x33,0x34,0x36,0x38,0x3a,0x3b,0x3c,0x3d,0x3e,0x40,0x41,0x42,0x43,0x44,0x46,0x47,0x48,0}; static const wchar_t el_char_apostrophe[] = {0x3c3,0}; // σ _ static const short stress_lengths_eo[8] = {150, 150, 230, 180, 0, 0, 300, 320}; static const unsigned char stress_amps_eo[] = {16,14, 20,20, 20,22, 22,21 }; static const wchar_t eo_char_apostrophe[2] = {'l',0}; static const short stress_lengths_es[8] = {180, 190, 230, 180, 0, 0, 240, 270}; static const unsigned char stress_amps_es[8] = {16,12, 18,18, 20,20, 20,20 }; // 'diminished' is used to mark a quieter, final unstressed syllable static const wchar_t ca_punct_within_word[] = {'\'',0xb7,0}; // ca: allow middle-dot within word static const short stress_lengths_eu[8] = {200, 200, 200, 200, 0, 0, 210, 230}; // very weak stress static const unsigned char stress_amps_eu[8] = {16,16, 18,18, 18,18, 18,18 }; // Convert characters in the range 0x620 to 0x6cc to the range 1 to 63. // 0 indicates no translation for this character static const char transpose_map_fa[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, // 0x620 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 0, // 0x630 0, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, // 0x640 42, 43, 0, 0, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x650 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x660 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 45, 0, // 0x670 0, 0, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x680 0, 0, 0, 0, 0, 0, 0, 0, 47, 0, 0, 0, 0, 0, 0, 0, // 0x690 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 49, // 0x6a0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x6b0 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51 }; // 0x6c0 static const unsigned char stress_amps_fi[8] = {18,16, 22,22, 20,22, 22,22 }; static const short stress_lengths_fi[8] = {150,180, 200,200, 0,0, 210,250}; static const short stress_lengths_hi[8] = {190, 190, 210, 210, 0, 0, 230, 250}; static const unsigned char stress_amps_hi[8] = {17,14, 20,19, 20,22, 22,21 }; static const short stress_lengths_ro[8] = {170, 170, 180, 180, 0, 0, 240, 260}; static const unsigned char stress_amps_ro[8] = {15,13, 18,18, 20,22, 22,21 }; static const short stress_lengths_pt[8] = {170, 115, 210, 240, 0, 0, 260, 280}; static const unsigned char stress_amps_pt[8] = {16,11, 19,21, 20,22, 22,21 }; // 'diminished' is used to mark a quieter, final unstressed syllable static const short stress_lengths_pl[8] = {160, 190, 175, 175, 0, 0, 200, 210}; static const unsigned char stress_amps_pl[8] = {17,13, 19,19, 20,22, 22,21 }; // 'diminished' is used to mark a quieter, final unstressed syllable static const unsigned char stress_amps_om[] = {18,15, 20,20, 20,22, 22,22 }; static const short stress_lengths_om[8] = {200,200, 200,200, 0,0, 200,200}; static const short stress_lengths_no[8] = {160,140, 200,200, 0,0, 220,230}; static const short stress_lengths_nl[8] = {160,135, 210,210, 0, 0, 260,280}; static wchar_t vowels_cyrillic[] = {0x440, // also include 'р' [R] 0x430,0x435,0x438,0x439,0x43e,0x443,0x44b,0x44d,0x44e,0x44f,0x450,0x451,0x456,0x457,0x45d,0x45e,0}; static const unsigned char stress_amps_mk[8] = {17,17, 20,20, 20,22, 22,21 }; static const short stress_lengths_mk[8] = {180,160, 200,200, 0,0, 220,230}; static const unsigned char stress_amps_lv[8] = {17,13, 20,20, 20,22, 22,21 }; static const short stress_lengths_lv[8] = {180,130, 210,210, 0,0, 210,210}; static const unsigned char stress_amps_ku[8] = {18,18, 20,20, 20,22, 22,21 }; static const short stress_lengths_ku[8] = {180,180, 190,180, 0,0, 230,240}; static const char ko_ivowels[] = {0x63,0x64,0x67,0x68,0x6d,0x72,0x74,0x75,0}; // y and i vowels static const unsigned char ko_voiced[] = {0x02,0x05,0x06,0xab,0xaf,0xb7,0xbc,0}; // voiced consonants, l,m,n,N static const char ka_vowels[] = {0x30,0x34,0x38,0x3d,0x43,0x55,0x57,0}; static const char ka_consonants[] = {0x31,0x32,0x33,0x35,0x36,0x37,0x39,0x3a,0x3b,0x3c,0x3e,0x3f,0x40,0x41,0x42,0x44, 0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x56,0}; static const short stress_lengths_jbo[8] = {145,145, 170,160, 0,0, 330,350}; static const wchar_t jbo_punct_within_word[] = {'.',',','\'',0x2c8,0}; // allow period and comma within a word, also stress marker (from LOPT_CAPS_IN_WORD) static const short stress_lengths_it[8] = {150, 140, 170, 170, 0, 0, 300, 330}; static const unsigned char stress_amps_it[8] = {15,14, 19,19, 20,22, 22,20 }; static const short stress_lengths_is[8] = {180,160, 200,200, 0,0, 240,250}; static const wchar_t is_lettergroup_B[] = {'c','f','h','k','p','t','x',0xfe,0}; // voiceless conants, including 'þ' ?? 's' static const short stress_lengths_id[8] = {160, 200, 180, 180, 0, 0, 220, 240}; static const unsigned char stress_amps_id[8] = {16,18, 18,18, 20,22, 22,21 }; static const short stress_lengths_hy[8] = {250, 200, 250, 250, 0, 0, 250, 250}; static const char hy_vowels[] = {0x31, 0x35, 0x37, 0x38, 0x3b, 0x48, 0x55, 0}; static const char hy_consonants[] = {0x32,0x33,0x34,0x36,0x39,0x3a,0x3c,0x3d,0x3e,0x3f, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x56,0}; static const unsigned char stress_amps_hu[8] = {17,17, 19,19, 20,22, 22,21 }; static const short stress_lengths_hu[8] = {185,195, 195,190, 0,0, 210,220}; static const unsigned char stress_amps_hr[8] = {17,17, 20,20, 20,22, 22,21 }; static const short stress_lengths_hr[8] = {180,160, 200,200, 0,0, 220,230}; static const short stress_lengths_sr[8] = {160,150, 200,200, 0,0, 250,260}; N::SpeechTranslator:: SpeechTranslator(void) { Reset ( ) ; } N::SpeechTranslator:: SpeechTranslator(const SpeechTranslator & translator) { assign ( translator ) ; } N::SpeechTranslator::~SpeechTranslator(void) { } N::SpeechTranslator & N::SpeechTranslator::assign(const SpeechTranslator & translator) { nMemberCopy ( translator , translatorName ) ; nMemberCopy ( translator , transposeMax ) ; nMemberCopy ( translator , transposeMin ) ; nMemberCopy ( translator , phonemesRepeatCount ) ; nMemberCopy ( translator , phonemeTabIndex ) ; nMemberCopy ( translator , dictCondition ) ; nMemberCopy ( translator , dictMinSize ) ; nMemberCopy ( translator , nGroups2 ) ; nMemberCopy ( translator , expectVerb ) ; nMemberCopy ( translator , expectPast ) ; nMemberCopy ( translator , expectVerbs ) ; nMemberCopy ( translator , expectNoun ) ; nMemberCopy ( translator , prevLastStress ) ; nMemberCopy ( translator , wordVowelCount ) ; nMemberCopy ( translator , wordStressedCount ) ; nMemberCopy ( translator , clauseUpperCount ) ; nMemberCopy ( translator , clauseLowerCount ) ; nMemberCopy ( translator , prepauseTimeout ) ; nMemberCopy ( translator , endStressedVowel ) ; nMemberCopy ( translator , clauseTerminator ) ; nMemberCopy ( translator , letterBitsOffset ) ; nMemberCopy ( translator , dataDictList ) ; options = translator.options ; memcpy(prevDictFlags ,translator.prevDictFlags ,(sizeof(int )* 2)) ; memcpy(dictionaryName,translator.dictionaryName,(sizeof(char )* 40)) ; memcpy(phonemeOut ,translator.phonemeOut ,(sizeof(char )*500)) ; memcpy(phonemesRepeat,translator.phonemesRepeat,(sizeof(char )* 20)) ; memcpy(stressLengths ,translator.stressLengths ,(sizeof(short)* 8)) ; memcpy(stressAmps ,translator.stressAmps ,(sizeof(char )* 8)) ; memcpy(stressAmpsR ,translator.stressAmpsR ,(sizeof(char )* 8)) ; memcpy(letterBits ,translator.letterBits ,(sizeof(char )*256)) ; memcpy(groups2Count ,translator.groups2Count ,(sizeof(char )*256)) ; memcpy(groups2Start ,translator.groups2Start ,(sizeof(char )*256)) ; memcpy(groups2Name ,translator.groups2Name ,(sizeof(int )*120)) ; // unsigned char punctToTone [8][6] ; // char * dataDictRules ; // char * clauseEnd ; // const char * transposeMap ; // const short * frequentPairs ; // const unsigned short * charsetA0 ; // const unsigned short * charsIgnore ; // const wchar_t * charPlusApostrophe ; // const wchar_t * punctWithinWord ; // char * dictHashTab [1024] ; // char * letterGroups [ 95] ; // char * groups1 [ 256] ; // char * groups2 [ 120] ; // char * groups3 [ 128] ; // const wchar_t * wLetterGroups [ 8] ; return ME ; } N::SpeechTranslator & N::SpeechTranslator::operator = (const SpeechTranslator & translator) { return assign ( translator ) ; } bool N::SpeechTranslator::Select(const char * name) { int name2 = 0 ; int length = strlen(name) ; if (length>2) { if (strncmp(name,"grc",3)==0) name2 = L_grc ; else if (strncmp(name,"pap",3)==0) name2 = L_pap ; else if (strncmp(name,"jbo",3)==0) name2 = L_jbo ; else if (strncmp(name,"zhy",3)==0) name2 = L_zhy ; } ; if (name2<=0) { if (length==2) { while ( (*name) != 0) { name2 = (name2 << 8) + *name++ ; } ; } ; } ; ////////////////////////////////////////////////////// #define CASTER(A,B,C) case L(A,B) : C () ; return true #define DASTER(A, C) case A : C () ; return true switch (name2) { CASTER ( 'a' , 'f' , SelectAF ) ; CASTER ( 'a' , 'm' , SelectAM ) ; CASTER ( 'a' , 'n' , SelectAN ) ; CASTER ( 'a' , 'r' , SelectAR ) ; CASTER ( 'a' , 'z' , SelectAZ ) ; CASTER ( 'b' , 'g' , SelectBG ) ; CASTER ( 'b' , 'n' , SelectBN ) ; CASTER ( 'b' , 'o' , SelectBO ) ; CASTER ( 'b' , 's' , SelectBS ) ; CASTER ( 'c' , 'a' , SelectCA ) ; CASTER ( 'c' , 's' , SelectCS ) ; CASTER ( 'c' , 'y' , SelectCY ) ; CASTER ( 'd' , 'a' , SelectDA ) ; CASTER ( 'd' , 'e' , SelectDE ) ; CASTER ( 'd' , 'v' , SelectDV ) ; CASTER ( 'e' , 'l' , SelectEL ) ; CASTER ( 'e' , 'n' , SelectEN ) ; CASTER ( 'e' , 'o' , SelectEO ) ; CASTER ( 'e' , 's' , SelectES ) ; CASTER ( 'e' , 't' , SelectET ) ; CASTER ( 'e' , 'u' , SelectEU ) ; CASTER ( 'f' , 'a' , SelectFA ) ; CASTER ( 'f' , 'i' , SelectFI ) ; CASTER ( 'f' , 'r' , SelectFR ) ; CASTER ( 'g' , 'u' , SelectGU ) ; CASTER ( 'h' , 'i' , SelectHI ) ; CASTER ( 'h' , 'r' , SelectHR ) ; CASTER ( 'h' , 't' , SelectHT ) ; CASTER ( 'h' , 'u' , SelectHU ) ; CASTER ( 'h' , 'y' , SelectHY ) ; CASTER ( 'i' , 'd' , SelectID ) ; CASTER ( 'i' , 's' , SelectIS ) ; CASTER ( 'i' , 't' , SelectIT ) ; CASTER ( 'j' , 'p' , SelectJP ) ; CASTER ( 'k' , 'a' , SelectKA ) ; CASTER ( 'k' , 'k' , SelectKK ) ; CASTER ( 'k' , 'l' , SelectKL ) ; CASTER ( 'k' , 'n' , SelectKN ) ; CASTER ( 'k' , 'o' , SelectKO ) ; CASTER ( 'k' , 'u' , SelectKU ) ; CASTER ( 'l' , 'a' , SelectLA ) ; CASTER ( 'l' , 't' , SelectLT ) ; CASTER ( 'l' , 'v' , SelectLV ) ; CASTER ( 'm' , 'k' , SelectMK ) ; CASTER ( 'm' , 't' , SelectMT ) ; CASTER ( 'm' , 'l' , SelectML ) ; CASTER ( 'm' , 'r' , SelectMR ) ; CASTER ( 'm' , 's' , SelectMS ) ; CASTER ( 'n' , 'e' , SelectNE ) ; CASTER ( 'n' , 'l' , SelectNL ) ; CASTER ( 'n' , 'o' , SelectNO ) ; CASTER ( 'o' , 'm' , SelectOM ) ; CASTER ( 'p' , 'a' , SelectPA ) ; CASTER ( 'p' , 'l' , SelectPL ) ; CASTER ( 'p' , 't' , SelectPT ) ; CASTER ( 'r' , 'o' , SelectRO ) ; CASTER ( 'r' , 'u' , SelectRU ) ; CASTER ( 'r' , 'w' , SelectRW ) ; CASTER ( 's' , 'i' , SelectSI ) ; CASTER ( 's' , 'k' , SelectSK ) ; CASTER ( 's' , 'l' , SelectSL ) ; CASTER ( 's' , 'q' , SelectSQ ) ; CASTER ( 's' , 'r' , SelectSR ) ; CASTER ( 's' , 'v' , SelectSV ) ; CASTER ( 's' , 'w' , SelectSW ) ; CASTER ( 't' , 'a' , SelectTA ) ; CASTER ( 't' , 'e' , SelectTE ) ; CASTER ( 't' , 'h' , SelectTH ) ; CASTER ( 't' , 'n' , SelectTN ) ; CASTER ( 't' , 'r' , SelectTR ) ; CASTER ( 't' , 't' , SelectTT ) ; CASTER ( 'u' , 'k' , SelectUK ) ; CASTER ( 'u' , 'r' , SelectUR ) ; CASTER ( 'v' , 'i' , SelectVI ) ; CASTER ( 'w' , 'o' , SelectWO ) ; CASTER ( 'z' , 'h' , SelectZH ) ; DASTER ( L_grc , SelectGRC ) ; DASTER ( L_pap , SelectPAP ) ; DASTER ( L_jbo , SelectJBO ) ; DASTER ( L_zhy , SelectZHY ) ; // disable check for unpronouncable words default : options.param[LOPT_UNPRONOUNCABLE] = 1 ; break ; } ; #undef CASTER #undef DASTER return false ; } void N::SpeechTranslator::setLanguage(int name) { translatorName = name ; if ( options.numbers & NUM_DECIMAL_COMMA) { // use . and ; for thousands and decimal separators options.thousandsSep = '.' ; options.decimalSep = ',' ; } ; if ( options.numbers & NUM_THOUS_SPACE) { options.thousandsSep = 0 ; // don't allow thousands separator, except space } ; } void N::SpeechTranslator::SelectAF(void) { static const short stress_lengths_af[8] = {170,140,220,220, 0, 0,250,270} ; Setup ( stress_lengths_af , NULL ) ; options . stressRule = STRESSPOSN_1L ; options . vowelPause = 0x30 ; options . param [ LOPT_DIERESES ] = 1 ; options . param [ LOPT_PREFIXES ] = 1 ; /* add 'y' to vowels */ setLetterVowel ( 'y' ) ; options . numbers = NUM_SWAP_TENS | NUM_HUNDRED_AND | NUM_SINGLE_AND | NUM_ROMAN | NUM_1900 ; options . accents = 1 ; setLanguage ( L('a','f') ) ; } void N::SpeechTranslator::SelectAM(void) { // Amharic, Ethiopia Setup ( stress_lengths_fr , stress_amps_fr ) ; letterBitsOffset = OFFSET_ETHIOPIC ; options.stressRule = STRESSPOSN_1L ; options.stressFlags = S_NO_AUTO_2 | S_FINAL_DIM ; // don't use secondary stress options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.param[LOPT_UNPRONOUNCABLE] = 1 ; // disable check for unpronouncable words options.numbers = NUM_OMIT_1_HUNDRED ; setLanguage ( L('a','m') ) ; } void N::SpeechTranslator::SelectAR(void) { // Arabic letterBitsOffset = OFFSET_ARABIC ; options.numbers = NUM_SWAP_TENS | NUM_AND_UNITS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_AND_HUNDRED | NUM_THOUSAND_AND | NUM_OMIT_1_THOUSAND ; options.param[LOPT_UNPRONOUNCABLE] = 1 ; setLanguage ( L('a','r') ) ; } void N::SpeechTranslator::SelectBG(void) { // Bulgarian setCyrillicLetters ( ) ; setLetterVowel ( 0x2a ) ; charsetA0 = charsets[5] ; // ISO-8859-5 options.param[LOPT_UNPRONOUNCABLE ] = 0x432 ; // [v] don't count this character at start of word options.param[LOPT_REGRESSIVE_VOICING] = 0x107 ; // devoice at end of word, and change voicing to match a following consonant (except v) options.param[LOPT_REDUCE ] = 2 ; options.stressRule = STRESSPOSN_2R ; options.numbers = NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_OMIT_1_HUNDRED | NUM_HUNDRED_AND | NUM_AND_UNITS | NUM_SINGLE_AND | NUM_ROMAN | NUM_ROMAN_ORDINAL | NUM_ROMAN_CAPITALS ; options.thousandsSep = ' ' ; // don't allow dot as thousands separator setLanguage ( L('b','g') ) ; } void N::SpeechTranslator::SelectBN(void) { // Bengali Setup ( stress_lengths_bn , stress_amps_bn ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L ; options.stressFlags = S_MID_DIM | S_FINAL_DIM ; // use 'diminished' for unstressed final syllable letterBitsOffset = OFFSET_BENGALI ; setIndicLetters ( ) ; // call this after setting OFFSET_BENGALI setLetterBitsRange ( LETTERGP_B , 0x01 , 0x01 ) ; // candranindu setLetterBitsRange ( LETTERGP_F , 0x3e , 0x4c ) ; // vowel signs, but not virama options.numbers = NUM_SWAP_TENS ; options.breakNumbers = 0x24924aa8 ; // for languages which have numbers for 100,000 and 100,00,000, eg Hindi setLanguage ( L('b','n') ) ; } void N::SpeechTranslator::SelectBO(void) { // Tibet options.stressRule = STRESSPOSN_1L ; letterBitsOffset = OFFSET_TIBET ; setLetterBitsRange ( LETTERGP_A , 0x71 , 0x7d ) ; // vowel signs setLetterBitsRange ( LETTERGP_B , 0x71 , 0x81 ) ; // vowel signs and subjoined letters setLetterBitsRange ( LETTERGP_B , 0x90 , 0xbc ) ; setLetterBitsRange ( LETTERGP_C , 0x40 , 0x6c ) ; // consonant letters (not subjoined) options.param[LOPT_UNPRONOUNCABLE] = 1 ; // disable check for unpronouncable words options.numbers = 1 ; setLanguage ( L('b','o') ) ; } void N::SpeechTranslator::SelectCY(void) { // Welsh Setup ( stress_lengths_cy , stress_amps_cy ) ; charsetA0 = charsets[14] ; // ISO-8859-14 options.stressRule = STRESSPOSN_2R ; // options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable // options.intonationGroup = 4 ; // 'diminished' is an unstressed final syllable options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 ; options.unstressedWD1 = 0 ; options.unstressedWD2 = 2 ; options.param[LOPT_SONORANT_MIN] = 120 ; // limit the shortening of sonorants before short vowels options.numbers = NUM_OMIT_1_HUNDRED ; setLetterVowel ( 'w' ) ; // add letter to vowels and remove from consonants setLetterVowel ( 'y' ) ; setLanguage ( L('c','y') ) ; } void N::SpeechTranslator::SelectDA(void) { // Danish Setup ( stress_lengths_da , NULL ) ; options.stressRule = STRESSPOSN_1L ; options.param[LOPT_PREFIXES] = 1 ; setLetterVowel('y') ; options.numbers = NUM_DECIMAL_COMMA | NUM_SWAP_TENS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_ORDINAL_DOT | NUM_1900 | NUM_ROMAN | NUM_ROMAN_CAPITALS | NUM_ROMAN_ORDINAL ; setLanguage ( L('d','a') ) ; } void N::SpeechTranslator::SelectDE(void) { Setup( stress_lengths_de, stress_amps_de) ; options.stressRule = STRESSPOSN_1L ; options.wordGap = 0x8 ; // don't use linking phonemes options.vowelPause = 0x30 ; options.param[LOPT_PREFIXES] = 1 ; options.param[LOPT_REGRESSIVE_VOICING] = 0x100 ; // devoice at end of word options.param[LOPT_LONG_VOWEL_THRESHOLD] = 175/2 ; options.numbers = NUM_DECIMAL_COMMA | NUM_SWAP_TENS | NUM_ALLOW_SPACE | NUM_ORDINAL_DOT | NUM_ROMAN ; // options.numbers = NUM_DECIMAL_COMMA | NUM_SWAP_TENS | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_ALLOW_SPACE | NUM_ORDINAL_DOT | NUM_ROMAN; setLetterVowel ( 'y' ) ; options.param[LOPT_UNPRONOUNCABLE] = 2 ; // use de_rules for unpronouncable rules setLanguage ( L('d','e') ) ; } void N::SpeechTranslator::SelectDV(void) { // Divehi (Maldives) Setup(stress_lengths_ta,stress_amps_ta); options.param[LOPT_UNPRONOUNCABLE] = 1; // disable check for unpronouncable words options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable letterBitsOffset = OFFSET_THAANA; options.stressRule = STRESSPOSN_1L; options.stressFlags = S_MID_DIM | S_FINAL_DIM; // use 'diminished' for unstressed final syllable setLetterBitsRange(LETTERGP_B,0x26,0x30); // vowel signs, and virama options.breakNumbers = 0x14a8; // 1000, 100,000 10,000,000 options.numbers = 1; setLanguage ( L('d','v') ) ; } void N::SpeechTranslator::SelectEN(void) { Setup(stress_lengths_en,NULL); options.stressRule = STRESSPOSN_1L; options.stressFlags = 0x08; options.numbers = NUM_HUNDRED_AND | NUM_ROMAN | NUM_1900; options.param[LOPT_COMBINE_WORDS] = 2; // allow "mc" to cmbine with the following word options.suffixAddE = 'e'; options.param[LOPT_UNPRONOUNCABLE] = 2; // use en_rules for unpronouncable rules setLetterBits(6,"aeiouy"); // Group Y: vowels, including y setLanguage ( L('e','n') ) ; } void N::SpeechTranslator::SelectEL(void) { // Greek Setup(stress_lengths_el,stress_amps_el); charsetA0 = charsets[7]; // ISO-8859-7 charPlusApostrophe = el_char_apostrophe; letterBitsOffset = OFFSET_GREEK; memset(letterBits,0,sizeof(char)*256); setLetterBits(LETTERGP_A,el_vowels); setLetterBits(LETTERGP_VOWEL2,el_vowels); setLetterBits(LETTERGP_B,el_voiceless); setLetterBits(LETTERGP_C,el_consonants); setLetterBits(LETTERGP_Y,el_fvowels); // front vowels: ε η ι υ _ options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_DIM_ONLY; // mark unstressed final syllables as diminished options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_SONORANT_MIN] = 130; // limit the shortening of sonorants before short vowels options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA; options.numbers2 = 0x2 | NUM2_MULTIPLE_ORDINAL | NUM2_ORDINAL_NO_AND; // variant form of numbers before thousands setLanguage ( L('e','l') ) ; } void N::SpeechTranslator::SelectGRC(void) { // Ancient Greek Setup(stress_lengths_el,stress_amps_el); charsetA0 = charsets[7]; // ISO-8859-7 charPlusApostrophe = el_char_apostrophe; letterBitsOffset = OFFSET_GREEK; memset(letterBits,0,sizeof(letterBits)); setLetterBits(LETTERGP_A,el_vowels); setLetterBits(LETTERGP_VOWEL2,el_vowels); setLetterBits(LETTERGP_B,el_voiceless); setLetterBits(LETTERGP_C,el_consonants); setLetterBits(LETTERGP_Y,el_fvowels); // front vowels: ε η ι υ _ options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_DIM_ONLY; // mark unstressed final syllables as diminished options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_SONORANT_MIN] = 130; // limit the shortening of sonorants before short vowels options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA; options.numbers2 = 0x2 | NUM2_MULTIPLE_ORDINAL | NUM2_ORDINAL_NO_AND; // variant form of numbers before thousands // ancient greek options.param[LOPT_UNPRONOUNCABLE] = 1; setLanguage ( L_grc ) ; } void N::SpeechTranslator::SelectEO(void) { Setup(stress_lengths_eo,stress_amps_eo); charsetA0 = charsets[3]; // ISO-8859-3 charPlusApostrophe = eo_char_apostrophe; // options.wordGap = 1; options.vowelPause = 2; options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2; // options.unstressedWD1 = 3; options.unstressedWD2 = 2; options.numbers = NUM_DECIMAL_COMMA | NUM_OMIT_1_HUNDRED | NUM_ALLOW_SPACE | NUM_ROMAN; setLanguage ( L('e','o') ) ; } void N::SpeechTranslator::SelectES(void) { // Spanish Setup(stress_lengths_es,stress_amps_es); options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_2R; // stress last syllable if it doesn't end in vowel or "s" or "n" // 'diminished' is an unstressed final syllable options.stressFlags = S_FINAL_SPANISH | S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_SONORANT_MIN] = 120; // limit the shortening of sonorants before short vowels options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_AND_UNITS | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_ROMAN | NUM_ROMAN_AFTER; options.numbers2 = NUM2_MULTIPLE_ORDINAL | NUM2_ORDINAL_NO_AND; options.param[LOPT_UNPRONOUNCABLE] = 2; // use es_rules for unpronouncable rules setLanguage ( L('e','s') ) ; } void N::SpeechTranslator::SelectAN(void) { // Aragonese Setup(stress_lengths_es,stress_amps_es); options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_2R; // stress last syllable if it doesn't end in vowel or "s" or "n" // 'diminished' is an unstressed final syllable options.stressFlags = S_FINAL_SPANISH | S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_SONORANT_MIN] = 120; // limit the shortening of sonorants before short vowels options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_AND_UNITS | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_ROMAN | NUM_ROMAN_AFTER; options.numbers2 = NUM2_MULTIPLE_ORDINAL | NUM2_ORDINAL_NO_AND; options.stressFlags = S_FINAL_SPANISH | S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.numbers2 = NUM2_ORDINAL_NO_AND; setLanguage ( L('a','n') ) ; } void N::SpeechTranslator::SelectCA(void) { // Catalan Setup(stress_lengths_es,stress_amps_es); options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_2R; // stress last syllable if it doesn't end in vowel or "s" or "n" // 'diminished' is an unstressed final syllable options.stressFlags = S_FINAL_SPANISH | S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_SONORANT_MIN] = 120; // limit the shortening of sonorants before short vowels options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_AND_UNITS | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_ROMAN | NUM_ROMAN_AFTER; options.numbers2 = NUM2_MULTIPLE_ORDINAL | NUM2_ORDINAL_NO_AND; // stress last syllable unless word ends with a vowel punctWithinWord = ca_punct_within_word; options.stressFlags = S_FINAL_SPANISH | S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_NO_AUTO_2; setLanguage ( L('c','a') ) ; } void N::SpeechTranslator::SelectPAP(void) { // Papiamento Setup(stress_lengths_es,stress_amps_es); options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_2R; // stress last syllable if it doesn't end in vowel or "s" or "n" // 'diminished' is an unstressed final syllable options.stressFlags = S_FINAL_SPANISH | S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_SONORANT_MIN] = 120; // limit the shortening of sonorants before short vowels options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_AND_UNITS | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_ROMAN | NUM_ROMAN_AFTER; options.numbers2 = NUM2_MULTIPLE_ORDINAL | NUM2_ORDINAL_NO_AND; // stress last syllable unless word ends with a vowel options.stressFlags = S_FINAL_STRESS_C | S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_NO_AUTO_2; setLanguage ( L_pap ) ; } void N::SpeechTranslator::SelectEU(void) { // basque Setup(stress_lengths_eu,stress_amps_eu); options.stressRule = STRESSPOSN_2L; // ?? second syllable ?? options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_AND_UNITS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_VIGESIMAL; setLanguage ( L('e','u') ) ; } void N::SpeechTranslator::SelectFA(void) { // Farsi transposeMin = 0x620; transposeMax = 0x6cc; transposeMap = transpose_map_fa; letterBitsOffset = OFFSET_ARABIC; options.numbers = NUM_AND_UNITS | NUM_HUNDRED_AND; options.param[LOPT_UNPRONOUNCABLE] = 1; // disable check for unpronouncable words charsIgnore = chars_ignore_zwnj_hyphen; // replace ZWNJ by hyphen setLanguage ( L('f','a') ) ; } void N::SpeechTranslator::SelectET(void) { // Estonian Setup(stress_lengths_fi,stress_amps_fi); charsetA0 = charsets[4]; // ISO-8859-4 options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_2_TO_HEAVY; // move secondary stress from light to a following heavy syllable options.param[LOPT_IT_DOUBLING] = 1; options.longStop = 130; options.numbers = NUM_DECIMAL_COMMA + NUM_ALLOW_SPACE; setLetterVowel('y'); // options.maxInitialConsonants = 2; // BUT foreign words may have 3 options.spellingStress = 1; options.intonationGroup = 3; // less intonation, don't raise pitch at comma setLanguage ( L('e','t') ) ; } void N::SpeechTranslator::SelectFI(void) { // Finnish Setup(stress_lengths_fi,stress_amps_fi); options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_2_TO_HEAVY; // move secondary stress from light to a following heavy syllable options.param[LOPT_IT_DOUBLING] = 1; options.longStop = 130; options.numbers = NUM_DECIMAL_COMMA + NUM_ALLOW_SPACE; setLetterVowel('y'); // options.maxInitialConsonants = 2; // BUT foreign words may have 3 options.spellingStress = 1; options.intonationGroup = 3; // less intonation, don't raise pitch at comma setLanguage ( L('f','i') ) ; } void N::SpeechTranslator::SelectFR(void) { // french Setup(stress_lengths_fr,stress_amps_fr); options.stressRule = STRESSPOSN_1R; // stress on final syllable options.stressFlags = S_NO_AUTO_2 | S_FINAL_DIM; // don't use secondary stress options.param[LOPT_IT_LENGTHEN] = 1; // remove lengthen indicator from unstressed syllables options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.accents = 2; // Say "Capital" after the letter. options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_OMIT_1_HUNDRED | NUM_NOPAUSE | NUM_ROMAN | NUM_ROMAN_CAPITALS | NUM_ROMAN_AFTER | NUM_VIGESIMAL | NUM_DFRACTION_4; setLetterVowel('y'); setLanguage ( L('f','r') ) ; } void N::SpeechTranslator::SelectGA(void) { // irish options.stressRule = STRESSPOSN_1L; options.numbers = 1; options.accents = 2; // 'capital' after letter name options.param[LOPT_UNPRONOUNCABLE] = 3; // don't count apostrophe setLanguage ( L('g','a') ) ; } void N::SpeechTranslator::SelectHI(void) { // Hindi Setup(stress_lengths_hi,stress_amps_hi); charsetA0 = charsets[19]; // ISCII options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = 6; // stress on last heaviest syllable, excluding final syllable options.stressFlags = S_MID_DIM | S_FINAL_DIM; // use 'diminished' for unstressed final syllable options.numbers = NUM_SWAP_TENS; options.breakNumbers = 0x14aa8; // for languages which have numbers for 100,000 and 100,00,000, eg Hindi letterBitsOffset = OFFSET_DEVANAGARI; setIndicLetters ( ) ; setLanguage ( L('h','i') ) ; } void N::SpeechTranslator::SelectNE(void) { // Nepali Setup(stress_lengths_hi,stress_amps_hi); charsetA0 = charsets[19]; // ISCII options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = 6; // stress on last heaviest syllable, excluding final syllable options.stressFlags = S_MID_DIM | S_FINAL_DIM; // use 'diminished' for unstressed final syllable options.numbers = NUM_SWAP_TENS; options.breakNumbers = 0x14aa8; // for languages which have numbers for 100,000 and 100,00,000, eg Hindi letterBitsOffset = OFFSET_DEVANAGARI; Setup(stress_lengths_equal,stress_amps_equal); options.breakNumbers = 0x2aaaa8; options.maxDigits = 22; options.numbers2 |= NUM2_ENGLISH_NUMERALS; setIndicLetters ( ) ; setLanguage ( L('n','e') ) ; } void N::SpeechTranslator::SelectPA(void) { // Punjabi Setup(stress_lengths_hi,stress_amps_hi); charsetA0 = charsets[19]; // ISCII options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = 6; // stress on last heaviest syllable, excluding final syllable options.stressFlags = S_MID_DIM | S_FINAL_DIM; // use 'diminished' for unstressed final syllable options.numbers = NUM_SWAP_TENS; options.breakNumbers = 0x14aa8; // for languages which have numbers for 100,000 and 100,00,000, eg Hindi letterBitsOffset = OFFSET_DEVANAGARI; letterBitsOffset = OFFSET_GURMUKHI; setIndicLetters ( ) ; setLanguage ( L('p','a') ) ; } void N::SpeechTranslator::SelectGU(void) { // Gujarati Setup(stress_lengths_hi,stress_amps_hi); charsetA0 = charsets[19]; // ISCII options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = 6; // stress on last heaviest syllable, excluding final syllable options.stressFlags = S_MID_DIM | S_FINAL_DIM; // use 'diminished' for unstressed final syllable options.numbers = NUM_SWAP_TENS; options.breakNumbers = 0x14aa8; // for languages which have numbers for 100,000 and 100,00,000, eg Hindi letterBitsOffset = OFFSET_DEVANAGARI; Setup(stress_lengths_equal,stress_amps_equal); letterBitsOffset = OFFSET_GUJARATI; options.stressRule = STRESSPOSN_2R; setIndicLetters ( ) ; setLanguage ( L('g','u') ) ; } void N::SpeechTranslator::SelectHR(void) { // Croatian Setup(stress_lengths_hr,stress_amps_hr); charsetA0 = charsets[2]; // ISO-8859-2 options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_NO_2; options.param[LOPT_REGRESSIVE_VOICING] = 0x3; options.maxInitialConsonants = 5; options.spellingStress = 1; options.accents = 1; options.numbers = NUM_SINGLE_STRESS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_DECIMAL_COMMA | NUM_THOUS_SPACE | NUM_DFRACTION_2 | NUM_ROMAN_CAPITALS; options.numbers2 = 0xa + NUM2_THOUSANDS_VAR5; // variant numbers before thousands,milliards options.replaceChars = replace_cyrillic_latin; options.ourAlphabet = OFFSET_CYRILLIC; // don't say "cyrillic" before letter names setLetterVowel('y'); setLetterVowel('r'); setLanguage ( L('h','r') ) ; } void N::SpeechTranslator::SelectBS(void) { // Bosnian Setup(stress_lengths_hr,stress_amps_hr); charsetA0 = charsets[2]; // ISO-8859-2 options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_NO_2; options.param[LOPT_REGRESSIVE_VOICING] = 0x3; options.maxInitialConsonants = 5; options.spellingStress = 1; options.accents = 1; options.numbers = NUM_SINGLE_STRESS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_DECIMAL_COMMA | NUM_THOUS_SPACE | NUM_DFRACTION_2 | NUM_ROMAN_CAPITALS; options.numbers2 = 0xa + NUM2_THOUSANDS_VAR5; // variant numbers before thousands,milliards options.replaceChars = replace_cyrillic_latin; options.ourAlphabet = OFFSET_CYRILLIC; // don't say "cyrillic" before letter names setLetterVowel('y'); setLetterVowel('r'); setLanguage ( L('b','s') ) ; } void N::SpeechTranslator::SelectSR(void) { // Serbian Setup(stress_lengths_sr,stress_amps_hr); charsetA0 = charsets[2]; // ISO-8859-2 options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_NO_2; options.param[LOPT_REGRESSIVE_VOICING] = 0x3; options.maxInitialConsonants = 5; options.spellingStress = 1; options.accents = 1; options.numbers = NUM_SINGLE_STRESS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_DECIMAL_COMMA | NUM_THOUS_SPACE | NUM_DFRACTION_2 | NUM_ROMAN_CAPITALS; options.numbers2 = 0xa + NUM2_THOUSANDS_VAR5; // variant numbers before thousands,milliards options.replaceChars = replace_cyrillic_latin; options.ourAlphabet = OFFSET_CYRILLIC; // don't say "cyrillic" before letter names setLetterVowel('y'); setLetterVowel('r'); setLanguage ( L('s','r') ) ; } void N::SpeechTranslator::SelectHT(void) { // Haitian Creole // memcpy(stressLengths,stress_lengths_fr,sizeof(stressLengths)); options.stressRule = STRESSPOSN_1R; // stress on final syllable options.stressFlags = S_NO_AUTO_2 | S_FINAL_DIM; // don't use secondary stress options.numbers = NUM_SINGLE_STRESS | NUM_OMIT_1_HUNDRED | NUM_NOPAUSE | NUM_ROMAN | NUM_VIGESIMAL | NUM_DFRACTION_4; setLanguage ( L('h','t') ) ; } void N::SpeechTranslator::SelectHU(void) { // Hungarian Setup(stress_lengths_hu,stress_amps_hu); charsetA0 = charsets[2]; // ISO-8859-2 options.vowelPause = 0x20; options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_NO_AUTO_2 | 0x8000 | S_HYPEN_UNSTRESS; options.unstressedWD1 = 2; options.param[LOPT_IT_DOUBLING] = 1; options.param[LOPT_ANNOUNCE_PUNCT] = 2; // don't break clause before announcing . ? ! options.numbers = NUM_DFRACTION_5 | NUM_ALLOW_SPACE | NUM_ROMAN | NUM_ROMAN_ORDINAL | NUM_ROMAN_CAPITALS | NUM_ORDINAL_DOT | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND; options.thousandsSep = ' '; // don't allow dot as thousands separator options.decimalSep = ','; options.maxRoman = 899; options.minRoman = 1; setLetterVowel('y'); options.spellingStress = 1; setLengthMods(3); // all equal setLanguage ( L('h','u') ) ; } void N::SpeechTranslator::SelectHY(void) { // Armenian Setup(stress_lengths_hy,NULL); options.stressRule = STRESSPOSN_1R; // default stress on final syllable letterBitsOffset = OFFSET_ARMENIAN; memset(letterBits,0,sizeof(char)*256); setLetterBits(LETTERGP_A,hy_vowels); setLetterBits(LETTERGP_VOWEL2,hy_vowels); setLetterBits(LETTERGP_C,hy_consonants); options.maxInitialConsonants = 6; options.numbers = NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_OMIT_1_HUNDRED; // options.param[LOPT_UNPRONOUNCABLE] = 1; // disable check for unpronouncable words setLanguage ( L('h','y') ) ; } void N::SpeechTranslator::SelectID(void) { // Indonesian Setup(stress_lengths_id,stress_amps_id); options.stressRule = STRESSPOSN_2R; options.numbers = NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_ROMAN; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.accents = 2; // "capital" after letter name setLanguage ( L('i','d') ) ; } void N::SpeechTranslator::SelectMS(void) { // Malay Setup(stress_lengths_id,stress_amps_id); options.stressRule = STRESSPOSN_2R; options.numbers = NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_ROMAN; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.accents = 2; // "capital" after letter name setLanguage ( L('m','s') ) ; } void N::SpeechTranslator::SelectIS(void) { // Icelandic Setup(stress_lengths_is,NULL); options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_NO_2; options.param[LOPT_IT_LENGTHEN] = 0x11; // remove lengthen indicator from unstressed vowels options.param[LOPT_REDUCE] = 2; resetLetterBits(0x18); setLetterBits(4,"kpst"); // Letter group F setLetterBits(3,"jvr"); // Letter group H wLetterGroups[1] = is_lettergroup_B; setLetterVowel('y'); options.numbers = NUM_DECIMAL_COMMA | NUM_SINGLE_AND | NUM_HUNDRED_AND | NUM_AND_UNITS | NUM_1900; options.numbers2 = 0x2; setLanguage ( L('i','s') ) ; } void N::SpeechTranslator::SelectIT(void) { // Italian Setup(stress_lengths_it,stress_amps_it); options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_NO_2 | S_PRIORITY_STRESS; options.vowelPause = 1; options.unstressedWD1 = 2; options.unstressedWD2 = 2; options.param[LOPT_IT_LENGTHEN] = 2; // remove lengthen indicator from unstressed or non-penultimate syllables options.param[LOPT_IT_DOUBLING] = 2; // double the first consonant if the previous word ends in a stressed vowel options.param[LOPT_SONORANT_MIN] = 130; // limit the shortening of sonorants before short vowels options.param[LOPT_REDUCE] = 1; // reduce vowels even if phonemes are specified in it_list options.param[LOPT_ALT] = 2; // call ApplySpecialAttributes2() if a word has $alt or $alt2 options.numbers = NUM_SINGLE_VOWEL | NUM_OMIT_1_HUNDRED |NUM_DECIMAL_COMMA | NUM_ROMAN | NUM_DFRACTION_1; options.accents = 2; // Say "Capital" after the letter. setLetterVowel('y'); setLanguage ( L('i','t') ) ; } void N::SpeechTranslator::SelectJBO(void) { // Lojban Setup(stress_lengths_jbo,NULL); options.stressRule = STRESSPOSN_2R; options.vowelPause = 0x20c; // pause before a word which starts with a vowel, or after a word which ends in a consonant // options.wordGap = 1; punctWithinWord = jbo_punct_within_word; options.param[LOPT_CAPS_IN_WORD] = 2; // capitals indicate stressed syllables setLetterVowel('y'); options.maxLengthMod = 368; setLanguage ( L_jbo ) ; } void N::SpeechTranslator::SelectJP(void) { // Japanese setLanguage ( L('j','p') ) ; } void N::SpeechTranslator::SelectKA(void) { // Georgian // character codes offset by 0x1080 Setup(stress_lengths_ta,stress_amps_ta); memset(letterBits,0,sizeof(char)*256); setLetterBits(LETTERGP_A,ka_vowels); setLetterBits(LETTERGP_C,ka_consonants); setLetterBits(LETTERGP_VOWEL2,ka_vowels); options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_NO_2; letterBitsOffset = OFFSET_GEORGIAN; // options.param[LOPT_UNPRONOUNCABLE] = 1; // disable check for unpronouncable words options.maxInitialConsonants = 7; options.numbers = NUM_VIGESIMAL | NUM_AND_UNITS | NUM_OMIT_1_HUNDRED |NUM_OMIT_1_THOUSAND | NUM_DFRACTION_5 | NUM_ROMAN; options.altAlphabet = OFFSET_CYRILLIC; options.altAlphabetLanguage = L('r','u'); setLanguage ( L('k','a') ) ; } void N::SpeechTranslator::SelectKK(void) { // Kazakh letterBitsOffset = OFFSET_CYRILLIC; memset(letterBits,0,sizeof(char)*256); setLetterBits(LETTERGP_A,(char *)ru_vowels); setLetterBits(LETTERGP_C,(char *)ru_consonants); setLetterBits(LETTERGP_VOWEL2,(char *)ru_vowels); Setup(stress_lengths_tr,stress_amps_tr); options.stressRule = 7; // stress on the last syllable, before any explicitly unstressed syllable options.stressFlags = S_NO_AUTO_2 + S_NO_EOC_LENGTHEN; //no automatic secondary stress, don't lengthen at end-of-clause options.lengthenTonic = 0; options.param[LOPT_SUFFIX] = 1; options.numbers = NUM_OMIT_1_HUNDRED | NUM_DFRACTION_6 ; options.maxInitialConsonants = 2; setLengthMods(3); // all equal setLanguage ( L('k','k') ) ; } void N::SpeechTranslator::SelectKL(void) { // Greenlandic Setup(stress_lengths_equal,stress_amps_equal); options.stressRule = 12; options.stressFlags = S_NO_AUTO_2; options.numbers = NUM_DECIMAL_COMMA | NUM_SWAP_TENS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_ORDINAL_DOT | NUM_1900 | NUM_ROMAN | NUM_ROMAN_CAPITALS | NUM_ROMAN_ORDINAL; setLanguage ( L('k','l') ) ; } void N::SpeechTranslator::SelectKO(void) { // Korean, TEST letterBitsOffset = OFFSET_KOREAN; options.ourAlphabet = 0xa700; memset(letterBits,0,sizeof(char)*256); setLetterBitsRange(LETTERGP_A,0x61,0x75); setLetterBits(LETTERGP_Y,ko_ivowels); setLetterBits(LETTERGP_G,(const char *)ko_voiced); options.stressRule = 8; // ?? 1st syllable if it is heavy, else 2nd syllable options.param[LOPT_UNPRONOUNCABLE] = 1; // disable check for unpronouncable words options.numbers = NUM_OMIT_1_HUNDRED; options.numbers2 = NUM2_MYRIADS; options.breakNumbers = 0x1111110; options.maxDigits = 20; setLanguage ( L('k','o') ) ; } void N::SpeechTranslator::SelectKU(void) { // Kurdish Setup(stress_lengths_ku,stress_amps_ku); charsetA0 = charsets[9]; // ISO-8859-9 - Latin5 options.stressRule = 7; // stress on the last syllable, before any explicitly unstressed syllable options.numbers = NUM_HUNDRED_AND | NUM_AND_UNITS | NUM_OMIT_1_HUNDRED | NUM_AND_HUNDRED; options.maxInitialConsonants = 2; setLanguage ( L('k','u') ) ; } void N::SpeechTranslator::SelectLA(void) { // Latin charsetA0 = charsets[4]; // ISO-8859-4, includes a,e,i,o,u-macron options.stressRule = STRESSPOSN_2R; options.stressFlags = S_NO_AUTO_2; options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_DIERESES] = 1; options.numbers = NUM_ROMAN; options.maxRoman = 5000; setLanguage ( L('l','a') ) ; } void N::SpeechTranslator::SelectLT(void) { // Lithuanian charsetA0 = charsets[4]; // ISO-8859-4 options.stressRule = STRESSPOSN_2R; options.stressFlags = S_NO_AUTO_2; options.unstressedWD1 = 0; options.unstressedWD2 = 2; options.param[LOPT_DIERESES] = 1; options.numbers = NUM_DECIMAL_COMMA | NUM_OMIT_1_HUNDRED | NUM_DFRACTION_4 | NUM_ORDINAL_DOT; options.numbers2 = NUM2_THOUSANDS_VAR4; options.maxRoman = 5000; setLanguage ( L('l','t') ) ; } void N::SpeechTranslator::SelectLV(void) { // latvian Setup(stress_lengths_lv,stress_amps_lv); options.stressRule = STRESSPOSN_1L; options.spellingStress = 1; charsetA0 = charsets[4]; // ISO-8859-4 options.numbers = NUM_DECIMAL_COMMA | NUM_OMIT_1_HUNDRED | NUM_DFRACTION_4 | NUM_ORDINAL_DOT; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_EO_CLAUSE1; setLanguage ( L('l','v') ) ; } void N::SpeechTranslator::SelectMK(void) { // Macedonian Setup(stress_lengths_mk,stress_amps_mk); charsetA0 = charsets[5]; // ISO-8859-5 wLetterGroups[0] = vowels_cyrillic ; wLetterGroups[7] = vowels_cyrillic ; letterBitsOffset = OFFSET_CYRILLIC ; options.stressRule = STRESSPOSN_3R ; // antipenultimate options.numbers = NUM_DECIMAL_COMMA | NUM_AND_UNITS | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_DFRACTION_2; options.numbers2 = 0x8a; // variant numbers before thousands,milliards setLanguage ( L('m','k') ) ; } void N::SpeechTranslator::SelectMT(void) { // Maltese charsetA0 = charsets[3]; // ISO-8859-3 options.param[LOPT_REGRESSIVE_VOICING] = 0x100; // devoice at end of word options.stressRule = STRESSPOSN_2R; // penultimate options.numbers = 1; setLanguage ( L('m','t') ) ; } void N::SpeechTranslator::SelectNL(void) { // Dutch options.stressRule = STRESSPOSN_1L; options.vowelPause = 0x30; // ?? options.param[LOPT_DIERESES] = 1; options.param[LOPT_PREFIXES] = 1; options.param[LOPT_REGRESSIVE_VOICING] = 0x100; // devoice at end of word setLetterVowel('y'); options.numbers = NUM_DECIMAL_COMMA | NUM_SWAP_TENS | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_ALLOW_SPACE | NUM_1900 | NUM_ORDINAL_DOT; options.ordinalIndicator = "e"; options.stressFlags = S_FIRST_PRIMARY; memcpy(stressLengths,stress_lengths_nl,sizeof(short)*8); setLanguage ( L('n','l') ) ; } void N::SpeechTranslator::SelectNO(void) { // Norwegian Setup(stress_lengths_no,NULL); options.stressRule = STRESSPOSN_1L; setLetterVowel('y'); options.numbers = NUM_DECIMAL_COMMA | NUM_HUNDRED_AND | NUM_ALLOW_SPACE | NUM_1900 | NUM_ORDINAL_DOT; setLanguage ( L('n','o') ) ; } void N::SpeechTranslator::SelectOM(void) { Setup(stress_lengths_om,stress_amps_om); options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 | 0x80000; setLanguage ( L('o','m') ) ; } void N::SpeechTranslator::SelectPL(void) { // Polish Setup(stress_lengths_pl,stress_amps_pl); charsetA0 = charsets[2]; // ISO-8859-2 options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_DIM_ONLY; // mark unstressed final syllables as diminished options.param[LOPT_REGRESSIVE_VOICING] = 0x9; options.maxInitialConsonants = 7; // for example: wchrzczony :) options.numbers = NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_DFRACTION_2; options.numbers2 = NUM2_THOUSANDS_VAR3; options.param[LOPT_COMBINE_WORDS] = 4 + 0x100; // combine 'nie' (marked with $alt2) with some 1-syllable (and 2-syllable) words (marked with $alt) setLetterVowel('y'); setLanguage ( L('p','l') ) ; } void N::SpeechTranslator::SelectPT(void) { // Portuguese Setup(stress_lengths_pt,stress_amps_pt); options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1R; // stress on final syllable options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_INITIAL_2 | S_PRIORITY_STRESS; options.numbers = NUM_DECIMAL_COMMA | NUM_DFRACTION_2 | NUM_HUNDRED_AND | NUM_AND_UNITS | NUM_ROMAN; options.numbers2 = NUM2_MULTIPLE_ORDINAL | NUM2_NO_TEEN_ORDINALS | NUM2_ORDINAL_NO_AND; setLetterVowel('y'); resetLetterBits(0x2); setLetterBits(1,"bcdfgjkmnpqstvxz"); // B hard consonants, excluding h,l,r,w,y options.param[LOPT_ALT] = 2; // call ApplySpecialAttributes2() if a word has $alt or $alt2 options.accents = 2; // 'capital' after letter name setLanguage ( L('p','t') ) ; } void N::SpeechTranslator::SelectRO(void) { // Romanian Setup(stress_lengths_ro,stress_amps_ro); options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_STRESS_C + S_FINAL_DIM_ONLY; charsetA0 = charsets[2]; // ISO-8859-2 options.numbers = NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_DFRACTION_3 | NUM_AND_UNITS | NUM_ROMAN; options.numbers2 = 0x1e; // variant numbers before all thousandplex setLanguage ( L('r','o') ) ; } void N::SpeechTranslator::SelectRU(void) { // Modern Russian Setup ( stress_lengths_ru , stress_amps_ru ) ; setCyrillicLetters ( ) ; setLetterBits(6,ru_ivowels2); options.param[LOPT_UNPRONOUNCABLE] = 0x432; // [v] don't count this character at start of word options.param[LOPT_REGRESSIVE_VOICING] = 1; options.param[LOPT_REDUCE] = 2; options.stressRule = 5; options.stressFlags = S_NO_AUTO_2; options.numbers = NUM_DECIMAL_COMMA | NUM_OMIT_1_HUNDRED; options.numbers2 = 0x2 + NUM2_THOUSANDS_VAR1; // variant numbers before thousands options.phonemeChange = 1; options.testing = 2; setLanguage ( L('r','u') ) ; } void N::SpeechTranslator::SelectRW(void) { // Kiryarwanda options.stressRule = STRESSPOSN_2R; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.param[LOPT_UNPRONOUNCABLE] = 1; // disable check for unpronouncable words. Need to allow "bw'" prefix options.numbers = NUM_HUNDRED_AND | NUM_AND_UNITS | NUM_DFRACTION_2 | NUM_AND_HUNDRED; options.numbers2 = 0x200; // say "thousands" before its number setLanguage ( L('r','w') ) ; } void N::SpeechTranslator::SelectSK(void) { // Slovak Setup(stress_lengths_sk,stress_amps_sk); charsetA0 = charsets[2]; // ISO-8859-2 options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.param[LOPT_REGRESSIVE_VOICING] = 0x3; options.maxInitialConsonants = 5; options.spellingStress = 1; options.param[LOPT_COMBINE_WORDS] = 4; // combine some prepositions with the following word options.numbers = NUM_OMIT_1_HUNDRED | NUM_DFRACTION_2 | NUM_ROMAN; options.numbers2 = NUM2_THOUSANDS_VAR2; options.thousandsSep = STRESSPOSN_1L; //no thousands separator options.decimalSep = ','; setLetterVowel('y'); setLetterVowel('r'); resetLetterBits(0x20); setLetterBits(5,sk_voiced); setLanguage ( L('s','k') ) ; } void N::SpeechTranslator::SelectCS(void) { // Czech Setup(stress_lengths_sk,stress_amps_sk); charsetA0 = charsets[2]; // ISO-8859-2 options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.param[LOPT_REGRESSIVE_VOICING] = 0x3; options.maxInitialConsonants = 5; options.spellingStress = 1; options.param[LOPT_COMBINE_WORDS] = 4; // combine some prepositions with the following word options.numbers = NUM_OMIT_1_HUNDRED | NUM_DFRACTION_2 | NUM_ROMAN; options.numbers2 = NUM2_THOUSANDS_VAR2; options.thousandsSep = STRESSPOSN_1L; //no thousands separator options.decimalSep = ','; options.numbers2 = 0x108; // variant numbers before milliards setLetterVowel('y'); setLetterVowel('r'); resetLetterBits(0x20); setLetterBits(5,sk_voiced); setLanguage ( L('c','s') ) ; } void N::SpeechTranslator::SelectSI(void) { // Sinhala Setup(stress_lengths_ta,stress_amps_ta); options.lengthMods0 = options.lengthMods; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2; options.spellingStress = 1; letterBitsOffset = OFFSET_SINHALA; memset ( letterBits , 0 , sizeof(char) * 256 ) ; setLetterBitsRange(LETTERGP_A,0x05,0x16); // vowel letters setLetterBitsRange(LETTERGP_A,0x4a,0x73); // + vowel signs, and virama setLetterBitsRange(LETTERGP_B,0x4a,0x73); // vowel signs, and virama setLetterBitsRange(LETTERGP_C,0x1a,0x46); // the main consonant range options.param[LOPT_UNPRONOUNCABLE] = 1; // disable check for unpronouncable words options.suffixAddE = letterBitsOffset + 0x4a; //virama options.numbers = NUM_OMIT_1_THOUSAND | NUM_SINGLE_STRESS_L | NUM_DFRACTION_7; options.numbers2 = NUM2_PERCENT_BEFORE; options.breakNumbers = 0x14aa8; // for languages which have numbers for 100,000 and 100,00,000, eg Hindi setLanguage ( L('s','i') ) ; } void N::SpeechTranslator::SelectSL(void) { // Slovenian charsetA0 = charsets[2] ; // ISO-8859-2 options.stressRule = STRESSPOSN_2R ; // Temporary options.stressFlags = S_NO_AUTO_2 ; options.param[LOPT_REGRESSIVE_VOICING] = 0x103 ; options.param[LOPT_UNPRONOUNCABLE ] = 0x76 ; // [v] don't count this character at start of word options.param[LOPT_ALT ] = 2 ; // call ApplySpecialAttributes2() if a word has $alt or $alt2 options.param[LOPT_IT_LENGTHEN ] = 1 ; // remove lengthen indicator from unstressed syllables letterBits['r'] |= 0x80 ; // add 'r' to letter group 7, vowels for Unpronouncable test options.numbers = NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_SWAP_TENS | NUM_OMIT_1_HUNDRED | NUM_DFRACTION_2 | NUM_ORDINAL_DOT | NUM_ROMAN ; options.numbers2 = 0x100 ; // plural forms of millions etc options.thousandsSep = ' ' ; // don't allow dot as thousands separator setLanguage ( L('s','l') ) ; } void N::SpeechTranslator::SelectSQ(void) { // Albanian Setup ( stress_lengths_sq , stress_amps_sq ) ; options.stressRule = STRESSPOSN_2R ; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 | S_FINAL_STRESS_C ; setLetterVowel ( 'y' ) ; options.numbers = NUM_DECIMAL_COMMA | NUM_HUNDRED_AND | NUM_AND_UNITS | NUM_DFRACTION_4 ; options.accents = 2 ; // "capital" after letter name setLanguage ( L('s','q') ) ; } void N::SpeechTranslator::SelectSV(void) { // Swedish Setup ( stress_lengths_sv , stress_amps_sv ) ; options.stressRule = STRESSPOSN_1L ; setLetterVowel ( 'y' ) ; options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_1900 ; options.accents = 1 ; setLanguage ( L('s','v') ) ; } void N::SpeechTranslator::SelectSW(void) { // Swahili Setup ( stress_lengths_sw , stress_amps_sw ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.vowelPause = 1 ; options.stressRule = STRESSPOSN_2R ; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 ; options.maxInitialConsonants = 4 ; // for example: mwngi options.numbers = NUM_AND_UNITS | NUM_HUNDRED_AND | NUM_SINGLE_AND | NUM_OMIT_1_HUNDRED ; options.breakNumbers = 0x49249268 ; // for languages which have numbers for 100,000 and 1,000,000 setLanguage ( L('s','w') ) ; } void N::SpeechTranslator::SelectTN(void) { // Setswana Setup ( stress_lengths_sw , stress_amps_sw ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.vowelPause = 1 ; options.stressRule = STRESSPOSN_2R ; options.stressFlags = S_FINAL_DIM_ONLY | S_FINAL_NO_2 ; options.maxInitialConsonants = 4 ; // for example: mwngi options.numbers = NUM_AND_UNITS | NUM_HUNDRED_AND | NUM_SINGLE_AND | NUM_OMIT_1_HUNDRED ; options.breakNumbers = 0x49249268 ; // for languages which have numbers for 100,000 and 1,000,000 setLanguage ( L('t','n') ) ; } void N::SpeechTranslator::SelectTA(void) { // Tamil Setup ( stress_lengths_ta2 , stress_amps_ta ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L ; options.stressFlags = S_FINAL_DIM_ONLY ; // use 'diminished' for unstressed final syllable options.spellingStress = 1 ; options.breakNumbers = 0x14a8 ; // 1000, 100,000 10,000,000 Setup ( stress_lengths_ta , NULL ) ; letterBitsOffset = OFFSET_TAMIL ; options.numbers = NUM_OMIT_1_THOUSAND ; options.param[LOPT_WORD_MERGE] = 1 ; // don't break vowels betwen words setIndicLetters ( ) ; // call this after setting OFFSET_ setLetterBitsRange ( LETTERGP_B , 0x4e , 0x4e ) ; // chillu-virama (unofficial) setLanguage ( L('t','a') ) ; } void N::SpeechTranslator::SelectML(void) { // Malayalam Setup ( stress_lengths_ta2 , stress_amps_ta ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L ; options.stressFlags = S_FINAL_DIM_ONLY ; // use 'diminished' for unstressed final syllable options.spellingStress = 1 ; options.breakNumbers = 0x14a8 ; // 1000, 100,000 10,000,000 letterBitsOffset = OFFSET_MALAYALAM ; options.numbers = NUM_OMIT_1_THOUSAND ; setIndicLetters ( ) ; // call this after setting OFFSET_ setLetterBitsRange ( LETTERGP_B , 0x4e , 0x4e ) ; // chillu-virama (unofficial) setLanguage ( L('m','l') ) ; } void N::SpeechTranslator::SelectKN(void) { // Kannada Setup ( stress_lengths_ta2 , stress_amps_ta ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L ; options.stressFlags = S_FINAL_DIM_ONLY ; // use 'diminished' for unstressed final syllable options.spellingStress = 1 ; options.breakNumbers = 0x14a8 ; // 1000, 100,000 10,000,000 letterBitsOffset = OFFSET_KANNADA ; options.numbers = 0x1 ; setIndicLetters ( ) ; // call this after setting OFFSET_ setLetterBitsRange ( LETTERGP_B , 0x4e , 0x4e ) ; // chillu-virama (unofficial) setLanguage ( L('k','n') ) ; } void N::SpeechTranslator::SelectMR(void) { // Marathi Setup ( stress_lengths_ta2 , stress_amps_ta ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L ; options.stressFlags = S_FINAL_DIM_ONLY ; // use 'diminished' for unstressed final syllable options.spellingStress = 1 ; options.breakNumbers = 0x14a8 ; // 1000, 100,000 10,000,000 letterBitsOffset = OFFSET_DEVANAGARI ; setIndicLetters ( ) ; // call this after setting OFFSET_ setLetterBitsRange ( LETTERGP_B , 0x4e , 0x4e ) ; // chillu-virama (unofficial) setLanguage ( L('m','r') ) ; } void N::SpeechTranslator::SelectTE(void) { // Telugu Setup ( stress_lengths_ta2 , stress_amps_ta ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L ; options.stressFlags = S_FINAL_DIM_ONLY ; // use 'diminished' for unstressed final syllable options.spellingStress = 1 ; options.breakNumbers = 0x14a8 ; // 1000, 100,000 10,000,000 letterBitsOffset = OFFSET_TELUGU ; options.numbers = 0x1 ; setIndicLetters ( ) ; // call this after setting OFFSET_ setLetterBitsRange ( LETTERGP_B , 0x4e , 0x4e ) ; // chillu-virama (unofficial) setLanguage ( L('t','e') ) ; } void N::SpeechTranslator::SelectTH(void) { // Thai Setup ( stress_lengths_th , stress_amps_th ) ; options.stressRule = 0 ; // stress on final syllable of a "word" options.stressFlags = S_NO_DIM ; // don't automatically set diminished stress (may be set in the intonation module) options.toneLanguage = 1 ; // Tone language, use CalcPitches_Tone() rather than CalcPitches() options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable // options.toneNumbers = 1 ; // a number after letters indicates a tone number (eg. pinyin or jyutping) options.wordGap = 0x21 ; // length of a final vowel is less dependent on the next consonant, don't merge consonant with next word setLanguage ( L('t','h') ) ; } void N::SpeechTranslator::SelectTR(void) { // Turkish Setup ( stress_lengths_tr , stress_amps_tr ) ; charsetA0 = charsets[9] ; // ISO-8859-9 - Latin5 options.stressRule = 7 ; // stress on the last syllable, before any explicitly unstressed syllable options.stressFlags = S_NO_AUTO_2 ; //no automatic secondary stress options.dotlessI = 1 ; options.param[LOPT_SUFFIX] = 1 ; options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_DFRACTION_2 ; options.maxInitialConsonants = 2 ; setLanguage ( L('t','r') ) ; } void N::SpeechTranslator::SelectAZ(void) { // Azerbaijan Setup ( stress_lengths_tr , stress_amps_tr ) ; charsetA0 = charsets[9] ; // ISO-8859-9 - Latin5 options.stressRule = 7 ; // stress on the last syllable, before any explicitly unstressed syllable options.stressFlags = S_NO_AUTO_2 ; //no automatic secondary stress options.dotlessI = 1 ; options.param[LOPT_SUFFIX] = 1 ; options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_ALLOW_SPACE | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_DFRACTION_2 ; options.maxInitialConsonants = 2 ; setLanguage ( L('a','z') ) ; } void N::SpeechTranslator::SelectTT(void) { // Tatar setCyrillicLetters ( ) ; Setup ( stress_lengths_fr , stress_amps_fr ) ; options.stressRule = STRESSPOSN_1R ; // stress on final syllable options.stressFlags = S_NO_AUTO_2 ; //no automatic secondary stress options.numbers = NUM_SINGLE_STRESS | NUM_DECIMAL_COMMA | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_DFRACTION_4 ; setLanguage ( L('t','t') ) ; } void N::SpeechTranslator::SelectUK(void) { // Ukrainian setCyrillicLetters ( ) ; options.param[LOPT_UNPRONOUNCABLE] = 0x432 ; // [v] don't count this character at start of word setLanguage ( L('u','k') ) ; } void N::SpeechTranslator::SelectUR(void) { // Urdu letterBitsOffset = OFFSET_ARABIC ; options.param[LOPT_UNPRONOUNCABLE] = 1 ; // disable check for unpronouncable words options.numbers = NUM_SWAP_TENS ; options.breakNumbers = 0x52a8 ; // for languages which have numbers for 100,000 and 100,00,000, eg Hindi setLanguage ( L('u','r') ) ; } void N::SpeechTranslator::SelectVI(void) { Setup ( stress_lengths_vi , stress_amps_vi ) ; options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.stressRule = STRESSPOSN_1L ; options.wordGap = 0x21 ; // length of a final vowel is less dependent on the next consonant, don't merge consonant with next word // options.vowelPause = 4 ; wLetterGroups[0] = vowels_vi ; wLetterGroups[7] = vowels_vi ; options.toneLanguage = 1 ; // Tone language, use CalcPitches_Tone() rather than CalcPitches() options.unstressedWD1 = 2 ; options.numbers = NUM_DECIMAL_COMMA | NUM_HUNDRED_AND_DIGIT | NUM_DFRACTION_4 | NUM_ZERO_HUNDRED ; setLanguage ( L('v','i') ) ; } void N::SpeechTranslator::SelectWO(void) { options.stressRule = STRESSPOSN_1L ; options.numbers = NUM_AND_UNITS | NUM_HUNDRED_AND | NUM_OMIT_1_HUNDRED | NUM_OMIT_1_THOUSAND | NUM_SINGLE_STRESS ; setLanguage ( L('w','o') ) ; } void N::SpeechTranslator::SelectZH(void) { Setup ( stress_lengths_zh , stress_amps_zh ) ; options.stressRule = STRESSPOSN_1R ; // stress on final syllable of a "word" options.stressFlags = S_NO_DIM ; // don't automatically set diminished stress (may be set in the intonation module) options.vowelPause = 0 ; options.toneLanguage = 1 ; // Tone language, use CalcPitches_Tone() rather than CalcPitches() options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.toneNumbers = 1 ; // a number after letters indicates a tone number (eg. pinyin or jyutping) options.ideographs = 1 ; options.ourAlphabet = 0x3100 ; options.wordGap = 0x21 ; // length of a final vowel is less dependent on the next consonant, don't merge consonant with next word options.textmode = 1 ; options.listx = 1 ; // compile zh_listx after zh_list setLanguage ( L('z','h') ) ; } void N::SpeechTranslator::SelectZHY(void) { Setup ( stress_lengths_zh , stress_amps_zh ) ; options.stressRule = STRESSPOSN_1R ; // stress on final syllable of a "word" options.stressFlags = S_NO_DIM ; // don't automatically set diminished stress (may be set in the intonation module) options.vowelPause = 0 ; options.toneLanguage = 1 ; // Tone language, use CalcPitches_Tone() rather than CalcPitches() options.lengthMods0 = options.lengthMods ; // don't lengthen vowels in the last syllable options.toneNumbers = 1 ; // a number after letters indicates a tone number (eg. pinyin or jyutping) options.ideographs = 1 ; options.ourAlphabet = 0x3100 ; options.wordGap = 0x21 ; // length of a final vowel is less dependent on the next consonant, don't merge consonant with next word setLanguage ( L_zhy ) ; } void N::SpeechTranslator::Reset(void) { int ix ; ///////////////////////////////////////////////////////////////// charsetA0 = charsets[1] ; // ISO-8859-1, this is for when the input is not utf8 dictionaryName[0] = 0 ; dictCondition = 0 ; dictMinSize = 0 ; dictSkipWords = 0 ; dataDictRules = NULL ; // language_1 translation rules file dataDictList = NULL ; // language_2 dictionary lookup file transposeMin = 0x60 ; transposeMax = 0x17f ; transposeMap = transpose_map_latin ; frequentPairs = NULL ; letterBitsOffset = 0 ; ::memset ( letterBits , 0 , sizeof(char ) * 256 ) ; ::memset ( wLetterGroups , 0 , sizeof(wchar_t) * 8 ) ; // 0-6 sets of characters matched by A B C H F G Y in pronunciation rules // these may be set differently for different languages setLetterBits ( 0 , "aeiou" ) ; // A vowels, except y setLetterBits ( 1 , "bcdfgjklmnpqstvxz" ) ; // B hard consonants, excluding h,r,w setLetterBits ( 2 , "bcdfghjklmnpqrstvwxz" ) ; // C all consonants setLetterBits ( 3 , "hlmnr" ) ; // H 'soft' consonants setLetterBits ( 4 , "cfhkpqstx" ) ; // F voiceless consonants setLetterBits ( 5 , "bdgjlmnrvwyz" ) ; // G voiced setLetterBits ( 6 , "eiy" ) ; // Letter group Y, front vowels setLetterBits ( 7 , "aeiouy" ) ; // vowels, including y charPlusApostrophe = empty_wstring ; punctWithinWord = punct_in_word ; charsIgnore = chars_ignore_default ; ///////////////////////////////////////////////////////////////// for ( ix = 0 ; ix < 8 ; ix++ ) { stressAmps [ix] = stress_amps2 [ix] ; stressAmpsR [ix] = stress_amps2 [ix] - 1 ; stressLengths [ix] = stress_lengths2 [ix] ; } ; ///////////////////////////////////////////////////////////////// options.maxLengthMod = 500 ; options.lengthenTonic = 20 ; options.stressRule = STRESSPOSN_2R ; options.unstressedWD1 = 1 ; options.unstressedWD2 = 3 ; options.param [ LOPT_SONORANT_MIN ] = 95 ; options.param [ LOPT_LONG_VOWEL_THRESHOLD ] = 190/2 ; options.param [ LOPT_MAXAMP_EOC ] = 19 ; options.param [ LOPT_UNPRONOUNCABLE ] = 's' ; // don't count this character at start of word options.param [ LOPT_BRACKET_PAUSE ] = 4 ; // pause at bracket options.param2 [ LOPT_BRACKET_PAUSE ] = 2 ; // pauses when announcing bracket names options.maxInitialConsonants = 3 ; options.replaceChars = NULL ; options.asciiLanguage[0] = 0 ; // Non-Latin alphabet languages, use this language to speak Latin words, default is English options.altAlphabetLanguage = L('e','n') ; ///////////////////////////////////////////////////////////////// setLengthMods ( 201 ) ; options.longStop = 100 ; options.maxRoman = 49 ; options.minRoman = 2 ; options.thousandsSep = ',' ; options.decimalSep = '.' ; options.breakNumbers = BREAK_THOUSANDS ; // 1000, 1000,000 1,000,000 etc options.maxDigits = 14 ; ::memcpy ( punctToTone ,punctuation_to_tone,sizeof(char)*8*6 ) ; ::memcpy ( options.tunes,default_tunes ,sizeof(char)*6 ) ; } void N::SpeechTranslator::setLetterVowel(int c) { // keep value for group 6 (front vowels e,i,y) letterBits[c] = (letterBits[c] & 0x40) | 0x81 ; } void N::SpeechTranslator::resetLetterBits(int groups) { unsigned int ix ; unsigned int mask = ~groups ; for ( ix = 0 ; ix < 256 ; ix++ ) { letterBits[ix] &= mask ; } ; } void N::SpeechTranslator::setLetterBits(int group,const char * string) { int bits = (1L << group) ; unsigned char c ; while ( ( c = *string++ ) != 0) { letterBits [ c ] |= bits ; } ; } void N::SpeechTranslator::setLetterBitsRange(int group,int first,int last) { int bits = (1L << group) ; int ix ; for ( ix = first ; ix <= last ; ix++ ) { letterBits[ix] |= bits ; } ; } void N::SpeechTranslator::setLengthMods(int value) { int value2 = ( value % 100 ) ; options.lengthMods = length_mod_tabs[value2] ; options.lengthMods0 = length_mod_tabs[value2] ; if ( ( value2 = ( value / 100 ) ) != 0) { options.lengthMods0 = length_mod_tabs[value2] ; } ; } void N::SpeechTranslator::setCyrillicLetters(void) { // character codes offset by 0x420 charsetA0 = charsets[18] ; // KOI8-R transposeMin = 0x430 ; // convert cyrillic from unicode into range 0x01 to 0x22 transposeMax = 0x451 ; transposeMap = NULL ; frequentPairs = pairs_ru ; letterBitsOffset = OFFSET_CYRILLIC ; memset ( letterBits , 0 , sizeof(char) * 256 ) ; setLetterBits ( LETTERGP_A , (char *)ru_vowels ) ; setLetterBits ( LETTERGP_B , ru_soft ) ; setLetterBits ( LETTERGP_C , (char *)ru_consonants ) ; setLetterBits ( LETTERGP_H , ru_hard ) ; setLetterBits ( LETTERGP_F , ru_nothard ) ; setLetterBits ( LETTERGP_G , ru_voiced ) ; setLetterBits ( LETTERGP_Y , ru_ivowels ) ; setLetterBits ( LETTERGP_VOWEL2 ,(char *)ru_vowels ) ; } void N::SpeechTranslator::setIndicLetters(void) { memset ( letterBits , 0 , sizeof(char) * 256 ) ; setLetterBitsRange ( LETTERGP_A , 0x04 , 0x14 ) ; // vowel letters setLetterBitsRange ( LETTERGP_A , 0x3e , 0x4d ) ; // + vowel signs, and virama setLetterBits ( LETTERGP_A , dev_vowels2 ) ; // + extra vowels and vowel signs setLetterBitsRange ( LETTERGP_B , 0x3e , 0x4d ) ; // vowel signs, and virama setLetterBits ( LETTERGP_B , dev_vowels2 ) ; // + extra vowels and vowel signs setLetterBitsRange ( LETTERGP_C , 0x15 , 0x39 ) ; // the main consonant range setLetterBits ( LETTERGP_C , dev_consonants2 ) ; // + additional consonants setLetterBitsRange ( LETTERGP_Y , 0x04 , 0x14 ) ; // vowel letters setLetterBitsRange ( LETTERGP_Y , 0x3e , 0x4c ) ; // + vowel signs setLetterBits ( LETTERGP_Y , dev_vowels2 ) ; // + extra vowels and vowel signs options.param[LOPT_UNPRONOUNCABLE] = 1 ; // disable check for unpronouncable words options.suffixAddE = letterBitsOffset + 0x4d ; //virama } void N::SpeechTranslator::Setup(const short * lengths,const unsigned char * amps) { if ( NotNull ( lengths ) ) { ::memcpy ( stressLengths , lengths , sizeof(short) * 8 ) ; } ; if ( NotNull ( amps ) ) { ::memcpy ( stressAmps , amps , sizeof(char ) * 8 ) ; } ; } int N::SpeechTranslator::isLetterGroup(char * word,int group,int pre) { // match the word against a list of utf-8 strings char * p ; char * w ; int len = 0 ; ////////////////////////////////////////////// p = letterGroups[group] ; if ( p == NULL ) return 0 ; while ( (*p) != RULE_GROUP_END) { if ( pre ) { len = strlen(p) ; w = word - len + 1 ; } else w = word ; while ( ( (*p) == (*w) ) && ( (*w) != 0) ) { w++ ; p++ ; } ; if ( (*p) == 0) { if ( pre ) return len ; return ( w - word ) ; // matched a complete string } ; while ( *p++ != 0) ; // skip to end of string } ; return 0 ; } bool N::SpeechTranslator::isLetter(int letter,int group) { int letter2; if ( NotNull(wLetterGroups[group])) { if ( wcschr ( wLetterGroups[group] , letter ) ) return true ; return false ; } ; if ( group > 7 ) return false ; if ( letterBitsOffset > 0) { letter2 = letter - letterBitsOffset ; if ( ( letter2 > 0) && (letter2 < 0x100) ) letter = letter2 ; else return false ; } else { if ( ( letter >= 0xc0 ) && ( letter < N_REMOVE_ACCENT ) ) { unsigned char lb ; lb = letterBits [ remove_accent [ ( letter - 0xc0 ) ] ] ; lb &= ( 1L << group ) ; return ( lb != 0 ) ; } ; } ; if ( ( letter >= 0 ) && ( letter < 0x100 ) ) { unsigned char lb = letterBits[letter] ; lb &= ( 1L << group ) ; return ( lb != 0 ) ; } ; return false ; } bool N::SpeechTranslator::isVowel(int letter) { return isLetter ( letter , LETTERGP_VOWEL2 ) ; } int N::SpeechTranslator::toUtf8(unsigned int c,char * buf) { static char unsigned code[4] = {0,0xc0,0xe0,0xf0} ; int n_bytes ; int shift ; /////////////////////////////////////////////////// if ( c < 0x80 ) { buf[0] = c ; return 1 ; } ; /////////////////////////////////////////////////// if ( c >= 0x110000 ) { buf[0] = ' ' ; return 1 ; } ; /////////////////////////////////////////////////// if ( c < 0x00800) n_bytes = 1 ; else if ( c < 0x10000) n_bytes = 2 ; else n_bytes = 3 ; /////////////////////////////////////////////////// shift = 6 * n_bytes ; buf[0] = code [ n_bytes ] | ( c >> shift ) ; for (int j = 0 ; j < n_bytes ; j++ ) { shift -= 6 ; buf[j+1] = 0x80 + ( ( c >> shift ) & 0x3f ) ; } ; /////////////////////////////////////////////////// return ( n_bytes + 1 ) ; } int N::SpeechTranslator::toGrapheme(int & grapheme,const char * buf,bool backward) { int c1 ; int bytes = 0 ; static const unsigned char mask[4] = {0xff,0x1f,0x0f,0x07} ; // find the start of the next/previous character while ( ( (*buf) & 0xc0) == 0x80) { // skip over non-initial bytes of a multi-byte utf8 character if (backward) buf-- ; else buf++ ; } ; if ( (c1 = *buf++) & 0x80 ) { if ( ( c1 & 0xe0 ) == 0xc0 ) bytes = 1 ; else if ( ( c1 & 0xf0 ) == 0xe0 ) bytes = 2 ; else if ( ( c1 & 0xf8 ) == 0xf0 ) bytes = 3 ; c1 &= mask[bytes] ; for (int i = 0 ; i < bytes ; i++ ) { c1 = (c1 << 6) + ( (*buf++) & 0x3f) ; } ; } ; grapheme = c1 ; return ( bytes + 1 ) ; } int N::SpeechTranslator::nBytes(unsigned char c) { if ( c < 0x80 ) return 1 ; if ( c < 0xe0 ) return 2 ; if ( c < 0xf0 ) return 3 ; return 4 ; } void N::SpeechTranslator::setSpellingStress(char * phonemes,int control,int chars) { // Individual letter names, reduce the stress of some. int ix ; unsigned int c ; int n_stress = 0 ; int prev = 0 ; int count ; unsigned char buf [ 200 ] ; /////////////////////////////////////////////////////////////////// for ( ix = 0 ; ( c = phonemes[ix] ) != 0 ; ix++ ) { if ( ( c == Speak::PcStressP ) && ( prev != Speak::PcSwitch ) ) n_stress++ ; buf [ ix ] = prev = c ; } ; buf [ ix ] = 0 ; count = 0 ; prev = 0 ; for ( ix = 0 ; ( c = buf[ix] ) != 0 ; ix++ ) { if ( ( c == Speak::PcStressP ) && ( chars > 1 ) && ( prev != Speak::PcSwitch ) ) { count++ ; if ( options.spellingStress == 1 ) { // stress on initial letter when spelling if ( count > 1 ) c = Speak::PcStress3 ; } else { if ( count != n_stress ) { if ( ( ( count % 3 ) != 0) || ( count == n_stress-1 ) ) { c = Speak::PcStress3 ; // reduce to secondary stress } ; } ; } ; } else if ( c == 0xff ) { if ( ( control < 2 ) || ( ix == 0 ) ) continue ; // don't insert pauses if ( control == 4) c = Speak::PcPause ; // pause after each character if ( ( ( count % 3 ) == 0 ) || ( control > 2 ) ) { c = Speak::PcPauseNoLink ; // pause following a primary stress } else c = Speak::PcPauseVShort ; } ; *phonemes++ = prev = c ; } ; if ( control >= 2 ) *phonemes++ = Speak::PcPauseNoLink ; *phonemes = 0 ; } int N::SpeechTranslator::RemoveEnding(char * word,int endType,char * wordCopy) { int i ; int len ; int len_ending ; int end_flags ; char * word_end ; const char * p ; char ending[12] ; ///////////////////////////////////////////////////////////////////////////// // static const char * add_e_additions [] = {"c", "rs", "ir", "ur", "ath", "ns", "lu", NULL } ; static const char * add_e_additions [] = {"c", "rs", "ir", "ur", "ath", "ns", "u", NULL } ; static const char * add_e_exceptions [] = { "ion", NULL } ; ///////////////////////////////////////////////////////////////////////////// for ( word_end = word ; *word_end != ' ' ; word_end++ ) { if(*word_end == REPLACED_E) *word_end = 'e' ; } ; i = word_end - word ; if ( NotNull(wordCopy) ) { memcpy(wordCopy,word,i) ; wordCopy[i] = 0 ; } ; ///////////////////////////////////////////////////////////////////////////// for ( len_ending = i = (endType & 0x3f) ; i>0 ; i-- ) { word_end-- ; while ( ( (*word_end) & 0xc0 ) == 0x80 ) { word_end-- ; len_ending++ ; } ; } ; ///////////////////////////////////////////////////////////////////////////// for ( i=0 ; i < len_ending ; i++ ) { ending [i] = word_end[i] ; word_end[i] = ' ' ; } ; ending[i] = 0 ; word_end -- ; end_flags = (endType & 0xfff0) | FLAG_SUFX ; if ( endType & SUFX_I ) { if ( word_end[0] == 'i' ) word_end[0] = 'y' ; } ; ///////////////////////////////////////////////////////////////////////////// if ( endType & SUFX_E ) { if (translatorName == L('n','l')) { if ( ( ( word_end[ 0] & 0x80 ) == 0 ) && ( ( word_end[-1] & 0x80 ) == 0 ) && isVowel ( word_end [-1] ) && isLetter ( word_end [ 0] , LETTERGP_C ) && !isVowel ( word_end [-2] ) ) { word_end [ 1 ] = word_end [ 0 ] ; word_end [ 0 ] = word_end [ -1 ] ; word_end [ 2 ] = ' ' ; } ; } else if ( translatorName == L('e','n')) { if ( isLetter ( word_end [ -1 ] , LETTERGP_VOWEL2 ) && isLetter ( word_end [ 0 ] , 1 ) ) { for ( i = 0 ; ( p = add_e_exceptions[i] ) != NULL ; i++ ) { len = strlen(p) ; if ( memcmp ( p , &word_end[1-len] , len ) == 0 ) break ; } ; if ( IsNull(p) ) end_flags |= FLAG_SUFX_E_ADDED ; } else { for ( i = 0 ; ( p = add_e_additions [i] ) != NULL ; i++ ) { len = strlen(p) ; if ( memcmp ( p , &word_end[1-len] , len ) == 0 ) { end_flags |= FLAG_SUFX_E_ADDED ; break ; } ; } ; } ; } else if ( options.suffixAddE != 0) end_flags |= FLAG_SUFX_E_ADDED ; /////////////////////////////////////////////////////////////////////////// if ( end_flags & FLAG_SUFX_E_ADDED ) { toUtf8 ( options.suffixAddE , &word_end[1] ) ; #ifdef ___NOT_YES_READY_PLEASE_REMOVE_THIS_AFTER_FINISHED__ if ( optionPhonemes == 2) { fprintf(f_trans,"add e\n") ; } ; #endif } ; } ; ///////////////////////////////////////////////////////////////////////////// if ( ( endType & SUFX_V) && ( expectVerb == 0 ) ) expectVerb = 1 ; if ( ( strcmp(ending,"s")==0) || (strcmp(ending,"es")==0)) { end_flags |= FLAG_SUFX_S ; } ; if ( ending[0] == '\'' ) end_flags &= ~FLAG_SUFX ; return end_flags ; } int N::SpeechTranslator::Hash(const char * string) { int c ; int chars = 0 ; int hash = 0 ; ////////////////////////////////////////// while ( ( c = (*string++ & 0xff)) != 0 ) { hash = (hash * 8 ) + c ; hash = (hash & 0x3ff) ^ (hash >> 8) ; /* exclusive or */ chars++ ; } ; return ( ( hash + chars ) & 0x3ff ) ; // a 10 bit hash code } bool N::SpeechTranslator::is(QString name) { QString D = QString(dictionaryName) ; return ( D.toLower() == name.toLower() ) ; } void N::SpeechTranslator::Install(QString name) { ::memset(dictionaryName,0,40 ) ; ::strcpy(dictionaryName,name.toUtf8().data()) ; } bool N::SpeechTranslator::Load(void) { if (dataDictList.size()<=0) return false ; /////////////////////////////////////////////////////////// int * pw = (int *)dataDictList.data() ; int length = pw[1] ; if ( dataDictList.size()<=(N_HASH_DICT + sizeof(int)*2) ) { return false ; } ; if ( pw[0] != N_HASH_DICT ) return false ; if ( length <= 0 ) return false ; if ( length > 0x8000000 ) return false ; dataDictRules = & dataDictList.data() [ length ] ; /////////////////////////////////////////////////////////// SetupRules ( ) ; int hash ; char * p = & dataDictList .data() [ 8 ] ; for ( hash = 0 ; hash < N_HASH_DICT ; hash++ ) { dictHashTab[hash] = p ; while ( ( length = *p ) != 0 ) p += length ; p++ ; } ; /////////////////////////////////////////////////////////// return true ; } // Called after dictionary 1 is loaded, to set up table of entry points // for translation rule chains for single-letters and two-letter combinations void N::SpeechTranslator::SetupRules(void) { int ix ; char * p ; char * p_name ; unsigned int * pw ; unsigned char c ; unsigned char c2 ; int len ; ////////////////////////////////////////////////////// nGroups2 = 0 ; for ( ix = 0 ; ix < 256 ; ix++ ) { groups1 [ ix ] = NULL ; groups2Count [ ix ] = 0 ; groups2Start [ ix ] = 255 ; // indicates "not set" } ; ////////////////////////////////////////////////////// ::memset ( letterGroups , 0 , sizeof(char) * 95 ) ; ::memset ( groups3 , 0 , sizeof(char) * 128 ) ; ////////////////////////////////////////////////////// p = dataDictRules ; while ( (*p) != 0) { if ( (*p) != RULE_GROUP_START) break ; //////////////////////////////////////////////////// p++ ; if ( p[0] == RULE_REPLACEMENTS) { pw = (unsigned int *)(((unsigned long)p+4) & ~3) ; // advance to next word boundary options.replaceChars = pw ; while ( pw[0] != 0 ) pw += 2 ; // find the end of the replacement list, each entry is 2 words. p = (char *)(pw+1) ; continue ; } ; //////////////////////////////////////////////////// if ( p[0] == RULE_LETTERGP2 ) { ix = p[1] - 'A' ; p += 2 ; if ( ( ix >= 0 ) && ( ix < N_LETTER_GROUPS ) ) { letterGroups[ix] = p ; } ; } else { len = strlen(p) ; p_name = p ; c = p_name[0] ; c2 = p_name[1] ; p += (len+1) ; if ( len == 1 ) groups1 [ c ] = p ; else if ( len == 0 ) groups1 [ 0 ] = p ; else // index by offset from letter base if ( c == 1 ) groups3 [ c2 - 1 ] = p ; else { if ( groups2Start[c] == 255 ) { groups2Start[c] = nGroups2 ; } ; groups2Count[ c ]++ ; groups2 [ nGroups2 ] = p ; groups2Name [ nGroups2 ] = ( c + ( c2 << 8 ) ) ; nGroups2++ ; } ; } ; // skip over all the rules in this group while ( (*p) != RULE_GROUP_END) { p += ( strlen(p) + 1 ) ; } ; p++ ; } ; } bool N::SpeechTranslator::StressCondition ( PhonemeLists & list , int condition , int control , bool translator ) // condition: // 0 if diminished // 1 if unstressed // 2 if not stressed // 3 if stressed // 4 if max stress { static int condition_level [ 4 ] = {1,2,4,15} ; int stress_level ; int phcode ; int index = 0 ; ////////////////////////////////////////////////////////// phcode = list[0]->phcode ; if ( phonemes[phcode]->Type == Speak::VOWEL ) { index = 0 ; } else { // consonant, get stress from the following vowel phcode = list[1]->phcode ; if ( phonemes[phcode]->Type == Speak::VOWEL ) { index = 1 ; } else return false ; } ; ////////////////////////////////////////////////////////// stress_level = list[index]->stresslevel & 0x0f ; if ( translator ) { if ( ( control & 1 ) && ( list[0]->synthflags & SFLAG_DICTIONARY) && // ??? questionable ( ( options.param[LOPT_REDUCE] & 1 ) == 0 ) ) { return false ; } ; if ( ( options.param[LOPT_REDUCE] & 0x2) && ( stress_level >= list[index]->wordstress ) ) { // treat the most stressed syllable in an unstressed word as stressed stress_level = 4 ; } ; } ; ////////////////////////////////////////////////////////// if ( condition == 4 ) { return ( stress_level >= list[0]->wordstress ) ; } ; if ( condition == 3 ) { // if stressed if ( stress_level > 3 ) return true ; } else { if ( stress_level < condition_level[condition]) { return true ; } ; } ; return false ; } void N::SpeechTranslator::PitchesTone(PhonemeLists & list) { // clause_tone: 0=. 1=, 2=?, 3=! 4=none int ix ; int count_stressed = 0 ; int final_stressed = 0 ; int tone_ph ; int pause ; int tone_promoted ; int tph ; int prev_tph ; int prevw_tph ; int prev_p ; int pitch_adjust = 0 ; // pitch gradient through the clause - inital value int pitch_decrement = 0 ; // decrease by this for each stressed syllable int pitch_low = 0 ; // until it drops to this int pitch_high = 0 ; // then reset to this // count number of stressed syllables for (int i=0;i<list.count();i++) { if ((list[i]->type==Speak::VOWEL) && (list[i]->stresslevel >= 4)) { if ( count_stressed == 0 ) final_stressed = i ; if ( list[i]->stresslevel >= 4) { final_stressed = i ; count_stressed++ ; } ; } ; } ; ///////////////////////////////////////////////////////////////////////////// list[final_stressed]->stresslevel = 7 ; // language specific, changes to tones if ( translatorName == L('v','i')) { // LANG=vi if ( list[final_stressed]->tone_ph == 0 ) { list[final_stressed]->tone_ph = phonemes.Code('7') ; // change default tone (tone 1) to falling tone at end of clause } ; } ; ///////////////////////////////////////////////////////////////////////////// pause = 1 ; tone_promoted = 0 ; ix = 0 ; prev_p = 0 ; prev_tph = Speak::PcPause ; prevw_tph = Speak::PcPause ; ///////////////////////////////////////////////////////////////////////////// // perform tone sandhi for (int i = 0 ; i < list.count() ; i++, ix++) { if ( (list[ix]->type == Speak::PAUSE) && (list[ix]->ph->Length > 50) ) { // there is a pause since the previous vowel pause = 1 ; prevw_tph = Speak::PcPause ; // forget previous tone } ; /////////////////////////////////////////////////////////////////////////// // forget across word boundaries if ( list[ix]->newword ) prev_tph = Speak::PcPause ; if ( list[ix]->synthflags & SFLAG_SYLLABLE) { tone_ph = list[ix]->tone_ph ; tph = tone_ph ; // Mandarin if ( translatorName == L('z','h') ) { if ( tone_ph == 0 ) { if ( pause || tone_promoted ) { tone_ph = phonemes.Code('5','5') ; // no previous vowel, use tone 1 tone_promoted = 1 ; } else { tone_ph = phonemes.Code('1','1') ; // default tone 5 } ; list[ix]->tone_ph = tone_ph ; tph = tone_ph ; } else tone_promoted = 0 ; /////////////////////////////////////////////////////////////////////// if ( i == final_stressed ) { if ( ( phonemes[tph]->Mnemonic == 0x3535 ) || ( phonemes[tph]->Mnemonic == 0x3135 ) ) { // change sentence final tone 1 or 4 to stress 6, not 7 list[final_stressed]->stresslevel = 6 ; } ; } ; /////////////////////////////////////////////////////////////////////// if ( phonemes[prevw_tph]->Mnemonic == 0x343132 ) { // [214] if ( phonemes[tph]->Mnemonic == 0x343132) { // [214] list[prev_p]->tone_ph = phonemes.Code('3','5') ; } else { list[prev_p]->tone_ph = phonemes.Code('2','1') ; } ; } ; if ( ( phonemes[prev_tph]->Mnemonic == 0x3135) && ( phonemes[tph ]->Mnemonic == 0x3135) ) { // [51] + [51] list[prev_p]->tone_ph = phonemes.Code('5','3') ; } ; /////////////////////////////////////////////////////////////////////// if ( phonemes[tph]->Mnemonic == 0x3131) { // [11] Tone 5 // tone 5, change its level depending on the previous tone (across word boundaries) if ( phonemes[prevw_tph]->Mnemonic == 0x3535) { list[ix]->tone_ph = phonemes.Code('2','2') ; } ; if ( phonemes[prevw_tph]->Mnemonic == 0x3533) { list[ix]->tone_ph = phonemes.Code('3','3') ; } ; if ( phonemes[prevw_tph]->Mnemonic == 0x343132) { list[ix]->tone_ph = phonemes.Code('4','4') ; } ; // tone 5 is unstressed (shorter) list[ix]->stresslevel = 0 ; // diminished stress } ; } ; ///////////////////////////////////////////////////////////////////////// prev_p = ix ; prevw_tph = prev_tph = tph ; pause = 0 ; } ; } ; ///////////////////////////////////////////////////////////////////////////// // convert tone numbers to pitch for (int i = 0 ; i < list.count() ; i++ ) { if (list[i]->synthflags & SFLAG_SYLLABLE) { tone_ph = list[i]->tone_ph ; if ( list[i]->stresslevel != 0 ) { // TEST, consider all syllables as stressed if ( i == final_stressed ) { // the last stressed syllable pitch_adjust = pitch_low ; } else { pitch_adjust -= pitch_decrement ; if ( pitch_adjust <= pitch_low ) pitch_adjust = pitch_high ; } ; } ; if ( tone_ph ==0 ) { tone_ph = Speak::PcDefaultTone ; // no tone specified, use default tone 1 list[i]->tone_ph = tone_ph ; } ; list[i]->pitch1 = pitch_adjust + phonemes[tone_ph]->StartType ; list[i]->pitch2 = pitch_adjust + phonemes[tone_ph]->EndType ; } ; } ; } void N::SpeechTranslator::Pitches ( PhonemeLists & list , SpeechTune & tune , Syllables & syllables , int clauseType , int toneflags ) { // clause_type: 0=. 1=, 2=?, 3=! 4=none int ix ; int x ; int st_ix ; int n_st = 0 ; int option ; int group_tone ; int group_tone_emph ; int group_tone_comma ; int ph_start = 0 ; int st_start ; int st_clause_end ; int count ; int n_primary = 0 ; int count_primary ; int ph_end = list.count() ; //////////////////////////////////////////////////////////////////////// for ( ix = 0 ; ix < ( list.count() - 1 ) ; ix++ ) { if ( list[ix]->synthflags & SFLAG_SYLLABLE) { Syllable * syllable ; syllable = new Syllable ( ) ; syllables << syllable ; syllables[n_st]->Flags = 0 ; syllables[n_st]->Envelope = PITCHfall ; syllables[n_st]->NextPhoneme = list[ix]->type ; syllables[n_st]->Stress = list[ix]->stresslevel ; n_st++ ; if ( list[ix]->stresslevel >= 4 ) n_primary++ ; } else if ( (list[ix]->ph->Code == Speak::PcPauseClause) && ( n_st > 0 ) ) { syllables[n_st-1]->Flags |= SYL_END_CLAUSE ; } ; } ; //////////////////////////////////////////////////////////////////////// syllables[n_st]->Stress = 0 ; // extra 0 entry at the end if ( n_st == 0 ) return ; // nothing to do //////////////////////////////////////////////////////////////////////// if ( options.toneLanguage == 1) { PitchesTone ( list ) ; return ; } ; //////////////////////////////////////////////////////////////////////// option = options.intonationGroup ; if ( option >= 8 ) option = 1 ; if ( option == 0 ) { group_tone = options . tunes [ clauseType ] ; group_tone_emph = options . tunes [ 5 ] ; group_tone_comma = options . tunes [ 1 ] ; } else { group_tone = punctToTone[option][clauseType] ; group_tone_emph = punctToTone[option][5 ] ; // emphatic form of statement group_tone_comma = punctToTone[option][1 ] ; // emphatic form of statement } ; //////////////////////////////////////////////////////////////////////// /* incomplete clause, used for abbreviations such as Mr. Dr. Mrs. */ if ( clauseType == 4 ) syllables.NoTonic = 1 ; else syllables.NoTonic = 0 ; //////////////////////////////////////////////////////////////////////// st_start = 0 ; count_primary = 0 ; for ( st_ix = 0; st_ix < n_st ; st_ix++ ) { if ( syllables[st_ix]->Stress >= 4 ) count_primary++ ; if ( syllables[st_ix]->Stress == 6 ) { // reduce the stress of the previous stressed syllable (review only the previous few syllables) for ( ix = st_ix - 1 ; ix >= st_start && ix >= (st_ix-3) ; ix-- ) { if ( syllables[ix]->Stress == 6 ) break ; if ( syllables[ix]->Stress == 4 ) { syllables[ix]->Stress = 3 ; break ; } ; } ; // are the next primary syllables also emphasized ? for ( ix = st_ix + 1 ; ix < n_st ; ix++ ) { if ( syllables[ix]->Stress == 4 ) break ; if ( syllables[ix]->Stress == 6 ) { // emphasize this syllable, but don't end the current tone group syllables[st_ix]->Flags = SYL_EMPHASIS ; syllables[st_ix]->Stress = 5 ; break ; } ; } ; } ; if ( syllables[st_ix]->Stress == 6 ) { // an emphasized syllable, end the tone group after the next primary stress syllables[st_ix]->Flags = SYL_EMPHASIS ; count = 0 ; if ( ( n_primary - count_primary ) > 1 ) count = 1 ; for ( ix = st_ix + 1 ; ix < n_st ; ix++ ) { if ( syllables[ix]->Stress > 4 ) break ; if ( syllables[ix]->Stress == 4 ) { count++ ; if ( count > 1 ) break ; } ; } ; syllables.PitchVowels(st_start,ix,n_st) ; if ( ( ix < n_st ) || ( clauseType == 0 ) ) { tune . Pitches ( syllables , st_start , ix , option , group_tone_emph , toneflags ) ; } else { tune . Pitches ( syllables , st_start , ix , option , group_tone , toneflags ) ; } ; st_start = ix ; } ; if ( ( st_start < st_ix ) && ( syllables[st_ix]->Flags & SYL_END_CLAUSE ) ) { // end of clause after this syllable, indicated by a phonPAUSE_CLAUSE phoneme st_clause_end = st_ix + 1 ; syllables.PitchVowels(st_start,st_clause_end,st_clause_end) ; tune . Pitches ( syllables , st_start , st_clause_end , option , group_tone_comma , toneflags ) ; st_start = st_clause_end ; } ; } ; //////////////////////////////////////////////////////////////////////// if ( st_start < st_ix ) { syllables . PitchVowels ( st_start , st_ix , n_st ) ; tune . Pitches ( syllables , st_start , st_ix , option , group_tone , toneflags ) ; } ; //////////////////////////////////////////////////////////////////////// // unpack pitch data st_ix = 0 ; for ( ix = ph_start ; ix < ph_end ; ix++ ) { list[ix]->stresslevel = syllables[st_ix]->Stress ; if ( list[ix]->synthflags & SFLAG_SYLLABLE) { list[ix]->pitch1 = syllables[st_ix]->Pitch1 ; list[ix]->pitch2 = syllables[st_ix]->Pitch2 ; list[ix]->envelope = PITCHfall ; if ( syllables[st_ix]->Flags & SYL_RISE ) { list[ix]->envelope = PITCHrise ; } else if (list[ix]->stresslevel > 5) { list[ix]->envelope = syllables[st_ix]->Envelope ; } ; if (list[ix]->pitch1 > list[ix]->pitch2) { // swap so that pitch2 is the higher x = list[ix]->pitch1 ; list[ix]->pitch1 = list[ix]->pitch2 ; list[ix]->pitch2 = x ; } ; if ( list[ix]->tone_ph ) { x = ( list[ix]->pitch1 + list[ix]->pitch2 ) / 2 ; list[ix]->pitch1 = x + phonemes[list[ix]->tone_ph]->StartType ; list[ix]->pitch2 = x + phonemes[list[ix]->tone_ph]->EndType ; } ; if (syllables[st_ix]->Flags & SYL_EMPHASIS) { list[ix]->stresslevel |= 8 ; // emphasized } ; st_ix++ ; } ; } ; } int N::SpeechTranslator::isspace2(unsigned int c) { // can't use isspace() because on Windows, isspace(0xe1) gives TRUE ! int c2 ; if ( ( ( c2 = (c & 0xff) ) == 0) || ( c > ' ' ) ) return 0 ; return 1 ; } int N::SpeechTranslator::iswalpha2(int c) { if ( c < 0x80 ) return isalpha ( c ) ; if ( ( c > 0x3040 ) && ( c <= 0xa700 ) ) return 1 ; // japanese, chinese characters if ( c > MAX_WALPHA ) return iswalpha ( c ) ; return ( walpha_tab [ c - 0x80 ] ) ; } int N::SpeechTranslator::iswlower2(int c) { if ( c < 0x80 ) return islower (c) ; if ( c > MAX_WALPHA ) return iswlower(c) ; if ( walpha_tab[c-0x80] == 0xff ) return true ; return false ; } int N::SpeechTranslator::iswupper2(int c) { int x; if ( c < 0x80 ) return isupper (c) ; if ( c > MAX_WALPHA ) return iswupper(c) ; if ( ( ( x = walpha_tab[c-0x80] ) > 0) && ( x < 0xfe ) ) return 1 ; return 0 ; } int N::SpeechTranslator::towlower2(unsigned int c) { int x ; int ix ; // check for non-standard upper to lower case conversions if ( c == 'I' ) { if ( options.dotlessI ) c = 0x131 ; // I -> ı } ; if ( c < 0x80 ) return tolower (c) ; if ( c > MAX_WALPHA ) return towlower(c) ; if ( ( x = walpha_tab[c-0x80] ) >= 0xfe ) return c ; // this is not an upper case letter if ( x == 0xfd ) { // special cases, lookup translation table for ( ix = 0 ; wchar_tolower[ix] != 0 ; ix+=2 ) { if ( wchar_tolower[ix] == (int)c ) { return ( wchar_tolower [ ix + 1 ] ) ; } ; } ; } ; return ( c + x ) ; // convert to lower case } int N::SpeechTranslator::towupper2(unsigned int c) { int ix; if ( c > MAX_WALPHA ) return ( towupper(c) ) ; // check whether a previous character code is the upper-case equivalent of this character if ( towlower2(c-32) == (int)c ) return ( c - 32 ) ; // yes, use it if ( towlower2(c- 1) == (int)c ) return ( c - 1 ) ; for ( ix = 0 ; wchar_toupper[ix] != 0 ; ix+=2 ) { if ( wchar_toupper[ix] == (int)c ) { return ( wchar_toupper [ ix + 1 ] ) ; } ; } ; return c ; // no } int N::SpeechTranslator::IsRomanU(unsigned int c) { if ( (c=='I') || (c=='V') || (c=='X') || (c=='L') ) return 1 ; return 0 ; } int N::SpeechTranslator::lookupwchar(const unsigned short *list,int c) { // Is the character c in the list ? int ix ; for ( ix = 0 ; list[ix] != 0 ; ix++ ) { if ( list [ ix ] == c ) return ( ix + 1 ) ; } ; return 0 ; } int N::SpeechTranslator::lookupwchar2(const unsigned short * list,int c) { // Replace character c by another character. // Returns 0 = not found, 1 = delete character int ix ; for ( ix = 0 ; list[ix] != 0 ; ix+=2 ) { if ( list [ ix ] == c ) return ( list [ ix + 1 ] ) ; } ; return 0 ; } int N::SpeechTranslator::IsBracket(int c) { if ( ( c >= 0x2014 ) && ( c <= 0x201f ) ) return 1 ; return lookupwchar ( brackets , c ) ; } int N::SpeechTranslator::IsAlpha(unsigned int c) { // Replacement for iswalph() which also checks for some in-word symbols static const unsigned short extra_indic_alphas[] = { 0xa70 , 0xa71 , // Gurmukhi: tippi, addak 0 } ; if ( iswalpha2(c) ) return 1 ; if ( c < 0x300 ) return 0 ; if ( ( c >= 0x901 ) && ( c <= 0xdf7 ) ) { // Indic scripts: Devanagari, Tamil, etc if ( ( c & 0x7f ) < 0x64 ) return 1 ; if ( lookupwchar(extra_indic_alphas,c)!=0 ) return 1 ; if ( ( c >= 0xd7a ) && ( c <= 0xd7f ) ) return 1 ; // malaytalam chillu characters return 0 ; } ; if ( ( c >= 0x5b0 ) && ( c <= 0x5c2 ) ) return 1 ; // Hebrew vowel marks if ( c == 0x0605) return 1 ; if ( ( c >= 0x64b ) && ( c <= 0x65e ) ) return 1 ; // arabic vowel marks if ( ( c >= 0x300 ) && ( c <= 0x36f ) ) return 1 ; // combining accents if ( ( c >= 0x780 ) && ( c <= 0x7b1 ) ) return 1 ; // taani/divehi (maldives) if ( ( c >= 0xf40 ) && ( c <= 0xfbc ) ) return 1 ; // tibetan if ( ( c >= 0x1100) && ( c <= 0x11ff ) ) return 1 ; //Korean jamo if ( ( c >= 0x2800) && ( c <= 0x28ff ) ) return 1 ; // braille if ( ( c > 0x3040) && ( c <= 0xa700 ) ) return 1 ; // Chinese/Japanese. Should never get here, but Mac OS 10.4's iswalpha seems to be broken, so just make sure return 0 ; } int N::SpeechTranslator::IsNumber(unsigned int c) { if ( ( c >= '0' ) && ( c <= '9' ) ) return 1 ; return 0 ; } int N::SpeechTranslator::IsDigit(unsigned int c) { if ( iswdigit(c) ) return 1 ; if ( ( c >= 0x966 ) && ( c <= 0x96f ) ) return 1 ; return 0 ; } int N::SpeechTranslator::IsSpace(unsigned int c) { if ( c == 0 ) return 0 ; if (( c >= 0x2500 ) && ( c < 0x25a0 ) ) return 1 ; // box drawing characters return iswspace(c) ; } int N::SpeechTranslator::IsAllUpper(const char * word) { int c ; while ( ( (*word) != 0 ) && !isspace2(*word) ) { word += toGrapheme(c,word) ; if ( !iswupper2(c) ) return 0 ; } ; return 1 ; } int N::SpeechTranslator::isHexDigit(int c) { if ( ( c >= '0' ) && ( c <= '9' ) ) return ( c - '0' ) ; if ( ( c >= 'a' ) && ( c <= 'f' ) ) return ( c - 'a' + 10 ) ; if ( ( c >= 'A' ) && ( c <= 'F' ) ) return ( c - 'A' + 10 ) ; return -1 ; } int N::SpeechTranslator::NonAsciiNumber(int letter) { // Change non-ascii digit into ascii digit '0' to '9', (or -1 if not) const int * p ; int base ; for ( p = number_ranges ; (base = *p) != 0 ; p++ ) { if ( letter < base ) break ; // not found if ( letter < (base+10) ) return (letter-base+'0') ; } ; return -1 ; } bool N::SpeechTranslator::thousandsGroup(const char * word,int groupLen) { // Is this a group of 3 digits which looks like a thousands group? if ( IsNumber(word[groupLen]) || IsNumber(-1) ) return false ; for (int i=0 ; i < groupLen ; i++) { if( ! IsNumber(word[i]) ) return false ; } ; return true ; } bool N::SpeechTranslator::IsNumberHuE(const char * word,int thousandplex,int value) { // lang-hu: variant form of numbers when followed by hyphen and a suffix starting with 'a' or 'e' (but not a, e, az, ez, azt, ezt, att. ett if ( ( word[0] == 'a' ) || ( word[0] == 'e' ) ) { if ( ( word[1] == ' ' ) || (word[1] == 'z') || ( ( word[1] == 't' ) && ( word[2] == 't' ) ) ) return false ; if ( ( ( thousandplex == 1 ) || ( ( value % 1000 ) == 0 ) ) && ( word[1] == 'l' ) ) return false ; // 1000-el return true ; } ; return false ; } char * N::SpeechTranslator::wstrchr(const char * s,int c) { if ( c >= 0x80 ) return NULL ; return strchr((char *)s,c) ; } int N::SpeechTranslator::Substitute ( unsigned int c , unsigned int next_in , int * insert , int * wordflags ) { #ifdef XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX int ix; unsigned int word; unsigned int new_c, c2, c_lower; int upper_case = 0; static int ignore_next = 0; const unsigned int *replace_chars; if(ignore_next) { ignore_next = 0; return(8); } if(c == 0) return(0); if((replace_chars = tr->langopts.replace_chars) == NULL) return(c); // there is a list of character codes to be substituted with alternative codes if(iswupper2(c_lower = c)) { c_lower = towlower2(c); upper_case = 1; } new_c = 0; for(ix=0; (word = replace_chars[ix]) != 0; ix+=2) { if(c_lower == (word & 0xffff)) { if((word >> 16) == 0) { new_c = replace_chars[ix+1]; break; } if((word >> 16) == (unsigned int)towlower2(next_in)) { new_c = replace_chars[ix+1]; ignore_next = 1; break; } } } if(new_c == 0) return(c); // no substitution if(new_c & 0xffe00000) { // there is a second character to be inserted // don't convert the case of the second character unless the next letter is also upper case c2 = new_c >> 16; if(upper_case && iswupper2(next_in)) c2 = towupper2(c2); *insert = c2; new_c &= 0xffff; } if(upper_case) new_c = towupper2(new_c); *wordflags |= FLAG_CHAR_REPLACED; return(new_c); #endif return 0 ; } bool N::SpeechTranslator::irishUpperCase(char * word,int c) { int len ; const char * p ; ////////////////////////////////////////////////// if ( translatorName != L('g','a') ) return false ; for (int i = 0 ; NotNull(UCase_ga[i]) ; i++ ) { p = UCase_ga[i] ; if (IsNull(p)) return false ; len = strlen ( p ) ; if ( ( word[-len]==' ' ) && ( memcmp(&word[-len+1], p, len-1) == 0)) { if ( ( c == p[len-1] ) || ( ( p[len-1]=='A' ) && isVowel(c) ) ) return true ; } ; } ; return false ; } wchar_t * N::SpeechTranslator::SsmlAttribute ( wchar_t * attr , wchar_t * pw , const char * name ) { // Gets the value string for an attribute. int ix ; attr[0] = 0 ; while ( (*pw) != 0) { if ( iswspace(pw[-1]) ) { ix = 0 ; while ( (*pw) == name[ix] ) { pw++ ; ix++ ; } ; if ( name[ix] == 0 ) { // found the attribute, now get the value while ( iswspace(*pw) ) pw++ ; if ( (*pw) == '=' ) pw++ ; while ( iswspace(*pw) ) pw++ ; if ( ( (*pw) == '"') || ( (*pw) == '\'')) return pw+1 ; else return attr ; } ; } ; pw++ ; } ; return NULL ; } int N::SpeechTranslator::VowelStress ( unsigned char * phs , signed char * vowel_stress , int & vowel_count , int & stressed_syllable , int control ) { // control = 1, set stress to 1 for forced unstressed vowels unsigned char phcode ; unsigned char * ph_out = phs ; int count = 1 ; int max_stress = -1 ; int ix ; int j ; int stress = -1 ; int primary_posn = 0 ; // PHONEME_TAB *ph; //////////////////////////////////////////////////////////////////////// vowel_stress[0] = 1 ; while ( ( ( phcode = *phs++ ) != 0 ) && ( count < ( N_WORD_PHONEMES / 2 ) - 1 ) ) { if ( ! phonemes.contains(phcode) ) continue ; if ( ( phonemes[phcode]->Type == Speak::STRESS ) && ( phonemes[phcode]->Program == 0 ) ) { /* stress marker, use this for the following vowel */ if ( phcode == Speak::PcStressPrev ) { /* primary stress on preceeding vowel */ j = count - 1 ; while ( ( j > 0 ) && ( stressed_syllable == 0 ) && ( vowel_stress[j] < 4 ) ) { if ( ( vowel_stress[j] != 0 ) && ( vowel_stress[j] != 1 ) ) { /* don't promote a phoneme which must be unstressed */ vowel_stress[j] = 4 ; if ( max_stress < 4 ) { max_stress = 4 ; primary_posn = j ; } ; /* reduce any preceding primary stress markers */ for ( ix = 1 ; ix < j ; ix++ ) { if ( vowel_stress[ix] == 4 ) vowel_stress[ix] = 3 ; } ; break ; } ; j-- ; } ; } else { if ( (phonemes[phcode]->Length<4) || (stressed_syllable==0) ) { stress = phonemes[phcode]->Length ; if ( stress > max_stress ) max_stress = stress ; } ; } ; continue ; } ; if ( ( phonemes[phcode]->Type == Speak::VOWEL ) && !( phonemes[phcode]->Flags & Speak::NONSYLLABIC ) ) { vowel_stress[count] = (char)stress ; if ( ( stress >= 4 ) && ( stress >= max_stress ) ) { primary_posn = count ; max_stress = stress ; } ; if ( ( stress < 0 ) && ( control & 1 ) && ( phonemes[phcode]->Flags & Speak::UNSTRESSED ) ) { /* weak vowel, must be unstressed */ vowel_stress[count] = 1 ; } ; count++ ; stress = -1 ; } else if ( phcode == Speak::PcSyllabic ) { // previous consonant phoneme is syllablic vowel_stress[count] = (char)stress ; if ( ( stress==0 ) && ( control & 1 ) ) vowel_stress[count++] = 1 ; // syllabic consonant, usually unstressed } ; *ph_out++ = phcode ; } ; //////////////////////////////////////////////////////////////////////// vowel_stress[count] = 1 ; *ph_out = 0 ; //////////////////////////////////////////////////////////////////////// /* has the position of the primary stress been specified by $1, $2, etc? */ if ( stressed_syllable > 0 ) { if ( stressed_syllable >= count ) stressed_syllable = count - 1 ; // the final syllable vowel_stress[stressed_syllable] = 4 ; max_stress = 4 ; primary_posn = stressed_syllable ; } ; //////////////////////////////////////////////////////////////////////// if ( max_stress == 5 ) { // priority stress, replaces any other primary stress marker for ( ix = 1 ; ix < count ; ix++ ) { if ( vowel_stress[ix] == 4 ) { if ( options.stressFlags & S_PRIORITY_STRESS) { vowel_stress[ix] = 1 ; } else { vowel_stress[ix] = 3 ; } ; } ; if ( vowel_stress[ix] == 5 ) { vowel_stress[ix] = 4 ; primary_posn = ix ; } ; } ; max_stress = 4 ; } ; stressed_syllable = primary_posn ; vowel_count = count ; return max_stress ; } void N::SpeechTranslator::ChangeStress(char * word,int newStress) { int ix ; unsigned char * p ; int max_stress ; int vowel_count ; // num of vowels + 1 int stressed_syllable = 0 ; // position of stressed syllable unsigned char phonetic [ N_WORD_PHONEMES ] ; signed char vowel_stress [ N_WORD_PHONEMES / 2 ] ; //////////////////////////////////////////////////////////////////////// strcpy ( (char *)phonetic , word ) ; max_stress = VowelStress ( phonetic , vowel_stress , vowel_count , stressed_syllable , 0 ) ; //////////////////////////////////////////////////////////////////////// if ( newStress >= 4) { // promote to primary stress for ( ix = 1 ; ix < vowel_count ; ix++ ) { if ( vowel_stress[ix] >= max_stress ) { vowel_stress[ix] = newStress ; break ; } ; } ; } else { // remove primary stress for ( ix = 1 ; ix < vowel_count ; ix++ ) { if ( vowel_stress[ix] > newStress ) { // >= allows for diminished stress (=1) vowel_stress[ix] = newStress ; } ; } ; } ; //////////////////////////////////////////////////////////////////////// // write out phonemes ix = 1 ; p = phonetic ; while ( (*p) != 0) { if (phonemes.contains(*p)) { if ( ( phonemes[*p]->Type == Speak::VOWEL ) && !( phonemes[*p]->Flags & Speak::NONSYLLABIC ) ) { if ( ( vowel_stress[ix] == 0) || ( vowel_stress[ix] > 1 ) ) { *word++ = stress_phonemes[(unsigned char)vowel_stress[ix]] ; } ; ix++ ; } ; } ; *word++ = *p++ ; } ; *word = 0 ; } void N::SpeechTranslator::SetStress ( char * output , unsigned int * dictionary_flags , int tonic , int control ) { /* Guess stress pattern of word. This is language specific 'output' is used for input and output 'dictionary_flags' has bits 0-3 position of stressed vowel (if > 0) or unstressed (if == 7) or syllables 1 and 2 (if == 6) bits 8... dictionary flags If 'tonic' is set (>= 0), replace highest stress by this value. control: bit 0 This is an individual symbol, not a word */ unsigned char phcode ; unsigned char * p ; int stress ; int max_stress ; int vowel_count ; // num of vowels + 1 int ix ; int v ; int v_stress ; int stressed_syllable ; // position of stressed syllable int max_stress_posn ; int unstressed_word = 0 ; char * max_output ; int final_ph ; int final_ph2 ; int mnem ; int post_tonic ; // currently not used int opt_length ; int done ; int stressflags ; int dflags = 0 ; int first_primary ; int long_vowel ; signed char vowel_stress [ N_WORD_PHONEMES / 2 ] ; char syllable_weight [ N_WORD_PHONEMES / 2 ] ; char vowel_length [ N_WORD_PHONEMES / 2 ] ; unsigned char phonetic [ N_WORD_PHONEMES ] ; //////////////////////////////////////////////////////////////////////// /* stress numbers STRESS_BASE + 0 diminished, unstressed within a word 1 unstressed, weak 2 3 secondary stress 4 main stress */ stressflags = options.stressFlags ; if ( IsNull(dictionary_flags) ) dflags = dictionary_flags[0] ; /* copy input string into internal buffer */ for ( ix = 0 ; ix < N_WORD_PHONEMES ; ix++ ) { phonetic[ix] = output[ix] ; // check for unknown phoneme codes if (!phonemes.contains(phonetic[ix])) { phonetic[ix] = Speak::PcSchwa ; } ; if (phonetic[ix] == 0) break ; } ; if ( ix == 0 ) return ; /////////////////////////////////////////////////////////////////////// final_ph = phonetic[ix-1] ; final_ph2 = phonetic[ix-2] ; max_output = output + (N_WORD_PHONEMES-3) ; /* check for overrun */ // any stress position marked in the xx_list dictionary ? stressed_syllable = dflags & 0x7 ; if ( dflags & 0x8 ) { // this indicates a word without a primary stress stressed_syllable = dflags & 0x3 ; unstressed_word = 1 ; } ; /////////////////////////////////////////////////////////////////////// max_stress = VowelStress ( phonetic , vowel_stress , vowel_count , stressed_syllable , 1 ) ; if ( ( max_stress < 0 ) && dictionary_flags ) max_stress = 0 ; /////////////////////////////////////////////////////////////////////// // heavy or light syllables ix = 1 ; for ( p = phonetic ; (*p) != 0 ; p++ ) { if ( ( phonemes[p[0]]->Type == Speak::VOWEL ) && !( phonemes[p[0]]->Flags & Speak::NONSYLLABIC ) ) { int weight = 0 ; int lengthened = 0 ; if ( phonemes[p[1]]->Code == Speak::PcLengthen ) { lengthened = 1 ; } ; if (lengthened || (phonemes[p[0]]->Flags & Speak::LONG)) { // long vowel, increase syllable weight weight++ ; } ; vowel_length [ ix ] = weight ; if ( lengthened ) p++ ; // advance over phonLENGTHEN if (consonant_types[phonemes[p[1]]->Type] && ( ( phonemes[p[2]]->Type != Speak::VOWEL ) || ( phonemes[p[1]]->Flags & Speak::LONG ) ) ) { // followed by two consonants, a long consonant, or consonant and end-of-word weight++ ; } ; syllable_weight[ix] = weight ; ix++ ; } ; } ; /////////////////////////////////////////////////////////////////////// switch ( options.stressRule ) { case 8 : // stress on first syllable, unless it is a light syllable followed by a heavy syllable if ( ( syllable_weight[1] > 0) || (syllable_weight[2] == 0 ) ) { break ; } ; // else drop through to case 1 case 1 : // stress on second syllable if ( ( stressed_syllable == 0 ) && ( vowel_count > 2 ) ) { stressed_syllable = 2 ; if ( max_stress == 0 ) { vowel_stress[stressed_syllable] = 4 ; } ; max_stress = 4 ; } ; break ; case 10 : // penultimate, but final if only 1 or 2 syllables if ( stressed_syllable == 0 ) { if ( vowel_count < 4 ) { vowel_stress[vowel_count - 1] = 4 ; max_stress = 4 ; break ; } ; } ; // drop through to next case case 2 : // a language with stress on penultimate vowel if ( stressed_syllable == 0 ) { /* no explicit stress - stress the penultimate vowel */ max_stress = 4 ; if ( vowel_count > 2 ) { stressed_syllable = vowel_count - 2 ; if ( stressflags & (S_FINAL_SPANISH | S_FINAL_STRESS_C) ) { // LANG=Spanish, stress on last vowel if the word ends in a consonant other than 'n' or 's' if ( phonemes[final_ph]->Type == Speak::VOWEL ) { if ( stressflags & S_FINAL_STRESS_C ) { stressed_syllable = vowel_count - 1 ; } else { mnem = phonemes[final_ph]->Mnemonic ; if ( translatorName == L('a','n') ) { if ( ( ( mnem != 's' ) && ( mnem !='n' ) ) || phonemes[final_ph2]->Type == Speak::VOWEL) stressed_syllable = vowel_count - 1 ; // stress on last syllable } else { if ( ( mnem == 's' ) && ( phonemes[final_ph2]->Type == Speak::NASAL)) { // -ns stress remains on penultimate syllable } else if ( ( ( phonemes[final_ph]->Type != Speak::NASAL) && (mnem != 's')) || ( phonemes[final_ph2]->Type != Speak::VOWEL)) { stressed_syllable = vowel_count - 1 ; } ; } ; } ; } ; } ; if ( stressflags & S_FINAL_LONG ) { // stress on last syllable if it has a long vowel, but previous syllable has a short vowel if ( vowel_length[vowel_count - 1] > vowel_length[vowel_count - 2]) { stressed_syllable = vowel_count - 1 ; } ; } ; if ( ( vowel_stress[stressed_syllable] == 0 ) || ( vowel_stress[stressed_syllable] == 1 ) ) { // but this vowel is explicitly marked as unstressed if ( stressed_syllable > 1 ) stressed_syllable-- ; else stressed_syllable++ ; } ; } else { stressed_syllable = 1 ; } ; // only set the stress if it's not already marked explicitly if ( vowel_stress[stressed_syllable] < 0 ) { // don't stress if next and prev syllables are stressed if ( ( vowel_stress[stressed_syllable-1] < 4 ) || ( vowel_stress[stressed_syllable+1] < 4 ) ) { vowel_stress[stressed_syllable] = max_stress ; } ; } ; } ; break ; case 3 : // stress on last vowel if ( stressed_syllable == 0 ) { /* no explicit stress - stress the final vowel */ stressed_syllable = vowel_count - 1 ; while ( stressed_syllable > 0 ) { // find the last vowel which is not unstressed if ( vowel_stress[stressed_syllable] < 0 ) { vowel_stress[stressed_syllable] = 4 ; break ; } else stressed_syllable-- ; } ; max_stress = 4 ; } ; break ; case 4 : // stress on antipenultimate vowel if ( stressed_syllable == 0 ) { stressed_syllable = vowel_count - 3 ; if ( stressed_syllable < 1 ) stressed_syllable = 1 ; if ( max_stress == 0 ) { vowel_stress[stressed_syllable] = 4 ; } ; max_stress = 4 ; } ; break ; case 5 : // LANG=Russian if ( stressed_syllable == 0 ) { /* no explicit stress - guess the stress from the number of syllables */ stressed_syllable = vowel_count - 3 ; if ( vowel_count < 16 ) { if ( phonemes[final_ph]->Type == Speak::VOWEL ) stressed_syllable = guess_ru_v[vowel_count] ; else if ( phonemes[final_ph]->Type == Speak::STOP ) stressed_syllable = guess_ru_t[vowel_count] ; else stressed_syllable = guess_ru[vowel_count] ; } ; vowel_stress[stressed_syllable] = 4 ; max_stress = 4 ; } ; break ; case 6 : // LANG=hi stress on the last heaviest syllable if ( stressed_syllable == 0 ) { int wt ; int max_weight = -1 ; // find the heaviest syllable, excluding the final syllable for ( ix = 1 ; ix < (vowel_count-1) ; ix++ ) { if ( vowel_stress[ix] < 0 ) { if ( ( wt = syllable_weight[ix] ) >= max_weight) { max_weight = wt ; // prev_stressed = stressed_syllable ; stressed_syllable = ix ; } ; } ; } ; if ( ( syllable_weight[vowel_count-1] == 2 ) && ( max_weight< 2 ) ) { // the only double=heavy syllable is the final syllable, so stress this stressed_syllable = vowel_count-1 ; } else if ( max_weight <= 0 ) { // all syllables, exclusing the last, are light. Stress the first syllable stressed_syllable = 1 ; } ; vowel_stress[stressed_syllable] = 4 ; max_stress = 4 ; } ; break ; case 7 : // LANG=tr, the last syllable for any vowel marked explicitly as unstressed if ( stressed_syllable == 0 ) { stressed_syllable = vowel_count - 1 ; for ( ix=1 ; ix < vowel_count ; ix++ ) { if ( vowel_stress[ix] == 1 ) { stressed_syllable = ix - 1 ; break ; } ; } ; vowel_stress[stressed_syllable] = 4 ; max_stress = 4 ; } ; break ; case 9 : // mark all as stressed for ( ix = 1 ; ix < vowel_count ; ix++ ) { if ( vowel_stress[ix] < 0 ) vowel_stress[ix] = 4 ; } ; break ; case 12 : // LANG=kl (Greenlandic) long_vowel = 0 ; for ( ix = 1 ; ix < vowel_count ; ix++ ) { if ( vowel_stress[ix] == 4 ) vowel_stress[ix] = 3 ; // change marked stress (consonant clusters) to secondary (except the last) if ( vowel_length[ix] > 0 ) { long_vowel = ix ; vowel_stress[ix] = 3 ; // give secondary stress to all long vowels } ; } ; // 'stressed_syllable' gives the last marked stress if ( stressed_syllable == 0 ) { // no marked stress, choose the last long vowel if ( long_vowel > 0 ) stressed_syllable = long_vowel ; else { // no long vowels or consonant clusters if ( vowel_count > 5 ) stressed_syllable = vowel_count - 3 ; // more than 4 syllables else stressed_syllable = vowel_count - 1 ; } ; } ; vowel_stress[stressed_syllable] = 4 ; max_stress = 4 ; break ; } ; /* now guess the complete stress pattern */ if ( max_stress < 4 ) stress = 4 ; /* no primary stress marked, use for 1st syllable */ else stress = 3 ; if ( unstressed_word == 0 ) { if ( ( stressflags & S_2_SYL_2 ) && ( vowel_count == 3 ) ) { // Two syllable word, if one syllable has primary stress, then give the other secondary stress if ( vowel_stress[1] == 4 ) vowel_stress[2] = 3 ; if ( vowel_stress[2] == 4 ) vowel_stress[1] = 3 ; } ; if ( ( stressflags & S_INITIAL_2 ) && ( vowel_stress[1] < 0 ) ) { // If there is only one syllable before the primary stress, give it a secondary stress if ( ( vowel_count > 3 ) && ( vowel_stress[2] >= 4 ) ) { vowel_stress[1] = 3 ; } ; } ; } ; /////////////////////////////////////////////////////////////////////// done = 0 ; first_primary = 0 ; for ( v = 1 ; v < vowel_count ; v++ ) { if ( vowel_stress[v] < 0 ) { if ( ( stressflags & S_FINAL_NO_2 ) && ( stress < 4 ) && ( v == vowel_count-1 ) ) { // flag: don't give secondary stress to final vowel } else if ( ( stressflags & 0x8000 ) && ( done == 0 ) ) { vowel_stress[v] = (char)stress ; done = 1 ; stress = 3 ; /* use secondary stress for remaining syllables */ } else if ( ( vowel_stress[v-1] <= 1 ) && ( ( vowel_stress[v+1] <= 1 ) || ( ( stress == 4 ) && ( vowel_stress[v+1] <= 2 ) ) ) ) { /* trochaic: give stress to vowel surrounded by unstressed vowels */ if ( (stress == 3) && ( stressflags & S_NO_AUTO_2 ) ) continue ; // don't use secondary stress if ( ( v > 1 ) && ( stressflags & S_2_TO_HEAVY ) && (syllable_weight[v]==0) && (syllable_weight[v+1] > 0) ) { // don't put secondary stress on a light syllable which is followed by a heavy syllable continue ; } ; // should start with secondary stress on the first syllable, or should it count back from // the primary stress and put secondary stress on alternate syllables? vowel_stress[v] = (char)stress ; done = 1 ; stress = 3 ; /* use secondary stress for remaining syllables */ } ; } ; ///////////////////////////////////////////////////////////////////// if ( vowel_stress[v] >= 4 ) { if ( first_primary == 0 ) first_primary = v ; else if ( stressflags & S_FIRST_PRIMARY ) { // reduce primary stresses after the first to secondary vowel_stress[v] = 3 ; } ; } ; } ; if ( ( unstressed_word ) && ( tonic < 0 ) ) { if ( vowel_count <= 2 ) tonic = options.unstressedWD1 ; /* monosyllable - unstressed */ else tonic = options.unstressedWD2 ; /* more than one syllable, used secondary stress as the main stress */ } ; max_stress = 0 ; max_stress_posn = 0 ; for ( v = 1 ; v < vowel_count ; v++ ) { if ( vowel_stress[v] >= max_stress ) { max_stress = vowel_stress[v] ; max_stress_posn = v ; } ; } ; if (tonic >= 0) { /* find position of highest stress, and replace it by 'tonic' */ /* don't disturb an explicitly set stress by 'unstress-at-end' flag*/ if ( ( tonic > max_stress ) || ( max_stress <= 4 ) ) { vowel_stress[max_stress_posn] = (char)tonic ; } ; max_stress = tonic ; } ; /* produce output phoneme string */ p = phonetic ; v = 1 ; if ( !(control & 1) && phonemes.contains(*p) ) { while ( ( phonemes[*p]->Type == Speak::STRESS ) || ( (*p) == Speak::PcEndWord ) ) { p++ ; } ; if ( ( options.vowelPause & 0x30 ) && ( phonemes[*p]->Type == Speak::VOWEL ) ) { // word starts with a vowel if ( ( options.vowelPause & 0x20) && (vowel_stress[1] >= 4)) { *output++ = Speak::PcPauseNoLink ; // not to be replaced by link } else { *output++ = Speak::PcPauseVShort ; // break, but no pause } ; } ; } ; p = phonetic ; post_tonic = 0 ; while ( ( ( phcode = *p++ ) != 0 ) && ( output < max_output ) ) { if (!phonemes.contains(phcode)) continue ; if ( phonemes[phcode]->Type == Speak::PAUSE ) { prevLastStress = 0 ; } else if ( ( ( phonemes[phcode]->Type == Speak::VOWEL ) && !( phonemes[phcode]->Flags & Speak::NONSYLLABIC ) ) || ( (*p) == Speak::PcSyllabic ) ) { // a vowel, or a consonant followed by a syllabic consonant marker v_stress = vowel_stress[v] ; prevLastStress = v_stress ; if ( vowel_stress[v-1] >= max_stress ) post_tonic = 1 ; if ( v_stress <= 1 ) { if ( ( v > 1 ) && ( max_stress >= 2 ) && ( stressflags & S_FINAL_DIM ) && (v == (vowel_count-1) ) ) { // option: mark unstressed final syllable as diminished v_stress = 0 ; } else if ( ( stressflags & S_NO_DIM ) || ( v == 1 ) || ( v == (vowel_count-1) ) ) { // first or last syllable, or option 'don't set diminished stress' v_stress = 1 ; } else if ( ( v == (vowel_count-2) ) && ( vowel_stress[vowel_count-1] <= 1 ) ) { // penultimate syllable, followed by an unstressed final syllable v_stress = 1 ; } else { // unstressed syllable within a word if ( ( vowel_stress[v-1] < 0 ) || ( ( stressflags & S_MID_DIM ) == 0 ) ) { v_stress = 0 ; /* change to 0 (diminished stress) */ vowel_stress[v] = v_stress ; } ; } ; } ; /////////////////////////////////////////////////////////////////// if ( ( v_stress == 0 ) || ( v_stress > 1 ) ) { // mark stress of all vowels except 1 (unstressed) *output++ = stress_phonemes[v_stress] ; } ; if ( vowel_stress[v] > max_stress ) { max_stress = vowel_stress[v] ; } ; /////////////////////////////////////////////////////////////////// if ( ( (*p) == Speak::PcLengthen ) && ( ( opt_length = options.param[LOPT_IT_LENGTHEN] ) & 1 ) ) { // remove lengthen indicator from non-stressed syllables int shorten = 0 ; if ( opt_length & 0x10 ) { // only allow lengthen indicator on the highest stress syllable in the word if ( v != max_stress_posn ) shorten = 1 ; } else if ( v_stress < 4 ) { // only allow lengthen indicator if stress >= 4. shorten = 1 ; } ; if ( shorten ) p++ ; } ; /////////////////////////////////////////////////////////////////// if ( (v_stress >= 4) && (options.param[LOPT_IT_LENGTHEN] == 2)) { // LANG=Italian, lengthen penultimate stressed vowels, unless followed by 2 consonants if ( ( v == (vowel_count - 2) ) && ( syllable_weight[v] == 0) ) { *output++ = phcode ; phcode = Speak::PcLengthen ; } ; } ; v++ ; } ; if ( phcode != 1 ) *output++ = phcode ; } ; *output++ = 0 ; } int N::SpeechTranslator::Transpose(char * text) { // transpose cyrillic alphabet (for example) into ascii // (single byte) character codes // return: number of bytes, bit 6: 1=used compression int c ; int c2 ; int ix ; int offset ; int min ; int max ; const char * map ; char * p = text ; char * p2 ; int all_alpha = 1 ; int bits ; int acc ; int pairs_start ; const short * pairs_list ; char buf[N_WORD_BYTES] ; /////////////////////////////////////////////////////////////////////// p2 = buf ; offset = transposeMin - 1 ; min = transposeMin ; max = transposeMax ; map = transposeMap ; pairs_start = max - min + 2 ; /////////////////////////////////////////////////////////////////////// do { p += toGrapheme(c,p) ; if ( c != 0 ) { if ( ( c >= min ) && ( c <= max ) ) { if ( IsNull(map) ) { *p2++ = c - offset ; } else { // get the code from the transpose map if ( map[c - min] > 0 ) { *p2++ = map[c - min] ; } else { p2 += toUtf8(c,p2) ; all_alpha = 0 ; } ; } ; } else { p2 += toUtf8(c,p2) ; all_alpha = 0 ; } ; } ; } while ( c != 0 ) ; /////////////////////////////////////////////////////////////////////// *p2 = 0 ; if ( all_alpha ) { // compress to 6 bits per character acc = 0 ; bits = 0 ; p = buf ; p2 = buf ; while ( ( c = *p++ ) != 0 ) { if ( ( pairs_list = frequentPairs ) != NULL ) { c2 = c + (*p << 8) ; for ( ix = 0 ; c2 >= pairs_list[ix] ; ix++ ) { if ( c2 == pairs_list[ix] ) { // found an encoding for a 2-character pair c = ix + pairs_start ; // 2-character codes start after the single letter codes p++ ; break ; } ; } ; } ; acc = ( acc << 6 ) + ( c & 0x3f ) ; bits += 6 ; if ( bits >= 8 ) { bits -= 8 ; *p2++ = (acc >> bits) ; } ; } ; if ( bits > 0 ) *p2++ = (acc << (8-bits)) ; *p2 = 0 ; ix = p2 - buf ; memcpy ( text , buf , ix ) ; } else return ( strlen ( text ) ) ; // bit 6 indicates compressed characters return ( ix | 0x40 ) ; } void N::SpeechTranslator::SpecialAttribute(char * phs,int dict_flags) { // apply after the translation is complete int ix ; int len ; char * p ; //////////////////////////////////////////////////////////////////////// len = strlen(phs) ; if ( options.param[LOPT_ALT] & 2 ) { for ( ix = 0 ; ix < ( len - 1 ) ; ix++ ) { if ( phs[ix] == Speak::PcStressP ) { p = &phs[ix+1] ; if ( ( dict_flags & FLAG_ALT2_TRANS ) != 0 ) { if ( (*p) == phonemes.Code((unsigned int)'E') ) { *p = phonemes.Code((unsigned int)'e') ; } ; if ( (*p) == phonemes.Code((unsigned int)'O') ) { *p = phonemes.Code((unsigned int)'o') ; } ; } else { if ( (*p) == phonemes.Code((unsigned int)'e') ) { *p = phonemes.Code((unsigned int)'E') ; } ; if ( (*p) == phonemes.Code((unsigned int)'o') ) { *p = phonemes.Code((unsigned int)'O') ; } ; } ; break ; } ; } ; } ; } void N::SpeechTranslator::Match ( SpeechMatch & result , char * word[] , char * word_start , int group_length , char * rule , int word_flags , int dict_flags ) { unsigned char rb ; // current instuction from rule unsigned char letter ; // current letter from input word, single byte unsigned char last_letter ; unsigned char condition_num ; int letter_w ; // current letter, wide character int letter_xbytes ; // number of extra bytes of multibyte character (num bytes - 1) int ix ; int match_type ; /* left, right, or consume */ int failed ; int unpron_ignore ; int consumed ; /* number of letters consumed from input */ int syllable_count ; int vowel ; int letter_group ; int distance_right ; int distance_left ; int lg_pts ; int n_bytes ; int add_points ; int command ; int check_atstart ; int total_consumed ; /* letters consumed for best match */ char * pre_ptr ; char * post_ptr ; /* pointer to first character after group */ char * rule_start ; /* start of current match template */ char * p ; char * common_phonemes ; /* common to a group of entries */ char * group_chars ; char word_buf [ N_WORD_BYTES ] ; SpeechMatch match ; ////////////////////////////////////////////////////////////////////////// group_chars = *word ; if ( IsNull(rule) ) { result.points = 0 ; (*word)++ ; return ; } ; ////////////////////////////////////////////////////////////////////////// total_consumed = 0 ; common_phonemes = NULL ; match_type = 0 ; result.points = 0 ; result.phonemes = "" ; result.end_type = 0 ; result.del_fwd = NULL ; ////////////////////////////////////////////////////////////////////////// /* search through dictionary rules */ while ( rule[0] != RULE_GROUP_END ) { unpron_ignore = word_flags & FLAG_UNPRON_TEST ; match_type = 0 ; consumed = 0 ; letter = 0 ; distance_right = -6 ; /* used to reduce points for matches further away the current letter */ distance_left = -2 ; check_atstart = 0 ; match.points = 1 ; match.end_type = 0 ; match.del_fwd = NULL ; pre_ptr = *word ; post_ptr = *word + group_length ; /* work through next rule until end, or until no-match proved */ rule_start = rule ; failed = 0 ; while ( !failed ) { rb = *rule++ ; if ( rb <= RULE_LINENUM ) { switch ( rb ) { case 0 : // no phoneme string for this rule, use previous common rule if ( common_phonemes != NULL ) { match.phonemes = common_phonemes ; while ( ( ( rb = *match.phonemes++ ) != 0 ) && ( rb != RULE_PHONEMES ) ) { if ( rb == RULE_CONDITION ) match.phonemes ++ ; // skip over condition number if ( rb == RULE_LINENUM ) match.phonemes += 2 ; // skip over line number } ; } else match.phonemes = "" ; rule -- ; // so we are still pointing at the 0 failed = 2 ; // matched OK break ; case RULE_PRE_ATSTART : // pre rule with implied 'start of word' check_atstart = 1 ; unpron_ignore = 0 ; match_type = RULE_PRE ; break ; case RULE_PRE : match_type = RULE_PRE ; if ( word_flags & FLAG_UNPRON_TEST ) { // checking the start of the word for unpronouncable character sequences, only // consider rules which explicitly match the start of a word // Note: Those rules now use RULE_PRE_ATSTART failed = 1 ; } ; break ; case RULE_POST : match_type = RULE_POST ; break ; case RULE_PHONEMES : match.phonemes = rule ; failed = 2 ; // matched OK break ; case RULE_PH_COMMON : common_phonemes = rule ; break ; case RULE_CONDITION : /* conditional rule, next byte gives condition number */ condition_num = *rule++ ; if ( condition_num >= 32 ) { // allow the rule only if the condition number is NOT set if ( ( dictCondition & (1L << (condition_num-32))) != 0 ) { failed = 1 ; } ; } else { // allow the rule only if the condition number is set if ( ( dictCondition & (1L << condition_num)) == 0) { failed = 1 ; } ; } ; if ( !failed ) match.points++ ; // add one point for a matched conditional rule break ; case RULE_LINENUM : rule += 2 ; break ; } ; continue ; } ; ////////////////////////////////////////////////////////////////////// add_points = 0 ; switch ( match_type ) { case 0 : /* match and consume this letter */ last_letter = letter ; letter = *post_ptr++ ; if ( ( letter == rb ) || ( ( letter == (unsigned char)REPLACED_E ) && (rb=='e') ) ) { if ( ( letter & 0xc0 ) != 0x80) add_points = 21 ; // don't add point for non-initial UTF-8 bytes consumed++ ; } else failed = 1 ; break ; case RULE_POST : /* continue moving fowards */ distance_right += 6 ; if ( distance_right > 18 ) distance_right = 19 ; last_letter = letter ; letter_xbytes = toGrapheme(letter_w,post_ptr) - 1 ; letter = *post_ptr++ ; switch ( rb ) { case RULE_LETTERGP : letter_group = *rule++ - 'A' ; if (isLetter(letter_w,letter_group)) { lg_pts = 20 ; if(letter_group==2) lg_pts = 19 ; // fewer points for C, general consonant add_points = ( lg_pts - distance_right ) ; post_ptr += letter_xbytes ; } else failed = 1 ; break ; case RULE_LETTERGP2 : // match against a list of utf-8 strings letter_group = *rule++ - 'A' ; n_bytes = isLetterGroup(post_ptr-1,letter_group,0) ; if ( n_bytes > 0 ) { add_points = ( 20 - distance_right ) ; post_ptr += ( n_bytes - 1 ) ; } else failed = 1 ; break ; case RULE_NOTVOWEL : if ( isLetter(letter_w,0) || ((letter_w == ' ') && (word_flags & FLAG_SUFFIX_VOWEL) ) ) { failed = 1 ; } else { add_points = ( 20 - distance_right ) ; post_ptr += letter_xbytes ; } ; break ; case RULE_DIGIT : if ( IsDigit(letter_w) ) { add_points = ( 20 - distance_right ) ; post_ptr += letter_xbytes ; } else if ( options.toneNumbers ) { // also match if there is no digit add_points = ( 20 - distance_right ) ; post_ptr -- ; } else failed = 1 ; break ; case RULE_NONALPHA : if ( ! iswalpha2(letter_w) ) { add_points = ( 21 - distance_right ) ; post_ptr += letter_xbytes ; } else failed = 1 ; break ; case RULE_DOUBLE : if ( letter == last_letter ) { add_points = ( 21 - distance_right ) ; } else failed = 1 ; break ; case RULE_DOLLAR : command = *rule++ ; if ( command == 0x01 ) { match.end_type = SUFX_UNPRON ; // $unpron } else if ( ( command & 0xf0 ) == 0x10 ) { // $w_alt if ( dict_flags & (1 << (BITNUM_FLAG_ALT + (command & 0xf)))) { add_points = 23 ; } else failed = 1 ; } else if ( ( command & 0xf0 ) == 0x20) { // $p_alt // make a copy of the word up to the post-match characters ix = *word - word_start + consumed + group_length + 1 ; memcpy(word_buf, word_start-1, ix) ; word_buf [ ix ] = ' ' ; word_buf [ ix + 1 ] = 0 ; // if (LookupFlags(&word_buf[1]) & (1 << (BITNUM_FLAG_ALT + (command & 0xf)))) // add_points = 23; // else failed = 1; } ; break ; case '-' : if ( ( letter == '-' ) || ( (letter == ' ') && (word_flags & FLAG_HYPHEN_AFTER))) { add_points = ( 22 - distance_right ) ; // one point more than match against space } else failed = 1 ; break ; case RULE_SYLLABLE : { /* more than specified number of vowel letters to the right */ char * p = post_ptr + letter_xbytes ; int vowel_count = 0 ; syllable_count = 1 ; while ( *rule == RULE_SYLLABLE ) { rule ++ ; syllable_count += 1 ; /* number of syllables to match */ } ; vowel = 0 ; while ( letter_w != RULE_SPACE ) { if ( ( vowel==0 ) && isLetter(letter_w,LETTERGP_VOWEL2)) { // this is counting vowels which are separated by non-vowel letters vowel_count++ ; } ; vowel = isLetter(letter_w,LETTERGP_VOWEL2) ; p += toGrapheme ( letter_w , p ) ; } ; if ( syllable_count <= vowel_count ) { add_points = ( 18 + syllable_count - distance_right ) ; } else failed = 1 ; } ; break ; case RULE_NOVOWELS : { char * p = post_ptr + letter_xbytes ; while ( letter_w != RULE_SPACE ) { if ( isLetter(letter_w,LETTERGP_VOWEL2) ) { failed = 1 ; break ; } ; p += toGrapheme ( letter_w , p ) ; } ; if ( ! failed ) add_points = ( 19 - distance_right ) ; } ; break ; case RULE_SKIPCHARS : { // Used for lang=Tamil, used to match on the next word after an unknown word ending // only look until the end of the word (including the end-of-word marker) // Jx means 'skip characters until x', where 'x' may be '_' for 'end of word' char * p = post_ptr + letter_xbytes ; char * p2 = p ; int rule_w ; // skip characters until this toGrapheme(rule_w,rule) ; while ( (letter_w != rule_w) && (letter_w != RULE_SPACE)) { p2 = p ; p += toGrapheme(letter_w,p) ; } ; if ( letter_w == rule_w ) post_ptr = p2 ; } ; break ; case RULE_INC_SCORE : add_points = 20 ; // force an increase in points break ; case RULE_DEL_FWD : // find the next 'e' in the word and replace by 'E' for ( p = *word + group_length ; p < post_ptr ; p++ ) { if ( *p == 'e' ) { match.del_fwd = p ; break ; } ; } ; break ; case RULE_ENDING : { int end_type ; // next 3 bytes are a (non-zero) ending type. 2 bytes of flags + suffix length end_type = ( rule [ 0 ] << 16 ) + (( rule [ 1 ] & 0x7f ) << 8) + ( rule [ 2 ] & 0x7f ) ; // don't match a suffix rule if there are no previous syllables (needed for lang=tr). if ( ( wordVowelCount == 0 ) && !( end_type & SUFX_P ) && ( options.param[LOPT_SUFFIX] & 1 ) ) failed = 1 ; else { match.end_type = end_type ; rule += 3 ; } ; } ; break ; case RULE_NO_SUFFIX : if ( word_flags & FLAG_SUFFIX_REMOVED ) failed = 1 ; // a suffix has been removed else add_points = 1 ; break ; default : if ( letter == rb ) { if ( ( letter & 0xc0 ) != 0x80) { // not for non-initial UTF-8 bytes add_points = ( 21 - distance_right ) ; } ; } else failed = 1 ; break ; } ; break ; case RULE_PRE : /* match backwards from start of current group */ distance_left += 2 ; if ( distance_left > 18 ) distance_left = 19 ; last_letter = *pre_ptr ; pre_ptr-- ; letter_xbytes = toGrapheme ( letter_w , pre_ptr , true ) - 1 ; letter = *pre_ptr ; switch ( rb ) { case RULE_LETTERGP : letter_group = *rule++ - 'A' ; if ( isLetter ( letter_w , letter_group ) ) { lg_pts = 20 ; if ( letter_group==2 ) lg_pts = 19 ; // fewer points for C, general consonant add_points = ( lg_pts - distance_left ) ; pre_ptr -= letter_xbytes ; } else failed = 1 ; break ; case RULE_LETTERGP2 : // match against a list of utf-8 strings letter_group = *rule++ - 'A' ; n_bytes = isLetterGroup (pre_ptr,letter_group,1) ; if ( n_bytes >0 ) { add_points = ( 20 - distance_right ) ; pre_ptr -= ( n_bytes - 1 ) ; } else failed = 1 ; break ; case RULE_NOTVOWEL : if ( ! isLetter ( letter_w , 0 ) ) { add_points = ( 20 - distance_left ) ; pre_ptr -= letter_xbytes ; } else failed = 1 ; break ; case RULE_DOUBLE : if ( letter == last_letter ) add_points = (21-distance_left) ; else failed = 1 ; break ; case RULE_DIGIT : if ( IsDigit(letter_w) ) { add_points = ( 21 - distance_left ) ; pre_ptr -= letter_xbytes ; } else failed = 1 ; break ; case RULE_NONALPHA : if ( ! iswalpha2(letter_w) ) { add_points = ( 21 - distance_right ) ; pre_ptr -= letter_xbytes ; } else failed = 1 ; break ; case RULE_SYLLABLE : /* more than specified number of vowels to the left */ syllable_count = 1 ; while ( *rule == RULE_SYLLABLE ) { rule ++ ; syllable_count ++ ; /* number of syllables to match */ } ; if ( syllable_count <= wordVowelCount ) { add_points = ( 18 + syllable_count - distance_left ) ; } else failed = 1 ; break ; case RULE_STRESSED : if ( wordStressedCount > 0 ) add_points = 19 ; else failed = 1 ; break ; case RULE_NOVOWELS : { char * p = pre_ptr - letter_xbytes - 1 ; while ( letter_w != RULE_SPACE ) { if ( isLetter(letter_w,LETTERGP_VOWEL2) ) { failed = 1 ; break ; } ; p -= toGrapheme(letter_w,p,true) ; } ; if ( ! failed ) add_points = 3 ; } ; break ; case RULE_IFVERB : if ( expectVerb ) add_points = 1 ; else failed = 1 ; break ; case RULE_CAPITAL : if ( word_flags & FLAG_FIRST_UPPER ) add_points = 1 ; else failed = 1 ; break ; case '.' : // dot in pre- section, match on any dot before this point in the word for ( p = pre_ptr ; *p != ' ' ; p-- ) { if ( (*p) == '.' ) { add_points = 50 ; break ; } ; } ; if ( (*p) == ' ') failed = 1 ; break ; case '-' : if ( ( letter == '-' ) || ( ( letter == ' ' ) && ( word_flags & FLAG_HYPHEN ) ) ) { add_points = (22-distance_right) ; // one point more than match against space } else failed = 1 ; break ; default : if ( letter == rb ) { if ( letter == RULE_SPACE ) add_points = 4 ; else { if ( ( letter & 0xc0 ) != 0x80 ) { // not for non-initial UTF-8 bytes add_points = ( 21 - distance_left ) ; } ; } ; } else failed = 1 ; break ; } ; break ; } ; if ( failed == 0 ) match.points += add_points ; } ; //////////////////////////////////////////////////////////////////////// if ( ( failed == 2 ) && ( unpron_ignore == 0 ) ) { // do we also need to check for 'start of word' ? if ( ( check_atstart == 0 ) || ( pre_ptr[-1] == ' ' ) ) { if ( check_atstart ) result.points += 4 ; /* matched OK, is this better than the last best match ? */ if ( match.points >= result.points) { result = match ; total_consumed = consumed ; } ; if (// ( option_phonemes == 2 ) && ( match.points > 0 ) && ( ( word_flags & FLAG_NO_TRACE ) == 0 ) ) { // show each rule that matches, and it's points score int pts ; char decoded_phonemes[80] ; pts = match.points ; if ( group_length > 1 ) pts += 35 ; // to account for an extra letter matching phonemes.toMnemonics(match.phonemes,decoded_phonemes) ; // fprintf(f_trans,"%3d\t%s [%s]\n",pts,DecodeRule(group_chars, group_length, rule_start, word_flags), decoded_phonemes); } ; } ; } ; while( *rule++ != 0) ; /* skip phoneme string to reach start of next template */ } ; ////////////////////////////////////////////////////////////////////////// // if ( ( option_phonemes == 2 ) && ((word_flags & FLAG_NO_TRACE)==0) ) { // if ( group_length <= 1 ) fprintf(f_trans,"\n") ; // } ; ////////////////////////////////////////////////////////////////////////// /* advance input data pointer */ total_consumed += group_length ; if ( total_consumed == 0 ) total_consumed = 1 ; /* always advance over 1st letter */ *word += total_consumed ; if ( result.points == 0 ) result.phonemes = "" ; } int N::SpeechTranslator::Rules ( char * p_start , char * phonemes , int ph_size , char * end_phonemes , int word_flags , unsigned int * dict_flags ) { /* Translate a word bounded by space characters Append the result to 'phonemes' and any standard prefix/suffix in 'end_phonemes' */ unsigned char c ; unsigned char c2 ; unsigned int c12 ; int wc = 0 ; int wc_bytes ; char * p2 ; /* copy of p for use in double letter chain match */ int found ; int g ; /* group chain number */ int g1 ; /* first group for this letter */ int n ; int letter ; int any_alpha = 0 ; int ix ; unsigned int digit_count = 0 ; char * p ; nSpeakAlphabet * alphabet ; int dict_flags0 = 0 ; SpeechMatch match1 ; SpeechMatch match2 ; char ph_buf[40] ; char word_copy [ N_WORD_BYTES ] ; static const char str_pause [ 2 ] = { Speak::PcPauseNoLink , 0 } ; //////////////////////////////////////////////////////////////////////////// if ( IsNull(dataDictRules) ) return 0 ; if ( NotNull(dict_flags ) ) dict_flags0 = dict_flags[0] ; for ( ix = 0 ; ix < ( N_WORD_BYTES-1 ) ; ) { c = p_start[ix] ; word_copy[ix++] = c ; if ( c == 0 ) break ; } ; word_copy[ix] = 0 ; //////////////////////////////////////////////////////////////////////////// if (// ( option_phonemes == 2 ) && ( ( word_flags & FLAG_NO_TRACE ) == 0 ) ) { char wordbuf [ 120 ] ; unsigned int ix ; for ( ix = 0 ; ( ( c = p_start[ix]) != ' ' ) && ( c != 0 ) && ( ix < (sizeof(wordbuf)-1) ) ; ix++ ) { wordbuf[ix] = c ; } ; wordbuf[ix] = 0 ; // if ( word_flags & FLAG_UNPRON_TEST ) fprintf(f_trans,"Unpronouncable? '%s'\n",wordbuf); // else fprintf(f_trans,"Translate '%s'\n",wordbuf); } ; //////////////////////////////////////////////////////////////////////////// p = p_start ; wordVowelCount = 0 ; wordStressedCount = 0 ; //////////////////////////////////////////////////////////////////////////// if ( NotNull(end_phonemes) ) end_phonemes[0] = 0 ; while ( ( ( c = (*p) ) != ' ' ) && ( c != 0 ) ) { wc_bytes = toGrapheme ( wc , p ) ; if ( IsAlpha(wc) ) any_alpha++ ; n = groups2Count [ c ] ; #ifdef XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX if ( IsDigit(wc) && ( ( options.toneNumbers == 0) || !any_alpha)) { // lookup the number in *_list not *_rules char string[8]; char buf[40]; string[0] = '_'; memcpy(&string[1],p,wc_bytes); string[1+wc_bytes] = 0; Lookup(tr, string,buf); if ( ++digit_count >= 2 ) { strcat(buf,str_pause); digit_count=0; } ; AppendPhonemes(tr,phonemes,ph_size,buf); p += wc_bytes; continue; } else { digit_count = 0; found = 0; if(((ix = wc - tr->letter_bits_offset) >= 0) && (ix < 128)) { if(tr->groups3[ix] != NULL) { MatchRule(tr, &p, p_start, wc_bytes, tr->groups3[ix], &match1, word_flags, dict_flags0); found = 1; } } if(!found && (n > 0)) { /* there are some 2 byte chains for this initial letter */ c2 = p[1]; c12 = c + (c2 << 8); /* 2 characters */ g1 = tr->groups2_start[c]; for(g=g1; g < (g1+n); g++) { if(tr->groups2_name[g] == c12) { found = 1; p2 = p; MatchRule(tr, &p2, p_start, 2, tr->groups2[g], &match2, word_flags, dict_flags0); if(match2.points > 0) match2.points += 35; /* to acount for 2 letters matching */ /* now see whether single letter chain gives a better match ? */ MatchRule(tr, &p, p_start, 1, tr->groups1[c], &match1, word_flags, dict_flags0); if(match2.points >= match1.points) { // use match from the 2-letter group memcpy(&match1,&match2,sizeof(MatchRecord)); p = p2; } } } } if(!found) { /* alphabetic, single letter chain */ if(tr->groups1[c] != NULL) MatchRule(tr, &p, p_start, 1, tr->groups1[c], &match1, word_flags, dict_flags0); else { // no group for this letter, use default group MatchRule(tr, &p, p_start, 0, tr->groups1[0], &match1, word_flags, dict_flags0); if((match1.points == 0) && ((option_sayas & 0x10) == 0)) { n = utf8_in(&letter,p-1)-1; if(tr->letter_bits_offset > 0) { // not a Latin alphabet, switch to the default Latin alphabet language if((letter <= 0x241) && iswalpha2(letter)) { sprintf(phonemes,"%c%s",phonSWITCH,tr->langopts.ascii_language); return(0); } } #ifdef deleted // can't switch to a tone language, because the tone-phoneme numbers are not valid for the original language if((letter >= 0x4e00) && (letter < 0xa000) && (tr->langopts.ideographs != 1)) { // Chinese ideogram sprintf(phonemes,"%czh",phonSWITCH); return(0); } #endif // is it a bracket ? if(letter == 0xe000+'(') { if(pre_pause < tr->langopts.param2[LOPT_BRACKET_PAUSE]) pre_pause = tr->langopts.param2[LOPT_BRACKET_PAUSE]; // a bracket, aleady spoken by AnnouncePunctuation() } if(IsBracket(letter)) { if(pre_pause < tr->langopts.param[LOPT_BRACKET_PAUSE]) pre_pause = tr->langopts.param[LOPT_BRACKET_PAUSE]; } // no match, try removing the accent and re-translating the word if((letter >= 0xc0) && (letter < N_REMOVE_ACCENT) && ((ix = remove_accent[letter-0xc0]) != 0)) { // within range of the remove_accent table if((p[-2] != ' ') || (p[n] != ' ')) { // not the only letter in the word p2 = p-1; p[-1] = ix; while((p[0] = p[n]) != ' ') p++; while(n-- > 0) *p++ = ' '; // replacement character must be no longer than original if(tr->langopts.param[LOPT_DIERESES] && (lookupwchar(diereses_list,letter) > 0)) { // vowel with dieresis, replace and continue from this point p = p2; continue; } phonemes[0] = 0; // delete any phonemes which have been produced so far p = p_start; tr->word_vowel_count = 0; tr->word_stressed_count = 0; continue; // start again at the beginning of the word } } if(((alphabet = AlphabetFromChar(letter)) != NULL) && (alphabet->offset != tr->letter_bits_offset)) { if(tr->langopts.alt_alphabet == alphabet->offset) { sprintf(phonemes,"%c%s",phonSWITCH, WordToString2(tr->langopts.alt_alphabet_lang)); return(0); } if(alphabet->flags & AL_WORDS) { // switch to the nominated language for this alphabet sprintf(phonemes,"%c%s",phonSWITCH, WordToString2(alphabet->language)); return(0); } } } } if(match1.points == 0) { if((wc >= 0x300) && (wc <= 0x36f)) { // combining accent inside a word, ignore } else if(IsAlpha(wc)) { if((any_alpha > 1) || (p[wc_bytes-1] > ' ')) { // an unrecognised character in a word, abort and then spell the word phonemes[0] = 0; if(dict_flags != NULL) dict_flags[0] |= FLAG_SPELLWORD; break; } } else { LookupLetter(tr, wc, -1, ph_buf, 0); if(ph_buf[0]) { match1.phonemes = ph_buf; match1.points = 1; } } p += (wc_bytes-1); } else { tr->phonemes_repeat_count = 0; } } } if(match1.phonemes == NULL) match1.phonemes = ""; if(match1.points > 0) { if(word_flags & FLAG_UNPRON_TEST) return(match1.end_type | 1); #ifdef deleted // ?? allow $unpr while translating rules, not just on initial FLAG_UNPRON_TEST if((match1.end_type & SUFX_UNPRON) && !(word_flags & FLAG_SUFFIX_REMOVED)) return(match1.end_type); #endif if((match1.phonemes[0] == phonSWITCH) && ((word_flags & FLAG_DONT_SWITCH_TRANSLATOR)==0)) { // an instruction to switch language, return immediately so we can re-translate strcpy(phonemes,match1.phonemes); return(0); } match1.end_type &= ~SUFX_UNPRON; if((match1.end_type != 0) && (end_phonemes != NULL)) { /* a standard ending has been found, re-translate the word without it */ if((match1.end_type & SUFX_P) && (word_flags & FLAG_NO_PREFIX)) { // ignore the match on a prefix } else { if((match1.end_type & SUFX_P) && ((match1.end_type & 0x7f) == 0)) { // no prefix length specified match1.end_type |= p - p_start; } strcpy(end_phonemes,match1.phonemes); memcpy(p_start,word_copy,strlen(word_copy)); return(match1.end_type); } } if(match1.del_fwd != NULL) *match1.del_fwd = REPLACED_E; AppendPhonemes(tr,phonemes,ph_size,match1.phonemes); } #endif } ; memcpy ( p_start , word_copy , N_WORD_BYTES ) ; return 0 ; } const char * N::SpeechTranslator :: Entry ( const char * word , const char * word2 , char * phonetic , unsigned int * flags , int end_flags , QList<SpeechWords> & wtab ) { char * p ; char * next ; int hash ; int phoneme_len ; int wlen ; unsigned char flag ; unsigned int dictionary_flags ; unsigned int dictionary_flags2 ; int condition_failed = 0 ; int n_chars ; int no_phonemes ; int skipwords ; int ix ; int c ; const char * word_end ; const char * word1 = word ; int wflags = 0 ; int lookup_symbol = flags[1] & FLAG_LOOKUP_SYMBOL ; char word_buf [ N_WORD_BYTES + 1 ] ; char dict_flags_buf [ 80 ] ; //////////////////////////////////////////////////////////////////////// if ( wtab.count() > 0 ) wflags = wtab[0].flags ; if ( transposeMin > 0) { wlen = strlen(word) ; if ( wlen > N_WORD_BYTES ) { memset ( word_buf , 0 , N_WORD_BYTES + 1 ) ; memcpy ( word_buf , word , N_WORD_BYTES ) ; } else strcpy ( word_buf , word ) ; wlen = Transpose ( word_buf ) ; word = word_buf ; } else { wlen = strlen ( word ) ; } ; hash = Hash ( word ) ; p = dictHashTab [ hash ] ; if ( IsNull(p) ) { if ( NotNull(flags) ) *flags = 0 ; return NULL ; } ; //////////////////////////////////////////////////////////////////////// // Find the first entry in the list for this hash value which matches. // This corresponds to the last matching entry in the *_list file. while ( (*p) != 0) { next = p + p[0] ; if ( ( ( p[1] & 0x7f ) != wlen ) || ( memcmp ( word , &p[2] , wlen & 0x3f ) != 0 ) ) { // bit 6 of wlen indicates whether the word has been compressed; // so we need to match on this also. p = next ; continue ; } ; /* found matching entry. Decode the phonetic string */ word_end = word2 ; dictionary_flags = 0 ; dictionary_flags2 = 0 ; no_phonemes = p[1] & 0x80 ; p += ( ( p[1] & 0x3f ) + 2 ) ; ////////////////////////////////////////////////////////////////////// if ( no_phonemes ) { phonetic[0] = 0 ; phoneme_len = 0 ; } else { strcpy ( phonetic , p ) ; phoneme_len = strlen(p) ; p += ( phoneme_len + 1 ) ; } ; ////////////////////////////////////////////////////////////////////// while ( p < next ) { // examine the flags which follow the phoneme string flag = *p++ ; if ( flag >= 100 ) { // conditional rule if ( flag >= 132 ) { // fail if this condition is set if ( ( dictCondition & ( 1 << ( flag - 132 ) ) ) != 0 ) { condition_failed = 1 ; } ; } else { // allow only if this condition is set if ( ( dictCondition & ( 1 << ( flag - 100 ) ) ) == 0 ) { condition_failed = 1 ; } ; } ; } else if ( flag > 80 ) { // flags 81 to 90 match more than one word // This comes after the other flags n_chars = next - p ; skipwords = flag - 80 ; // don't use the contraction if any of the words are emphasized // or has an embedded command, such as MARK if ( wtab.count() > 0 ) { for ( ix = 0 ; ix <= skipwords ; ix++ ) if (ix < wtab.count()) { if ( wtab[ix].flags & FLAG_EMPHASIZED2) { condition_failed = 1 ; } ; } ; } ; ////////////////////////////////////////////////////////////////// if ( memcmp ( word2 , p , n_chars ) != 0 ) condition_failed = 1 ; if ( condition_failed ) { p = next ; break ; } ; ////////////////////////////////////////////////////////////////// dictionary_flags |= FLAG_SKIPWORDS ; dictSkipWords = skipwords ; p = next ; word_end = word2 + n_chars ; } else if ( flag > 64 ) { // stressed syllable information, put in bits 0-3 dictionary_flags = (dictionary_flags & ~0xf) | (flag & 0xf) ; if ( ( flag & 0xc ) == 0xc ) { dictionary_flags |= FLAG_STRESS_END ; } ; } else if ( flag >= 32 ) { dictionary_flags2 |= ( 1L << ( flag - 32 ) ) ; } else { dictionary_flags |= ( 1L << flag ) ; } ; } ; ////////////////////////////////////////////////////////////////////// if ( condition_failed ) { condition_failed = 0 ; continue ; } ; ////////////////////////////////////////////////////////////////////// if ( ( end_flags & FLAG_SUFX ) == 0 ) { // no suffix has been removed if ( dictionary_flags2 & FLAG_STEM ) continue ; // this word must have a suffix } ; ////////////////////////////////////////////////////////////////////// if ( ( end_flags & SUFX_P ) && ( dictionary_flags2 & (FLAG_ONLY | FLAG_ONLY_S) ) ) continue ; // $only or $onlys, don't match if a prefix has been removed ////////////////////////////////////////////////////////////////////// if ( end_flags & FLAG_SUFX ) { // a suffix was removed from the word if ( dictionary_flags2 & FLAG_ONLY ) continue ; // no match if any suffix if ( ( dictionary_flags2 & FLAG_ONLY_S ) && ( ( end_flags & FLAG_SUFX_S ) == 0 ) ) { // only a 's' suffix allowed, but the suffix wasn't 's' continue ; } ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags2 & FLAG_HYPHENATED ) { if ( ! ( wflags & FLAG_HYPHEN_AFTER ) ) continue ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags2 & FLAG_CAPITAL ) { if ( ! ( wflags & FLAG_FIRST_UPPER ) ) continue ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags2 & FLAG_ALLCAPS ) { if ( ! ( wflags & FLAG_ALL_UPPER ) ) continue ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags & FLAG_NEEDS_DOT ) { if ( ! ( wflags & FLAG_HAS_DOT ) ) continue ; } ; ////////////////////////////////////////////////////////////////////// if ( ( dictionary_flags2 & FLAG_ATEND ) && ( word_end < clauseEnd ) && ( lookup_symbol == 0 ) ) { // only use this pronunciation if it's the last word of the clause, or called from Lookup() continue ; } ; ////////////////////////////////////////////////////////////////////// if ( ( dictionary_flags2 & FLAG_ATSTART ) && !( wtab[0].flags & FLAG_FIRST_WORD ) ) { // only use this pronunciation if it's the first word of a clause continue ; } ; ////////////////////////////////////////////////////////////////////// if ( ( dictionary_flags2 & FLAG_SENTENCE ) && !( clauseTerminator & CLAUSE_BIT_SENTENCE ) ) { // only if this clause is a sentence , i.e. terminator is {. ? !} not {, : :} continue ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags2 & FLAG_VERB ) { // this is a verb-form pronunciation if ( expectVerb || ( expectVerbs && ( end_flags & FLAG_SUFX_S ) )) { // OK, we are expecting a verb if ( ( translatorName == L('e','n') ) && ( prevDictFlags[0] & FLAG_ALT6_TRANS ) && ( end_flags & FLAG_SUFX_S ) ) { // lang=en, don't use verb form after 'to' if the word has 's' suffix continue ; } ; } else { /* don't use the 'verb' pronunciation unless we are expecting a verb */ continue ; } ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags2 & FLAG_PAST ) { if ( ! expectPast ) { /* don't use the 'past' pronunciation unless we are expecting past tense */ continue ; } ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags2 & FLAG_NOUN ) { if ( ( ! expectNoun ) || ( end_flags & SUFX_V ) ) { /* don't use the 'noun' pronunciation unless we are expecting a noun */ continue ; } ; } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags2 & FLAG_NATIVE ) { // if ( tr != translator) continue ; // don't use if we've switched translators } ; ////////////////////////////////////////////////////////////////////// if ( dictionary_flags & FLAG_ALT2_TRANS ) { // language specific if ( ( translatorName == L('h','u') ) && !( prevDictFlags[0] & FLAG_ALT_TRANS ) ) continue ; } ; ////////////////////////////////////////////////////////////////////// if ( flags != NULL ) { flags[0] = dictionary_flags | FLAG_FOUND_ATTRIBUTES ; flags[1] = dictionary_flags2 ; } ; ////////////////////////////////////////////////////////////////////// if ( phoneme_len == 0 ) { // if ( option_phonemes == 2 ) { // print_dictionary_flags(flags, dict_flags_buf, sizeof(dict_flags_buf)); // fprintf(f_trans,"Flags: %s %s\n", word1, dict_flags_buf); // } ; return NULL ; // no phoneme translation found here, only flags. So use rules } ; ////////////////////////////////////////////////////////////////////// if ( flags != NULL ) { flags[0] |= FLAG_FOUND ; // this flag indicates word was found in dictionary } ; #ifdef XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX if ( option_phonemes == 2 ) { char ph_decoded[N_WORD_PHONEMES] ; int textmode ; DecodePhonemes(phonetic,ph_decoded) ; if ( ( dictionary_flags & FLAG_TEXTMODE ) == 0) textmode = 0 ; else textmode = 1 ; if ( textmode == translator->langopts.textmode ) { // only show this line if the word translates to phonemes, not replacement text if ( ( dictionary_flags & FLAG_SKIPWORDS) && (wtab != NULL)) { // matched more than one word // (check for wtab prevents showing RULE_SPELLING byte when speaking individual letters) memcpy(word_buf,word2,word_end-word2); word_buf[word_end-word2-1] = 0; fprintf(f_trans,"Found: '%s %s\n",word1,word_buf); } else { fprintf(f_trans,"Found: '%s",word1) ; } ; print_dictionary_flags(flags, dict_flags_buf, sizeof(dict_flags_buf)); fprintf(f_trans,"' [%s] %s\n", ph_decoded,dict_flags_buf) ; } ; } ; #endif ix = toGrapheme ( c , word ) ; if ( ( word[ix] == 0 ) && ! IsAlpha ( c ) ) { flags[0] |= FLAG_MAX3 ; } ; return word_end ; } ; //////////////////////////////////////////////////////////////////////// return NULL ; } bool N::SpeechTranslator :: Lookup ( char ** wordptr , char * ph_out , unsigned int * flags , int end_flags , QList<SpeechWords> & wtab ) /* Lookup a specified word in the word dictionary. Returns phonetic data in 'phonetic' and bits in 'flags' end_flags: indicates if a suffix has been removed */ { int length = 0 ; const char * found = NULL ; const char * word1 = *wordptr ; const char * word2 = *wordptr ; unsigned char c ; int nbytes ; int len ; char word[N_WORD_BYTES] ; /////////////////////////////////////////////////////////////////////////// while ( ( word2[ nbytes = nBytes(*word2) ] == ' ' ) && ( word2[ nbytes + 1 ] == '.' ) ) { // look for an abbreviation of the form a.b.c // try removing the spaces between the dots and looking for a match memcpy ( &word[length] , word2 , nbytes ) ; length += nbytes ; word [ length++ ] = '.' ; word2 += ( nbytes + 3 ) ; } ; /////////////////////////////////////////////////////////////////////////// if ( length > 0 ) { // found an abbreviation containing dots nbytes = 0 ; while ( ( ( c = word2[nbytes] ) != 0 ) && ( c != ' ' ) ) { nbytes++ ; } ; memcpy ( &word[length] , word2 , nbytes ) ; word [ length + nbytes ] = 0 ; found = Entry(word,word2,ph_out,flags,end_flags,wtab) ; if ( found ) { // set the skip words flag flags[0] |= FLAG_SKIPWORDS ; dictSkipWords = length ; return true ; } ; } ; /////////////////////////////////////////////////////////////////////////// for ( length = 0 ; length < ( N_WORD_BYTES - 1 ) ; length++ ) { if ( ( ( c = *word1++ ) == 0 ) || ( c == ' ' ) ) break ; if ( ( c == '.' ) && ( length > 0 ) && ( IsNumber ( word[length-1] )) ) { // needed for lang=hu, eg. "december 2.-ig" break ; } ; word [ length ] = c ; } ; word[length] = 0 ; found = Entry(word,word1,ph_out,flags,end_flags,wtab) ; /////////////////////////////////////////////////////////////////////////// if ( flags[0] & FLAG_MAX3 ) { if ( strcmp ( ph_out , phonemesRepeat ) == 0 ) { phonemesRepeatCount++ ; if ( phonemesRepeatCount > 3 ) ph_out[0] = 0 ; } else { strncpy(phonemesRepeat,ph_out,20) ; phonemesRepeatCount = 1 ; } ; } else { phonemesRepeatCount = 0 ; } ; /////////////////////////////////////////////////////////////////////////// if ( ( IsNull(found) ) && ( flags[1] & FLAG_ACCENT ) ) { int letter ; word2 = word ; if ( (*word2) == '_') word2++ ; len = toGrapheme ( letter , word2 ) ; // LookupAccentedLetter(tr,letter, ph_out); found = word2 + len ; } ; /////////////////////////////////////////////////////////////////////////// if ( found == 0 ) { ph_out[0] = 0 ; // try modifications to find a recognised word if ( ( end_flags & FLAG_SUFX_E_ADDED ) && ( word[length-1] == 'e' ) ) { // try removing an 'e' which has been added by RemoveEnding word[length-1] = 0 ; found = Entry(word,word1,ph_out,flags,end_flags,wtab) ; } else if ( ( end_flags & SUFX_D ) && ( word[length-1] == word[length-2] ) ) { // try removing a double letter word[length-1] = 0 ; found = Entry(word,word1,ph_out,flags,end_flags,wtab) ; } ; } ; /////////////////////////////////////////////////////////////////////////// if ( IsNull(found) ) { ph_out[0] = 0 ; return false ; } ; /////////////////////////////////////////////////////////////////////////// // if textmode is the default, then words which have phonemes are marked. if ( options.textmode )*flags ^= FLAG_TEXTMODE ; /////////////////////////////////////////////////////////////////////////// if (!(*flags & FLAG_TEXTMODE)) return true ; // the word translates to replacement text, not to phonemes /////////////////////////////////////////////////////////////////////////// if ( end_flags & FLAG_ALLOW_TEXTMODE ) { // only use replacement text if this is the original word, not if a prefix or suffix has been removed wordReplacement [ 0 ] = 0 ; wordReplacement [ 1 ] = ' ' ; // replacement word, preceded by zerochar and space sprintf(&wordReplacement[2],"%s ",ph_out) ; word1 = *wordptr ; *wordptr = &wordReplacement[2] ; // if ( option_phonemes == 2 ) { // len = found - word1 ; // include multiple matching words // memcpy(word,word1,len) ; // word[len] = 0 ; // fprintf(f_trans,"Replace: %s %s\n",word,*wordptr) ; // } ; } else { // check lang=hu január 21.-ig (error: suffix repeated ??) // flags[0] &= ~FLAG_SKIPWORDS ; } ; /////////////////////////////////////////////////////////////////////////// ph_out[0] = 0 ; return false ; } bool N::SpeechTranslator::Lookup(const char * word,char * ph_out) { bool found ; unsigned int flags[ 2 ] ; int say_as ; char * word1 = (char *)word ; char text [ 80 ] ; QList<SpeechWords> Words ; ///////////////////////////////////////////////////////////////////// flags[0] = 0 ; flags[1] = FLAG_LOOKUP_SYMBOL ; found = Lookup ( &word1,ph_out,flags,FLAG_ALLOW_TEXTMODE,Words ) ; ///////////////////////////////////////////////////////////////////// if ( ! (flags[0] & FLAG_TEXTMODE) ) return found ; say_as = OptionSayAs ; OptionSayAs = 0 ; // don't speak replacement word as letter names text[0] = 0 ; strncpy ( &text[1] , word1 , 78 ) ; // found = TranslateWord(tr, &text[1], 0, NULL, NULL) ; strcpy(ph_out,wordPhonemes) ; OptionSayAs = say_as ; ///////////////////////////////////////////////////////////////////// return found ; } int N::SpeechTranslator::LookupFlags(const char * word) { char buf [ 100 ] ; unsigned int flags [ 2 ] ; char * word1 = (char *)word ; QList<SpeechWords> Words ; flags[0] = flags[1] = 0 ; Lookup ( &word1,buf,flags,0,Words ) ; return flags [ 0 ] ; } void N::SpeechTranslator::WordEmbeddedCmd(UUIDs Cmds) { // Process embedded commands for emphasis, sayas, and break SUID embedded_cmd ; SUID value ; ////////////////////////////////////////////////////////////////// do { embedded_cmd = Cmds[0] ; value = embedded_cmd >> 8 ; Cmds.takeAt(0) ; switch ( embedded_cmd & 0x1f ) { case EMBED_Y : OptionSayAs = value ; break ; case EMBED_F : OptionEmphasis = value ; break ; case EMBED_B : // break command if ( value == 0 ) PrePause = 0 ; // break=none else PrePause += value ; break ; } ; } while ( ( ( embedded_cmd & 0x80 ) == 0 ) && Cmds.count() > 0 ) ; } // end of Word_EmbeddedCmd bool N::SpeechTranslator::GetWord(QString & word,char * p) { int len = p[1] & 0x7F ; int wlen = p[1] & 0x3F ; char w[128] ; word . clear ( ) ; nKickOut ( (*p) == 0 , false ) ; if ( wlen != len ) { // compressed memcpy(w,&p[2],wlen) ; w[wlen] = 0 ; printf("Compressed\n") ; } else { memcpy(w,&p[2],wlen) ; w[wlen] = 0 ; } ; word = QString(w) ; return true ; } bool N::SpeechTranslator::GetPhonemes(char * p,char * phs) { bool noPhoneme = p[1] & 0x80 ; if ( noPhoneme ) { phs[0] = 0 ; return false ; } ; p += ( ( p[1] & 0x3f ) + 2 ) ; strcpy ( phs , p ) ; return ( strlen ( phs ) > 0 ) ; } int N::SpeechTranslator::GetFlags(char * p,char * flags) { int size = p[0] ; int len = ( p[1] & 0x3F ) + 2 ; bool noPhoneme = p[1] & 0x80 ; if ( ! noPhoneme ) { char * s = p + len ; len ++ ; len += strlen(s) ; } ; size -= len ; if (size<=0) return 0 ; memcpy(flags,&p[len],size) ; return size ; } void N::SpeechTranslator::listings(void) { int hash ; int offset ; int len ; int wlen ; char m[512] ; char e[512] ; char f[512] ; char * p ; char * n ; char * d = dataDictList.data() ; if (dataDictList.size()<=0) return ; QString X ; for ( hash = 0 ; hash < N_HASH_DICT ; hash++ ) { p = dictHashTab[hash] ; offset = ( p - d ) ; printf("Hash [%5d] = %d\n",hash,offset) ; while ( (*p) != 0 ) { n = p + p[0] ; len = p[1] & 0x3F ; wlen = p[1] & 0x7F ; if ( //( len == wlen ) && GetWord ( X , p ) ) { int fs ; GetPhonemes(p,m) ; fs = GetFlags(p,f) ; phonemes.toMnemonics(m,e) ; N::printf ( QString("%1 = [ %2 | %3 ], %4").arg(X).arg(QString(m)).arg(QString(e)).arg(fs),true) ; } ; p = n ; } ; } ; }
57.724367
196
0.390793
[ "3d" ]
88322f746f0fcf158cc0b4f80c52c090010fc5e4
1,800
hpp
C++
STL_container/vector.hpp
JackieVan/JackieToys
ce9fee81fbf35794e0aa8965a35b787c9b5fbc59
[ "MIT" ]
null
null
null
STL_container/vector.hpp
JackieVan/JackieToys
ce9fee81fbf35794e0aa8965a35b787c9b5fbc59
[ "MIT" ]
null
null
null
STL_container/vector.hpp
JackieVan/JackieToys
ce9fee81fbf35794e0aa8965a35b787c9b5fbc59
[ "MIT" ]
null
null
null
/*==Header-File=====================================tab=2==============// FileName [Jackie_vector.hpp] Synopsis [A simple C++ header-file implementation of STL: vector] Author [Jackie Van] Date [Oct 4, 2021] Vision [ 0.1 : basic function, do not include iterator and algorithms ] =======================================================================*/ #pragma once #include <memory> // typedef and macro added here.. //=======================================================// //=======================================================// //===----------------------------------------------------------------------===// // vector class // //===----------------------------------------------------------------------===// template <class Type> class vector { public: vector() : __size(0), __capacity(2){ __data = new Type[__capacity]; } ~vector() { delete []__data; } public: void push_back(const Type& _val) { if (__size == __capacity) { __capacity *= 2; Type *__ptr = new Type[__capacity]; for (size_t i = 0; i < __size; ++i) { __ptr[i] = __data[i]; } delete []__data; __data = __ptr; } __data[__size++] = _val; } void clear() { __size = 0; for (size_t i = 0; i < __size; ++i) { __data[i] = nullptr; } } size_t size() const { return __size; } size_t capacity() const { return __capacity; } void resize() private: void erase_from_end_to(size_t _index) { } private: std::allocator<Type> __alloc; size_t __size; // the first index of unused __data ptr, it also be the real size size_t __capacity; // the length of __data ptr owned Type *__data; };
25
87
0.437778
[ "vector" ]
88343c169e60aae67542abd4fec3fe951045642d
4,160
cc
C++
PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/vc6/ublas_sysv.cc
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
1
2019-01-14T19:18:21.000Z
2019-01-14T19:18:21.000Z
PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/vc6/ublas_sysv.cc
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
null
null
null
PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/vc6/ublas_sysv.cc
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
1
2020-11-23T09:56:06.000Z
2020-11-23T09:56:06.000Z
// solving A * X = B // A symmetric // driver function sysv() #define BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS #define BOOST_NO_FUNCTION_TEMPLATE_ORDERING #include <cstddef> #include <iostream> #include <complex> #include <boost/numeric/bindings/lapack/sysv.hpp> #include <boost/numeric/bindings/traits/ublas_matrix.hpp> #include <boost/numeric/bindings/traits/ublas_symmetric.hpp> #include <boost/numeric/bindings/traits/ublas_hermitian.hpp> #include "utils2.h" namespace ublas = boost::numeric::ublas; namespace lapack = boost::numeric::bindings::lapack; using std::size_t; using std::cin; using std::cout; using std::endl; typedef double real; typedef std::complex<real> cmplx_t; typedef ublas::matrix<real, ublas::column_major> m_t; typedef ublas::matrix<cmplx_t, ublas::column_major> cm_t; typedef ublas::symmetric_adaptor<m_t, ublas::lower> symml_t; typedef ublas::symmetric_adaptor<m_t, ublas::upper> symmu_t; typedef ublas::symmetric_adaptor<cm_t, ublas::lower> csymml_t; typedef ublas::symmetric_adaptor<cm_t, ublas::upper> csymmu_t; template <typename M> void init_symm2 (M& m) { for (int i = 0; i < m.size1(); ++i) for (int j = i; j < m.size1(); ++j) m (i, j) = m (j, i) = 1 + j - i; } int main() { cout << endl; // symmetric cout << "real symmetric\n" << endl; size_t n; cout << "n -> "; cin >> n; if (n < 5) n = 5; cout << "min n = 5" << endl << endl; size_t nrhs = 2; m_t al (n, n), au (n, n); // matrices (storage) symml_t sal (al); // symmetric adaptor symmu_t sau (au); // symmetric adaptor m_t x (n, nrhs); m_t bl (n, nrhs), bu (n, nrhs); // RHS matrices init_symm2 (al); ublas::swap (row (al, 1), row (al, 4)); ublas::swap (column (al, 1), column (al, 4)); print_m (al, "al"); cout << endl; init_symm2 (au); ublas::swap (row (au, 2), row (au, 3)); ublas::swap (column (au, 2), column (au, 3)); print_m (au, "au"); cout << endl; for (int i = 0; i < x.size1(); ++i) { x (i, 0) = 1.; x (i, 1) = 2.; } bl = ublas::prod (sal, x); bu = ublas::prod (sau, x); print_m (bl, "bl"); cout << endl; print_m (bu, "bu"); cout << endl; m_t al1 (al), au1 (au); // for part 2 m_t bl1 (bl), bu1 (bu); lapack::sysv (sal, bl); print_m (bl, "xl"); cout << endl; lapack::sysv (sau, bu); print_m (bu, "xu"); cout << endl; // part 2 std::vector<int> ipiv (n); std::vector<real> work (1); int err = lapack::sysv ('L', al1, ipiv, bl1, work); print_m (al1, "al1 factored"); cout << endl; print_v (ipiv, "ipiv"); cout << endl; print_m (bl1, "xl1"); cout << endl; err = lapack::sysv ('U', au1, ipiv, bu1, work); print_m (au1, "au1 factored"); cout << endl; print_v (ipiv, "ipiv"); cout << endl; print_m (bu1, "xu1"); cout << endl; cout << endl; ////////////////////////////////////////////////////////// cout << "\n==========================================\n" << endl; cout << "complex symmetric\n" << endl; cm_t cal (n, n), cau (n, n); // matrices (storage) csymml_t scal (cal); // hermitian adaptor csymmu_t scau (cau); // hermitian adaptor cm_t cx (n, 1); cm_t cbl (n, 1), cbu (n, 1); // RHS init_symm2 (cal); init_symm2 (cau); cal *= cmplx_t (1, 1); cau *= cmplx_t (1, -0.5); print_m (cal, "cal"); cout << endl; print_m (cau, "cau"); cout << endl; for (int i = 0; i < cx.size1(); ++i) cx (i, 0) = cmplx_t (1, -1); print_m (cx, "cx"); cout << endl; cbl = ublas::prod (scal, cx); cbu = ublas::prod (scau, cx); print_m (cbl, "cbl"); cout << endl; print_m (cbu, "cbu"); cout << endl; int ierr = lapack::sysv (scal, cbl); if (ierr == 0) print_m (cbl, "cxl"); else cout << "matrix is not regular: ierr = " << ierr << endl; cout << endl; std::vector<cmplx_t> cwork (n); ierr = lapack::sysv (scau, ipiv, cbu, cwork); if (ierr == 0) { print_v (ipiv, "ipiv"); cout << endl; print_m (cbu, "cxu"); } else cout << "matrix is not regular: ierr = " << ierr << endl; cout << endl; }
23.502825
68
0.557933
[ "vector" ]
88392c98c05f9da2db3b3abd41a5969e29aecc89
4,363
cpp
C++
Code/Framework/AzNetworking/AzNetworking/DataStructures/TimeoutQueue.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2022-03-12T14:13:45.000Z
2022-03-12T14:13:45.000Z
Code/Framework/AzNetworking/AzNetworking/DataStructures/TimeoutQueue.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Code/Framework/AzNetworking/AzNetworking/DataStructures/TimeoutQueue.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzNetworking/DataStructures/TimeoutQueue.h> #include <AzCore/Console/ILogger.h> #include <climits> #include <cinttypes> namespace AzNetworking { void TimeoutQueue::Reset() { m_timeoutItemMap.clear(); m_timeoutItemQueue = TimeoutItemQueue(); m_nextTimeoutId = TimeoutId{0}; } TimeoutId TimeoutQueue::RegisterItem(uint64_t userData, AZ::TimeMs timeoutMs) { const TimeoutId timeoutId = m_nextTimeoutId; const AZ::TimeMs timeoutTimeMs = AZ::GetElapsedTimeMs() + timeoutMs; AZLOG(TimeoutQueue, "Pushing timeoutid %u with user data %" PRIu64 " to expire at time %u", aznumeric_cast<uint32_t>(timeoutId), userData, aznumeric_cast<uint32_t>(timeoutTimeMs) ); TimeoutQueueItem queueItem(timeoutId, timeoutTimeMs); m_timeoutItemMap[timeoutId] = TimeoutItem(userData, timeoutMs); m_timeoutItemQueue.push(queueItem); ++m_nextTimeoutId; return timeoutId; } TimeoutQueue::TimeoutItem *TimeoutQueue::RetrieveItem(TimeoutId timeoutId) { TimeoutItemMap::iterator iter = m_timeoutItemMap.find(timeoutId); if (iter != m_timeoutItemMap.end()) { return &(iter->second); } return nullptr; } void TimeoutQueue::RemoveItem(TimeoutId timeoutId) { m_timeoutItemMap.erase(timeoutId); } void TimeoutQueue::UpdateTimeouts(ITimeoutHandler& timeoutHandler, int32_t maxTimeouts) { int32_t numTimeouts = 0; if (maxTimeouts < 0) { maxTimeouts = INT_MAX; } AZ::TimeMs currentTimeMs = AZ::GetElapsedTimeMs(); while (m_timeoutItemQueue.size() > 0) { const TimeoutQueueItem queueItem = m_timeoutItemQueue.top(); const TimeoutId itemTimeoutId = queueItem.m_timeoutId; const AZ::TimeMs itemTimeoutMs = queueItem.m_timeoutTimeMs; // Head item has not timed out yet, we can terminate because we've run out of timed out items if (itemTimeoutMs >= currentTimeMs) { break; } ++numTimeouts; if (numTimeouts >= maxTimeouts) { AZLOG_WARN("Terminating timeout queue iteration due to hitting timeout count limit: %d", numTimeouts); break; } // Pop the item, we're either going to time it out or reinsert it m_timeoutItemQueue.pop(); TimeoutItemMap::iterator iter = m_timeoutItemMap.find(itemTimeoutId); if (iter == m_timeoutItemMap.end()) { // Item has already been deleted, just continue continue; } TimeoutItem mapItem = iter->second; // Check to see if the item has been refreshed since it was inserted if (mapItem.m_nextTimeoutTimeMs > currentTimeMs) { TimeoutQueueItem reQueueItem(itemTimeoutId, mapItem.m_nextTimeoutTimeMs); m_timeoutItemQueue.push(reQueueItem); continue; } // By this point, the item is definitely timed out // Invoke the timeout function to see how to proceed const TimeoutResult result = timeoutHandler.HandleTimeout(mapItem); if (result == TimeoutResult::Refresh) { mapItem.UpdateTimeoutTime(currentTimeMs); // Re-insert into priority queue TimeoutQueueItem reQueueItem(itemTimeoutId, mapItem.m_nextTimeoutTimeMs); m_timeoutItemQueue.push(reQueueItem); continue; } AZLOG(TimeoutQueue, "Popping timeoutid %u with user data %" PRIu64 ", expire time %d, current time %u", aznumeric_cast<uint32_t>(itemTimeoutId), mapItem.m_userData, aznumeric_cast<uint32_t>(mapItem.m_nextTimeoutTimeMs), aznumeric_cast<uint32_t>(currentTimeMs)); m_timeoutItemMap.erase(itemTimeoutId); } } }
34.626984
118
0.611735
[ "3d" ]
8839710a4abc1680d8cf6d56d57bd8a1a51ba246
2,003
cpp
C++
aws-cpp-sdk-iotsecuretunneling/source/model/ConnectionState.cpp
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-iotsecuretunneling/source/model/ConnectionState.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-iotsecuretunneling/source/model/ConnectionState.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/iotsecuretunneling/model/ConnectionState.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace IoTSecureTunneling { namespace Model { ConnectionState::ConnectionState() : m_status(ConnectionStatus::NOT_SET), m_statusHasBeenSet(false), m_lastUpdatedAtHasBeenSet(false) { } ConnectionState::ConnectionState(JsonView jsonValue) : m_status(ConnectionStatus::NOT_SET), m_statusHasBeenSet(false), m_lastUpdatedAtHasBeenSet(false) { *this = jsonValue; } ConnectionState& ConnectionState::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("status")) { m_status = ConnectionStatusMapper::GetConnectionStatusForName(jsonValue.GetString("status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("lastUpdatedAt")) { m_lastUpdatedAt = jsonValue.GetDouble("lastUpdatedAt"); m_lastUpdatedAtHasBeenSet = true; } return *this; } JsonValue ConnectionState::Jsonize() const { JsonValue payload; if(m_statusHasBeenSet) { payload.WithString("status", ConnectionStatusMapper::GetNameForConnectionStatus(m_status)); } if(m_lastUpdatedAtHasBeenSet) { payload.WithDouble("lastUpdatedAt", m_lastUpdatedAt.SecondsWithMSPrecision()); } return payload; } } // namespace Model } // namespace IoTSecureTunneling } // namespace Aws
23.564706
97
0.751373
[ "model" ]
883a4d3ce30e5d46e714dcc7606cfa79abc8366d
6,752
cpp
C++
tcob/src/core/io/FileSystem.cpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
2
2021-08-18T19:14:35.000Z
2021-12-01T14:14:49.000Z
tcob/src/core/io/FileSystem.cpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
tcob/src/core/io/FileSystem.cpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Tobias Bohnen // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include <tcob/core/io/FileSystem.hpp> #include <filesystem> #include <physfs.h> #include <tcob/core/io/FileStream.hpp> #include <tcob/core/io/Logger.hpp> namespace tcob { inline auto check(const std::string& msg, i32 c) -> bool { if (c == 0) { TCOB_LOG(msg + ": " + PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()), LogLevel::Error); } return c != 0; } void FileSystem::init(const char* argv0, const std::string& name) { check("init", PHYSFS_init(argv0)); check("setSaneConfig", PHYSFS_setSaneConfig(TCOB_ORGANIZATION_NAME, name.c_str(), "", 0, 0)); mount(".", "/"); } void FileSystem::done() { Logger::GetInstance().done(); PHYSFS_deinit(); } auto FileSystem::mount(const std::string& loc, const std::string& mp) -> bool { return check("mount", PHYSFS_mount(loc.c_str(), mp.c_str(), true)); } auto FileSystem::unmount(const std::string& loc) -> bool { return check("ummount", PHYSFS_unmount(loc.c_str())); } auto FileSystem::get_filesize(const std::string& path) -> i64 { if (!is_file(path)) { return -1; } return get_stat(path).FileSize; } auto FileSystem::read_as_string(const std::string& path) -> std::string { if (!is_file(path)) { return ""; } std::string retValue; retValue.reserve(get_filesize(path)); PHYSFS_File* handle { PHYSFS_openRead(path.c_str()) }; i64 read { 0 }; do { std::array<byte, 1024> buffer {}; read = PHYSFS_readBytes(handle, buffer.data(), buffer.size()); retValue.append(buffer.data(), read); } while (read != 0); check("close", PHYSFS_close(handle)); return retValue; } auto FileSystem::get_extension(const std::string& path) -> std::string { return std::filesystem::path { path }.extension().string(); } auto FileSystem::get_stem(const std::string& path) -> std::string { return std::filesystem::path { path }.stem().string(); } auto FileSystem::is_file(const std::string& path) -> bool { if (!exists(path)) { return false; } return get_stat(path).Type == FileType::File; } auto FileSystem::is_folder(const std::string& path) -> bool { if (!exists(path)) { return false; } return get_stat(path).Type == FileType::Folder; } auto FileSystem::get_stat(const std::string& path) -> Stat { PHYSFS_Stat stat; if (check("stat", PHYSFS_stat(path.c_str(), &stat))) { FileType type; switch (stat.filetype) { case PHYSFS_FILETYPE_REGULAR: type = FileType::File; break; case PHYSFS_FILETYPE_DIRECTORY: type = FileType::Folder; break; case PHYSFS_FILETYPE_SYMLINK: type = FileType::Symlink; break; default: type = FileType::Other; break; } return { .FileSize = stat.filesize, .ModTime = stat.modtime, .CreateTime = stat.createtime, .AccessTime = stat.accesstime, .Type = type, .ReadOnly = stat.readonly != 0 }; } return {}; } auto FileSystem::exists(const std::string& path) -> bool { return path.empty() ? false : PHYSFS_exists(path.c_str()); } auto FileSystem::delete_file(const std::string& path) -> bool { if (!is_file(path)) { return false; } return check("delete", PHYSFS_delete(path.c_str())); } auto FileSystem::delete_folder(const std::string& path) -> bool { if (!is_folder(path)) { return false; } const char* folder { path.c_str() }; char** items { PHYSFS_enumerateFiles(folder) }; for (char** item { items }; *item != nullptr; item++) { std::string file { path + "/" + *item }; if (is_folder(file)) { delete_folder(file); } else { delete_file(file); } } PHYSFS_freeList(items); return check("delete", PHYSFS_delete(folder)); } auto FileSystem::create_file(const std::string& path) -> bool { delete_file(path); const isize idx { path.find_last_of('/') }; if (idx != std::string::npos && idx > 0) { const std::string folder { path.substr(0, idx) }; if (!exists(folder)) { if (!create_folder(folder)) { return false; } } } return PHYSFS_close(PHYSFS_openWrite(path.c_str())) != 0; } auto FileSystem::create_folder(const std::string& path) -> bool { return check("create folder", PHYSFS_mkdir(path.c_str())); } struct CallbackData { std::vector<std::string> files; std::vector<std::string> folders; std::string pattern; }; // based on: https://www.geeksforgeeks.org/wildcard-pattern-matching/ auto wildcard_match(std::string_view str, std::string_view pattern) -> bool { if (pattern.empty()) return str.empty(); auto n { str.size() }; auto m { pattern.size() }; std::vector<bool> lookup((n + 1) * (m + 1), false); lookup[0] = true; for (isize j { 1 }; j <= m; j++) if (pattern[j - 1] == '*') lookup[j] = lookup[j - 1]; for (isize i { 1 }; i <= n; ++i) { for (isize j { 1 }; j <= m; j++) { if (pattern[j - 1] == '*') lookup[i * m + j] = lookup[i * m + j - 1] || lookup[(i - 1) * m + j]; else if (pattern[j - 1] == '?' || str[i - 1] == pattern[j - 1]) lookup[i * m + j] = lookup[(i - 1) * m + j - 1]; else lookup[i * m + j] = false; } } return lookup[n * m + m]; } auto enumCallback(void* data, const char* origdir, const char* fname) -> PHYSFS_EnumerateCallbackResult { auto* cd { static_cast<CallbackData*>(data) }; std::string entry { std::string(origdir) + "/" + std::string(fname) }; switch (FileSystem::get_stat(entry).Type) { case FileSystem::FileType::File: if (wildcard_match(entry, cd->pattern)) { cd->files.push_back(entry); } break; case FileSystem::FileType::Folder: cd->folders.push_back(entry); break; default: break; } return PHYSFS_ENUM_OK; } auto FileSystem::enumerate(const std::string& dir, const std::string& pattern, bool recursive) -> std::vector<std::string> { CallbackData cd; cd.pattern = pattern; PHYSFS_enumerate(dir.c_str(), &enumCallback, &cd); if (recursive) { for (const auto& folder : cd.folders) { auto files { enumerate(folder, pattern, true) }; cd.files.insert(cd.files.end(), files.begin(), files.end()); } } return cd.files; } }
25.28839
122
0.579236
[ "vector" ]
883ce0c35c247d08ee41f9cf8b347fcfc5999ee3
4,017
cpp
C++
plugins/graph_algorithm/src/strongly_connected_components.cpp
citypw/hal
c906c8fc34b8623533725d240aebcbce2d5a1c68
[ "MIT" ]
null
null
null
plugins/graph_algorithm/src/strongly_connected_components.cpp
citypw/hal
c906c8fc34b8623533725d240aebcbce2d5a1c68
[ "MIT" ]
null
null
null
plugins/graph_algorithm/src/strongly_connected_components.cpp
citypw/hal
c906c8fc34b8623533725d240aebcbce2d5a1c68
[ "MIT" ]
1
2020-01-09T23:38:55.000Z
2020-01-09T23:38:55.000Z
#include "plugin_graph_algorithm.h" #include "core/log.h" #include "netlist/gate.h" #include "netlist/net.h" #include "netlist/netlist.h" #include <boost/graph/graphviz.hpp> #include <boost/graph/strong_components.hpp> std::set<std::set<std::shared_ptr<gate>>> plugin_graph_algorithm::get_strongly_connected_components(std::shared_ptr<netlist> g, std::set<std::shared_ptr<gate>> gates) { if (g == nullptr) { log_error(this->get_name(), "{}", "parameter 'g' is nullptr"); return std::set<std::set<std::shared_ptr<gate>>>(); } /* check validity of gates */ if (gates.empty()) { gates = g->get_gates(); } for (const auto& current_gate : gates) { if (current_gate != nullptr) continue; log_error(this->get_name(), "{}", "parameter 'gates' contains a nullptr"); return std::set<std::set<std::shared_ptr<gate>>>(); } boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS> boost_graph; typedef boost::graph_traits<boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS>>::vertex_descriptor vertex_t; /* add ordered gates to directed boost graph */ std::set<u32> gate_ids; for (const auto& current_gate : gates) gate_ids.insert(current_gate->get_id()); std::map<u32, vertex_t> gate_id_to_vertex; std::map<vertex_t, u32> vertex_id_to_gate_id; u32 vertex_id_cnt = 0; for (const auto& gate_id : gate_ids) { auto vertex_descriptor = boost::add_vertex(boost_graph); gate_id_to_vertex[gate_id] = vertex_descriptor; vertex_id_to_gate_id[vertex_id_cnt++] = gate_id; } /* add ordered edges to directed boost graph */ std::map<u32, std::shared_ptr<net>> ordered_nets; for (const auto& current_gate : gates) { for (const auto& net : current_gate->get_fan_out_nets()) ordered_nets[net->get_id()] = net; } for (auto it_net : ordered_nets) { auto src = it_net.second->get_src(); if (src.gate == nullptr) continue; std::set<u32> dst_ids; for (auto dst : it_net.second->get_dsts()) dst_ids.insert(dst.gate->get_id()); for (const auto& dst_id : dst_ids) boost::add_edge(gate_id_to_vertex[src.gate->get_id()], gate_id_to_vertex[dst_id], boost_graph); } /* initialize parameters for strong_components() */ std::vector<int> component(g->get_gates().size()); std::vector<int> discover_time(g->get_gates().size()); std::vector<boost::default_color_type> color(g->get_gates().size()); std::vector<vertex_t> root(g->get_gates().size()); int num = strong_components(boost_graph, make_iterator_property_map(component.begin(), boost::get(boost::vertex_index, boost_graph)), root_map(make_iterator_property_map(root.begin(), boost::get(boost::vertex_index, boost_graph))) .color_map(make_iterator_property_map(color.begin(), boost::get(boost::vertex_index, boost_graph))) .discover_time_map(make_iterator_property_map(discover_time.begin(), boost::get(boost::vertex_index, boost_graph)))); log("SCC BOOST: {}", num); /* post process boost result */ std::map<int, std::set<u32>> component_to_gate_ids; for (std::vector<int>::size_type i = 0; i != component.size(); ++i) component_to_gate_ids[component[i]].insert(vertex_id_to_gate_id[i]); std::set<std::set<std::shared_ptr<gate>>> result; for (auto it_component : component_to_gate_ids) { std::set<std::shared_ptr<gate>> component_set; for (const auto& gate_id : it_component.second) component_set.insert(g->get_gate_by_id(gate_id)); if (!component_set.empty()) result.insert(component_set); } log_debug(this->get_name(), "found {} components in graph ", num); return result; }
39.382353
166
0.633806
[ "vector" ]
8842d359853e66422ca4fd9b6ddb100edc2d5b8c
1,779
cxx
C++
src/vw/Core/tests/TestThreadQueue.cxx
digimatronics/ComputerVision
2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24
[ "NASA-1.3" ]
1
2021-05-16T23:57:32.000Z
2021-05-16T23:57:32.000Z
src/vw/Core/tests/TestThreadQueue.cxx
rkrishnasanka/visionworkbench
2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24
[ "NASA-1.3" ]
null
null
null
src/vw/Core/tests/TestThreadQueue.cxx
rkrishnasanka/visionworkbench
2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24
[ "NASA-1.3" ]
2
2017-03-18T04:06:32.000Z
2019-01-17T10:34:39.000Z
// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <gtest/gtest.h> #include <vw/Core/ThreadQueue.h> using namespace vw; TEST(ThreadQueue, Basic) { ThreadQueue<uint32> q; ASSERT_TRUE(q.empty()); for (uint32 i = 0; i < 50; ++i) q.push(i); ASSERT_FALSE(q.empty()); uint32 pop; for (uint32 i = 0; i < 50; ++i) { ASSERT_FALSE(q.empty()); q.wait_pop(pop); EXPECT_EQ(i, pop); } } class PushTask { ThreadQueue<uint32>& m_queue; unsigned m_count, m_value; public: PushTask(ThreadQueue<uint32>& q, uint32 count, uint32 value) : m_queue(q), m_count(count), m_value(value) {} void operator()() { for (uint32 i = 0; i < m_count; ++i) { m_queue.push(m_value); } } }; TEST(ThreadQueue, Threaded) { typedef boost::shared_ptr<PushTask> TheTask; typedef boost::shared_ptr<vw::Thread> TheThread; ThreadQueue<uint32> q; ASSERT_TRUE(q.empty()); std::vector<std::pair<TheTask, TheThread> > threads(20); for (size_t i = 0; i < threads.size(); ++i) { TheTask task(new PushTask(q, 10, uint32(i))); TheThread thread( new Thread(task) ); threads[i] = std::make_pair(task, thread); } for (size_t i = 0; i < threads.size(); ++i) { threads[i].second->join(); } ASSERT_FALSE(q.empty()); std::vector<uint32> ret(threads.size()); uint32 value = uint32(ret.size())+1; while (!q.empty()) { EXPECT_TRUE(q.timed_wait_pop(value, 0)); EXPECT_LT(value, ret.size()); ret[value]++; } EXPECT_FALSE(q.timed_wait_pop(value, 0)); for (size_t i = 0; i < ret.size(); ++i) { EXPECT_EQ(10u, ret[i]); } }
23.407895
112
0.632378
[ "vector" ]