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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0adc51608e92df23cbb3156c1e48357b3352a505 | 2,499 | hh | C++ | src/Utilities/QuadraticInterpolator.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/Utilities/QuadraticInterpolator.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/Utilities/QuadraticInterpolator.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// QuadraticInterpolator
//
// Encapsulates the algorithm and data for parabolic interpolation in 1D
// Assumes the results is interpolated as y_interp = a + b*x + c*x^2
//
// Created by JMO, Fri Dec 4 14:28:08 PST 2020
//----------------------------------------------------------------------------//
#ifndef __Spheral_QuadraticInterpolator__
#define __Spheral_QuadraticInterpolator__
#include <cstddef>
#include <vector>
namespace Spheral {
class QuadraticInterpolator {
public:
//--------------------------- Public Interface ---------------------------//
// Constructors, destructors
QuadraticInterpolator(const double xmin,
const double xmax,
const std::vector<double>& yvals);
QuadraticInterpolator();
~QuadraticInterpolator();
// Initialize for interpolating in the given data
void initialize(const double xmin,
const double xmax,
const std::vector<double>& yvals);
// Interpolate for the y value
double operator()(const double x) const;
double prime(const double x) const; // First derivative
double prime2(const double x) const; // Second derivative
// Same as above, but use a pre-computed table position (from lowerBound)
double operator()(const double x, const size_t i0) const;
double prime(const double x, const size_t i0) const; // First derivative
double prime2(const double x, const size_t i0) const; // Second derivative
// Return the lower bound index in the table for the given x coordinate
size_t lowerBound(const double x) const;
// Allow read access the internal data representation
size_t size() const; // The size of the tabulated coefficient arrays
double xmin() const; // Minimum x coordinate for table
double xmax() const; // Maximum x coordinate for table
double xstep() const; // delta x between tabulated values
const std::vector<double>& coeffs() const; // the fitting coefficients
private:
//--------------------------- Private Interface --------------------------//
// Member data
size_t mN1;
double mXmin, mXmax, mXstep;
std::vector<double> mcoeffs;
};
}
#include "QuadraticInterpolatorInline.hh"
#else
// Forward declaration
namespace Spheral {
class QuadraticInterpolator;
}
#endif
| 34.708333 | 93 | 0.59904 | [
"vector"
] |
0ade53118d77fc33871eaf09d98340b4c80fc26c | 25,313 | cpp | C++ | cmds/statsd/src/logd/LogEvent.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 164 | 2015-01-05T16:49:11.000Z | 2022-03-29T20:40:27.000Z | cmds/statsd/src/logd/LogEvent.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 127 | 2015-01-12T12:02:32.000Z | 2021-11-28T08:46:25.000Z | cmds/statsd/src/logd/LogEvent.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 1,141 | 2015-01-01T22:54:40.000Z | 2022-02-09T22:08:26.000Z | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define DEBUG false // STOPSHIP if true
#include "logd/LogEvent.h"
#include "stats_log_util.h"
#include "statslog.h"
#include <binder/IPCThreadState.h>
#include <private/android_filesystem_config.h>
namespace android {
namespace os {
namespace statsd {
// for TrainInfo experiment id serialization
const int FIELD_ID_EXPERIMENT_ID = 1;
using namespace android::util;
using android::util::ProtoOutputStream;
using std::string;
using std::vector;
LogEvent::LogEvent(log_msg& msg) {
mContext =
create_android_log_parser(msg.msg() + sizeof(uint32_t), msg.len() - sizeof(uint32_t));
mLogdTimestampNs = msg.entry_v1.sec * NS_PER_SEC + msg.entry_v1.nsec;
mLogUid = msg.entry_v4.uid;
init(mContext);
if (mContext) {
// android_log_destroy will set mContext to NULL
android_log_destroy(&mContext);
}
}
LogEvent::LogEvent(const LogEvent& event) {
mTagId = event.mTagId;
mLogUid = event.mLogUid;
mElapsedTimestampNs = event.mElapsedTimestampNs;
mLogdTimestampNs = event.mLogdTimestampNs;
mValues = event.mValues;
}
LogEvent::LogEvent(const StatsLogEventWrapper& statsLogEventWrapper, int workChainIndex) {
mTagId = statsLogEventWrapper.getTagId();
mLogdTimestampNs = statsLogEventWrapper.getWallClockTimeNs();
mElapsedTimestampNs = statsLogEventWrapper.getElapsedRealTimeNs();
mLogUid = 0;
int workChainPosOffset = 0;
if (workChainIndex != -1) {
const WorkChain& wc = statsLogEventWrapper.getWorkChains()[workChainIndex];
// chains are at field 1, level 2
int depth = 2;
for (int i = 0; i < (int)wc.uids.size(); i++) {
int pos[] = {1, i + 1, 1};
mValues.push_back(FieldValue(Field(mTagId, pos, depth), Value(wc.uids[i])));
pos[2]++;
mValues.push_back(FieldValue(Field(mTagId, pos, depth), Value(wc.tags[i])));
mValues.back().mField.decorateLastPos(2);
}
mValues.back().mField.decorateLastPos(1);
workChainPosOffset = 1;
}
for (int i = 0; i < (int)statsLogEventWrapper.getElements().size(); i++) {
Field field(statsLogEventWrapper.getTagId(), getSimpleField(i + 1 + workChainPosOffset));
switch (statsLogEventWrapper.getElements()[i].type) {
case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::INT:
mValues.push_back(
FieldValue(field, Value(statsLogEventWrapper.getElements()[i].int_value)));
break;
case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::LONG:
mValues.push_back(
FieldValue(field, Value(statsLogEventWrapper.getElements()[i].long_value)));
break;
case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::FLOAT:
mValues.push_back(FieldValue(
field, Value(statsLogEventWrapper.getElements()[i].float_value)));
break;
case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::DOUBLE:
mValues.push_back(FieldValue(
field, Value(statsLogEventWrapper.getElements()[i].double_value)));
break;
case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::STRING:
mValues.push_back(
FieldValue(field, Value(statsLogEventWrapper.getElements()[i].str_value)));
break;
case android::os::StatsLogValue::STATS_LOG_VALUE_TYPE::STORAGE:
mValues.push_back(FieldValue(
field, Value(statsLogEventWrapper.getElements()[i].storage_value)));
break;
default:
break;
}
}
}
void LogEvent::createLogEvents(const StatsLogEventWrapper& statsLogEventWrapper,
std::vector<std::shared_ptr<LogEvent>>& logEvents) {
if (statsLogEventWrapper.getWorkChains().size() == 0) {
logEvents.push_back(std::make_shared<LogEvent>(statsLogEventWrapper, -1));
} else {
for (size_t i = 0; i < statsLogEventWrapper.getWorkChains().size(); i++) {
logEvents.push_back(std::make_shared<LogEvent>(statsLogEventWrapper, i));
}
}
}
LogEvent::LogEvent(int32_t tagId, int64_t wallClockTimestampNs, int64_t elapsedTimestampNs) {
mLogdTimestampNs = wallClockTimestampNs;
mElapsedTimestampNs = elapsedTimestampNs;
mTagId = tagId;
mLogUid = 0;
mContext = create_android_logger(1937006964); // the event tag shared by all stats logs
if (mContext) {
android_log_write_int64(mContext, elapsedTimestampNs);
android_log_write_int32(mContext, tagId);
}
}
LogEvent::LogEvent(int32_t tagId, int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
int32_t uid,
const std::map<int32_t, int32_t>& int_map,
const std::map<int32_t, int64_t>& long_map,
const std::map<int32_t, std::string>& string_map,
const std::map<int32_t, float>& float_map) {
mLogdTimestampNs = wallClockTimestampNs;
mElapsedTimestampNs = elapsedTimestampNs;
mTagId = android::util::KEY_VALUE_PAIRS_ATOM;
mLogUid = uid;
int pos[] = {1, 1, 1};
mValues.push_back(FieldValue(Field(mTagId, pos, 0 /* depth */), Value(uid)));
pos[0]++;
for (const auto&itr : int_map) {
pos[2] = 1;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
pos[2] = 2;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
mValues.back().mField.decorateLastPos(2);
pos[1]++;
}
for (const auto&itr : long_map) {
pos[2] = 1;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
pos[2] = 3;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
mValues.back().mField.decorateLastPos(2);
pos[1]++;
}
for (const auto&itr : string_map) {
pos[2] = 1;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
pos[2] = 4;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
mValues.back().mField.decorateLastPos(2);
pos[1]++;
}
for (const auto&itr : float_map) {
pos[2] = 1;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.first)));
pos[2] = 5;
mValues.push_back(FieldValue(Field(mTagId, pos, 2 /* depth */), Value(itr.second)));
mValues.back().mField.decorateLastPos(2);
pos[1]++;
}
if (!mValues.empty()) {
mValues.back().mField.decorateLastPos(1);
mValues.at(mValues.size() - 2).mField.decorateLastPos(1);
}
}
LogEvent::LogEvent(const string& trainName, int64_t trainVersionCode, bool requiresStaging,
bool rollbackEnabled, bool requiresLowLatencyMonitor, int32_t state,
const std::vector<uint8_t>& experimentIds, int32_t userId) {
mLogdTimestampNs = getWallClockNs();
mElapsedTimestampNs = getElapsedRealtimeNs();
mTagId = android::util::BINARY_PUSH_STATE_CHANGED;
mLogUid = android::IPCThreadState::self()->getCallingUid();
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(1)), Value(trainName)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(2)), Value(trainVersionCode)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(3)), Value((int)requiresStaging)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(4)), Value((int)rollbackEnabled)));
mValues.push_back(
FieldValue(Field(mTagId, getSimpleField(5)), Value((int)requiresLowLatencyMonitor)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(6)), Value(state)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(7)), Value(experimentIds)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(8)), Value(userId)));
}
LogEvent::LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
const VendorAtom& vendorAtom) {
mLogdTimestampNs = wallClockTimestampNs;
mElapsedTimestampNs = elapsedTimestampNs;
mTagId = vendorAtom.atomId;
mLogUid = AID_STATSD;
mValues.push_back(
FieldValue(Field(mTagId, getSimpleField(1)), Value(vendorAtom.reverseDomainName)));
for (int i = 0; i < (int)vendorAtom.values.size(); i++) {
switch (vendorAtom.values[i].getDiscriminator()) {
case VendorAtom::Value::hidl_discriminator::intValue:
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
Value(vendorAtom.values[i].intValue())));
break;
case VendorAtom::Value::hidl_discriminator::longValue:
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
Value(vendorAtom.values[i].longValue())));
break;
case VendorAtom::Value::hidl_discriminator::floatValue:
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
Value(vendorAtom.values[i].floatValue())));
break;
case VendorAtom::Value::hidl_discriminator::stringValue:
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(i + 2)),
Value(vendorAtom.values[i].stringValue())));
break;
}
}
}
LogEvent::LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
const InstallTrainInfo& trainInfo) {
mLogdTimestampNs = wallClockTimestampNs;
mElapsedTimestampNs = elapsedTimestampNs;
mTagId = android::util::TRAIN_INFO;
mValues.push_back(
FieldValue(Field(mTagId, getSimpleField(1)), Value(trainInfo.trainVersionCode)));
std::vector<uint8_t> experimentIdsProto;
writeExperimentIdsToProto(trainInfo.experimentIds, &experimentIdsProto);
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(2)), Value(experimentIdsProto)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(3)), Value(trainInfo.trainName)));
mValues.push_back(FieldValue(Field(mTagId, getSimpleField(4)), Value(trainInfo.status)));
}
LogEvent::LogEvent(int32_t tagId, int64_t timestampNs) : LogEvent(tagId, timestampNs, timestampNs) {
}
LogEvent::LogEvent(int32_t tagId, int64_t timestampNs, int32_t uid) {
mLogdTimestampNs = timestampNs;
mTagId = tagId;
mLogUid = uid;
mContext = create_android_logger(1937006964); // the event tag shared by all stats logs
if (mContext) {
android_log_write_int64(mContext, timestampNs);
android_log_write_int32(mContext, tagId);
}
}
void LogEvent::init() {
if (mContext) {
const char* buffer;
size_t len = android_log_write_list_buffer(mContext, &buffer);
// turns to reader mode
android_log_context contextForRead = create_android_log_parser(buffer, len);
if (contextForRead) {
init(contextForRead);
// destroy the context to save memory.
// android_log_destroy will set mContext to NULL
android_log_destroy(&contextForRead);
}
android_log_destroy(&mContext);
}
}
LogEvent::~LogEvent() {
if (mContext) {
// This is for the case when LogEvent is created using the test interface
// but init() isn't called.
android_log_destroy(&mContext);
}
}
bool LogEvent::write(int32_t value) {
if (mContext) {
return android_log_write_int32(mContext, value) >= 0;
}
return false;
}
bool LogEvent::write(uint32_t value) {
if (mContext) {
return android_log_write_int32(mContext, value) >= 0;
}
return false;
}
bool LogEvent::write(int64_t value) {
if (mContext) {
return android_log_write_int64(mContext, value) >= 0;
}
return false;
}
bool LogEvent::write(uint64_t value) {
if (mContext) {
return android_log_write_int64(mContext, value) >= 0;
}
return false;
}
bool LogEvent::write(const string& value) {
if (mContext) {
return android_log_write_string8_len(mContext, value.c_str(), value.length()) >= 0;
}
return false;
}
bool LogEvent::write(float value) {
if (mContext) {
return android_log_write_float32(mContext, value) >= 0;
}
return false;
}
bool LogEvent::writeKeyValuePairs(int32_t uid,
const std::map<int32_t, int32_t>& int_map,
const std::map<int32_t, int64_t>& long_map,
const std::map<int32_t, std::string>& string_map,
const std::map<int32_t, float>& float_map) {
if (mContext) {
if (android_log_write_list_begin(mContext) < 0) {
return false;
}
write(uid);
for (const auto& itr : int_map) {
if (android_log_write_list_begin(mContext) < 0) {
return false;
}
write(itr.first);
write(itr.second);
if (android_log_write_list_end(mContext) < 0) {
return false;
}
}
for (const auto& itr : long_map) {
if (android_log_write_list_begin(mContext) < 0) {
return false;
}
write(itr.first);
write(itr.second);
if (android_log_write_list_end(mContext) < 0) {
return false;
}
}
for (const auto& itr : string_map) {
if (android_log_write_list_begin(mContext) < 0) {
return false;
}
write(itr.first);
write(itr.second.c_str());
if (android_log_write_list_end(mContext) < 0) {
return false;
}
}
for (const auto& itr : float_map) {
if (android_log_write_list_begin(mContext) < 0) {
return false;
}
write(itr.first);
write(itr.second);
if (android_log_write_list_end(mContext) < 0) {
return false;
}
}
if (android_log_write_list_end(mContext) < 0) {
return false;
}
return true;
}
return false;
}
bool LogEvent::write(const std::vector<AttributionNodeInternal>& nodes) {
if (mContext) {
if (android_log_write_list_begin(mContext) < 0) {
return false;
}
for (size_t i = 0; i < nodes.size(); ++i) {
if (!write(nodes[i])) {
return false;
}
}
if (android_log_write_list_end(mContext) < 0) {
return false;
}
return true;
}
return false;
}
bool LogEvent::write(const AttributionNodeInternal& node) {
if (mContext) {
if (android_log_write_list_begin(mContext) < 0) {
return false;
}
if (android_log_write_int32(mContext, node.uid()) < 0) {
return false;
}
if (android_log_write_string8(mContext, node.tag().c_str()) < 0) {
return false;
}
if (android_log_write_list_end(mContext) < 0) {
return false;
}
return true;
}
return false;
}
/**
* The elements of each log event are stored as a vector of android_log_list_elements.
* The goal is to do as little preprocessing as possible, because we read a tiny fraction
* of the elements that are written to the log.
*
* The idea here is to read through the log items once, we get as much information we need for
* matching as possible. Because this log will be matched against lots of matchers.
*/
void LogEvent::init(android_log_context context) {
android_log_list_element elem;
int i = 0;
int depth = -1;
int pos[] = {1, 1, 1};
bool isKeyValuePairAtom = false;
do {
elem = android_log_read_next(context);
switch ((int)elem.type) {
case EVENT_TYPE_INT:
// elem at [0] is EVENT_TYPE_LIST, [1] is the timestamp, [2] is tag id.
if (i == 2) {
mTagId = elem.data.int32;
isKeyValuePairAtom = (mTagId == android::util::KEY_VALUE_PAIRS_ATOM);
} else {
if (depth < 0 || depth > 2) {
return;
}
mValues.push_back(
FieldValue(Field(mTagId, pos, depth), Value((int32_t)elem.data.int32)));
pos[depth]++;
}
break;
case EVENT_TYPE_FLOAT: {
if (depth < 0 || depth > 2) {
ALOGE("Depth > 2. Not supported!");
return;
}
// Handles the oneof field in KeyValuePair atom.
if (isKeyValuePairAtom && depth == 2) {
pos[depth] = 5;
}
mValues.push_back(FieldValue(Field(mTagId, pos, depth), Value(elem.data.float32)));
pos[depth]++;
} break;
case EVENT_TYPE_STRING: {
if (depth < 0 || depth > 2) {
ALOGE("Depth > 2. Not supported!");
return;
}
// Handles the oneof field in KeyValuePair atom.
if (isKeyValuePairAtom && depth == 2) {
pos[depth] = 4;
}
mValues.push_back(FieldValue(Field(mTagId, pos, depth),
Value(string(elem.data.string, elem.len))));
pos[depth]++;
} break;
case EVENT_TYPE_LONG: {
if (i == 1) {
mElapsedTimestampNs = elem.data.int64;
} else {
if (depth < 0 || depth > 2) {
ALOGE("Depth > 2. Not supported!");
return;
}
// Handles the oneof field in KeyValuePair atom.
if (isKeyValuePairAtom && depth == 2) {
pos[depth] = 3;
}
mValues.push_back(
FieldValue(Field(mTagId, pos, depth), Value((int64_t)elem.data.int64)));
pos[depth]++;
}
} break;
case EVENT_TYPE_LIST:
depth++;
if (depth > 2) {
ALOGE("Depth > 2. Not supported!");
return;
}
pos[depth] = 1;
break;
case EVENT_TYPE_LIST_STOP: {
int prevDepth = depth;
depth--;
if (depth >= 0 && depth < 2) {
// Now go back to decorate the previous items that are last at prevDepth.
// So that we can later easily match them with Position=Last matchers.
pos[prevDepth]--;
int path = getEncodedField(pos, prevDepth, false);
for (auto it = mValues.rbegin(); it != mValues.rend(); ++it) {
if (it->mField.getDepth() >= prevDepth &&
it->mField.getPath(prevDepth) == path) {
it->mField.decorateLastPos(prevDepth);
} else {
// Safe to break, because the items are in DFS order.
break;
}
}
pos[depth]++;
}
break;
}
case EVENT_TYPE_UNKNOWN:
break;
default:
break;
}
i++;
} while ((elem.type != EVENT_TYPE_UNKNOWN) && !elem.complete);
if (isKeyValuePairAtom && mValues.size() > 0) {
mValues[0] = FieldValue(Field(android::util::KEY_VALUE_PAIRS_ATOM, getSimpleField(1)),
Value((int32_t)mLogUid));
}
}
int64_t LogEvent::GetLong(size_t key, status_t* err) const {
// TODO(b/110561208): encapsulate the magical operations in Field struct as static functions
int field = getSimpleField(key);
for (const auto& value : mValues) {
if (value.mField.getField() == field) {
if (value.mValue.getType() == LONG) {
return value.mValue.long_value;
} else if (value.mValue.getType() == INT) {
return value.mValue.int_value;
} else {
*err = BAD_TYPE;
return 0;
}
}
if ((size_t)value.mField.getPosAtDepth(0) > key) {
break;
}
}
*err = BAD_INDEX;
return 0;
}
int LogEvent::GetInt(size_t key, status_t* err) const {
int field = getSimpleField(key);
for (const auto& value : mValues) {
if (value.mField.getField() == field) {
if (value.mValue.getType() == INT) {
return value.mValue.int_value;
} else {
*err = BAD_TYPE;
return 0;
}
}
if ((size_t)value.mField.getPosAtDepth(0) > key) {
break;
}
}
*err = BAD_INDEX;
return 0;
}
const char* LogEvent::GetString(size_t key, status_t* err) const {
int field = getSimpleField(key);
for (const auto& value : mValues) {
if (value.mField.getField() == field) {
if (value.mValue.getType() == STRING) {
return value.mValue.str_value.c_str();
} else {
*err = BAD_TYPE;
return 0;
}
}
if ((size_t)value.mField.getPosAtDepth(0) > key) {
break;
}
}
*err = BAD_INDEX;
return NULL;
}
bool LogEvent::GetBool(size_t key, status_t* err) const {
int field = getSimpleField(key);
for (const auto& value : mValues) {
if (value.mField.getField() == field) {
if (value.mValue.getType() == INT) {
return value.mValue.int_value != 0;
} else if (value.mValue.getType() == LONG) {
return value.mValue.long_value != 0;
} else {
*err = BAD_TYPE;
return false;
}
}
if ((size_t)value.mField.getPosAtDepth(0) > key) {
break;
}
}
*err = BAD_INDEX;
return false;
}
float LogEvent::GetFloat(size_t key, status_t* err) const {
int field = getSimpleField(key);
for (const auto& value : mValues) {
if (value.mField.getField() == field) {
if (value.mValue.getType() == FLOAT) {
return value.mValue.float_value;
} else {
*err = BAD_TYPE;
return 0.0;
}
}
if ((size_t)value.mField.getPosAtDepth(0) > key) {
break;
}
}
*err = BAD_INDEX;
return 0.0;
}
string LogEvent::ToString() const {
string result;
result += StringPrintf("{ uid(%d) %lld %lld (%d)", mLogUid, (long long)mLogdTimestampNs,
(long long)mElapsedTimestampNs, mTagId);
for (const auto& value : mValues) {
result +=
StringPrintf("%#x", value.mField.getField()) + "->" + value.mValue.toString() + " ";
}
result += " }";
return result;
}
void LogEvent::ToProto(ProtoOutputStream& protoOutput) const {
writeFieldValueTreeToStream(mTagId, getValues(), &protoOutput);
}
void writeExperimentIdsToProto(const std::vector<int64_t>& experimentIds,
std::vector<uint8_t>* protoOut) {
ProtoOutputStream proto;
for (const auto& expId : experimentIds) {
proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
(long long)expId);
}
protoOut->resize(proto.size());
size_t pos = 0;
sp<ProtoReader> reader = proto.data();
while (reader->readBuffer() != NULL) {
size_t toRead = reader->currentToRead();
std::memcpy(protoOut->data() + pos, reader->readBuffer(), toRead);
pos += toRead;
reader->move(toRead);
}
}
} // namespace statsd
} // namespace os
} // namespace android
| 36.007112 | 100 | 0.567851 | [
"vector"
] |
0ae449dd526b8a112567338f90ff209c14b4cb6f | 1,213 | hpp | C++ | include/matazure/tensor_initializer.hpp | matazure/mtensor | 4289284b201cb09ed1dfc49f44d6738751affd63 | [
"MIT"
] | 82 | 2020-04-11T09:33:36.000Z | 2022-03-23T03:47:25.000Z | include/matazure/tensor_initializer.hpp | Lexxos/mtensor | feb120923dad3fb4ae3b31dd09931622a63c3d06 | [
"MIT"
] | 28 | 2017-04-26T17:12:35.000Z | 2019-04-08T04:05:24.000Z | include/matazure/tensor_initializer.hpp | Lexxos/mtensor | feb120923dad3fb4ae3b31dd09931622a63c3d06 | [
"MIT"
] | 22 | 2017-01-10T14:57:29.000Z | 2019-12-17T08:55:59.000Z | #pragma once
#include <initializer_list>
#include <matazure/point.hpp>
#include <vector>
namespace matazure {
template <typename _ValueType, int_t _Rank>
struct nested_initializer_list {
using type =
std::initializer_list<typename nested_initializer_list<_ValueType, _Rank - 1>::type>;
static _ValueType access(const type& init, pointi<_Rank> idx) {
auto tmp_i = idx[0];
auto& sub_init = *(init.begin() + tmp_i);
return nested_initializer_list<_ValueType, _Rank - 1>::access(sub_init,
gather_point<0>(idx));
}
static pointi<_Rank> shape(const type& init) {
return scatter_point<0>(
nested_initializer_list<_ValueType, _Rank - 1>::shape(*init.begin()),
static_cast<int_t>(init.size()));
};
};
template <typename _ValueType>
struct nested_initializer_list<_ValueType, 1> {
using type = std::initializer_list<_ValueType>;
static _ValueType access(const type& init, pointi<1> idx) { return *(init.begin() + idx[0]); }
static pointi<1> shape(const type& init) { return pointi<1>{static_cast<int_t>(init.size())}; };
};
} // namespace matazure
| 32.783784 | 100 | 0.641385 | [
"shape",
"vector"
] |
0ae7d64c8cb8ea4931bcbaa40c591dbce8c03f3e | 2,326 | hpp | C++ | src/animator.hpp | DavoSK/baliksena | c347055084b8e5ea9b0f970cbceb0769ab4504d3 | [
"BSD-3-Clause"
] | 5 | 2021-11-12T18:03:06.000Z | 2021-12-19T14:22:05.000Z | src/animator.hpp | DavoSK/baliksena | c347055084b8e5ea9b0f970cbceb0769ab4504d3 | [
"BSD-3-Clause"
] | null | null | null | src/animator.hpp | DavoSK/baliksena | c347055084b8e5ea9b0f970cbceb0769ab4504d3 | [
"BSD-3-Clause"
] | 1 | 2021-11-12T18:03:08.000Z | 2021-11-12T18:03:08.000Z | #pragma once
#include <string>
#include "logger.hpp"
#include "mafia/parser_5ds.hpp"
#include "single_mesh.hpp"
enum class Key
{
Trans,
Rot,
Scale,
Count
};
class Sequence {
public:
Sequence(Frame* frame) :
mFrame(frame)
{
assert(mFrame != nullptr);
start();
}
void update() {
if(!Translations.empty()) {
const auto& mov = Translations.at(TranslationKeyId);
mFrame->setPos({ mov.x, mov.y, mov.z });
if(TranslationKeyId + 1 < Translations.size())
TranslationKeyId++;
else
Finished[0] = true;
}
if(!Rotations.empty()) {
const auto& rot = Rotations.at(RotationKeyId);
glm::quat rotation{};
rotation.w = rot.w;
rotation.x = rot.x;
rotation.y = rot.y;
rotation.z = rot.z;
mFrame->setRot(rotation);
if(RotationKeyId + 1 < Rotations.size())
RotationKeyId++;
else
Finished[1] = true;
}
if(!Scales.empty()) {
const auto& scl = Scales.at(ScaleKeyId);
mFrame->setScale({ scl.x, scl.y, scl.z});
if(ScaleKeyId + 1 < Scales.size())
ScaleKeyId++;
else
Finished[2] = true;
}
}
bool isFinished() const {
return (Finished[0] && Finished[1] && Finished[2]);
}
void start() {
TranslationKeyId = 0;
RotationKeyId = 0;
ScaleKeyId = 0;
Finished[0] = Translations.empty();
Finished[1] = Rotations.empty();
Finished[2] = Scales.empty();
}
Frame* mFrame;
std::vector<glm::vec3> Translations{};
std::vector<glm::quat> Rotations{};
std::vector<glm::vec3> Scales{};
int32_t TranslationKeyId = 0;
int32_t RotationKeyId = 0;
int32_t ScaleKeyId = 0;
bool Finished[3];
};
class Animator {
public:
Animator(SingleMesh* mesh);
bool open(const std::string& path);
void update();
void init();
private:
bool mInited = false;
int mSequenceId = 0;
uint64_t mLastFrameTime = 0;
MFFormat::DataFormat5DS mParsedAnim{};
std::vector<Sequence> mSequences;
SingleMesh* mSingleMesh{ nullptr };
}; | 23.029703 | 64 | 0.530525 | [
"mesh",
"vector"
] |
0aed71d5a0c7e289a796bf9e72c7e12eb9b1f0cd | 1,021 | cpp | C++ | leetcode/0496_next_greater_element_i.cpp | jacquerie/leetcode | a05e6b832eb0e0740aaff7b2eb3109038ad404bf | [
"MIT"
] | 3 | 2018-05-10T09:56:49.000Z | 2020-11-07T18:09:42.000Z | leetcode/0496_next_greater_element_i.cpp | jacquerie/leetcode | a05e6b832eb0e0740aaff7b2eb3109038ad404bf | [
"MIT"
] | null | null | null | leetcode/0496_next_greater_element_i.cpp | jacquerie/leetcode | a05e6b832eb0e0740aaff7b2eb3109038ad404bf | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Jacopo Notarstefano
#include <cassert>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
vector<int> result(findNums.size());
for (int i = 0; i < findNums.size(); i++) {
result[i] = nextGreaterElementHelper(findNums[i], nums);
}
return result;
}
private:
int nextGreaterElementHelper(int findNum, const vector<int>& nums) {
bool found = false;
for (auto num : nums) {
if (found && num > findNum) {
return num;
} else if (num == findNum) {
found = true;
}
}
return -1;
}
};
int main() {
auto solution = Solution();
vector<int> findNums = {4, 1, 2};
vector<int> nums = {1, 3, 4, 2};
vector<int> expected = {-1, 3, -1};
vector<int> result = solution.nextGreaterElement(findNums, nums);
assert(expected == result);
}
| 22.195652 | 78 | 0.550441 | [
"vector"
] |
0aee15569f3ca7c7258813aac56968490d754f56 | 559 | cc | C++ | uva/00927.cc | algoriddle/cp | 9596654f921c9da0710e2743b235bd76d938a62c | [
"MIT"
] | null | null | null | uva/00927.cc | algoriddle/cp | 9596654f921c9da0710e2743b235bd76d938a62c | [
"MIT"
] | null | null | null | uva/00927.cc | algoriddle/cp | 9596654f921c9da0710e2743b235bd76d938a62c | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <vector>
typedef unsigned long long ull;
using namespace std;
int main() {
ios::sync_with_stdio(false);
int C;
cin >> C;
while (C--) {
int t;
double d, k;
cin >> t;
vector<ull> c(t + 1);
for (int i = 0; i <= t; ++i) {
cin >> c[i];
}
cin >> d >> k;
ull nb = ull(floor((sqrt(d * (d + 8.0 * (k - 1.0))) - d) / (2.0 * d))) + 1;
ull r = 0, n = 1;
for (int i = 0; i <= t; ++i) {
r += c[i] * n;
n *= nb;
}
cout << r << endl;
}
return 0;
}
| 17.46875 | 79 | 0.440072 | [
"vector"
] |
0aeff9625e0932c57bb12d04167deda6d27dc9e2 | 4,023 | cpp | C++ | packages/monte_carlo/collision/neutron/test/tstNeutronAbsorptionReaction.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 10 | 2019-11-14T19:58:30.000Z | 2021-04-04T17:44:09.000Z | packages/monte_carlo/collision/neutron/test/tstNeutronAbsorptionReaction.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 43 | 2020-03-03T19:59:20.000Z | 2021-09-08T03:36:08.000Z | packages/monte_carlo/collision/neutron/test/tstNeutronAbsorptionReaction.cpp | bam241/FRENSIE | e1760cd792928699c84f2bdce70ff54228e88094 | [
"BSD-3-Clause"
] | 6 | 2020-02-12T17:37:07.000Z | 2020-09-08T18:59:51.000Z | //---------------------------------------------------------------------------//
//!
//! \file tstNeutronAbsorptionReaction.cpp
//! \author Alex Robinson
//! \brief Nuclear reaction unit tests.
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
// FRENSIE Includes
#include "MonteCarlo_NeutronAbsorptionReaction.hpp"
#include "Data_ACEFileHandler.hpp"
#include "Data_XSSNeutronDataExtractor.hpp"
#include "Utility_UnitTestHarnessWithMain.hpp"
//---------------------------------------------------------------------------//
// Testing Variables.
//---------------------------------------------------------------------------//
std::shared_ptr<const MonteCarlo::NeutronNuclearReaction> nuclear_reaction;
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
// Check that the number of emitted neutrons can be returned
FRENSIE_UNIT_TEST( NeutronAbsorptionReaction,
getNumberOfEmittedParticles )
{
FRENSIE_CHECK_EQUAL( nuclear_reaction->getNumberOfEmittedParticles( 0.0 ), 0);
}
//---------------------------------------------------------------------------//
// Check that the reaction can be simulated
FRENSIE_UNIT_TEST( NeutronAbsorptionReaction,
react )
{
MonteCarlo::ParticleBank bank;
{
std::shared_ptr<MonteCarlo::NeutronState>
neutron( new MonteCarlo::NeutronState(0ull) );
neutron->setDirection( 0.0, 0.0, 1.0 );
neutron->setEnergy( 1.0 );
bank.push( neutron );
}
nuclear_reaction->react( dynamic_cast<MonteCarlo::NeutronState&>(bank.top()),
bank );
FRENSIE_CHECK( bank.top().isGone() );
FRENSIE_CHECK_EQUAL( bank.size(), 1 );
}
//---------------------------------------------------------------------------//
// Custom Setup
//---------------------------------------------------------------------------//
FRENSIE_CUSTOM_UNIT_TEST_SETUP_BEGIN();
std::string test_basic_ace_file_name;
unsigned test_basic_ace_file_start_line;
FRENSIE_CUSTOM_UNIT_TEST_COMMAND_LINE_OPTIONS()
{
ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_basic_ace_file",
test_basic_ace_file_name, "",
"Test basic ACE file name" );
ADD_STANDARD_OPTION_AND_ASSIGN_VALUE( "test_basic_ace_file_start_line",
test_basic_ace_file_start_line, 1,
"Test basic ACE file start line" );
}
FRENSIE_CUSTOM_UNIT_TEST_INIT()
{
std::unique_ptr<Data::ACEFileHandler> ace_file_handler(
new Data::ACEFileHandler( test_basic_ace_file_name,
"1001.70c",
test_basic_ace_file_start_line ) );
std::unique_ptr<Data::XSSNeutronDataExtractor> xss_data_extractor(
new Data::XSSNeutronDataExtractor( ace_file_handler->getTableNXSArray(),
ace_file_handler->getTableJXSArray(),
ace_file_handler->getTableXSSArray()));
std::shared_ptr<const std::vector<double> > energy_grid(
new std::vector<double>( xss_data_extractor->extractEnergyGrid() ) );
std::shared_ptr<const std::vector<double> > cross_section(
new std::vector<double>( xss_data_extractor->extractElasticCrossSection() ) );
nuclear_reaction.reset( new MonteCarlo::NeutronAbsorptionReaction(
energy_grid,
cross_section,
0u,
MonteCarlo::N__N_ELASTIC_REACTION,
0.0,
ace_file_handler->getTableTemperature().value() ) );
}
FRENSIE_CUSTOM_UNIT_TEST_SETUP_END();
//---------------------------------------------------------------------------//
// end tstNeutronAbsorptionReaction.cpp
//---------------------------------------------------------------------------//
| 36.572727 | 88 | 0.512553 | [
"vector"
] |
0af89b723cf1e73b94d3346c3c58764b7d27f458 | 2,669 | cpp | C++ | mqtt_service.cpp | markondej/mqtt_service | 01ed25448c4d3762f3d4518cd90d87af2eba3275 | [
"BSD-3-Clause"
] | null | null | null | mqtt_service.cpp | markondej/mqtt_service | 01ed25448c4d3762f3d4518cd90d87af2eba3275 | [
"BSD-3-Clause"
] | null | null | null | mqtt_service.cpp | markondej/mqtt_service | 01ed25448c4d3762f3d4518cd90d87af2eba3275 | [
"BSD-3-Clause"
] | null | null | null | #include "mqtt/service.hpp"
#ifdef _WIN32
#include "console_window.hpp"
using Console = ConsoleWindow;
#else
#include "console.hpp"
#include <csignal>
#endif
#include <cstring>
#ifndef _WIN32
#define CONSOLE_NOP_DELAY 500000
#endif
mqtt::Service *service = nullptr;
std::vector<uint8_t> GeneratePayload(const std::string &string) {
std::vector<uint8_t> payload;
payload.resize(string.size());
std::memcpy(payload.data(), string.data(), string.size());
return payload;
};
#ifndef _WIN32
void signalHandler(int sigNum)
{
if ((service != nullptr) && service->IsEnabled()) {
service->Disable();
}
}
#endif
#ifdef _WIN32
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#else
int main(int argc, char** argv)
#endif
{
std::string address = SERVICE_DEFAULT_ADDRESS;
#ifndef SERVICE_OPERATION_MODE_QUEUE
std::string filename = SERVICE_DEFAULT_TOPICS_FILENAME;
#endif
uint16_t port = SERVICE_DEFAULT_PORT;
#ifdef _WIN32
int argc = __argc;
char** argv = __argv;
#endif
if (argc > 1) { address = argv[1]; }
if (argc > 2) { port = std::stoi(argv[2]); }
#ifndef SERVICE_OPERATION_MODE_QUEUE
if (argc > 3) { filename = argv[3]; }
#endif
#ifndef _WIN32
std::signal(SIGINT, signalHandler);
std::signal(SIGTSTP, signalHandler);
int result = EXIT_SUCCESS;
#else
WPARAM result = 1;
#endif
Console *console = nullptr;
try {
console = new Console();
service = new mqtt::Service(
address,
port,
#ifndef SERVICE_OPERATION_MODE_QUEUE
filename,
#endif
nullptr,
nullptr,
nullptr,
[&](const std::exception &exception) {
if (console != nullptr) {
console->Print(exception.what());
}
#ifdef _WIN32
MessageBox(NULL, exception.what(), "Error", MB_OK | MB_ICONERROR);
#endif
}, [&](const std::string &message) {
if (console != nullptr) {
console->Print(message);
}
});
#ifndef _WIN32
while (service->IsEnabled()) {
std::this_thread::sleep_for(std::chrono::microseconds(CONSOLE_NOP_DELAY));
}
#else
result = Window::HandleMessages(*service);
#endif
} catch (...) {
#ifndef _WIN32
result = EXIT_FAILURE;
#endif
}
if (service != nullptr) {
auto temp = service;
service = nullptr;
delete temp;
}
if (console != nullptr) {
auto temp = console;
console = nullptr;
delete temp;
}
return result;
}
| 23.208696 | 95 | 0.602848 | [
"vector"
] |
0afc447f6cf9efba6a1855893b66a68aa5ee1f1f | 29,231 | hpp | C++ | sources/xrn/Ecs/Entity/Container.hpp | DiantArts/xrnEcs | 821ad9504dc022972f499721a8f494ab78d4d2d8 | [
"MIT"
] | null | null | null | sources/xrn/Ecs/Entity/Container.hpp | DiantArts/xrnEcs | 821ad9504dc022972f499721a8f494ab78d4d2d8 | [
"MIT"
] | 13 | 2022-03-18T00:36:09.000Z | 2022-03-28T14:14:26.000Z | sources/xrn/Ecs/Entity/Container.hpp | DiantArts/xrnEcs | 821ad9504dc022972f499721a8f494ab78d4d2d8 | [
"MIT"
] | null | null | null | #pragma once
///////////////////////////////////////////////////////////////////////////
// Headers
///////////////////////////////////////////////////////////////////////////
#include <xrn/Ecs/Component/Container.hpp>
#include <xrn/Ecs/Entity/Entity.hpp>
#include <xrn/Ecs/Entity/Reference.hpp>
namespace xrn::ecs::entity {
///////////////////////////////////////////////////////////////////////////
/// \brief Contains all the entities
/// \ingroup ecs-entity
///
/// \include Container.hpp <xrn/Ecs/Entity/Container.hpp>
///
/// Contains all ::xrn::ecs::entity::Entity needed for the ECS architecture. All the
/// entity components are placed in the ::xrn::ecs::component::Container passed
/// as constructor argument. This container is kept as reference.
///
/// Usage example:
/// \code
/// ::xrn::ecs::component::Container components;
/// ::xrn::ecs::entity::Container entities{ components };
/// auto entity1{ entities.emplace<::xrn::ecs::component::test::ComponentA>() };
/// auto entity2{ entities.get(entity1.getId()) }; // same as entity1
/// auto entity3{ entities[entity1.getId()] }; // same as entity1
///
/// entities.contains(entity1.getId()); // true
/// &entities.unsafeGet(entity1.getId()).get() == &entity1.get(); // true
/// &entity1.get() == &entity2.get(); // true
/// &entity1.get() == &entity3.get(); // true
/// \endcode
///
/// \see ::xrn::ecs::entity::Entity
///
///////////////////////////////////////////////////////////////////////////
class Container {
public:
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// static elements
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Type internally contained by the class
///
///////////////////////////////////////////////////////////////////////////
using Type = ::std::vector<::xrn::ecs::entity::Entity>;
public:
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Constructors
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Constructor
///
/// Constructs an ::xrn::ecs::entity::Container.
///
/// \param amount Time in milliseconds
///
/// \see ::xrn::ecs::component::declaration::detail::AComponent
///
///////////////////////////////////////////////////////////////////////////
inline explicit Container(
::xrn::ecs::component::Container& componentContainer
);
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Rule of 5
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// Clears every component of every entity.
///
///////////////////////////////////////////////////////////////////////////
inline ~Container();
///////////////////////////////////////////////////////////////////////////
/// \brief Copy constructor
///
///////////////////////////////////////////////////////////////////////////
Container(
const ::xrn::ecs::entity::Container& other
) noexcept = delete;
///////////////////////////////////////////////////////////////////////////
/// \brief Copy assign operator
///
///////////////////////////////////////////////////////////////////////////
auto operator=(
const ::xrn::ecs::entity::Container& other
) noexcept
-> ::xrn::ecs::entity::Container& = delete;
///////////////////////////////////////////////////////////////////////////
/// \brief Move constructor
///
///////////////////////////////////////////////////////////////////////////
Container(
::xrn::ecs::entity::Container&& that
) noexcept = delete;
///////////////////////////////////////////////////////////////////////////
/// \brief Move assign operator
///
///////////////////////////////////////////////////////////////////////////
auto operator=(
::xrn::ecs::entity::Container&& that
) noexcept
-> ::xrn::ecs::entity::Container& = delete;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Emplace
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Emplaces an entity
///
/// Creates an entity from the component given as template parameter.
///
/// \warning The returned ::xrn::ecs::entity::Reference may be invalid.
/// The user must call ::xrn::ecs::entity::Reference::isValid()
/// if he isn't certain that the entity is present in the
/// container to check its validity.
/// \warning This reference may be invalidated when an entity is created.
///
/// \tparam ComponentTypes Type of components to emplace inside the
/// ::xrn::ecs::entity::Entity when creating it
///
/// \param amount Time in milliseconds
///
/// \returns An ::xrn::ecs::entity::Reference to the entity emplaced
///
/// \see ::xrn::ecs::component::declaration::detail::AComponent
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isEcsRegistered... ComponentTypes
> auto emplace()
-> ::xrn::ecs::entity::Reference;
///////////////////////////////////////////////////////////////////////////
/// \brief Emplaces an entity
///
/// Creates an entity from the component given as template parameter.
///
/// \warning The returned ::xrn::ecs::entity::Reference may be invalid.
/// The user must call ::xrn::ecs::entity::Reference::isValid()
/// if he isn't certain that the entity is present in the
/// container to check its validity.
/// \warning This reference may be invalidated when an entity is created.
///
/// \param components Components to emplace inside the entity created
///
/// \returns An ::xrn::ecs::entity::Reference to the entity emplaced
///
/// \see ::xrn::ecs::component::declaration::detail::AComponent
///
///////////////////////////////////////////////////////////////////////////
inline auto emplace(
::xrn::ecs::detail::constraint::isComponent auto&&... components
) -> ::xrn::ecs::entity::Reference;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Remove
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Removes an ::xrn::ecs::entity::Entity from the container
///
/// Remove the entity that matches the ::xrn::util::BasicForwardId given as
/// parameter.
///
/// \param Entity entity to find and delete
///
/// \see ::xrn::ecs::entity::Entity
///
///////////////////////////////////////////////////////////////////////////
inline void remove(
::xrn::Id entityId
);
///////////////////////////////////////////////////////////////////////////
/// \brief Removes an ::xrn::ecs::entity::Entity from the container
///
/// Remove the entity that matches the ::xrn::util::BasicForwardId given as
/// parameter.
///
/// \param entity Id to find and delete
///
/// \see ::xrn::util::BasicForwardId
///
///////////////////////////////////////////////////////////////////////////
inline void remove(
const ::xrn::ecs::Entity& entity
);
///////////////////////////////////////////////////////////////////////////
/// \brief Removes an ::xrn::ecs::entity::Entity from the container
///
/// Remove the entity referenced by the ::xrn::ecs::entity::Reference.
///
/// \param entityReference Entity to find and delete
///
/// \see ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
inline void remove(
const ::xrn::ecs::entity::Reference& entityReference
);
///////////////////////////////////////////////////////////////////////////
/// \brief Removes an ::xrn::ecs::entity::Entity from the container
///
/// Remove the entity referenced by the ::xrn::ecs::entity::ConstReference.
///
/// \param entityReference Entity to find and delete
///
/// \see ::xrn::ecs::entity::ConstReference
///
///////////////////////////////////////////////////////////////////////////
inline void remove(
const ::xrn::ecs::entity::ConstReference& entityReference
);
///////////////////////////////////////////////////////////////////////////
/// \brief Removes all ::xrn::ecs::entity::Entity from the container
///
///////////////////////////////////////////////////////////////////////////
inline void clear();
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Get
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Gets a ::xrn::ecs::entity::ConstReference to an entity contained
/// it the container
///
/// \param entityId Entity to find and return
///
/// \warning The returned ::xrn::ecs::entity::Reference may be invalid.
/// The user must call ::xrn::ecs::entity::Reference::isValid()
/// if he isn't certain that the entity is present in the
/// container to check its validity.
/// \warning This reference may be invalidated when an entity is created.
///
/// \see ::xrn::util::BasicForwardId, ::xrn::ecs::entity::ConstReference
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto operator[](
::xrn::Id entityId
) const
-> ::xrn::ecs::entity::ConstReference;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets a mutable ::xrn::ecs::entity::Reference to an entity
/// contained it the container
///
/// \param entityId Entity to find and return
///
/// \warning The returned ::xrn::ecs::entity::Reference may be invalid.
/// The user must call ::xrn::ecs::entity::Reference::isValid()
/// if he isn't certain that the entity is present in the
/// container to check its validity.
/// \warning This reference may be invalidated when an entity is created.
///
/// \see ::xrn::util::BasicForwardId, ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto operator[](
::xrn::Id entityId
) -> ::xrn::ecs::entity::Reference;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets a ::xrn::ecs::entity::ConstReference to an entity contained
/// it the container
///
/// \param entityId Entity to find and return
///
/// \warning The returned ::xrn::ecs::entity::Reference may be invalid.
/// The user must call ::xrn::ecs::entity::Reference::isValid()
/// if he isn't certain that the entity is present in the
/// container to check its validity.
/// \warning This reference may be invalidated when an entity is created.
///
/// \see ::xrn::util::BasicForwardId, ::xrn::ecs::entity::ConstReference
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto get(
::xrn::Id entityId
) const
-> ::xrn::ecs::entity::ConstReference;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets a mutable ::xrn::ecs::entity::Reference to an entity
/// contained it the container
///
/// \param entityId Entity to find and return
///
/// \warning The returned ::xrn::ecs::entity::Reference may be invalid.
/// The user must call ::xrn::ecs::entity::Reference::isValid()
/// if he isn't certain that the entity is present in the
/// container to check its validity.
/// \warning This reference may be invalidated when an entity is created.
///
/// \see ::xrn::util::BasicForwardId, ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto get(
::xrn::Id entityId
) -> ::xrn::ecs::entity::Reference;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets a ::xrn::ecs::entity::ConstReference to an entity contained
/// it the container
///
/// \warning Calling this function while the entity is not present in the
/// container leads to undefined behaviors.
/// \warning This reference may be invalidated when an entity is created.
///
/// \param entityId Entity to find and return
///
/// \see ::xrn::util::BasicForwardId, ::xrn::ecs::entity::ConstReference
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto unsafeGet(
::xrn::Id entityId
) const
-> ::xrn::ecs::entity::ConstReference;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets a mutable ::xrn::ecs::entity::Reference to an entity
/// contained it the container
///
/// \warning Calling this function while the entity is not present in the
/// container leads to undefined behaviors.
/// \warning This reference may be invalidated when an entity is created.
///
/// \param entityId Entity to find and return
///
/// \see ::xrn::util::BasicForwardId, ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto unsafeGet(
::xrn::Id entityId
) -> ::xrn::ecs::entity::Reference;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// GetComponents
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entityId Entity to find
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::util::BasicForwardId
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
::xrn::Id entityId
) const
-> const ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entity Reference to the Entity
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::ecs::Entity
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
const ::xrn::ecs::Entity& entity
) const
-> const ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entityReference Reference to the Entity
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
const ::xrn::ecs::entity::Reference& entityReference
) const
-> const ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entityReference Reference to the Entity
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
const ::xrn::ecs::entity::ConstReference& entityReference
) const
-> const ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the mutable entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entityId Entity to find
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::util::BasicForwardId
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
::xrn::Id entityId
) -> ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the mutable entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entity Reference to the Entity
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::ecs::Entity
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
const ::xrn::ecs::Entity& entity
) -> ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the mutable entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entityReference Reference to the Entity
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
const ::xrn::ecs::entity::Reference& entityReference
) -> ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the mutable entity component
///
/// \warning The component pointer might be invalidated if an action other
/// than accessing is performed on the component container.
///
/// \tparam ComponentType Component to search in the container and return
/// if existing
///
/// \param entityReference Reference to the Entity
///
/// \return Pointer to the component, or nullptr if the component does not
/// exist.
///
/// \see ::xrn::ecs::entity::ConstReference
///
///////////////////////////////////////////////////////////////////////////
template <
::xrn::ecs::detail::constraint::isComponent ComponentType
> [[ nodiscard ]] auto getComponent(
const ::xrn::ecs::entity::ConstReference& entityReference
) -> ::std::remove_cvref_t<::std::remove_pointer_t<ComponentType>>*;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Contains
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Checks whether the entityId given as parameter is contained by
/// the container
///
/// \param entityId Entity to find
///
/// \return True if the entity is contained. False otherwise
///
/// \see ::xrn::util::BasicForwardId, ::xrn::ecs::entity::Reference
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto contains(
::xrn::Id entityId
) const
-> bool;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Iterators support
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Gets an iterator to the begining of the vector of entities
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto begin()
-> Container::Type::iterator;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets an iterator to the begining of the vector of entities
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto begin() const
-> Container::Type::const_iterator;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets an iterator to the begining of the vector of entities
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto cbegin() const
-> Container::Type::const_iterator;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets an iterator to the end of the vector of entities
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto end()
-> Container::Type::iterator;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets an iterator to the end of the vector of entities
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto end() const
-> Container::Type::const_iterator;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets an iterator to the end of the vector of entities
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto cend() const
-> Container::Type::const_iterator;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// Component Container
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the linked component container
///
/// \see ::xrn::ecs::component::Container
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto getComponentContainer()
-> ::xrn::ecs::component::Container&;
///////////////////////////////////////////////////////////////////////////
/// \brief Gets the linked component container
///
/// \see ::xrn::ecs::component::Container
///
///////////////////////////////////////////////////////////////////////////
[[ nodiscard ]] inline auto getComponentContainer() const
-> const ::xrn::ecs::component::Container&;
private:
Container::Type m_entities{};
///////////////////////////////////////////////////////////////////////////
// Container where components will be emplaced
///////////////////////////////////////////////////////////////////////////
::xrn::ecs::component::Container& m_components;
};
} // namespace xrn::ecs::entity
///////////////////////////////////////////////////////////////////////////
// Header-implimentation
///////////////////////////////////////////////////////////////////////////
#include <xrn/Ecs/Entity/Container.impl.hpp>
| 41.286723 | 99 | 0.386131 | [
"vector"
] |
e400ec52652b651971514011de2069961f933d75 | 29,162 | cpp | C++ | VSTGL/VSTGLEditor.cpp | vinz9/vstvisframework | 0c4e1508d313c8deb588def77aa1a23f131c9333 | [
"MIT"
] | 14 | 2015-10-03T00:29:55.000Z | 2020-06-13T00:49:33.000Z | VSTGL/VSTGLEditor.cpp | vinz9/vstvisframework | 0c4e1508d313c8deb588def77aa1a23f131c9333 | [
"MIT"
] | null | null | null | VSTGL/VSTGLEditor.cpp | vinz9/vstvisframework | 0c4e1508d313c8deb588def77aa1a23f131c9333 | [
"MIT"
] | null | null | null | // VSTGLEditor.cpp - Editor window for a VST plugin using OpenGL to handle
// all the drawing.
// --------------------------------------------------------------------------
// Copyright (c) 2005-2006 Niall Moody
//
// 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 "VSTGLEditor.h"
#include "audioeffect.h"
#include <cstdio>
#ifdef WIN32
//This is the instance of the application, set in the main source file.
extern void* hInstance;
//Used to check/setup Vertical Sync.
typedef void (APIENTRY *PFNWGLEXTSWAPCONTROLPROC) (int);
typedef int (*PFNWGLEXTGETSWAPINTERVALPROC) (void);
//Used to check/setup Antialiasing.
typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
#endif
//----------------------------------------------------------------------------
VSTGLEditor::VSTGLEditor(AudioEffect *effect, WindowFlags flags):
AEffEditor(effect),
useVSync(false),
antialiasing(0)
{
char tempstr[32];
effect->setEditor(this);
_rect.left = 0;
_rect.top = 0;
_rect.right = 0;
_rect.bottom = 0;
if((flags&WaitForVerticalSync) == WaitForVerticalSync)
useVSync = true;
if((flags&Antialias6x) == Antialias6x)
antialiasing = 2;
else if((flags&Antialias4x) == Antialias4x)
antialiasing = 4;
else if((flags&Antialias2x) == Antialias2x)
antialiasing = 6;
#ifdef WIN32
dc = 0;
glRenderingContext = 0;
//Register window class.
WNDCLASSEX winClass;
//most of this stuff is copied from VSTGUI
winClass.cbSize = sizeof(WNDCLASSEX);
winClass.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC;
winClass.lpfnWndProc = GLWndProc;
winClass.cbClsExtra = 0;
winClass.cbWndExtra = 0;
winClass.hInstance = static_cast<HINSTANCE>(hInstance);
winClass.hIcon = 0;
winClass.hCursor = LoadCursor(NULL, IDC_ARROW);
winClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
winClass.lpszMenuName = 0;
sprintf(tempstr, "VSTGLWindow%08x", static_cast<HINSTANCE>(hInstance));
winClass.lpszClassName = tempstr;
winClass.hIconSm = NULL;
//Register the window class (this is unregistered in the VSTGLEditor
//destructor).
RegisterClassEx(&winClass);
#elif MACX
context = NULL;
pixels = NULL;
boundsX = 0;
boundsY = 0;
//Register our dummy HIView object.
//Not sure that all of these are needed, but I don't want to risk breaking
//anything.
EventTypeSpec eventList[] = {{kEventClassControl, kEventControlBoundsChanged},
{kEventClassControl, kEventControlHitTest},
{kEventClassControl, kEventControlDraw},
{kEventClassMouse, kEventMouseWheelMoved},
{kEventClassControl, kEventControlClick},
{kEventClassControl, kEventControlTrack},
{kEventClassControl, kEventControlContextualMenuClick},
{kEventClassKeyboard, kEventRawKeyRepeat},
{kEventClassControl, kEventControlDragEnter},
{kEventClassControl, kEventControlDragWithin},
{kEventClassControl, kEventControlDragLeave},
{kEventClassControl, kEventControlDragReceive},
{kEventClassControl, kEventControlGetClickActivation},
{kEventClassControl, kEventControlGetOptimalBounds},
{kEventClassScrollable, kEventScrollableGetInfo},
{kEventClassScrollable, kEventScrollableScrollTo},
{kEventClassControl, kEventControlSetFocusPart},
{kEventClassControl, kEventControlGetFocusPart}};
sprintf(tempstr, "com.vstgl.%08x", reinterpret_cast<int>(this));
classId = CFStringCreateWithCString(NULL, tempstr, 0);
controlSpec.defType = kControlDefObjectClass;
controlSpec.u.classRef = NULL;
ToolboxObjectClassRef controlClass = NULL;
OSStatus status = RegisterToolboxObjectClass(classId,
NULL,
GetEventTypeCount (eventList),
eventList,
macEventHandler,
this,
&controlClass);
if (status == noErr)
controlSpec.u.classRef = controlClass;
#endif
}
//----------------------------------------------------------------------------
VSTGLEditor::~VSTGLEditor()
{
#ifdef WIN32
char tempstr[32];
sprintf(tempstr, "VSTGLWindow%08x", static_cast<HINSTANCE>(hInstance));
//unregisters the window class
UnregisterClass(tempstr, static_cast<HINSTANCE>(hInstance));
#elif MACX
//Unregister our HIView object.
UnregisterToolboxObjectClass((ToolboxObjectClassRef)controlSpec.u.classRef);
#endif
}
//----------------------------------------------------------------------------
bool VSTGLEditor::open(void *ptr)
{
AEffEditor::open(ptr);
createWindow();
#ifdef WIN32
int tempint;
dc = GetDC(tempHWnd);
//Have to set the pixel format first...
pixelformat.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pixelformat.nVersion = 1;
pixelformat.dwFlags = PFD_DRAW_TO_WINDOW |
PFD_SUPPORT_OPENGL |
PFD_DOUBLEBUFFER;
pixelformat.iPixelType = PFD_TYPE_RGBA;
pixelformat.cColorBits = 32;
pixelformat.cRedBits = 0;
pixelformat.cRedShift = 0;
pixelformat.cGreenBits = 0;
pixelformat.cGreenShift = 0;
pixelformat.cBlueBits = 0;
pixelformat.cBlueShift = 0;
pixelformat.cAlphaBits = 0;
pixelformat.cAlphaShift = 0;
pixelformat.cAccumBits = 0;
pixelformat.cAccumRedBits = 0;
pixelformat.cAccumGreenBits = 0;
pixelformat.cAccumBlueBits = 0;
pixelformat.cAccumAlphaBits = 0;
pixelformat.cDepthBits = 32;
pixelformat.cStencilBits = 0;
pixelformat.cAuxBuffers = 0;
pixelformat.iLayerType = PFD_MAIN_PLANE;
pixelformat.bReserved = 0;
pixelformat.dwLayerMask = 0;
pixelformat.dwVisibleMask = 0;
pixelformat.dwDamageMask = 0;
tempint = ChoosePixelFormat(dc, &pixelformat);
SetPixelFormat(dc, tempint, &pixelformat);
glRenderingContext = wglCreateContext(dc);
wglMakeCurrent(dc, glRenderingContext);
//SetFocus(tempHWnd);
#elif MACX
WindowAttributes attr;
HIRect bounds;
window = static_cast<WindowRef>(ptr);
//If the host's provided us with a composited window, add an HIView to
//the window, since this is what the latest vstsdk requires.
GetWindowAttributes((WindowRef)window, &attr);
if(attr & kWindowCompositingAttribute)
{
HIViewRef contentView;
if(HIViewFindByID(HIViewGetRoot((WindowRef)window),
kHIViewWindowContentID,
&contentView) == noErr)
{
Rect r = {0,
0,
(_rect.right-_rect.left),
(_rect.bottom-_rect.top)};
//Create our control/HIView
CreateCustomControl(NULL, &r, &controlSpec, NULL, &controlRef);
//Are these necessary?
SetControlDragTrackingEnabled(controlRef, true);
SetAutomaticControlDragTrackingEnabledForWindow(window, true);
//Search for parent HIView.
if(HIViewFindByID(HIViewGetRoot(window),
kHIViewWindowContentID,
&contentView) == noErr)
{
//Add our HIView to the parent.
HIViewAddSubview (contentView, controlRef);
//Set our HIView's size.
//Is all of this necessary?
HIViewGetFrame(controlRef, &bounds);
HIViewConvertPoint(&(bounds.origin), contentView, controlRef);
bounds.size.width = _rect.right-_rect.left;
bounds.size.height = _rect.bottom-_rect.top;
HIViewSetFrame(controlRef, &bounds);
//Install our extra event handler on the window.
//(because we never seem to receive these events if we try to
//install them on the control)
EventHandlerUPP eventHandler;
EventTypeSpec eventList[] = {{kEventClassMouse, kEventMouseUp},
{kEventClassMouse, kEventMouseMoved},
{kEventClassMouse, kEventMouseDragged},
{kEventClassKeyboard, kEventRawKeyDown},
{kEventClassKeyboard, kEventRawKeyUp}};
eventHandler = NewEventHandlerUPP(macEventHandler);
InstallWindowEventHandler(window,
eventHandler,
GetEventTypeCount(eventList),
eventList,
this,
&eventHandlerRef);
}
}
}
else
{
//If it's not a compositing window, we don't need to add a dummy
//HIView, so we install our event handler on the window itself.
EventHandlerUPP eventHandler;
EventTypeSpec eventList[] = {{kEventClassMouse, kEventMouseDown},
{kEventClassMouse, kEventMouseUp},
{kEventClassMouse, kEventMouseMoved},
{kEventClassMouse, kEventMouseDragged},
{kEventClassMouse, kEventMouseWheelMoved},
{kEventClassKeyboard, kEventRawKeyDown},
{kEventClassKeyboard, kEventRawKeyUp}};
eventHandler = NewEventHandlerUPP(macEventHandler);
InstallWindowEventHandler(window,
eventHandler,
GetEventTypeCount(eventList),
eventList,
this,
&eventHandlerRef);
}
//Set up the AGL control.
if(!antialiasing)
{
GLint attributes[] = {AGL_RGBA,
AGL_ACCELERATED,
AGL_DOUBLEBUFFER,
AGL_DEPTH_SIZE, 32,
AGL_NONE};
pixels = aglChoosePixelFormat(NULL, 0, attributes);
}
else //If we want antialiasing.
{
GLint attributes[] = {AGL_RGBA,
AGL_ACCELERATED,
AGL_DOUBLEBUFFER,
AGL_DEPTH_SIZE, 32,
AGL_SAMPLE_BUFFERS_ARB, 1,
AGL_SAMPLES_ARB, antialiasing,
AGL_NO_RECOVERY,
AGL_NONE};
pixels = aglChoosePixelFormat(NULL, 0, attributes);
//Check it worked, get a pixel format without antialiasing if it
//didn't.
if(!pixels)
{
GLint attributes[] = {AGL_RGBA,
AGL_ACCELERATED,
AGL_DOUBLEBUFFER,
AGL_DEPTH_SIZE, 32,
AGL_NONE};
pixels = aglChoosePixelFormat(NULL, 0, attributes);
}
}
if(pixels)
context = aglCreateContext(pixels, NULL);
else
return false;
if(context)
{
if(!aglSetDrawable(context, GetWindowPort(window)))
return false;
if(!aglSetCurrentContext(context))
return false;
}
else
return false;
#endif
//If one of the antialiasing options was specified in the constructor,
//try to switch it on.
if(antialiasing)
setupAntialiasing();
//If WaitForVerticalSync was specified in the constructor, try to switch
//it on.
if(useVSync)
setupVSync();
guiOpen();
return true;
}
//----------------------------------------------------------------------------
void VSTGLEditor::close()
{
setupContext();
guiClose();
swapBuffers();
#ifdef WIN32
wglMakeCurrent(NULL, NULL);
wglDeleteContext(glRenderingContext);
ReleaseDC(tempHWnd, dc);
DestroyWindow(tempHWnd);
#elif MACX
aglSetCurrentContext(NULL);
aglSetDrawable(context, NULL);
if(context)
{
aglDestroyContext(context);
context = NULL;
}
if(pixels)
{
aglDestroyPixelFormat(pixels);
pixels = NULL;
}
HIViewRemoveFromSuperview(controlRef);
if(controlRef)
DisposeControl(controlRef);
#endif
}
//----------------------------------------------------------------------------
void VSTGLEditor::refreshGraphics()
{
setupContext();
draw();
swapBuffers();
}
#ifdef MACX
//----------------------------------------------------------------------------
void VSTGLEditor::updateBounds(int x, int y)
{
int tempHeight;
Rect tempRect2;
HIRect tempRect;
//Get the new bounds of our dummy HIView.
HIViewGetFrame(controlRef, &tempRect);
//Invert tempRect's y-axis (honestly, who designed this API!).
GetWindowBounds(window, kWindowContentRgn, &tempRect2);
tempHeight = (tempRect2.bottom-tempRect2.top);
tempRect.origin.y = tempHeight - tempRect.origin.y - tempRect.size.height;
boundsX = (int)tempRect.origin.x;
boundsY = (int)tempRect.origin.y;
}
#endif
//----------------------------------------------------------------------------
//This is only necessary in Windows (and only really for Tracktion) - the
//window will have already been constructed for us on OS X.
void VSTGLEditor::createWindow()
{
#ifdef WIN32
char tempstr[32];
HWND parentHWnd = static_cast<HWND>(systemWindow);
sprintf(tempstr, "VSTGLWindow%08x", static_cast<HINSTANCE>(hInstance));
tempHWnd = CreateWindowEx(0, //extended window style
tempstr, //pointer to registered class name
"VSTGLEditor", //pointer to window name
WS_CHILD|
WS_VISIBLE, //window style
0, //horizontal position of window
0, //vertical position of window
(_rect.right-_rect.left),//window width
(_rect.bottom-_rect.top),//window height
parentHWnd, //handle to parent or owner window
NULL, //handle to menu, or child-window identifier
(HINSTANCE)hInstance, //handle to application instance
NULL); //pointer to window-creation data
//This is so we can send messages to this object from the message loop.
SetWindowLong(tempHWnd, GWL_USERDATA, (long)this);
#endif
}
//----------------------------------------------------------------------------
void VSTGLEditor::setupVSync()
{
#ifdef WIN32
unsigned char *extensions;
PFNWGLEXTSWAPCONTROLPROC wglSwapIntervalEXT = NULL;
//Check the graphics card's extensions.
extensions = const_cast<unsigned char *>(glGetString(GL_EXTENSIONS));
//Check if extensions contains the vertical sync string.
if(strstr(reinterpret_cast<char *>(extensions),"WGL_EXT_swap_control"))
{
//Get the address of the relevant functions.
wglSwapIntervalEXT = reinterpret_cast<PFNWGLEXTSWAPCONTROLPROC>(wglGetProcAddress("wglSwapIntervalEXT"));
//Turn it on.
if(wglSwapIntervalEXT)
wglSwapIntervalEXT(1);
}
#elif MACX
GLint swap = 1;
//Some things are so much easier on OSX...
aglSetInteger(context, AGL_SWAP_INTERVAL, &swap);
#endif
}
//----------------------------------------------------------------------------
void VSTGLEditor::setupAntialiasing()
{
#ifdef WIN32
unsigned char *extensions;
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
int pixelFormat;
UINT numFormats;
float fAttributes[] = {0,0};
//Check the graphics card's extensions.
extensions = const_cast<unsigned char *>(glGetString(GL_EXTENSIONS));
//Check if extensions contains the multisample string.
if(strstr(reinterpret_cast<char *>(extensions),"GL_ARB_multisample"))
{
//Get the address of the relevant functions.
wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
if(wglChoosePixelFormatARB)
{
int iAttributes[] = {
WGL_DRAW_TO_WINDOW_ARB,GL_TRUE,
WGL_SUPPORT_OPENGL_ARB,GL_TRUE,
WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB,
WGL_COLOR_BITS_ARB,24,
WGL_ALPHA_BITS_ARB,8,
WGL_DEPTH_BITS_ARB,16,
WGL_STENCIL_BITS_ARB,0,
WGL_DOUBLE_BUFFER_ARB,GL_TRUE,
WGL_SAMPLE_BUFFERS_ARB,GL_TRUE,
WGL_SAMPLES_ARB, antialiasing,
0,0};
//Try and get the correct pixel format.
if(wglChoosePixelFormatARB(dc,
iAttributes,
fAttributes,
1,
&pixelFormat,
&numFormats))
{
if(numFormats > 0)
{
//Destroy the current window.
wglMakeCurrent(NULL, NULL);
wglDeleteContext(glRenderingContext);
ReleaseDC(tempHWnd, dc);
DestroyWindow(tempHWnd);
//Create a new one with the correct pixel format.
createWindow();
dc = GetDC(tempHWnd);
SetPixelFormat(dc, pixelFormat, &pixelformat);
glRenderingContext = wglCreateContext(dc);
wglMakeCurrent(dc, glRenderingContext);
}
}
}
}
#endif
}
//----------------------------------------------------------------------------
void VSTGLEditor::setupContext()
{
#ifdef WIN32
wglMakeCurrent(dc, glRenderingContext);
#elif MACX
GLint tempBounds[4];
tempBounds[0] = boundsX;
tempBounds[1] = boundsY;
tempBounds[2] = (_rect.right-_rect.left);
tempBounds[3] = (_rect.bottom-_rect.top);
//Move the port to the correct offset.
aglSetInteger(context, AGL_BUFFER_RECT, tempBounds);
aglEnable(context, AGL_BUFFER_RECT);
//Also necessary for Bidule.
aglSetCurrentContext(context);
#endif
}
//----------------------------------------------------------------------------
void VSTGLEditor::swapBuffers()
{
#ifdef WIN32
SwapBuffers(dc);
#elif MACX
aglSwapBuffers(context);
#endif
}
//----------------------------------------------------------------------------
void VSTGLEditor::setRect(int x, int y, int width, int height)
{
_rect.left = x;
_rect.top = y;
_rect.right = x+width;
_rect.bottom = y+height;
}
//----------------------------------------------------------------------------
#ifdef WIN32
//Don't know why MSVC doesn't seem to recognise WM_MOUSEWHEEL for me...
//(this probably won't work)
#ifndef WM_MOUSEWHEEL
#define WM_MOUSEWHEEL 0x020A
#endif
LONG WINAPI VSTGLEditor::GLWndProc(HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
VstKeyCode tempkey;
VSTGLEditor *ed = reinterpret_cast<VSTGLEditor *>(GetWindowLong(hwnd, GWL_USERDATA));
switch(message)
{
case WM_LBUTTONDOWN:
if(ed)
ed->onMouseDown(1, LOWORD(lParam), HIWORD(lParam));
break;
case WM_MBUTTONDOWN:
if(ed)
ed->onMouseDown(3, LOWORD(lParam), HIWORD(lParam));
break;
case WM_RBUTTONDOWN:
if(ed)
ed->onMouseDown(2, LOWORD(lParam), HIWORD(lParam));
break;
case WM_LBUTTONUP:
if(ed)
ed->onMouseUp(1, LOWORD(lParam), HIWORD(lParam));
break;
case WM_MBUTTONUP:
if(ed)
ed->onMouseUp(3, LOWORD(lParam), HIWORD(lParam));
break;
case WM_RBUTTONUP:
if(ed)
ed->onMouseUp(2, LOWORD(lParam), HIWORD(lParam));
break;
case WM_MOUSEMOVE:
if(ed)
ed->onMouseMove(LOWORD(lParam), HIWORD(lParam));
break;
case WM_MOUSEWHEEL:
if(ed)
ed->onMouseWheel(HIWORD(wParam), LOWORD(lParam), HIWORD(lParam));
break;
case WM_KEYDOWN:
if(ed)
{
//This could be improved?
tempkey.character = wParam;
ed->onGLKeyDown(tempkey);
}
break;
case WM_KEYUP:
if(ed)
{
tempkey.character = wParam;
ed->onGLKeyUp(tempkey);
}
break;
case WM_PAINT:
if(ed)
ed->idle();
break;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
#endif
//----------------------------------------------------------------------------
#ifdef MACX
pascal OSStatus VSTGLEditor::macEventHandler(EventHandlerCallRef handler,
EventRef event,
void *userData)
{
int width;
int height;
int tempHeight;
Rect tempRect;
int actualButton;
EventMouseButton button;
HIPoint location;
EventMouseWheelAxis wheelAxis;
SInt32 wheelDelta;
UInt32 key;
VstKeyCode tempKey;
WindowRef win;
Rect titleBounds;
OSStatus result = eventNotHandledErr;
VSTGLEditor *ed = static_cast<VSTGLEditor *>(userData);
UInt32 eventClass = GetEventClass(event);
UInt32 eventType = GetEventKind(event);
if(ed)
{
if(eventClass == kEventClassMouse)
{
switch(eventType)
{
case kEventMouseDown:
GetEventParameter(event,
kEventParamMouseButton,
typeMouseButton,
NULL,
sizeof(EventMouseButton),
NULL,
&button);
GetEventParameter(event,
kEventParamWindowMouseLocation,
typeHIPoint,
NULL,
sizeof(HIPoint),
NULL,
&location);
switch(button)
{
case kEventMouseButtonPrimary:
actualButton = 1;
break;
case kEventMouseButtonSecondary:
actualButton = 2;
break;
case kEventMouseButtonTertiary:
actualButton = 3;
break;
default:
actualButton = -1;
}
//Make sure we're not picking up a mouse click on the
//title bar.
win = ed->getWindowRef();
GetWindowBounds(win, kWindowTitleBarRgn, &titleBounds);
location.y -= (titleBounds.bottom - titleBounds.top);
if(location.y > -1)
{
if(actualButton != -1)
ed->onMouseDown(actualButton,
static_cast<int>(location.x),
static_cast<int>(location.y));
}
else
{
//So we can still click on the title bar.
CallNextEventHandler(handler, event);
}
result = noErr;
break;
case kEventMouseUp:
GetEventParameter(event,
kEventParamMouseButton,
typeMouseButton,
NULL,
sizeof(EventMouseButton),
NULL,
&button);
GetEventParameter(event,
kEventParamWindowMouseLocation,
typeHIPoint,
NULL,
sizeof(HIPoint),
NULL,
&location);
switch(button)
{
case kEventMouseButtonPrimary:
actualButton = 1;
break;
case kEventMouseButtonSecondary:
actualButton = 2;
break;
case kEventMouseButtonTertiary:
actualButton = 3;
break;
default:
actualButton = -1;
}
//Make sure we're not picking up a mouse click on the
//title bar.
win = ed->getWindowRef();
GetWindowBounds(win, kWindowTitleBarRgn, &titleBounds);
location.y -= (titleBounds.bottom - titleBounds.top);
if(location.y > -1)
{
if(actualButton != -1)
{
ed->onMouseUp(actualButton,
static_cast<int>(location.x),
static_cast<int>(location.y));
}
}
else
{
//So we can still click on the title bar.
CallNextEventHandler(handler, event);
}
result = noErr;
break;
case kEventMouseMoved:
width = ed->getWidth();
height = ed->getHeight();
GetEventParameter(event,
kEventParamWindowMouseLocation,
typeHIPoint,
NULL,
sizeof(HIPoint),
NULL,
&location);
//Make sure we're not picking up a mouse click on the
//title bar.
win = ed->getWindowRef();
GetWindowBounds(win, kWindowContentRgn, &tempRect);
GetWindowBounds(win, kWindowTitleBarRgn, &titleBounds);
location.y -= (titleBounds.bottom - titleBounds.top);
if(location.y > -1)
{
tempHeight = (tempRect.bottom-tempRect.top);
location.y -= tempHeight - ed->getBoundsY() - ed->getHeight();
if(location.y < height)
{
location.x -= ed->getBoundsX();
if((location.x > -1) && (location.x < width))
{
ed->onMouseMove(static_cast<int>(location.x),
static_cast<int>(location.y));
}
}
}
result = noErr;
break;
//We handle dragging as well as moving events, because OS X
//makes a specific distinction between them, whereas I
//prefer to use the mouseUp and mouseDown events to tell
//whether I'm supposed to be dragging...
case kEventMouseDragged:
width = ed->getWidth();
height = ed->getHeight();
GetEventParameter(event,
kEventParamWindowMouseLocation,
typeHIPoint,
NULL,
sizeof(HIPoint),
NULL,
&location);
//Make sure we're not picking up a mouse click on the
//title bar.
win = ed->getWindowRef();
GetWindowBounds(win, kWindowContentRgn, &tempRect);
GetWindowBounds(win, kWindowTitleBarRgn, &titleBounds);
location.y -= (titleBounds.bottom - titleBounds.top);
if(location.y > -1)
{
tempHeight = (tempRect.bottom-tempRect.top);
location.y -= tempHeight - ed->getBoundsY() - ed->getHeight();
if(location.y < height)
{
location.x -= ed->getBoundsX();
if((location.x > -1) && (location.x < width))
{
ed->onMouseMove(static_cast<int>(location.x),
static_cast<int>(location.y));
}
}
}
result = noErr;
break;
case kEventMouseWheelMoved:
GetEventParameter(event,
kEventParamMouseWheelAxis,
typeMouseWheelAxis,
NULL,
sizeof(EventMouseWheelAxis),
NULL,
&wheelAxis);
GetEventParameter(event,
kEventParamMouseWheelDelta,
typeLongInteger,
NULL,
sizeof(SInt32),
NULL,
&wheelDelta);
GetEventParameter(event,
kEventParamWindowMouseLocation,
typeHIPoint,
NULL,
sizeof(HIPoint),
NULL,
&location);
//Make sure we're not picking up a mouse click on the
//title bar.
win = ed->getWindowRef();
GetWindowBounds(win, kWindowTitleBarRgn, &titleBounds);
location.y -= (titleBounds.bottom - titleBounds.top);
if(location.y > -1)
{
if(wheelAxis == kEventMouseWheelAxisY)
{
ed->onMouseWheel(static_cast<int>(wheelDelta),
static_cast<int>(location.x),
static_cast<int>(location.y));
}
}
result = noErr;
break;
}
}
else if(eventClass == kEventClassKeyboard)
{
switch(eventType)
{
case kEventRawKeyDown:
GetEventParameter(event,
kEventParamKeyCode,
typeUInt32,
NULL,
sizeof(UInt32),
NULL,
&key);
tempKey.character = key;
ed->onGLKeyDown(tempKey);
result = noErr;
break;
case kEventRawKeyUp:
GetEventParameter(event,
kEventParamKeyCode,
typeUInt32,
NULL,
sizeof(UInt32),
NULL,
&key);
tempKey.character = key;
ed->onGLKeyUp(tempKey);
result = noErr;
break;
}
}
else if((eventClass == kEventClassControl)||(eventClass == kEventClassWindow))
{
switch(eventType)
{
case kEventWindowBoundsChanged:
case kEventControlBoundsChanged:
Rect tempRect;
OSStatus err;
err = GetEventParameter(event,
kEventParamCurrentBounds,
typeQDRectangle,
NULL,
sizeof(Rect),
NULL,
&tempRect);
if(err == noErr)
ed->updateBounds(tempRect.left, tempRect.top);
else
ed->updateBounds(0, 0);
result = noErr;
break;
case kEventControlHitTest:
{
ControlPartCode part = 127;
SetEventParameter(event, kEventParamControlPart, typeControlPartCode, sizeof(part), &part);
}
result = noErr;
break;
case kEventControlClick:
GetEventParameter(event,
kEventParamMouseButton,
typeMouseButton,
NULL,
sizeof(EventMouseButton),
NULL,
&button);
GetEventParameter(event,
kEventParamWindowMouseLocation,
typeHIPoint,
NULL,
sizeof(HIPoint),
NULL,
&location);
switch(button)
{
case kEventMouseButtonPrimary:
actualButton = 1;
break;
case kEventMouseButtonSecondary:
actualButton = 2;
break;
case kEventMouseButtonTertiary:
actualButton = 3;
break;
default:
actualButton = -1;
}
//Make sure we're not picking up a mouse click on the
//title bar.
if(actualButton != -1)
{
ed->onMouseDown(actualButton,
static_cast<int>(location.x),
static_cast<int>(location.y));
}
result = noErr;
break;
case kEventControlContextualMenuClick:
GetEventParameter(event,
kEventParamMouseButton,
typeMouseButton,
NULL,
sizeof(EventMouseButton),
NULL,
&button);
GetEventParameter(event,
kEventParamWindowMouseLocation,
typeHIPoint,
NULL,
sizeof(HIPoint),
NULL,
&location);
switch(button)
{
case kEventMouseButtonPrimary:
actualButton = 1;
break;
case kEventMouseButtonSecondary:
actualButton = 2;
break;
case kEventMouseButtonTertiary:
actualButton = 3;
break;
default:
actualButton = -1;
}
//Make sure we're not picking up a mouse click on the
//title bar.
if(actualButton != -1)
{
ed->onMouseDown(actualButton,
static_cast<int>(location.x),
static_cast<int>(location.y));
}
result = noErr;
break;
case kEventControlTrack:
result = noErr;
break;
case kEventControlHiliteChanged:
result = noErr;
break;
case kEventControlDraw:
result = noErr;
break;
default:
CallNextEventHandler(handler, event);
}
}
}
return result;
}
#endif
| 27.694207 | 172 | 0.633427 | [
"object"
] |
e407298d187ecc1e69deb41fcdcbe6f71ea693a8 | 7,787 | cpp | C++ | DiveIntoC++11/2_Arkanoid/p2.cpp | raptoravis/Tutorials | d2362c7688201a50ba2de5515897aeca012ce929 | [
"AFL-3.0"
] | null | null | null | DiveIntoC++11/2_Arkanoid/p2.cpp | raptoravis/Tutorials | d2362c7688201a50ba2de5515897aeca012ce929 | [
"AFL-3.0"
] | null | null | null | DiveIntoC++11/2_Arkanoid/p2.cpp | raptoravis/Tutorials | d2362c7688201a50ba2de5515897aeca012ce929 | [
"AFL-3.0"
] | null | null | null | // Copyright (c) 2013-2015 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#include <cmath>
#include <chrono>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
// This is a modern C++11 `typedef` replacement:
// we just defined an alias for `float`, called `FrameTime`
using FrameTime = float;
constexpr unsigned int windowWidth{800}, windowHeight{600};
constexpr float ballRadius{10.f}, ballVelocity{8.f};
constexpr float paddleWidth{60.f}, paddleHeight{20.f}, paddleVelocity{6.f};
constexpr float blockWidth{60.f}, blockHeight{20.f};
constexpr int countBlocksX{11}, countBlocksY{4};
struct Ball
{
CircleShape shape;
Vector2f velocity{-ballVelocity, -ballVelocity};
Ball(float mX, float mY)
{
shape.setPosition(mX, mY);
shape.setRadius(ballRadius);
shape.setFillColor(Color::Red);
shape.setOrigin(ballRadius, ballRadius);
}
void update()
{
shape.move(velocity);
if(left() < 0)
velocity.x = ballVelocity;
else if(right() > windowWidth)
velocity.x = -ballVelocity;
if(top() < 0)
velocity.y = ballVelocity;
else if(bottom() > windowHeight)
velocity.y = -ballVelocity;
}
float x() const noexcept { return shape.getPosition().x; }
float y() const noexcept { return shape.getPosition().y; }
float left() const noexcept { return x() - shape.getRadius(); }
float right() const noexcept { return x() + shape.getRadius(); }
float top() const noexcept { return y() - shape.getRadius(); }
float bottom() const noexcept { return y() + shape.getRadius(); }
};
struct Rectangle
{
RectangleShape shape;
float x() const noexcept { return shape.getPosition().x; }
float y() const noexcept { return shape.getPosition().y; }
float left() const noexcept { return x() - shape.getSize().x / 2.f; }
float right() const noexcept { return x() + shape.getSize().x / 2.f; }
float top() const noexcept { return y() - shape.getSize().y / 2.f; }
float bottom() const noexcept { return y() + shape.getSize().y / 2.f; }
};
struct Paddle : public Rectangle
{
Vector2f velocity;
Paddle(float mX, float mY)
{
shape.setPosition(mX, mY);
shape.setSize({paddleWidth, paddleHeight});
shape.setFillColor(Color::Red);
shape.setOrigin(paddleWidth / 2.f, paddleHeight / 2.f);
}
void update()
{
shape.move(velocity);
if(Keyboard::isKeyPressed(Keyboard::Key::Left) && left() > 0)
velocity.x = -paddleVelocity;
else if(Keyboard::isKeyPressed(Keyboard::Key::Right) &&
right() < windowWidth)
velocity.x = paddleVelocity;
else
velocity.x = 0;
}
};
struct Brick : public Rectangle
{
bool destroyed{false};
Brick(float mX, float mY)
{
shape.setPosition(mX, mY);
shape.setSize({blockWidth, blockHeight});
shape.setFillColor(Color::Yellow);
shape.setOrigin(blockWidth / 2.f, blockHeight / 2.f);
}
};
template <class T1, class T2>
bool isIntersecting(T1& mA, T2& mB) noexcept
{
return mA.right() >= mB.left() && mA.left() <= mB.right() &&
mA.bottom() >= mB.top() && mA.top() <= mB.bottom();
}
void testCollision(Paddle& mPaddle, Ball& mBall) noexcept
{
if(!isIntersecting(mPaddle, mBall)) return;
mBall.velocity.y = -ballVelocity;
if(mBall.x() < mPaddle.x())
mBall.velocity.x = -ballVelocity;
else
mBall.velocity.x = ballVelocity;
}
void testCollision(Brick& mBrick, Ball& mBall) noexcept
{
if(!isIntersecting(mBrick, mBall)) return;
mBrick.destroyed = true;
float overlapLeft{mBall.right() - mBrick.left()};
float overlapRight{mBrick.right() - mBall.left()};
float overlapTop{mBall.bottom() - mBrick.top()};
float overlapBottom{mBrick.bottom() - mBall.top()};
bool ballFromLeft(abs(overlapLeft) < abs(overlapRight));
bool ballFromTop(abs(overlapTop) < abs(overlapBottom));
float minOverlapX{ballFromLeft ? overlapLeft : overlapRight};
float minOverlapY{ballFromTop ? overlapTop : overlapBottom};
if(abs(minOverlapX) < abs(minOverlapY))
mBall.velocity.x = ballFromLeft ? -ballVelocity : ballVelocity;
else
mBall.velocity.y = ballFromTop ? -ballVelocity : ballVelocity;
}
// Our code has a critical issue: it is framerate dependent!
// We set the framerate to 60 to prevent frame-dependent behavior,
// but it's not a good solution at all.
// We should, instead, pass the time the last frame took to update
// in our `update()` methods, so that we can "scale" our movements
// and actions with the frame time, achieving framerate indepedent
// behavior.
// Let's begin by getting the time a frame takes to update/draw,
// using C++11's fantastic `std::chrono` library.
int main()
{
Ball ball{windowWidth / 2, windowHeight / 2};
Paddle paddle{windowWidth / 2, windowHeight - 50};
vector<Brick> bricks;
for(int iX{0}; iX < countBlocksX; ++iX)
for(int iY{0}; iY < countBlocksY; ++iY)
bricks.emplace_back(
(iX + 1) * (blockWidth + 3) + 22, (iY + 2) * (blockHeight + 3));
RenderWindow window{{windowWidth, windowHeight}, "Arkanoid - 11"};
// Let's comment out the frame rate limit for now.
// window.setFramerateLimit(60);
while(true)
{
// Start of our time interval.
auto timePoint1(chrono::high_resolution_clock::now());
window.clear(Color::Black);
Event event;
while(window.pollEvent(event))
{
if(event.type == Event::Closed)
{
window.close();
break;
}
}
if(Keyboard::isKeyPressed(Keyboard::Key::Escape)) break;
ball.update();
paddle.update();
testCollision(paddle, ball);
for(auto& brick : bricks) testCollision(brick, ball);
bricks.erase(remove_if(begin(bricks), end(bricks),
[](const Brick& mBrick)
{
return mBrick.destroyed;
}),
end(bricks));
window.draw(ball.shape);
window.draw(paddle.shape);
for(auto& brick : bricks) window.draw(brick.shape);
window.display();
// End of our time interval.
auto timePoint2(chrono::high_resolution_clock::now());
// Let's calculate the frame time in milliseconds,
// and "print it out" as the window's title.
// Subtracting two std::chrono::time_point objects
// returns an `std::chrono::duration` object, which
// represents a time period.
auto elapsedTime(timePoint2 - timePoint1);
// We want to get the frametime in milliseconds, so we can
// just use the safe `std::chrono::duration_cast` function.
// To convert the duration to a `float`, we will use `.count()`
// at the end.
FrameTime ft{
chrono::duration_cast<chrono::duration<float, milli>>(elapsedTime)
.count()};
// We can approximate fps by dividing 1.f by the
// elapsed seconds, calculated converting ft
// to seconds (ms / 1000.f).
auto ftSeconds(ft / 1000.f);
auto fps(1.f / ftSeconds);
// std::to_string is another very useful C++11 function,
// that transforms many different types to an std::string.
window.setTitle("FT: " + to_string(ft) + "\tFPS: " + to_string(fps));
}
return 0;
}
// The game should now run insanely fast... let's see what
// we can do about it in the next code segment. | 31.783673 | 80 | 0.615898 | [
"object",
"shape",
"vector"
] |
e407b37b34ed49a3654ff76bedf6769461b5457f | 605 | hpp | C++ | include/med/ThreadManager.hpp | OmniNegro123/med | 48b00bfb9319f735a2406ff2efe7253c46007236 | [
"BSD-3-Clause"
] | 37 | 2015-10-05T17:44:20.000Z | 2022-03-24T02:55:04.000Z | include/med/ThreadManager.hpp | OmniNegro123/med | 48b00bfb9319f735a2406ff2efe7253c46007236 | [
"BSD-3-Clause"
] | 6 | 2017-04-01T02:26:22.000Z | 2022-02-19T07:46:29.000Z | include/med/ThreadManager.hpp | OmniNegro123/med | 48b00bfb9319f735a2406ff2efe7253c46007236 | [
"BSD-3-Clause"
] | 4 | 2020-07-23T17:27:36.000Z | 2021-12-25T20:29:56.000Z | #ifndef THREAD_MANAGER
#define THREAD_MANAGER
#include <functional>
#include <vector>
#include <future>
#include <condition_variable>
#include <mutex>
typedef std::function<void()> TMTask;
class ThreadManager {
public:
explicit ThreadManager(int maxThread = 4);
virtual ~ThreadManager();
void queueTask(TMTask* fn);
void clear();
void start();
void setMaxThreads(int num);
private:
std::vector<TMTask*> container;
int maxThreads;
int numOfRunningThreads;
int currThreadIndex;
std::condition_variable cv;
std::mutex mut;
std::future<void> startTask(int index);
};
#endif
| 16.805556 | 44 | 0.728926 | [
"vector"
] |
e409c512379e174b4b6de64b8ba5037a16aa0845 | 3,053 | cpp | C++ | infra/kafka/Producer.cpp | danielcompton/smyte-db | 34129e0184408086cde6fe9694d9a7d7ca9c2016 | [
"Apache-2.0"
] | 47 | 2016-12-18T21:50:28.000Z | 2022-02-25T06:00:19.000Z | infra/kafka/Producer.cpp | danielcompton/smyte-db | 34129e0184408086cde6fe9694d9a7d7ca9c2016 | [
"Apache-2.0"
] | 4 | 2017-08-14T20:39:53.000Z | 2020-11-28T20:14:53.000Z | infra/kafka/Producer.cpp | danielcompton/smyte-db | 34129e0184408086cde6fe9694d9a7d7ca9c2016 | [
"Apache-2.0"
] | 20 | 2017-01-02T13:39:09.000Z | 2021-12-04T00:42:17.000Z | #include "infra/kafka/Producer.h"
#include <memory>
#include <string>
#include "glog/logging.h"
#include "infra/kafka/EventCallback.h"
#include "librdkafka/rdkafkacpp.h"
namespace infra {
namespace kafka {
void Producer::initialize() {
setConf("metadata.broker.list", brokerList_);
// disable verbose logging
setConf("log.connection.close", "false");
if (useCompression_) {
// use snappy codec when compression is requested
setConf("compression.codec", "snappy");
}
std::string errstr;
if (conf_->set("event_cb", static_cast<RdKafka::EventCb*>(this), errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "Setting Kafka event callback failed: " << errstr;
}
if (conf_->set("dr_cb", static_cast<RdKafka::DeliveryReportCb*>(this), errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "Setting Kafka delivery report callback failed: " << errstr;
}
// Send messages asap in low latency mode
if (lowLatency_) {
// Use 10ms instead of 0 so that the producer client still has a chance to batch
if (conf_->set("queue.buffering.max.ms", "10", errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "Setting Kafka queue.buffering.max.ms failed: " << errstr;
}
}
// by default, require messages to be committed by all in sync replica (ISRs)
if (topicConf_->set("request.required.acks", "-1", errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "Setting request.required.acks for topic [" << topicStr_ << "] failed: " << errstr;
}
// always return the produced offset to the client
if (topicConf_->set("produce.offset.report", "true", errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "Setting produce.offset.report for topic [" << topicStr_ << "] failed: " << errstr;
}
if (partitioner_ && topicConf_->set(
"partitioner_cb", static_cast<RdKafka::PartitionerCb*>(this), errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "Setting partitioner callback for topic [" << topicStr_ << "] failed: " << errstr;
}
for (const auto& entry : topicConfigs_) {
if (topicConf_->set(entry.first, entry.second, errstr) != RdKafka::Conf::CONF_OK) {
LOG(FATAL) << "Setting config for topic [" << topicStr_ << "] failed: " << errstr;
}
}
producer_.reset(RdKafka::Producer::create(conf_.get(), errstr));
if (!producer_) {
LOG(FATAL) << "Failed to create producer: " << errstr;
}
topic_.reset(RdKafka::Topic::create(producer_.get(), topicStr_, topicConf_.get(), errstr));
if (!topic_) {
LOG(FATAL) << "Failed to create producer topic object for topic [" << topicStr_ << "]: " << errstr;
}
RdKafka::Metadata* metadataTmp = nullptr;
auto errorCode = producer_->metadata(false /* one topic only */, topic_.get(), &metadataTmp, 10000);
std::unique_ptr<RdKafka::Metadata> metadata(metadataTmp);
if (errorCode != RdKafka::ERR_NO_ERROR) {
LOG(FATAL) << "Getting topic metadata failed: " << RdKafka::err2str(errorCode);
}
LOG(INFO) << "Kafka producer initialized: " << producer_->name();
}
} // namespace kafka
} // namespace infra
| 36.783133 | 109 | 0.663282 | [
"object"
] |
e411b1187e1e73b0870b44e5bd1dbc465229fd09 | 4,473 | cc | C++ | ui/base/clipboard/custom_data_helper_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ui/base/clipboard/custom_data_helper_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ui/base/clipboard/custom_data_helper_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2012 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 "ui/base/clipboard/custom_data_helper.h"
#include <utility>
#include "base/pickle.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::ASCIIToUTF16;
namespace ui {
namespace {
void PrepareEmptyTestData(base::Pickle* pickle) {
std::unordered_map<std::u16string, std::u16string> data;
WriteCustomDataToPickle(data, pickle);
}
void PrepareTestData(base::Pickle* pickle) {
std::unordered_map<std::u16string, std::u16string> data = {
{u"abc", std::u16string()}, {u"de", u"1"}, {u"f", u"23"}};
WriteCustomDataToPickle(data, pickle);
}
TEST(CustomDataHelperTest, EmptyReadTypes) {
base::Pickle pickle;
PrepareEmptyTestData(&pickle);
std::vector<std::u16string> types;
ReadCustomDataTypes(pickle.data(), pickle.size(), &types);
EXPECT_EQ(0u, types.size());
}
TEST(CustomDataHelperTest, EmptyReadSingleType) {
base::Pickle pickle;
PrepareEmptyTestData(&pickle);
std::u16string result;
ReadCustomDataForType(pickle.data(), pickle.size(), u"f", &result);
EXPECT_EQ(std::u16string(), result);
}
TEST(CustomDataHelperTest, EmptyReadMap) {
base::Pickle pickle;
PrepareEmptyTestData(&pickle);
std::unordered_map<std::u16string, std::u16string> result;
ReadCustomDataIntoMap(pickle.data(), pickle.size(), &result);
EXPECT_EQ(0u, result.size());
}
TEST(CustomDataHelperTest, ReadTypes) {
base::Pickle pickle;
PrepareTestData(&pickle);
std::vector<std::u16string> types;
ReadCustomDataTypes(pickle.data(), pickle.size(), &types);
std::vector<std::u16string> expected = {u"abc", u"de", u"f"};
// We need to sort to compare equality, as the underlying custom data is
// unordered
std::sort(types.begin(), types.end());
std::sort(expected.begin(), expected.end());
EXPECT_EQ(expected, types);
}
TEST(CustomDataHelperTest, ReadSingleType) {
base::Pickle pickle;
PrepareTestData(&pickle);
std::u16string result;
ReadCustomDataForType(pickle.data(), pickle.size(), u"abc", &result);
EXPECT_EQ(std::u16string(), result);
ReadCustomDataForType(pickle.data(), pickle.size(), u"de", &result);
EXPECT_EQ(u"1", result);
ReadCustomDataForType(pickle.data(), pickle.size(), u"f", &result);
EXPECT_EQ(u"23", result);
}
TEST(CustomDataHelperTest, ReadMap) {
base::Pickle pickle;
PrepareTestData(&pickle);
std::unordered_map<std::u16string, std::u16string> result;
ReadCustomDataIntoMap(pickle.data(), pickle.size(), &result);
std::unordered_map<std::u16string, std::u16string> expected = {
{u"abc", std::u16string()}, {u"de", u"1"}, {u"f", u"23"}};
EXPECT_EQ(expected, result);
}
TEST(CustomDataHelperTest, BadReadTypes) {
// ReadCustomDataTypes makes the additional guarantee that the contents of the
// result vector will not change if the input is malformed.
std::vector<std::u16string> expected = {u"abc", u"de", u"f"};
base::Pickle malformed;
malformed.WriteUInt32(1000);
malformed.WriteString16(u"hello");
malformed.WriteString16(u"world");
std::vector<std::u16string> actual(expected);
ReadCustomDataTypes(malformed.data(), malformed.size(), &actual);
EXPECT_EQ(expected, actual);
base::Pickle malformed2;
malformed2.WriteUInt32(1);
malformed2.WriteString16(u"hello");
std::vector<std::u16string> actual2(expected);
ReadCustomDataTypes(malformed2.data(), malformed2.size(), &actual2);
EXPECT_EQ(expected, actual2);
}
TEST(CustomDataHelperTest, BadPickle) {
std::u16string result_data;
std::unordered_map<std::u16string, std::u16string> result_map;
base::Pickle malformed;
malformed.WriteUInt32(1000);
malformed.WriteString16(u"hello");
malformed.WriteString16(u"world");
ReadCustomDataForType(malformed.data(), malformed.size(), u"f", &result_data);
ReadCustomDataIntoMap(malformed.data(), malformed.size(), &result_map);
EXPECT_EQ(0u, result_data.size());
EXPECT_EQ(0u, result_map.size());
base::Pickle malformed2;
malformed2.WriteUInt32(1);
malformed2.WriteString16(u"hello");
ReadCustomDataForType(malformed2.data(), malformed2.size(), u"f",
&result_data);
ReadCustomDataIntoMap(malformed2.data(), malformed2.size(), &result_map);
EXPECT_EQ(0u, result_data.size());
EXPECT_EQ(0u, result_map.size());
}
} // namespace
} // namespace ui
| 30.222973 | 80 | 0.71831 | [
"vector"
] |
e414865e344842c6f84a244e4b3a52d212e0b7cc | 5,271 | hpp | C++ | include/caffe/training_utils.hpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 933 | 2016-08-29T14:29:20.000Z | 2022-03-20T09:03:49.000Z | include/caffe/training_utils.hpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 286 | 2016-08-30T01:33:01.000Z | 2021-08-22T08:34:19.000Z | include/caffe/training_utils.hpp | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 611 | 2016-08-30T07:22:04.000Z | 2021-12-18T11:53:08.000Z | /*
All modification made by Intel Corporation: © 2016 Intel Corporation
All contributions by the University of California:
Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
All rights reserved.
All other contributions:
Copyright (c) 2014, 2015, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md
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 Intel 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 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.
*/
#include <string>
#include <vector>
using caffe::Solver;
using caffe::shared_ptr;
using caffe::string;
using caffe::vector;
vector<string> get_stages_from_flags(const std::string& stages_flag) {
vector<string> stages;
boost::split(stages, stages_flag, boost::is_any_of(","));
return stages;
}
void use_flags(caffe::SolverParameter* solver_param,
const std::string& flag_solver,
const std::string& flag_engine,
const int& flag_level,
const std::string& stages_flag) {
caffe::UpgradeSolverAsNeeded(flag_solver, solver_param);
vector<string> stages = get_stages_from_flags(stages_flag);
// Override engine if provided in cmd line
if (flag_engine != "") {
solver_param->set_engine(flag_engine);
}
solver_param->mutable_train_state()->set_level(flag_level);
for (int i = 0; i < stages.size(); i++) {
solver_param->mutable_train_state()->add_stage(stages[i]);
}
}
int multiphase_train(caffe::MultiPhaseSolverParameter* multi_solver_params,
const std::string& flag_solver,
const std::string& flag_engine,
const int& flag_level,
const std::string& stages_flag) {
LOG(INFO) << "Running multiphase solver.";
caffe::NetParameter solver_phase_net_param;
caffe::NetParameter topology_net_param;
caffe::SolverParameter solver_param;
CHECK(multi_solver_params->params_pair(0).has_solver_params())
<< "Solver parameters should be provided in at least first params pair";
CHECK(caffe::ReadProtoFromTextFile(
multi_solver_params->params_pair(0).solver_params().net(),
&topology_net_param))
<< "Could not read from net parameter of solver proto file";
string snapshot_prefix = multi_solver_params->
params_pair(0).solver_params().snapshot_prefix() + "_phase_";
for (int j = 0; j < multi_solver_params->params_pair_size(); j++) {
if (multi_solver_params->params_pair(j).has_solver_params()) {
solver_param = multi_solver_params->params_pair(j).solver_params();
if (solver_param.solver_mode() !=
caffe::SolverParameter_SolverMode_CPU) {
LOG(ERROR) << "CPU mode supported only";
return -1;
}
}
if (multi_solver_params->params_pair(j).has_batch_size()) {
for (int i = 0; i < topology_net_param.layer_size(); i++) {
if (topology_net_param.layer(i).type() == "Data") {
topology_net_param.mutable_layer(i)->mutable_data_param()->
set_batch_size(multi_solver_params->params_pair(j).batch_size());
break;
}
}
}
solver_param.set_snapshot_prefix(snapshot_prefix
+ boost::lexical_cast<string>(j));
solver_param.set_allocated_net_param(&topology_net_param);
solver_param.clear_net();
use_flags(
&solver_param,
flag_solver,
flag_engine,
flag_level,
stages_flag);
shared_ptr<caffe::Solver<float> >
solver(caffe::SolverRegistry<float>::CreateSolver(solver_param));
topology_net_param = *solver_param.release_net_param();
solver->net()->CopyTrainedLayersFrom(solver_phase_net_param);
for (int i = 0; i < solver->test_nets().size(); ++i) {
solver->test_nets()[i]->CopyTrainedLayersFrom(solver_phase_net_param);
}
solver->Solve();
solver->net()->ToProto(
&solver_phase_net_param,
solver->param().snapshot_diff());
}
LOG(INFO) << "Optimization Done.";
return 0;
}
| 37.119718 | 92 | 0.728894 | [
"vector"
] |
e41f44d3144de14b6cfbbeeb10fc164a4b6b1f49 | 1,656 | cpp | C++ | LeetCode/Problems/Algorithms/#1349_MaximumStudentsTakingExam_sol1_backtracking_O(2^(RC))_time_O(RC)_extra_space_TLE.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#1349_MaximumStudentsTakingExam_sol1_backtracking_O(2^(RC))_time_O(RC)_extra_space_TLE.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#1349_MaximumStudentsTakingExam_sol1_backtracking_O(2^(RC))_time_O(RC)_extra_space_TLE.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
private:
static const char BROKEN_SEAT = '#';
static const char PERSON = 'p';
const vector<pair<int, int>> DIRECTIONS = {{-1, -1}, {0, -1}, {0, 1}, {-1, 1}};
bool isValid(int row, int col, const int& ROWS, const int& COLS, vector<vector<char>>& seats){
for(const pair<int, int>& DIRECTION: DIRECTIONS){
int nextRow = row + DIRECTION.first;
int nextCol = col + DIRECTION.second;
if(0 <= nextRow && nextRow < ROWS && 0 <= nextCol && nextCol < COLS){
if(seats[nextRow][nextCol] == PERSON){
return false;
}
}
}
return (seats[row][col] != BROKEN_SEAT);
}
void back(int row, int col, int count, int& maxCount, vector<vector<char>>& seats){
const int ROWS = seats.size();
const int COLS = seats[0].size();
maxCount = max(maxCount, count);
if(row == ROWS){
// stop
}else if(col == COLS){
back(row + 1, 0, count, maxCount, seats);
}else if(isValid(row, col, ROWS, COLS, seats)){
char initialSeat = seats[row][col];
seats[row][col] = PERSON;
back(row, col + 1, count + 1, maxCount, seats);
seats[row][col] = initialSeat;
back(row, col + 1, count, maxCount, seats);
}else{
back(row, col + 1, count, maxCount, seats);
}
}
public:
int maxStudents(vector<vector<char>>& seats) {
int maxCount = 0;
back(0, 0, 0, maxCount, seats);
return maxCount;
}
}; | 36.8 | 99 | 0.500604 | [
"vector"
] |
e4215fbed0c07c0fef05de358cb4ef239a14b198 | 4,736 | cpp | C++ | topcoder/srm/src/SRM611/LCMSetEasy.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | topcoder/srm/src/SRM611/LCMSetEasy.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | 19 | 2016-05-04T02:46:31.000Z | 2021-11-27T06:18:33.000Z | topcoder/srm/src/SRM611/LCMSetEasy.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | #include <algorithm>
#include <complex>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define REP(i, n) for(int i=0; i<(int)n; ++i)
#define FOR(i, c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(),(c).end()
#define each(i, c) FOR(i, c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
class LCMSetEasy {
public:
string include(vector <int> S, int x)
{
sort(S.begin(), S.end());
if (binary_search(S.begin(), S.end(), x)) {
return "Possible";
}
// 1,000,000,000,
const int M = 100000;
bool prime[M];
fill(prime, prime + M, true);
prime[0] = prime[1] = false;
for (int i = 2; i * i < M; ++i) {
for (int j = 2; i * j < M; ++j) {
prime[i * j] = false;
}
}
vector<int> p;
for (int i = 0; i < M; ++i) {
if (prime[i]) p.push_back(i);
}
const int N = S.size();
map<int, int> A;
map<int, int> B;
const int P = p.size();
int n = x;
for (int i = 0; i < P; ++i) {
while (n % p[i] == 0) {
++A[p[i]];
n /= p[i];
}
}
if (n != 1) ++A[n];
for (int i = 0; i < N; ++i) {
int n = S[i];
map<int, int> C;
for (int j = 0; j < P; ++j) {
while (n % p[j] == 0) {
++C[p[j]];
n /= p[j];
}
}
if (n != 1) ++C[n];
bool flg = true;
each (j, C) {
int m = j->first;
flg = flg && (0 < A.count(m));
flg = flg && (C[m] <= A[m]);
}
if (flg) {
each (j, C) {
int m = j->first;
B[m] = max(B[m], C[m]);
}
}
}
bool flg = (A.size() == B.size());
each (i, A) {
int m = i->first;
flg = flg && (A[m] == B[m]);
}
return flg ? "Possible" : "Impossible";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {2,3,4,5}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 20; string Arg2 = "Possible"; verify_case(0, Arg2, include(Arg0, Arg1)); }
void test_case_1() { int Arr0[] = {2,3,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 611; string Arg2 = "Impossible"; verify_case(1, Arg2, include(Arg0, Arg1)); }
void test_case_2() { int Arr0[] = {2,3,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 12; string Arg2 = "Possible"; verify_case(2, Arg2, include(Arg0, Arg1)); }
void test_case_3() { int Arr0[] = {1,2,3,4,5,6,7,8,9,10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 24; string Arg2 = "Possible"; verify_case(3, Arg2, include(Arg0, Arg1)); }
void test_case_4() { int Arr0[] = {100,200,300,400,500,600}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2000; string Arg2 = "Possible"; verify_case(4, Arg2, include(Arg0, Arg1)); }
void test_case_5() { int Arr0[] = {100,200,300,400,500,600}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8000; string Arg2 = "Impossible"; verify_case(5, Arg2, include(Arg0, Arg1)); }
void test_case_6() { int Arr0[] = {1000000000,999999999,999999998}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 999999999; string Arg2 = "Possible"; verify_case(6, Arg2, include(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
LCMSetEasy ___test;
___test.run_test(-1);
}
// END CUT HERE
| 34.823529 | 364 | 0.545608 | [
"vector"
] |
e42e9b71f4195bc07dd8aafae5c0e5024efcf603 | 21,769 | cc | C++ | elements/ctx/ctxmanager.cc | regufo/fastclick | d56d31c722266ea5d0cfd31435e81ca10dda5e69 | [
"BSD-3-Clause-Clear"
] | null | null | null | elements/ctx/ctxmanager.cc | regufo/fastclick | d56d31c722266ea5d0cfd31435e81ca10dda5e69 | [
"BSD-3-Clause-Clear"
] | null | null | null | elements/ctx/ctxmanager.cc | regufo/fastclick | d56d31c722266ea5d0cfd31435e81ca10dda5e69 | [
"BSD-3-Clause-Clear"
] | null | null | null | /*
* ctxmanager.{cc,hh} Context/Flow Manager
*/
#include <click/config.h>
#include <click/glue.hh>
#include <click/args.hh>
#include <click/routervisitor.hh>
#include "ctxmanager.hh"
#include "ctxdispatcher.hh"
#include <click/idletask.hh>
#include <click/hashtable.hh>
#include <algorithm>
#include <set>
#include <click/flow/flowelement.hh>
CLICK_DECLS
CTXManager::CTXManager(): _aggcache(false), _cache(0),_cache_size(4096), _cache_ring_size(8),_pull_burst(0),_builder(true),_collision_is_life(false), cache_miss(0),cache_sharing(0),cache_hit(0),_clean_timer(5000), _timer(this), _early_drop(true),
_ordered(true),_nocut(false), _optimize(true), Router::InitFuture(this) {
in_batch_mode = BATCH_MODE_NEEDED;
#if DEBUG_CLASSIFIER
_verbose = 3;
_size_verbose = 3;
#else
_verbose = 0;
_size_verbose = 0;
#endif
}
CTXManager::~CTXManager() {
}
int
CTXManager::configure(Vector<String> &conf, ErrorHandler *errh)
{
int reserve = 0;
String context = "ETHER";
if (Args(conf, this, errh)
.read_p("AGGCACHE",_aggcache)
.read_p("RESERVE",reserve)
.read("CACHESIZE", _cache_size)
.read("CACHERINGSIZE", _cache_ring_size)
.read("BUILDER",_builder)
.read("AGGTRUST",_collision_is_life)
.read("VERBOSE",_verbose)
.read("VERBOSE_FCB", _size_verbose)
.read("CONTEXT",context)
#if HAVE_FLOW_RELEASE_SLOPPY_TIMEOUT
.read("CLEAN_TIMER",_clean_timer)
#endif
.read("EARLYDROP", _early_drop)
.read("ORDERED", _ordered) //Enforce FCB order of access
.read("NOCUT", _nocut)
.read("OPTIMIZE", _optimize)
#if HAVE_FLOW_DYNAMIC
.read_or_set("RELEASE", _do_release, true)
#endif
.complete() < 0)
return -1;
find_children(_verbose);
//As all VirtualFlowManager, we must ensure the main future is called
router()->get_root_init_future()->post(&_fcb_builded_init_future);
//Once all CTXDispatchers have been initialized, we can initialize the CTXManager
ctx_builded_init_future()->post(this);
_fcb_builded_init_future.post(ctx_builded_init_future());
_reserve = sizeof(FlowNodeData) + (_aggcache?sizeof(uint32_t):0) + reserve;
_cache_mask = _cache_size - 1;
if ((_cache_size & _cache_mask) != 0)
return errh->error("Chache size must be a power of 2 !");
if (context == "ETHER") {
_context = FLOW_ETHER;
} else if (context == "NONE") {
_context = FLOW_NONE;
} else
return errh->error("Invalid context %s !",context.c_str());
return 0;
}
FlowNode* CTXManager::resolveContext(FlowType t, Vector<FlowElement*> contextStack) {
String prot;
if (_context == FLOW_ETHER) {
switch (t) {
case FLOW_IP:
prot = "12/0800!";
break;
case FLOW_ARP:
prot = "12/0806!";
break;
default:
return FlowElement::resolveContext(t, contextStack);
}
} else {
return FlowElement::resolveContext(t, contextStack);
}
return FlowClassificationTable::parse(this,prot).root;
}
#if HAVE_FLOW_RELEASE_SLOPPY_TIMEOUT
void CTXManager::run_timer(Timer*) {
click_chatter("Release timer!");
#if DEBUG_CLASSIFIER_RELEASE
click_chatter("Force run check-release");
#endif
fcb_table = &_table;
_table.check_release();
fcb_table = 0;
if (_clean_timer > 0)
_timer.reschedule_after_msec(_clean_timer);
}
#endif
void CTXManager::fcb_built() {
_table.get_pool()->initialize(_reserve, &_table);
}
/**
* Remove a fcb from the tree, deleting empty dynamic nodes in the parents
* The FCB release itself is handled by the caller
*/
void release_subflow(FlowControlBlock* fcb, void* thunk) {
#if DEBUG_CLASSIFIER_RELEASE
click_chatter("[%d] Release from tree fcb %p data %d, parent %p, thread %d",click_current_cpu_id(), fcb,fcb->data_64[0],fcb->parent, fcb->thread);
#endif
flow_assert(thunk);
CTXManager* fc = static_cast<CTXManager*>(thunk);
#if DEBUG_CLASSIFIER
if (fcb->parent != fc->table().get_root() && (!fcb->parent || !fc->table().get_root()->find_node(fcb->parent))) {
click_chatter("GOING TO CRASH WHILE REMOVING fcb %p, with parent %p", fcb, fcb->parent);
click_chatter("Parent exists : %d",fc->table().get_root()->find_node(fcb->parent));
assert(false);
}
#endif
//A -> B -> F
//Parent of the fcb is release_ptr
if (fc->is_dynamic_cache_enabled())
fc->remove_cache_fcb(fcb);
FlowNode* child = static_cast<FlowNode*>(fcb->parent); //Child is B
flow_assert(child->getNum() == child->findGetNum());
flow_assert(fcb->parent);
FlowNodeData data = *fcb->node_data;
child->release_child(FlowNodePtr(fcb), data); //B->release(F)
#if DEBUG_CLASSIFIER_RELEASE
fcb->parent = 0;
#endif
flow_assert(child->getNum() == child->findGetNum());
data = child->node_data; //Data is B data inside A
FlowNode* parent = child->parent(); //Parent is A
//If parent is dynamic, we cannot be the child of a default
//Release nodes up to the root
int up = 0;
while (parent && parent->level()->is_dynamic() && child->getNum() == 0) { //A && B is empty and A is dynamic (so B was a duplicate as it comes from a FCB)
#if DEBUG_CLASSIFIER_RELEASE
click_chatter("[%d] Releasing parent %s's child %p, growing %d, num %d, child is type %s num %d",up,parent->name().c_str(), child, parent->growing(), parent->getNum(),child->name().c_str(),child->getNum());
#endif
flow_assert(parent->threads[click_current_cpu_id()]);
parent->check(true, false);
flow_assert(child->level()->is_dynamic());
if (parent->growing() && !child->growing() && child == parent->default_ptr()->ptr) {
//If child is the non-growing default path of a growing parent, it is the default child table of a growing table and must not be deleted
//click_chatter("Non growing child of its growing original, not deleting");
flow_assert(parent->getNum() == parent->findGetNum());
break;
}
if (child->growing()) {
debug_flow("Releasing a growing child, we can remove it from the tree. Parent num is %d",parent->getNum());
flow_assert(parent->getNum() == parent->findGetNum());
FlowNode* subchild = child->default_ptr()->node;
if (child == parent->default_ptr()->ptr) { //Growing child was the default path
debug_flow("Default");
child->set_growing(false);
child->destroy();
parent->default_ptr()->ptr = subchild;
subchild->set_parent(parent);
} else { //Growing child of normal or growing
debug_flow("Child");
if (parent->growing()) { //Release growing of growing but unrelated as it is not the default
click_chatter("Growing of unrelated growing, not deleting");
break;
} else { //Release growing of normal, we cannot swap pointer because find could give a different bucket
parent->release_child(FlowNodePtr(child), data); //A->release(B). As growing flag is set, the parent will not keep the pointer even if KEEP_STRUCTURE
}
//the child has been destroyed by release_child, because of the growing flag
bool need_grow;
parent->find(data,need_grow)->set_node(subchild);
subchild->set_parent(parent);
subchild->node_data = data;
parent->inc_num();
break; //No need to continue, parent now has a child
}
} else { //Child is not growing, we remove a normal child
debug_flow_2("Non-growing");
flow_assert(parent->getNum() == parent->findGetNum());
parent->release_child(FlowNodePtr(child), data); //A->release(B)
}
#if DEBUG_CLASSIFIER_CHECK || DEBUG_CLASSIFIER
if (parent->getNum() != parent->findGetNum()) {
click_chatter("Parent has %d != %d counted children",parent->getNum(),parent->findGetNum());
assert(false);
}
#endif
parent->check(true, false);
child = parent; //Child is A
data = child->node_data;
parent = child->parent(); //Parent is 0
up++;
};
#if DEBUG_CLASSIFIER
check_thread(parent, child);
#endif
fc->table().get_root()->check();
}
int CTXManager::_initialize_classifier(ErrorHandler *errh) {
if (input_is_pull(0)) {
assert(input(0).element());
}
auto passing = get_passing_threads();
_table.get_pool()->compress(passing);
Vector<FlowElement*> s(1,0);
s[0] = this;
FlowNode* table = FlowElementVisitor::get_downward_table(this, 0, s);
if (!table)
return errh->error("%s: CTXManager without any downward dispatcher?",name().c_str());
_table.set_release_fnt(release_subflow,this);
if (table->is_dummy()) {
return errh->error("%p{element} : CTXManager without classification !");
}
if (_verbose > 1) {
click_chatter("Table of %s before optimization :",name().c_str());
table->print(-1,false);
}
table->check();
if (_optimize) {
_table.set_root(table->optimize(passing));
} else {
_table.set_root(table);
}
_table.get_root()->check();
if (_verbose) {
click_chatter("Table of %s after optimization :",name().c_str());
bool showptr = false;
#if DEBUG_CLASSIFIER
showptr = true;
#endif
_table.get_root()->print(-1,showptr);
}
FCBPool::initialized --;
return 0;
}
/**
* Replace all leafs of the tree by the final pool-alocated ones.
* During initialization leafs have a double size to note which field are initialized.
*/
int CTXManager::_replace_leafs(ErrorHandler *errh) {
//Replace FCBs by the final run-time ones
//Also have common static FCBs
HashTable<FlowControlBlockRef, FlowControlBlock*> known_static_fcbs;
_table.get_root()->traverse_all_leaves([this,&known_static_fcbs](FlowNodePtr* ptr) {
FlowControlBlock* nfcb;
auto it = known_static_fcbs.find(FlowControlBlockRef(ptr->leaf));
while (!ptr->parent()->level()->is_dynamic() && it) {
nfcb = it->second;
if (ptr->parent()->default_ptr()->leaf != ptr->leaf && !nfcb->get_data().equals(ptr->leaf->get_data())) {
//The data is not the same, we need to change the FCB by a classification node with the right data
//Change : this adds a classification step for a bit of memory. We don't care.
++it;
continue;
/*
if (_verbose > 1) {
click_chatter("Need a new node to keep data");
ptr->leaf->print("");
nfcb->print("");
}
FlowNode* n = new FlowNodeDummy();
n->threads = ptr->parent()->threads;
n->set_parent(ptr->parent());
n->set_level(new FlowLevelDummy());
n->node_data = ptr->data();
delete ptr->leaf;
ptr->set_node(n);
ptr = n->default_ptr();*/
} else
delete ptr->leaf;
//Delete parent to specify this FCB has multiple parents
if (nfcb->parent)
nfcb->parent = 0;
goto set;
}
{
nfcb = _table.get_pool()->allocate();
FlowNode* p = ptr->parent();
memcpy(nfcb->data, ptr->leaf->data, _table.get_pool()->data_size());
nfcb->parent = ptr->leaf->parent;
nfcb->flags = ptr->leaf->flags;
#if DEBUG_CLASSIFIER
if (nfcb->parent->threads.weight() == 1) {
nfcb->thread = nfcb->parent->threads.clz();
} else
nfcb->thread = -1;
#endif
known_static_fcbs.set(FlowControlBlockRef(nfcb), nfcb);
assert(known_static_fcbs.find(FlowControlBlockRef(nfcb)));
delete ptr->leaf;
}
set:
#if HAVE_FLOW_DYNAMIC
nfcb->reset_count(1);
#endif
nfcb->release_fnt = 0;
ptr->set_leaf(nfcb);
}, true, true);
if (_verbose > 1) {
click_chatter("Table of %s after replacing nodes :",name().c_str());
bool showptr = false;
#if DEBUG_CLASSIFIER
showptr = true;
#endif
_table.get_root()->print(-1,showptr);
}
bool have_dynamic = false;
_table.get_root()->traverse_all_nodes([this,&have_dynamic](FlowNode* n) {
if (n->level()->is_dynamic()) {
have_dynamic = true;
return false;
}
return true;
});
#if HAVE_VERBOSE_BATCH
if (!have_dynamic && _do_release) {
click_chatter("CTXManager is fully static, disabling release, consider compiling with --disable-dynamic-flow");
}
#endif
#ifndef HAVE_FLOW_DYNAMIC
if (have_dynamic) {
return errh->error("You have dynamic flow elements, but this was build without dynamic support. Rebuild with --enable-flow-dynamic.");
}
#endif
//If aggcache is enabled, initialize the cache
if (_aggcache && _cache_size > 0) {
for (unsigned i = 0; i < _cache.weight(); i++) {
_cache.get_value(i) = (FlowCache*)CLICK_LALLOC(sizeof(FlowCache) * _cache_size * _cache_ring_size);
bzero(_cache.get_value(i), sizeof(FlowCache) * _cache_size * _cache_ring_size);
}
}
return 0;
}
/**
* Initialize timeout timers
*/
int CTXManager::_initialize_timers(ErrorHandler *errh) {
if (_do_release) {
#if HAVE_FLOW_RELEASE_SLOPPY_TIMEOUT
auto pushing = get_pushing_threads();
for (unsigned i = 0; i < click_max_cpu_ids(); i++) {
if (pushing[i]) {
IdleTask* idletask = new IdleTask(this);
idletask->initialize(this, i, 100);
}
}
_timer.initialize(this);
if (_clean_timer > 0)
_timer.schedule_after_msec(_clean_timer);
#endif
}
return 0;
}
int CTXManager::solve_initialize(ErrorHandler *errh) {
if (_initialize_classifier(errh) != 0)
return -1;
if (_replace_leafs(errh) != 0)
return -1;
if (_initialize_timers(errh) != 0)
return -1;
return Router::InitFuture::solve_initialize(errh);
}
void CTXManager::cleanup(CleanupStage stage) {
fcb_table = &_table;
bool previous = pool_allocator_mt_base::dying();
pool_allocator_mt_base::set_dying(true);
if (_table.get_root()) {
// _table.get_root()->print();
// click_chatter("Deleting!");
//
#if HAVE_FLOW_RELEASE_SLOPPY_TIMEOUT
//We are not on the right thread, so we'll delete the cache by ourselves
//TODO : elements and cache assume release is done on the same thread, we must implement thread_cleanup
//_table.delete_all_flows();
#endif
// _table.get_root()->print();
}
pool_allocator_mt_base::set_dying(previous);
if (_table.get_root()) {
_table.get_root()->traverse_all_leaves([this](FlowNodePtr* ptr) {
_table.get_pool()->release(ptr->leaf);
ptr->leaf = 0;
}, true, true);
}
fcb_table = 0;
//If aggcache is enabled, initialize the cache
if (_aggcache && _cache_size > 0) {
for (unsigned i = 0; i < _cache.weight(); i++) {
if (_cache.get_value(i))
CLICK_LFREE(_cache.get_value(i),sizeof(FlowCache) * _cache_size * _cache_ring_size);
}
}
/*click_chatter("%p{element} Hit : %d",this,cache_hit);
click_chatter("%p{element} Shared : %d",this,cache_sharing);
click_chatter("%p{element} Miss : %d",this,cache_miss);*/
}
bool CTXManager::run_idle_task(IdleTask*) {
#if HAVE_FLOW_RELEASE_SLOPPY_TIMEOUT
//#if !HAVE_DYNAMIC_FLOW_RELEASE_FNT
fcb_table = &_table;
//#endif
#if DEBUG_CLASSIFIER_TIMEOUT > 0
click_chatter("%p{element} Idle release",this);
#endif
bool work_done = _table.check_release();
//#if !HAVE_DYNAMIC_FLOW_RELEASE_FNT
fcb_table = 0;
//#endif
#endif
return work_done;
}
/**
* Testing function
* Search a FCB in the cache, linearly
*/
inline int CTXManager::cache_find(FlowControlBlock* fcb) {
if (!_aggcache)
return 0;
FlowCache* bucket = _cache.get();
int n = 0;
int i = 0;
while (bucket < _cache.get() + (_cache_size * _cache_ring_size)) {
if (bucket->agg != 0 && bucket->fcb == fcb) {
n++;
}
bucket++;
i++;
}
return n;
}
/**
* Remove a FCB from the cache
*/
inline void CTXManager::remove_cache_fcb(FlowControlBlock* fcb) {
uint32_t agg = *((uint32_t*)&(fcb->node_data[1]));
if (agg == 0)
return;
uint16_t hash = (agg ^ (agg >> 16)) & _cache_mask;
#if USE_CACHE_RING
FlowCache* bucket = _cache.get() + ((uint32_t)hash * _cache_ring_size);
FlowCache* c = bucket;
int ic = 0;
do {
if (c->agg == agg && c->fcb == fcb) {
FlowCache* bxch = bucket + _cache_ring_size - 1;
while (bxch->agg == 0) {
bxch--;
}
c->agg = bxch->agg;
c->fcb = bxch->fcb;
bxch->agg = 0;
return;
}
ic++;
c++;
} while (ic < _cache_ring_size);
click_chatter("REMOVING a FCB from the cache that was not in the cache %p, agg %u",fcb, agg);
#else
FlowCache* bucket = _cache.get() + hash;
if (bucket->agg == agg) {
bucket->agg = 0;
}
#endif
}
/**
* Push batch simple simply classify packets and push a batch when a packet
* is different
*/
inline void CTXManager::push_batch_simple(int port, PacketBatch* batch) {
PacketBatch* awaiting_batch = NULL;
Packet* p = batch->first();
Packet* last = NULL;
uint32_t lastagg = 0;
Timestamp now = Timestamp::recent_steady();
int count =0;
FlowControlBlock* fcb = 0;
#if DEBUG_CLASSIFIER > 1
click_chatter("Simple have %d packets.",batch->count());
#endif
while (p != NULL) {
#if DEBUG_CLASSIFIER > 1
click_chatter("Packet %p in %s",p,name().c_str());
#endif
Packet* next = p->next();
if (!get_fcb_for(p,fcb,lastagg,last,next,now)) {
continue;
}
handle_simple(p, last, fcb, awaiting_batch, count, now);
last = p;
p = next;
}
flush_simple(last, awaiting_batch, count, now);
}
/**
* Push_batch_builder use double connection to build a ring and process packets trying to reconcile flows more
*
*/
inline void CTXManager::push_batch_builder(int, PacketBatch* batch) {
Packet* p = batch->first();
FlowControlBlock* fcb = 0;
uint32_t lastagg = 0;
Packet* last = 0;
Builder builder;
Timestamp now = Timestamp::recent_steady();
process:
//click_chatter("Builder have %d packets.",batch->count());
while (p != NULL) {
#if DEBUG_CLASSIFIER > 1
click_chatter("Packet %p in %s",p,name().c_str());
#endif
Packet* next = p->next();
if (!get_fcb_for(p,fcb,lastagg,last,next,now))
continue;
handle_builder(p, last, fcb, builder, now);
last = p;
p = next;
}
flush_builder(last, builder, now);
fcb_stack = 0;
//click_chatter("End");
}
void CTXManager::push_batch(int, PacketBatch* batch) {
FlowControlBlock* tmp_stack = fcb_stack;
FlowTableHolder* tmp_table = fcb_table;
//#if !HAVE_DYNAMIC_FLOW_RELEASE_FNT
fcb_table = &_table;
//#endif
if (_builder)
push_batch_builder(0,batch);
else
push_batch_simple(0,batch);
check_release_flows();
fcb_stack = tmp_stack;
//#if !HAVE_DYNAMIC_FLOW_RELEASE_FNT
fcb_table = tmp_table;
//#endif
}
enum {h_leaves_count, h_active_count, h_print, h_timeout_count};
String CTXManager::read_handler(Element* e, void* thunk) {
CTXManager* fc = static_cast<CTXManager*>(e);
fcb_table = &fc->_table;
switch ((intptr_t)thunk) {
case h_active_count:
case h_leaves_count: {
int n = 0;
fc->_table.get_root()->traverse_all_leaves([&n](FlowNodePtr* ptr) {
#if HAVE_FLOW_DYNAMIC && FLOW_DEBUG_CLASSIFIER
click_chatter("%d",ptr->leaf->count());
#endif
n++;
},true,(intptr_t)thunk==h_leaves_count);
fcb_table = 0;
return String(n);
}
case h_print:
fc->_table.get_root()->print(-1,false,true,false);
fcb_table = 0;
return String("");
#if HAVE_DYNAMIC_FLOW
case h_timeout_count:
return String(fc->_table.old_flows->count());
#endif
default:
return String("<unknown>");
}
};
CounterInitFuture CTXManager::_ctx_builded_init_future("CTXBuilder", [](){});
void CTXManager::add_handlers() {
add_read_handler("leaves_count", CTXManager::read_handler, h_leaves_count);
add_read_handler("leaves_all_count", CTXManager::read_handler, h_leaves_count);
add_read_handler("leaves_nondefault_count", CTXManager::read_handler, h_active_count);
add_read_handler("print_tree", CTXManager::read_handler, h_print);
add_read_handler("timeout_count", CTXManager::read_handler, h_timeout_count);
}
//int FlowBufferVisitor::shared_position[NR_SHARED_FLOW] = {-1};
CLICK_ENDDECLS
ELEMENT_REQUIRES(flow)
EXPORT_ELEMENT(CTXManager)
ELEMENT_MT_SAFE(CTXManager)
| 32.834087 | 246 | 0.60701 | [
"vector"
] |
e42fb743a38ef23118c8d8c8264e304899b7742d | 16,531 | hpp | C++ | include/RAJA/pattern/forall.hpp | jonesholger/RAJA | e1f3de7f71637383665379c97802481bfce9318f | [
"BSD-3-Clause"
] | 1 | 2020-04-28T20:35:12.000Z | 2020-04-28T20:35:12.000Z | include/RAJA/pattern/forall.hpp | jonesholger/RAJA | e1f3de7f71637383665379c97802481bfce9318f | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/pattern/forall.hpp | jonesholger/RAJA | e1f3de7f71637383665379c97802481bfce9318f | [
"BSD-3-Clause"
] | 1 | 2020-06-07T13:26:40.000Z | 2020-06-07T13:26:40.000Z | /*!
******************************************************************************
*
* \file
*
* \brief Header file containing RAJA index set and segment iteration
* template methods that take an execution policy as a template
* parameter.
*
* The templates for segments support the following usage pattern:
*
* forall<exec_policy>( index set, loop body );
*
* which is equivalent to:
*
* forall( exec_policy(), index set, loop body );
*
* The former is slightly more concise. Here, the execution policy
* type is associated with a tag struct defined in the exec_poilicy
* hearder file. Usage of the forall_Icount() is similar.
*
* The forall() and forall_Icount() methods that take an index set
* take an execution policy of the form:
*
* TypedIndexSet::ExecPolicy< seg_it_policy, seg_exec_policy >
*
* Here, the first template parameter determines the scheme for
* iteratiing over the index set segments and the second determines
* how each segment is executed.
*
* The forall() templates accept a loop body argument that takes
* a single Index_type argument identifying the index of a loop
* iteration. The forall_Icount() templates accept a loop body that
* takes two Index_type arguments. The first is the number of the
* iteration in the indes set or segment, the second if the actual
* index of the loop iteration.
*
*
* IMPORTANT: Use of any of these methods requires a specialization
* for the given index set type and execution policy.
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-20, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef RAJA_forall_generic_HPP
#define RAJA_forall_generic_HPP
#include "RAJA/config.hpp"
#include <functional>
#include <iterator>
#include <type_traits>
#include "RAJA/internal/Iterators.hpp"
#include "RAJA/policy/PolicyBase.hpp"
#include "RAJA/index/IndexSet.hpp"
#include "RAJA/index/ListSegment.hpp"
#include "RAJA/index/RangeSegment.hpp"
#include "RAJA/internal/fault_tolerance.hpp"
#include "RAJA/util/concepts.hpp"
#include "RAJA/util/Span.hpp"
#include "RAJA/util/types.hpp"
#include "RAJA/policy/sequential/forall.hpp"
#include "RAJA/pattern/detail/forall.hpp"
#include "RAJA/pattern/detail/privatizer.hpp"
#include "RAJA/internal/get_platform.hpp"
#include "RAJA/util/plugins.hpp"
namespace RAJA
{
//
//////////////////////////////////////////////////////////////////////
//
// Iteration over generic iterators
//
//////////////////////////////////////////////////////////////////////
//
namespace internal
{
template <typename T>
auto trigger_updates_before(T&& item) -> typename std::remove_reference<T>::type
{
return item;
}
} // end namespace internal
namespace detail
{
/// Adapter to replace specific implementations for the icount variants
template <typename Range, typename Body, typename IndexT>
struct icount_adapter {
using index_type = typename std::decay<IndexT>::type;
typename std::decay<Body>::type body;
using container_type = typename std::decay<Range>::type;
typename container_type::iterator begin_it;
Index_type icount;
icount_adapter(Range const& r, Body const& b, IndexT icount_)
: body{b}, icount{icount_}
{
using std::begin;
begin_it = begin(r);
}
RAJA_SUPPRESS_HD_WARN
template <typename T>
RAJA_HOST_DEVICE void operator()(T const& i) const
{
body(static_cast<index_type>(i + icount), begin_it[i]);
}
};
struct CallForall {
template <typename T, typename ExecPol, typename Body>
RAJA_INLINE void operator()(T const&, ExecPol, Body) const;
};
struct CallForallIcount {
constexpr CallForallIcount(int s);
template <typename T, typename ExecPol, typename Body>
RAJA_INLINE void operator()(T const&, ExecPol, Body) const;
const int start;
};
} // namespace detail
/*!
******************************************************************************
*
* \brief The RAJA::wrap layer unwraps dynamic policies before dispatch
*
******************************************************************************
*/
namespace wrap
{
/*!
******************************************************************************
*
* \brief Generic dispatch over containers with a value-based policy
*
******************************************************************************
*/
template <typename ExecutionPolicy, typename Container, typename LoopBody>
RAJA_INLINE concepts::enable_if<
concepts::negate<type_traits::is_indexset_policy<ExecutionPolicy>>,
type_traits::is_range<Container>>
forall(ExecutionPolicy&& p, Container&& c, LoopBody&& loop_body)
{
using RAJA::internal::trigger_updates_before;
auto body = trigger_updates_before(loop_body);
forall_impl(std::forward<ExecutionPolicy>(p),
std::forward<Container>(c),
body);
}
/*!
******************************************************************************
*
* \brief Generic dispatch over containers with a value-based policy with icount
*
******************************************************************************
*/
template <typename ExecutionPolicy,
typename Container,
typename IndexType,
typename LoopBody>
RAJA_INLINE void forall_Icount(ExecutionPolicy&& p,
Container&& c,
IndexType&& icount,
LoopBody&& loop_body)
{
using RAJA::internal::trigger_updates_before;
auto body = trigger_updates_before(loop_body);
using std::begin;
using std::distance;
using std::end;
auto range = RangeSegment(0, distance(begin(c), end(c)));
detail::icount_adapter<Container, LoopBody, IndexType> adapted(c,
body,
icount);
using policy::sequential::forall_impl;
forall_impl(std::forward<ExecutionPolicy>(p), range, adapted);
}
/*!
******************************************************************************
*
* \brief Execute segments from forall_Icount traversal method.
*
* For usage example, see reducers.hxx.
*
******************************************************************************
*/
template <typename SegmentIterPolicy,
typename SegmentExecPolicy,
typename... SegmentTypes,
typename LoopBody>
RAJA_INLINE void forall_Icount(ExecPolicy<SegmentIterPolicy, SegmentExecPolicy>,
const TypedIndexSet<SegmentTypes...>& iset,
LoopBody loop_body)
{
using RAJA::internal::trigger_updates_before;
auto body = trigger_updates_before(loop_body);
// no need for icount variant here
wrap::forall(SegmentIterPolicy(), iset, [=](int segID) {
iset.segmentCall(segID,
detail::CallForallIcount(iset.getStartingIcount(segID)),
SegmentExecPolicy(),
body);
});
}
template <typename SegmentIterPolicy,
typename SegmentExecPolicy,
typename LoopBody,
typename... SegmentTypes>
RAJA_INLINE void forall(ExecPolicy<SegmentIterPolicy, SegmentExecPolicy>,
const TypedIndexSet<SegmentTypes...>& iset,
LoopBody loop_body)
{
using RAJA::internal::trigger_updates_before;
auto body = trigger_updates_before(loop_body);
wrap::forall(SegmentIterPolicy(), iset, [=](int segID) {
iset.segmentCall(segID, detail::CallForall{}, SegmentExecPolicy(), body);
});
}
} // end namespace wrap
/*!
******************************************************************************
*
* \brief Generic dispatch over with icount
*
******************************************************************************
*/
template <typename ExecutionPolicy, typename IdxSet, typename LoopBody>
RAJA_INLINE void forall_Icount(ExecutionPolicy&& p,
IdxSet&& c,
LoopBody&& loop_body)
{
static_assert(type_traits::is_index_set<IdxSet>::value,
"Expected a TypedIndexSet but did not get one. Are you using "
"a TypedIndexSet policy by mistake?");
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
wrap::forall_Icount(std::forward<ExecutionPolicy>(p),
std::forward<IdxSet>(c),
std::forward<LoopBody>(loop_body));
util::callPostLaunchPlugins(context);
}
/*!
******************************************************************************
*
* \brief Generic dispatch over with icount
*
******************************************************************************
*/
template <typename ExecutionPolicy, typename IdxSet, typename LoopBody>
RAJA_INLINE concepts::enable_if<
type_traits::is_indexset_policy<ExecutionPolicy>>
forall(ExecutionPolicy&& p, IdxSet&& c, LoopBody&& loop_body)
{
static_assert(type_traits::is_index_set<IdxSet>::value,
"Expected a TypedIndexSet but did not get one. Are you using "
"a TypedIndexSet policy by mistake?");
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
wrap::forall(std::forward<ExecutionPolicy>(p),
std::forward<IdxSet>(c),
std::forward<LoopBody>(loop_body));
util::callPostLaunchPlugins(context);
}
/*!
******************************************************************************
*
* \brief Generic dispatch over containers with icount
*
******************************************************************************
*/
template <typename ExecutionPolicy,
typename Container,
typename IndexType,
typename LoopBody>
RAJA_INLINE concepts::enable_if<type_traits::is_range<Container>,
type_traits::is_integral<IndexType>>
forall_Icount(ExecutionPolicy&& p,
Container&& c,
IndexType icount,
LoopBody&& loop_body)
{
static_assert(type_traits::is_random_access_range<Container>::value,
"Container does not model RandomAccessIterator");
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
wrap::forall_Icount(std::forward<ExecutionPolicy>(p),
std::forward<Container>(c),
icount,
std::forward<LoopBody>(loop_body));
util::callPostLaunchPlugins(context);
}
/*!
******************************************************************************
*
* \brief Generic dispatch over containers with a value-based policy
*
******************************************************************************
*/
template <typename ExecutionPolicy, typename Container, typename LoopBody>
RAJA_INLINE concepts::enable_if<
concepts::negate<type_traits::is_indexset_policy<ExecutionPolicy>>,
type_traits::is_range<Container>>
forall(ExecutionPolicy&& p, Container&& c, LoopBody&& loop_body)
{
static_assert(type_traits::is_random_access_range<Container>::value,
"Container does not model RandomAccessIterator");
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
wrap::forall(std::forward<ExecutionPolicy>(p),
std::forward<Container>(c),
std::forward<LoopBody>(loop_body));
util::callPostLaunchPlugins(context);
}
//
//////////////////////////////////////////////////////////////////////
//
// Function templates that iterate over indirection arrays.
//
//////////////////////////////////////////////////////////////////////
//
/*!
******************************************************************************
*
* \brief Generic iteration over indices in indirection array.
*
******************************************************************************
*/
template <typename ExecutionPolicy,
typename ArrayIdxType,
typename IndexType,
typename LoopBody>
RAJA_INLINE concepts::enable_if<
type_traits::is_integral<IndexType>,
concepts::negate<type_traits::is_iterator<IndexType>>>
forall(ExecutionPolicy&& p,
const ArrayIdxType* idx,
const IndexType len,
LoopBody&& loop_body)
{
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
wrap::forall(std::forward<ExecutionPolicy>(p),
TypedListSegment<ArrayIdxType>(idx, len, Unowned),
std::forward<LoopBody>(loop_body));
util::callPostLaunchPlugins(context);
}
/*!
******************************************************************************
*
* \brief Generic iteration over indices in indirection array with index count.
*
* NOTE: lambda loop body requires two args (icount, index).
*
******************************************************************************
*/
template <typename ExecutionPolicy,
typename ArrayIdxType,
typename IndexType,
typename OffsetType,
typename LoopBody>
RAJA_INLINE concepts::enable_if<
type_traits::is_integral<IndexType>,
concepts::negate<type_traits::is_iterator<IndexType>>,
type_traits::is_integral<OffsetType>,
concepts::negate<type_traits::is_iterator<OffsetType>>,
type_traits::is_integral<ArrayIdxType>,
concepts::negate<type_traits::is_iterator<ArrayIdxType>>>
forall_Icount(ExecutionPolicy&& p,
const ArrayIdxType* idx,
const IndexType len,
const OffsetType icount,
LoopBody&& loop_body)
{
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
// turn into an iterator
forall_Icount(std::forward<ExecutionPolicy>(p),
TypedListSegment<ArrayIdxType>(idx, len, Unowned),
icount,
std::forward<LoopBody>(loop_body));
util::callPostLaunchPlugins(context);
}
/*!
* \brief Conversion from template-based policy to value-based policy for forall
*
* this reduces implementation overhead and perfectly forwards all arguments
*/
template <typename ExecutionPolicy, typename... Args>
RAJA_INLINE void forall(Args&&... args)
{
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
RAJA_FORCEINLINE_RECURSIVE
wrap::forall(ExecutionPolicy(), std::forward<Args>(args)...);
util::callPostLaunchPlugins(context);
}
/*!
* \brief Conversion from template-based policy to value-based policy for
* forall_Icount
*
* this reduces implementation overhead and perfectly forwards all arguments
*/
template <typename ExecutionPolicy, typename... Args>
RAJA_INLINE void forall_Icount(Args&&... args)
{
util::PluginContext context{util::make_context<ExecutionPolicy>()};
util::callPreLaunchPlugins(context);
forall_Icount(ExecutionPolicy(), std::forward<Args>(args)...);
util::callPostLaunchPlugins(context);
}
namespace detail
{
template <typename T, typename ExecutionPolicy, typename LoopBody>
RAJA_INLINE void CallForall::operator()(T const& segment,
ExecutionPolicy,
LoopBody body) const
{
// this is only called inside a region, use impl
using policy::sequential::forall_impl;
forall_impl(ExecutionPolicy(), segment, body);
}
constexpr CallForallIcount::CallForallIcount(int s) : start(s) {}
template <typename T, typename ExecutionPolicy, typename LoopBody>
RAJA_INLINE void CallForallIcount::operator()(T const& segment,
ExecutionPolicy,
LoopBody body) const
{
// go through wrap to unwrap icount
wrap::forall_Icount(ExecutionPolicy(), segment, start, body);
}
} // namespace detail
} // namespace RAJA
#endif // closing endif for header file include guard
| 32.036822 | 80 | 0.582723 | [
"model"
] |
e4393f7d67584fe0ed6ba2a435358f73917c7e11 | 69,512 | cpp | C++ | src/game/etpro_mdx.cpp | jumptohistory/jaymod | 92d0a0334ac27da94b12280b0b42b615b8813c23 | [
"Apache-2.0"
] | 25 | 2016-05-27T11:53:58.000Z | 2021-10-17T00:13:41.000Z | src/game/etpro_mdx.cpp | jumptohistory/jaymod | 92d0a0334ac27da94b12280b0b42b615b8813c23 | [
"Apache-2.0"
] | 1 | 2016-07-09T05:25:03.000Z | 2016-07-09T05:25:03.000Z | src/game/etpro_mdx.cpp | jumptohistory/jaymod | 92d0a0334ac27da94b12280b0b42b615b8813c23 | [
"Apache-2.0"
] | 16 | 2016-05-28T23:06:50.000Z | 2022-01-26T13:47:12.000Z | /*
Copyright (C) 2003-2005 Christopher Lais (aka "Zinx Verituse")
and is covered by the following license:
***
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. Modified source for this software, as used in any binaries you have
distributed, must be provided on request, free of charge and/or penalty.
4. This notice may not be removed or altered from any source distribution.
***
*/
#include <bgame/impl.h>
#include <game/etpro_mdx_lut.h>
/* ******************* MDM/MDX file format, etc */
/* from http://games.theteamkillers.net/rtcw/mdx/ */
struct mdm_hdr {
char ident[4]; /* "MDMW" */
byte version[4]; /* uint32 */
char filename[64];
byte lod_bias[4]; /* vec_t */
byte lod_scale[4]; /* vec_t */
byte surface_count[4]; /* uint32 */
byte surface_offset[4]; /* uint32 */
byte tag_count[4]; /* uint32 */
byte tag_offset[4]; /* uint32 */
byte eof_offset[4]; /* uint32 */
};
struct mdm_tag {
char name[64];
byte axis[3][3][4]; /* vec_t[3][3] */
byte attach_bone[4]; /* uint32 */
byte offset[3][4]; /* vec_t[3] */
byte bone_count[4]; /* uint32 */
byte bone_offset[4]; /* uint32 */
byte tag_size[4]; /* uint32 */
/* bone indexes (uint32) follow */
};
struct mdx_hdr {
char ident[4]; /* "MDXW" */
byte version[4]; /* uint32 */
char filename[64];
byte frame_count[4]; /* uint32 */
byte bone_count[4]; /* uint32 */
byte frame_offset[4]; /* uint32 */
byte bone_offset[4]; /* uint32 */
byte torso_parent[4]; /* uint32 */
byte eof_offset[4]; /* uint32 */
};
struct mdx_frame_bone {
byte angles[3][2]; /* int16[3] */
byte unused[2]; /* int16 */
byte offset_angles[2][2]; /* int16[2] */
};
struct mdx_frame {
byte mins[3][4]; /* vec_t[3] */
byte maxs[3][4]; /* vec_t[3] */
byte origin[3][4]; /* vec_t[3] */
byte radius[4]; /* vec_t */
byte parent_offset[3][4]; /* vec_t[3] */
/* mdx_frame_bones follow */
};
struct mdx_bone {
char name[64];
byte parent_index[4]; /* int32 */
byte torso_weight[4]; /* vec_t */
byte parent_dist[4]; /* vec_t */
byte is_tag[4]; /* uint32 */
};
struct mdx {
struct mdx_hdr *hdr;
void *frame; /* struct mdx_frame; struct mdx_frame_bone*bone_count; ... */
struct mdx_bone *bone;
int frames, bones;
};
/* ******************* Internal */
#ifdef BONE_HITTESTS
const char *mdx_hit_type_names[MDX_HIT_TYPE_MAX] = {
"none",
"gun",
"head",
"body",
"arm_L",
"arm_R",
"leg_L",
"leg_R",
};
#endif
struct bone {
char name[64];
int parent_index;
vec_t parent_dist;
vec_t torso_weight;
};
struct frame_bone {
short angles[3]; /* Orientation angle */
short offset_angles[2]; /* Offset angle */
};
struct frame {
vec_t radius;
vec3_t parent_offset;
struct frame_bone *bones;
};
struct hit_area {
int hit_type;
animScriptImpactPoint_t impactpoint;
int tag[2]; /* internal (cached) tag numbers */
vec3_t scale[2];
qboolean ishead[2];
qboolean isbox;
vec3_t axis[3]; /* additional axis rotation before scale */
};
struct tag {
char name[64];
vec3_t axis[3];
vec3_t offset;
int attach_bone;
};
/**************************************************************/
#define TAG_INTERNAL (1<<30)
#define TAG_INTERNAL_MASK (~TAG_INTERNAL)
#define INTERNTAG_TAG (1<<29) /* based off tag, not bone */
#define INTERNTAG_TAG_MASK (~INTERNTAG_TAG)
typedef struct interntag_s interntag_t;
typedef struct mdm_s mdm_t;
typedef struct mdx_s mdx_t;
typedef struct hit_s hit_t;
struct interntag_s {
struct tag tag;
qboolean merged; /* merge with cachetag */
float weight; /* weight for merge (1.0 = only first) */
qboolean ishead; /* use head angles (for offset) */
};
struct mdm_s {
char path[MAX_QPATH];
int tag_count;
struct tag *tags;
/* quick lookup */
int tag_head;
int tag_armleft;
int tag_armright;
int tag_weapon2;
int tag_weapon;
int tag_back;
int tag_chest;
int tag_torso;
int tag_legleft;
int tag_legright;
int tag_footleft;
int tag_footright;
#ifdef BONE_HITTESTS
int *cachetags; /* cachetag_count entries */
#endif /* BONE_HITTESTS */
};
struct mdx_s {
char path[MAX_QPATH];
int bone_count;
struct bone *bones;
int frame_count;
struct frame *frames;
int torso_parent;
};
struct hit_s {
const animModelInfo_t *animModelInfo;
int hit_count;
struct hit_area *hits;
};
static int mdm_model_count = 0;
static mdm_t *mdm_models = NULL;
static int mdx_model_count = 0;
static mdx_t *mdx_models = NULL;
#ifdef BONE_HITTESTS
static int interntag_count = 0;
static interntag_t *interntags = NULL;
static int cachetag_count = 0;
static char (*cachetag_names)[64] = NULL;
#endif /* BONE_HITTESTS */
static int hit_count = 0;
static hit_t *hits = NULL;
/* Space for calculated bone origins -- new calculations overwrite the previous */
static int mdx_bones_max = 0;
static vec3_t *mdx_bones = NULL;
#define INDEXTOQHANDLE(idx) (qhandle_t)((idx)+1)
// Index may be NULL sometimes, so just default to the first model (FIXME: This is a HACK.)
#define QHANDLETOINDEX(qh) ((qh>=1)?((int)(qh) - 1):0)
#define QHANDLETOINDEX_SAFE(qh,old) ((qh>=1)?(int)(qh) - 1:QHANDLETOINDEX(old))
/**************************************************************/
/* free allocated memory */
void mdx_cleanup(void)
{
int i;
mdx_bones_max = 0;
free(mdx_bones);
mdx_bones = NULL;
#ifdef BONE_HITTESTS
cachetag_count = 0;
free(cachetag_names);
cachetag_names = NULL;
#endif /* BONE_HITTESTS */
for (i = 0; i < mdm_model_count; i++) {
free(mdm_models[i].tags);
#ifdef BONE_HITTESTS
free(mdm_models[i].cachetags);
#endif /* BONE_HITTESTS */
}
mdm_model_count = 0;
free(mdm_models);
mdm_models = NULL;
for (i = 0; i < mdx_model_count; i++) {
free(mdx_models[i].bones);
free(mdx_models[i].frames);
}
mdx_model_count = 0;
free(mdx_models);
mdx_models = NULL;
for (i = 0; i < hit_count; i++)
free(hits[i].hits);
hit_count = 0;
free(hits);
hits = NULL;
}
/**************************************************************/
/* Utility functions */
/* VectorRotate uses the transpose; I have no idea what use it is. */
static void PointRotate(const vec3_t in, vec3_t axis[3], vec3_t out)
{
out[0] = in[0]*axis[0][0] + in[1]*axis[1][0] + in[2]*axis[2][0];
out[1] = in[0]*axis[0][1] + in[1]*axis[1][1] + in[2]*axis[2][1];
out[2] = in[0]*axis[0][2] + in[1]*axis[1][2] + in[2]*axis[2][2];
}
static void MatrixTranspose(/*const*/ vec3_t in[3], vec3_t out[3])
{
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
out[i][j] = in[j][i];
}
}
}
static void MatrixWeight(/*const*/ vec3_t m[3], float weight, vec3_t mout[3])
{
float one = 1.0 - weight;
mout[0][0] = m[0][0]*weight + one;
mout[0][1] = m[0][1]*weight;
mout[0][2] = m[0][2]*weight;
mout[1][0] = m[1][0]*weight;
mout[1][1] = m[1][1]*weight + one;
mout[1][2] = m[1][2]*weight;
mout[2][0] = m[2][0]*weight;
mout[2][1] = m[2][1]*weight;
mout[2][2] = m[2][2]*weight + one;
}
/* The engine transforms short angles to an axis somewhat brokenly -
it uses a LUT and has truely perplexing values */
static void AnglesToAxisBroken(const short angles[2], vec3_t matrix[3])
{
int idx;
float sp, sy, cp, cy;
idx = angles[0]>>4;
if (idx < 0) idx += 4096;
sp = sintable[idx];
cp = sintable[(idx + 1024) % 4096];
idx = angles[1]>>4;
if (idx < 0) idx += 4096;
sy = sintable[idx];
cy = sintable[(idx + 1024) % 4096];
matrix[0][0] = cp*cy;
matrix[0][1] = cp*sy;
matrix[0][2] = -sp;
matrix[1][0] = -sy;
matrix[1][1] = cy;
matrix[1][2] = 0;
matrix[2][0] = sp*cy;
matrix[2][1] = sp*sy;
matrix[2][2] = cp;
}
#ifdef BONE_HITTESTS
static void mdx_matrix_to_quaternion(vec3_t m[3], vec4_t q)
{
vec_t w4;
q[3] = sqrt(1.0 + m[0][0] + m[1][1] + m[2][2]) / 2.0;
w4 = q[3] * 4.0;
q[0] = (m[1][2] - m[2][1]) / w4;
q[1] = (m[2][0] - m[0][2]) / w4;
q[2] = (m[0][1] - m[1][0]) / w4;
}
static void mdx_quaternion_to_matrix(vec4_t q, vec3_t m[3])
{
m[0][0] = 1 - 2*(q[1]*q[1] + q[2]*q[2]);
m[0][1] = 2*(q[0]*q[1] + q[2]*q[3]);
m[0][2] = 2*(q[0]*q[2] - q[1]*q[3]);
m[1][0] = 2*(q[0]*q[1] - q[2]*q[3]);
m[1][1] = 1 - 2*(q[0]*q[0] + q[2]*q[2]);
m[1][2] = 2*(q[1]*q[2] + q[0]*q[3]);
m[2][0] = 2*(q[0]*q[2] + q[1]*q[3]);
m[2][1] = 2*(q[1]*q[2] - q[0]*q[3]);
m[2][2] = 1 - 2*(q[0]*q[0] + q[1]*q[1]);
}
static void mdx_quaternion_nlerp(const vec4_t q1, const vec4_t q2, vec4_t qout, float backlerp)
{
float fwdlerp = 1.0 - backlerp;
float len;
qout[0] = q1[0]*backlerp + q2[0]*fwdlerp;
qout[1] = q1[1]*backlerp + q2[1]*fwdlerp;
qout[2] = q1[2]*backlerp + q2[2]*fwdlerp;
qout[3] = q1[3]*backlerp + q2[3]*fwdlerp;
len = sqrt(qout[0]*qout[0] + qout[1]*qout[1] + qout[2]*qout[2] + qout[3]*qout[3]);
if (len) {
qout[0] /= len;
qout[1] /= len;
qout[2] /= len;
qout[3] /= len;
} else {
// very rare -- quaternions pointing in opposite direction with backlerp 0.5
// since they're exactly opposite, they're the same rotation :x
Vector4Copy(q1, qout);
}
}
// lerp two rotation matrcies; too lazy to work out how to do it in matrix space.
static void mdx_lerp_matrix(vec3_t m1[3], vec3_t m2[3], vec3_t mout[3], float backlerp)
{
vec4_t q1, q2, q;
mdx_matrix_to_quaternion(m1, q1);
mdx_matrix_to_quaternion(m2, q2);
mdx_quaternion_nlerp(q1, q2, q, backlerp);
mdx_quaternion_to_matrix(q, mout);
}
#endif /* BONE_HITTESTS */
void mdx_gentity_to_grefEntity(gentity_t *ent, grefEntity_t *refent, int lerpTime)
{
bg_character_t *character;
vec3_t legsAngles, torsoAngles, headAngles;
memset(refent, 0, sizeof(*refent));
if (ent->s.eType == ET_PLAYER) {
character = BG_GetCharacter(ent->client->sess.sessionTeam, ent->client->sess.playerType);
} else {
character = BG_GetCharacter(BODY_TEAM(ent), BODY_CLASS(ent));
}
refent->hModel = character->mesh;
VectorCopy(ent->r.currentOrigin, refent->origin);
refent->frame = ent->legsFrame.frame;
refent->frameModel = ent->legsFrame.frameModel;
refent->oldframe = ent->legsFrame.oldFrame;
refent->oldframeModel = ent->legsFrame.oldFrameModel;
if (ent->legsFrame.frameTime == ent->legsFrame.oldFrameTime)
refent->backlerp = 0.0;
else
refent->backlerp = 1.0 - (float)( lerpTime - ent->legsFrame.oldFrameTime ) / ( ent->legsFrame.frameTime - ent->legsFrame.oldFrameTime );
refent->torsoFrame = ent->torsoFrame.frame;
refent->torsoFrameModel = ent->torsoFrame.frameModel;
refent->oldTorsoFrame = ent->torsoFrame.oldFrame;
refent->oldTorsoFrameModel = ent->torsoFrame.oldFrameModel;
if (ent->torsoFrame.frameTime == ent->torsoFrame.oldFrameTime)
refent->torsoBacklerp = 0.0;
else
refent->torsoBacklerp = 1.0 - (float)( lerpTime - ent->torsoFrame.oldFrameTime ) / ( ent->torsoFrame.frameTime - ent->torsoFrame.oldFrameTime );
mdx_PlayerAngles(ent, legsAngles, torsoAngles, headAngles, qfalse);
AnglesToAxis(legsAngles, refent->axis);
AnglesToAxis(torsoAngles, refent->torsoAxis);
AnglesToAxis(headAngles, refent->headAxis);
}
/**************************************************************/
/* tag management */
#ifdef BONE_HITTESTS
static int mdm_tag_lookup(const mdm_t *model, const char tagName[64]);
static interntag_t *interntag_alloc(void)
{
interntag_t *tag;
interntags = realloc(interntags, (interntag_count+1) * sizeof(*interntags));
tag = &interntags[interntag_count++];
tag->tag.name[0] = '\0';
AxisCopy(axisDefault, tag->tag.axis);
VectorClear(tag->tag.offset);
tag->merged = -1;
tag->weight = 0.5;
tag->ishead = qfalse;
return tag;
}
static void interntag_dealloc(void)
{
--interntag_count;
}
static int cachetag_cache(const char tagName[64])
{
int i;
for (i = 0; i < cachetag_count; i++) {
if (!Q_stricmp(cachetag_names[i], tagName))
return i;
}
cachetag_names = realloc(cachetag_names, (cachetag_count+1) * sizeof(*cachetag_names));
Q_strncpyz(&cachetag_names[cachetag_count][0], tagName, sizeof(*cachetag_names));
return (cachetag_count++);
}
static void mdm_cachetag_resize(mdm_t *model, int oldcount)
{
int i;
model->cachetags = realloc(model->cachetags, cachetag_count * sizeof(*model->cachetags));
for (i = oldcount; i < cachetag_count; i++) {
model->cachetags[i] = mdm_tag_lookup(model, cachetag_names[i]);
if (model->cachetags[i] == -1) {
G_Printf(S_COLOR_YELLOW GAME_VERSION " MDX WARNING: Unable to find tag %s in model %s\n", cachetag_names[i], model->path);
model->cachetags[i] = 0; // FIXME: Do proper handling of tags that aren't in models..
}
}
}
static void cachetag_resize(int oldcount)
{
int i;
for (i = 0; i < mdm_model_count; i++)
mdm_cachetag_resize(&mdm_models[i], oldcount);
}
#endif /* BONE_HITTESTS */
/**************************************************************/
/* File I/O */
static int mdx_read_int(const byte *data)
{
return (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
}
static short mdx_read_short(const byte *data)
{
return (data[0]<<0) | (data[1]<<8);
}
static vec_t mdx_read_vec(const byte *data)
{
/* FIXME: depends on size of int */
int int_val = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
return *(float*)&int_val;
}
#ifdef BONE_HITTESTS
static int mdx_bone_lookup(const mdx_t *mdxModel, const char *name)
{
int i;
for (i = 0; i < mdxModel->bone_count; i++) {
if (!strcmp(mdxModel->bones[i].name, name))
return i;
}
return -1;
}
#endif /* BONE_HITTESTS */
static int mdm_tag_lookup(const mdm_t *model, const char tagName[64])
{
int i;
for (i = 0; i < model->tag_count; i++) {
if (!Q_stricmp(model->tags[i].name, tagName))
return i;
}
#ifdef BONE_HITTESTS
for (i = 0; i < interntag_count; i++) {
if (!Q_stricmp(interntags[i].tag.name, tagName))
return (i | TAG_INTERNAL);
}
#endif /* BONE_HITTESTS */
return -1;
}
static void mdx_load(mdx_t *mdxModel, char *mem)
{
char *ptr;
int frame_count, bone_count;
int frame_offset, bone_offset;
struct mdx_hdr *hdr;
struct mdx_bone *bones;
char *frames;
int i, j;
hdr = (mdx_hdr*)mem;
frame_offset = mdx_read_int(hdr->frame_offset);
frames = (char*)(mem + frame_offset);
frame_count = mdx_read_int(hdr->frame_count);
bone_offset = mdx_read_int(hdr->bone_offset);
bones = (mdx_bone*)(mem + bone_offset);
bone_count = mdx_read_int(hdr->bone_count);
mdxModel->torso_parent = mdx_read_int(hdr->torso_parent);
if (bone_count > mdx_bones_max) {
free(mdx_bones);
mdx_bones_max = bone_count;
mdx_bones = (vec3_t*)malloc(mdx_bones_max * sizeof(*mdx_bones));
}
/* Load bones */
mdxModel->bone_count = bone_count;
free(mdxModel->bones);
mdxModel->bones = (bone*)malloc(mdxModel->bone_count * sizeof(struct bone));
for (i = 0; i < mdxModel->bone_count; i++) {
struct bone *bone = &mdxModel->bones[i];
bone->parent_index = mdx_read_int(bones[i].parent_index);
if (bone->parent_index >= i)
G_Error(GAME_VERSION " MDX: parent_index >= index\n");
Q_strncpyz(bone->name, bones[i].name, sizeof(bone->name));
bone->parent_dist = mdx_read_vec(bones[i].parent_dist);
bone->torso_weight = mdx_read_vec(bones[i].torso_weight);
}
/* Load frames */
mdxModel->frame_count = frame_count;
free(mdxModel->frames);
ptr = (char*)malloc(mdxModel->frame_count * (sizeof(struct frame) + mdxModel->bone_count*sizeof(struct frame_bone)));
mdxModel->frames = (frame*)ptr;
ptr += mdxModel->frame_count * sizeof(struct frame);
for (i = 0; i < mdxModel->frame_count; i++) {
struct mdx_frame *frame = (mdx_frame*)(frames + i*(sizeof(struct mdx_frame) + sizeof(struct mdx_frame_bone)*bone_count));
struct mdx_frame_bone *frame_bone = (mdx_frame_bone*)&frame[1];
struct frame_bone *bones;
bones = mdxModel->frames[i].bones = (struct frame_bone*)ptr;
ptr += mdxModel->bone_count * sizeof(struct frame_bone);
mdxModel->frames[i].radius = mdx_read_vec(frame->radius);
mdxModel->frames[i].parent_offset[0] = mdx_read_vec(frame->parent_offset[0]);
mdxModel->frames[i].parent_offset[1] = mdx_read_vec(frame->parent_offset[1]);
mdxModel->frames[i].parent_offset[2] = mdx_read_vec(frame->parent_offset[2]);
for (j = 0; j < mdxModel->bone_count; j++) {
bones[j].angles[0] = mdx_read_short(frame_bone[j].angles[0]);
bones[j].angles[1] = mdx_read_short(frame_bone[j].angles[1]);
bones[j].angles[2] = mdx_read_short(frame_bone[j].angles[2]);
bones[j].offset_angles[0] = mdx_read_short(frame_bone[j].offset_angles[0]);
bones[j].offset_angles[1] = mdx_read_short(frame_bone[j].offset_angles[1]);
}
}
}
static void mdm_load(mdm_t *mdmModel, char *mem)
{
struct mdm_hdr *hdr;
struct mdm_tag *tag;
int i, tags;
hdr = (mdm_hdr*)mem;
tags = mdx_read_int(hdr->tag_count);
tag = (mdm_tag*)(mem + mdx_read_int(hdr->tag_offset));
free(mdmModel->tags);
mdmModel->tag_count = tags;
mdmModel->tags = (struct tag*)malloc(mdmModel->tag_count * sizeof(struct tag));
mdmModel->tag_head = -1; // neck
mdmModel->tag_armleft = -1; // elbow-left
mdmModel->tag_armright = -1; // elbow-right
mdmModel->tag_weapon2 = -1; // hand-left
mdmModel->tag_weapon = -1; // hand-right
mdmModel->tag_back = -1; // upper-backside
mdmModel->tag_chest = -1; // upper-frontside
mdmModel->tag_torso = -1; // pelvis
mdmModel->tag_legleft = -1; // knee-left
mdmModel->tag_legright = -1; // knee-right
mdmModel->tag_footleft = -1; // ankle-left
mdmModel->tag_footright = -1; // ankle-right
#ifdef BONE_HITTESTS
mdmModel->cachetags = NULL;
#endif /* BONE_HITTESTS */
for (i = 0; i < tags; i++) {
int n, p;
Q_strncpyz(mdmModel->tags[i].name, tag->name, sizeof(mdmModel->tags[i].name));
// lookup
if (!Q_stricmp(tag->name, "tag_head"))
mdmModel->tag_head = i;
else if (!Q_stricmp(tag->name, "tag_armleft"))
mdmModel->tag_armleft = i;
else if (!Q_stricmp(tag->name, "tag_armright"))
mdmModel->tag_armright = i;
else if (!Q_stricmp(tag->name, "tag_weapon2"))
mdmModel->tag_weapon2 = i;
else if (!Q_stricmp(tag->name, "tag_weapon"))
mdmModel->tag_weapon = i;
else if (!Q_stricmp(tag->name, "tag_back"))
mdmModel->tag_back = i;
else if (!Q_stricmp(tag->name, "tag_chest"))
mdmModel->tag_chest = i;
else if (!Q_stricmp(tag->name, "tag_torso"))
mdmModel->tag_torso = i;
else if (!Q_stricmp(tag->name, "tag_legleft"))
mdmModel->tag_legleft = i;
else if (!Q_stricmp(tag->name, "tag_legright"))
mdmModel->tag_legright = i;
else if (!Q_stricmp(tag->name, "tag_footleft"))
mdmModel->tag_footleft = i;
else if (!Q_stricmp(tag->name, "tag_footright"))
mdmModel->tag_footright = i;
for (n = 0; n < 3; n++)
for (p = 0; p < 3; p++)
mdmModel->tags[i].axis[n][p] = mdx_read_vec(tag->axis[n][p]);
for (p = 0; p < 3; p++)
mdmModel->tags[i].offset[p] = mdx_read_vec(tag->offset[p]);
mdmModel->tags[i].attach_bone = mdx_read_int(tag->attach_bone);
tag = (mdm_tag*)(((char*)tag) + mdx_read_int(tag->tag_size));
}
#ifdef BONE_HITTESTS
mdm_cachetag_resize(mdmModel, 0);
#endif /* BONE_HITTESTS */
}
#ifdef BONE_HITTESTS
static qboolean hit_parse_tag(hit_t *hitModel, mdx_t *mdx, char **ptr)
{
char *token;
interntag_t *firsttag, *tag;
int bone;
firsttag = tag = interntag_alloc();
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected new bone/tag name\n"); goto err; }
Q_strncpyz(tag->tag.name, token, sizeof(tag->tag.name));
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected bone/tag name\n"); goto err; }
bone = mdx_bone_lookup(mdx, token);
if (bone == -1)
bone = cachetag_cache(token) | INTERNTAG_TAG;
tag->tag.attach_bone = bone;
while (ptr) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0])
break;
if (!Q_stricmp(token, "weight")) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected weight\n"); goto err; }
firsttag->weight = strtod(token, NULL);
} else if (!Q_stricmp(token, "offset")) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected X offset\n"); goto err; }
tag->tag.offset[0] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected Y offset\n"); goto err; }
tag->tag.offset[1] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected Z offset\n"); goto err; }
tag->tag.offset[2] = strtod(token, NULL);
} else if (!Q_stricmp(token, "axis")) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected forward vector[X]\n"); goto err; }
tag->tag.axis[0][0] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected forward vector[Y]\n"); goto err; }
tag->tag.axis[0][1] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected forward vector[Z]\n"); goto err; }
tag->tag.axis[0][2] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected left vector[X]\n"); goto err; }
tag->tag.axis[1][0] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected left vector[Y]\n"); goto err; }
tag->tag.axis[1][1] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected left vector[Z]\n"); goto err; }
tag->tag.axis[1][2] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected up vector[X]\n"); goto err; }
tag->tag.axis[2][0] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected up vector[Y]\n"); goto err; }
tag->tag.axis[2][1] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected up vector[Z]\n"); goto err; }
tag->tag.axis[2][2] = strtod(token, NULL);
} else if (!Q_stricmp(token, "headangles")) {
tag->ishead = qtrue;
} else {
if (tag != firsttag) { COM_ParseError("Too many bones/tags for internal tag\n"); goto err; }
bone = mdx_bone_lookup(mdx, token);
if (bone == -1)
bone = cachetag_cache(token) | INTERNTAG_TAG;
tag = interntag_alloc();
firsttag = tag - 1; /* interntag_alloc reallocs :x */
tag->tag.attach_bone = bone;
Q_strncpyz(tag->tag.name, va("_%s_m", firsttag->tag.name), sizeof(tag->tag.name));
firsttag->merged = cachetag_cache(tag->tag.name);
}
}
return qtrue;
err:
if (firsttag != tag) interntag_dealloc();
interntag_dealloc();
return qfalse;
}
static qboolean hit_parse_hit(hit_t *hitModel, mdx_t *mdx, char **ptr)
{
char *token;
struct hit_area *hit;
int tagidx;
int tag;
hitModel->hits = realloc(hitModel->hits, (hitModel->hit_count + 1) * sizeof(*hitModel->hits));
hit = &hitModel->hits[hitModel->hit_count++];
for (tagidx = 0; tagidx < 2; tagidx++) {
hit->hit_type = -1;
hit->impactpoint = NUM_ANIM_COND_IMPACTPOINT;
hit->tag[tagidx] = -1;
VectorSet(hit->scale[tagidx], 1.0, 1.0, 1.0);
AxisCopy(axisDefault, hit->axis);
hit->ishead[tagidx] = qfalse;
}
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected hit type\n"); goto err; }
for (hit->hit_type = 0; hit->hit_type < MDX_HIT_TYPE_MAX; hit->hit_type++) {
if (!Q_stricmp(mdx_hit_type_names[hit->hit_type], token))
break;
}
if (hit->hit_type >= MDX_HIT_TYPE_MAX) { COM_ParseError("Invalid hit type: %s\n", token); goto err; }
tagidx = -1;
while (ptr) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0])
break;
if (tagidx > -1) {
if (!Q_stricmp(token, "scale")) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected X scale\n"); goto err; }
hit->scale[tagidx][0] *= strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected Y scale\n"); goto err; }
hit->scale[tagidx][1] *= strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected Z scale\n"); goto err; }
hit->scale[tagidx][2] *= strtod(token, NULL);
continue;
} else if (!Q_stricmp(token, "radius")) {
float radius;
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected radius\n"); goto err; }
radius = strtod(token, NULL);
hit->scale[tagidx][0] *= radius;
hit->scale[tagidx][1] *= radius;
hit->scale[tagidx][2] *= radius;
continue;
} else if (!Q_stricmp(token, "headangles")) {
hit->ishead[tagidx] = qtrue;
continue;
}
}
if (!Q_stricmp(token, "axis")) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected forward vector [X]\n"); goto err; }
hit->axis[0][0] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected forward vector [Y]\n"); goto err; }
hit->axis[0][1] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected forward vector [Z]\n"); goto err; }
hit->axis[0][2] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected left vector [X]\n"); goto err; }
hit->axis[1][0] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected left vector [Y]\n"); goto err; }
hit->axis[1][1] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected left vector [Z]\n"); goto err; }
hit->axis[1][2] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected up vector [X]\n"); goto err; }
hit->axis[2][0] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected up vector [Y]\n"); goto err; }
hit->axis[2][1] = strtod(token, NULL);
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected up vector [Z]\n"); goto err; }
hit->axis[2][2] = strtod(token, NULL);
continue;
} else if (!Q_stricmp(token, "impactpoint") || !Q_stricmp(token, "impact")) {
token = COM_ParseExt(ptr, qfalse);
if (!token[0]) { COM_ParseError("Expected impact point name/number\n"); goto err; }
if (!Q_stricmp(token, "head"))
hit->impactpoint = IMPACTPOINT_HEAD;
else if (!Q_stricmp(token, "chest"))
hit->impactpoint = IMPACTPOINT_CHEST;
else if (!Q_stricmp(token, "gut"))
hit->impactpoint = IMPACTPOINT_GUT;
else if (!Q_stricmp(token, "groin"))
hit->impactpoint = IMPACTPOINT_GROIN;
else if (!Q_stricmp(token, "shoulder_right"))
hit->impactpoint = IMPACTPOINT_SHOULDER_RIGHT;
else if (!Q_stricmp(token, "shoulder_left"))
hit->impactpoint = IMPACTPOINT_SHOULDER_LEFT;
else if (!Q_stricmp(token, "knee_right"))
hit->impactpoint = IMPACTPOINT_KNEE_RIGHT;
else if (!Q_stricmp(token, "knee_left"))
hit->impactpoint = IMPACTPOINT_KNEE_LEFT;
else {
hit->impactpoint = atoi(token);
if (hit->impactpoint < 0 || hit->impactpoint > NUM_ANIM_COND_IMPACTPOINT)
hit->impactpoint = NUM_ANIM_COND_IMPACTPOINT;
}
continue;
} else if (!Q_stricmp(token, "box")) {
hit->isbox = qtrue;
continue;
}
tag = cachetag_cache(token);
if (tag == -1) { COM_ParseError("Unexpected token: %s\n", token); goto err; }
if (++tagidx >= 2) { COM_ParseError("Too many tags for hit\n"); goto err; }
hit->tag[tagidx] = tag;
}
if (tagidx == -1) { COM_ParseError("Expected bone/tag name\n"); goto err; }
return qtrue;
err:
hitModel->hit_count--;
return qfalse;
}
/* Must be called _AFTER_ animModelInfo has valid animations[0] */
/* Assumes all animations have mdxFiles with the same bones, which
I *hope* is a pretty safe assumption. */
static qboolean hit_load(hit_t *hitModel, const animModelInfo_t *animModelInfo, const char *filename)
{
mdx_t *mdx;
char *ptr, *token;
char *pScript;
int len;
fileHandle_t fh;
int cachetag_oldcount;
cachetag_oldcount = cachetag_count;
mdx = &mdx_models[animModelInfo->animations[0]->mdxFile];
hitModel->animModelInfo = animModelInfo;
len = trap_FS_FOpenFile(filename, &fh, FS_READ);
if (len <= 0) {
#if DEBUG /* zinx - don't show this normally, for now.. */
G_Printf(S_COLOR_YELLOW GAME_VERSION " MDX WARNING: Missing %s (only needed for per-bone hits)\n", filename);
#endif
return qfalse;
}
ptr = pScript = malloc(len + 1);
trap_FS_Read(pScript, len, fh);
pScript[len] = '\0';
trap_FS_FCloseFile(fh);
free(hitModel->hits);
hitModel->hits = NULL;
COM_SetCurrentParseLine(1);
while (ptr) {
token = COM_Parse(&ptr);
if (!token[0])
continue;
if (!Q_stricmp(token, "TAG")) {
if (!hit_parse_tag(hitModel, mdx, &ptr))
goto err;
continue;
}
if (!Q_stricmp(token, "HIT")) {
if (!hit_parse_hit(hitModel, mdx, &ptr))
goto err;
continue;
}
COM_ParseError("Unexpected token: %s\n", token);
goto err;
}
cachetag_resize(cachetag_oldcount);
free(pScript);
return qtrue;
err:
cachetag_resize(cachetag_oldcount);
free(pScript);
free(hitModel->hits);
hitModel->hit_count = 0;
hitModel->hits = NULL;
return qfalse;
}
#endif /* BONE_HITTESTS */
qhandle_t trap_R_RegisterModel(const char *filename)
{
fileHandle_t fh;
char *mem;
int ret;
int i;
int len;
for (i = 0; i < mdm_model_count; i++) {
if (!strcmp(mdm_models[i].path, filename))
return INDEXTOQHANDLE(i);
}
for (i = 0; i < mdx_model_count; i++) {
if (!strcmp(mdx_models[i].path, filename))
return INDEXTOQHANDLE(i);
}
len = trap_FS_FOpenFile(filename, &fh, FS_READ);
if (len <= 0)
G_Error(GAME_VERSION " MDX: File not found: %s\n", filename);
mem = (char*)malloc(len);
trap_FS_Read(mem, len, fh);
trap_FS_FCloseFile(fh);
if (!memcmp(mem, "MDXW", 4)) {
ret = mdx_model_count++;
mdx_models = (mdx_t*)realloc(mdx_models, mdx_model_count * sizeof(*mdx_models));
memset(&mdx_models[ret], 0, sizeof(mdx_models[ret]));
Q_strncpyz(mdx_models[ret].path, filename, sizeof(mdx_models[ret].path));
mdx_load(&mdx_models[ret], mem);
} else if (!memcmp(mem, "MDMW", 4)) {
ret = mdm_model_count++;
mdm_models = (mdm_t*)realloc(mdm_models, mdm_model_count * sizeof(*mdm_models));
memset(&mdm_models[ret], 0, sizeof(mdm_models[ret]));
Q_strncpyz(mdm_models[ret].path, filename, sizeof(mdm_models[ret].path));
mdm_load(&mdm_models[ret], mem);
} else {
ret = -1;
G_Error(GAME_VERSION " MDX: Not a model: %s\n", filename);
}
free(mem);
return INDEXTOQHANDLE(ret);
}
#ifdef BONE_HITTESTS
qhandle_t mdx_RegisterHits(animModelInfo_t *animModelInfo, const char *filename)
{
int i;
for (i = 0; i < hit_count; i++) {
if (hits[i].animModelInfo == animModelInfo)
return i;
}
i = hit_count++;
hits = realloc(hits, hit_count * sizeof(*hits));
memset(&hits[i], 0, sizeof(hits[i]));
if (hit_load(&hits[i], animModelInfo, filename) < 0) {
hit_count--;
return 0;
} else {
return INDEXTOQHANDLE(i);
}
}
#endif /* BONE_HITTESTS */
/**************************************************************/
/* Bone Calculations */
static void mdx_calculate_bone(
vec3_t dest,
const struct bone *bone,
const struct frame_bone *frameBone
) {
vec3_t tmp;
vec3_t axis[3];
tmp[1] = tmp[2] = 0;
tmp[0] = bone->parent_dist;
/* frame bone rotation */
AnglesToAxisBroken(frameBone->offset_angles, axis);
PointRotate(tmp, axis, dest);
}
static void mdx_calculate_bone_lerp(
/*const*/ grefEntity_t *refent,
mdx_t *frameModel,
mdx_t *oldFrameModel,
mdx_t *torsoFrameModel,
mdx_t *oldTorsoFrameModel,
int i,
qboolean recursive
)
{
mdx_t *oldBoneFrameModel, *boneFrameModel;
int oldFrame, frame;
float backlerp;
struct bone *oldBone, *bone;
struct frame_bone *oldFrameBone, *frameBone;
vec3_t point, oldpoint;
if ( frameModel->bones[i].torso_weight ) {
boneFrameModel = torsoFrameModel;
oldBoneFrameModel = oldTorsoFrameModel;
frame = refent->torsoFrame;
oldFrame = refent->oldTorsoFrame;
backlerp = refent->torsoBacklerp;
} else {
boneFrameModel = frameModel;
oldBoneFrameModel = oldFrameModel;
frame = refent->frame;
oldFrame = refent->oldframe;
backlerp = refent->backlerp;
}
bone = &boneFrameModel->bones[i];
oldBone = &oldBoneFrameModel->bones[i];
if ( i == 0 ) {
VectorMA( vec3_origin, 1.0 - backlerp, boneFrameModel->frames[frame].parent_offset, mdx_bones[i] );
VectorMA( mdx_bones[i], backlerp, oldBoneFrameModel->frames[oldFrame].parent_offset, mdx_bones[i] );
return; // It's offset funny if we do the calculations for the top-most bone
} else {
if (recursive) {
mdx_calculate_bone_lerp(
refent,
frameModel, oldFrameModel,
torsoFrameModel, oldTorsoFrameModel,
bone->parent_index,
qtrue
);
}
}
frameBone = &boneFrameModel->frames[frame].bones[i];
oldFrameBone = &oldBoneFrameModel->frames[oldFrame].bones[i];
mdx_calculate_bone(oldpoint, oldBone, oldFrameBone);
mdx_calculate_bone(point, bone, frameBone);
/* This frame's position */
VectorAdd(mdx_bones[bone->parent_index], point, mdx_bones[i]);
/* Lerp in old frame */
VectorSubtract(oldpoint, point, oldpoint);
VectorMA(mdx_bones[i], backlerp, oldpoint, mdx_bones[i]);
}
#ifdef BONE_HITTESTS
/* Calculates all bones */
static void mdx_calculate_bones(/*const*/ grefEntity_t *refent)
{
int i;
mdx_t *frameModel = &mdx_models[QHANDLETOINDEX(refent->frameModel)];
mdx_t *oldFrameModel = &mdx_models[QHANDLETOINDEX_SAFE(refent->oldframeModel, refent->frameModel)];
mdx_t *torsoFrameModel = &mdx_models[QHANDLETOINDEX(refent->torsoFrameModel)];
mdx_t *oldTorsoFrameModel = &mdx_models[QHANDLETOINDEX_SAFE(refent->oldTorsoFrameModel, refent->torsoFrameModel)];
#ifdef DEBUG
if (frameModel->bone_count != torsoFrameModel->bone_count
|| frameModel->bone_count != oldFrameModel->bone_count
|| frameModel->bone_count != oldTorsoFrameModel->bone_count) {
G_Error(GAME_VERSION " MDX: Frame count mismatch\n");
}
#endif
for (i = 0; i < frameModel->bone_count; i++) {
mdx_calculate_bone_lerp(
refent,
frameModel, oldFrameModel,
torsoFrameModel, oldTorsoFrameModel,
i,
qfalse
);
}
}
#endif /* BONE_HITTESTS */
void mdx_calculate_bones_single(/*const*/ grefEntity_t *refent, int i)
{
mdx_t *frameModel = &mdx_models[QHANDLETOINDEX(refent->frameModel)];
mdx_t *oldFrameModel = &mdx_models[QHANDLETOINDEX_SAFE(refent->oldframeModel, refent->frameModel)];
mdx_t *torsoFrameModel = &mdx_models[QHANDLETOINDEX(refent->torsoFrameModel)];
mdx_t *oldTorsoFrameModel = &mdx_models[QHANDLETOINDEX_SAFE(refent->oldTorsoFrameModel, refent->torsoFrameModel)];
#ifdef DEBUG
if (frameModel->bone_count != torsoFrameModel->bone_count
|| frameModel->bone_count != oldFrameModel->bone_count
|| frameModel->bone_count != oldTorsoFrameModel->bone_count) {
G_Error(GAME_VERSION " MDX: Frame count mismatch\n");
}
#endif
mdx_calculate_bone_lerp(
refent,
frameModel, oldFrameModel,
torsoFrameModel, oldTorsoFrameModel,
i,
qtrue
);
}
static void mdx_bone_orientation(/*const*/ grefEntity_t *refent, int idx, vec3_t origin, vec3_t axis[3])
{
mdx_t *frameModel = &mdx_models[QHANDLETOINDEX(refent->frameModel)];
mdx_t *oldFrameModel = &mdx_models[QHANDLETOINDEX_SAFE(refent->oldframeModel, refent->frameModel)];
mdx_t *torsoFrameModel = &mdx_models[QHANDLETOINDEX(refent->torsoFrameModel)];
mdx_t *oldTorsoFrameModel = &mdx_models[QHANDLETOINDEX_SAFE(refent->oldTorsoFrameModel, refent->torsoFrameModel)];
mdx_t *oldBoneFrameModel, *boneFrameModel;
struct bone *oldBone, *bone;
struct frame_bone *oldFrameBone, *frameBone;
int oldFrame, frame;
float backlerp;
vec3_t realangles, angles;
vec3_t axis1[3], tmpaxis[3];
if ( frameModel->bones[idx].torso_weight ) {
boneFrameModel = torsoFrameModel;
oldBoneFrameModel = oldTorsoFrameModel;
frame = refent->torsoFrame;
oldFrame = refent->oldTorsoFrame;
backlerp = refent->torsoBacklerp;
} else {
boneFrameModel = frameModel;
oldBoneFrameModel = oldFrameModel;
frame = refent->frame;
oldFrame = refent->oldframe;
backlerp = refent->backlerp;
}
bone = &boneFrameModel->bones[idx];
oldBone = &oldBoneFrameModel->bones[idx];
frameBone = &boneFrameModel->frames[frame].bones[idx];
oldFrameBone = &oldBoneFrameModel->frames[oldFrame].bones[idx];
/* Calculate origin */
VectorCopy( mdx_bones[idx], origin );
/* Apply torso rotation to origin */
// FIXME: This probably isn't entirely correct; my test models fail,
// in any case. It seems to produce the proper results with a real
// player model, though.
if (bone->torso_weight) {
vec3_t tmp, torso_origin;
/* Rotate around torso_parent */
VectorSubtract(origin, mdx_bones[boneFrameModel->torso_parent], tmp);
PointRotate(tmp, refent->torsoAxis, torso_origin);
VectorAdd(torso_origin, mdx_bones[boneFrameModel->torso_parent], torso_origin);
/* Lerp torso-rotated point with non-rotated */
VectorSubtract(torso_origin, origin, torso_origin);
VectorMA(origin, bone->torso_weight, torso_origin, origin);
}
/* Calculate angles */
/* bone angles */
realangles[0] = SHORT2ANGLE(oldFrameBone->angles[0]);
realangles[1] = SHORT2ANGLE(oldFrameBone->angles[1]);
realangles[2] = SHORT2ANGLE(oldFrameBone->angles[2]);
VectorScale(realangles, backlerp, angles);
realangles[0] = SHORT2ANGLE(frameBone->angles[0]);
realangles[1] = SHORT2ANGLE(frameBone->angles[1]);
realangles[2] = SHORT2ANGLE(frameBone->angles[2]);
VectorMA(angles, (1.0 - backlerp), realangles, angles);
AnglesToAxis(angles, tmpaxis);
// FIXME: Why is this transpose needed?
MatrixTranspose(tmpaxis, axis1);
/* torso angles */
// FIXME: This probably isn't how the engine decides.
MatrixWeight(refent->torsoAxis, bone->torso_weight, tmpaxis);
MatrixMultiply(axis1, tmpaxis, axis);
}
#ifdef BONE_HITTESTS
static void mdx_tag_orientation(/*const*/ grefEntity_t *refent, int idx, vec3_t origin, vec3_t axis[3], qboolean withhead, int recursion)
{
int i;
vec3_t tmpaxis[3];
vec3_t offset;
mdm_t *model;
interntag_t *itag;
struct tag *tag;
model = &mdm_models[QHANDLETOINDEX(refent->hModel)];
i = model->cachetags[idx];
if (i & TAG_INTERNAL) {
itag = &interntags[i & TAG_INTERNAL_MASK];
tag = &itag->tag;
} else {
itag = NULL;
tag = &model->tags[i];
}
if (tag->attach_bone & INTERNTAG_TAG) {
mdx_tag_orientation(refent, tag->attach_bone & INTERNTAG_TAG_MASK, origin, tmpaxis, qfalse, recursion+1);
} else {
mdx_bone_orientation(refent, tag->attach_bone, origin, tmpaxis);
}
/* Apply head rotation, if this is a head tag */
if (itag && itag->ishead) {
vec3_t tmp[3];
AxisCopy(tmpaxis, tmp);
MatrixMultiply(refent->headAxis, tmp, tmpaxis);
}
/* Tag offset */
PointRotate(tag->offset, tmpaxis, offset);
VectorAdd(origin, offset, origin);
/* Tag axis */
MatrixMultiply(tag->axis, tmpaxis, axis);
if (!recursion) {
VectorCopy(origin, offset);
VectorCopy(refent->origin, origin);
for (i = 0; i < 3; i++)
VectorMA(origin, offset[i], refent->axis[i], origin);
if (withhead) {
MatrixMultiply(refent->headAxis, axis, tmpaxis);
MatrixMultiply(tmpaxis, refent->axis, axis);
} else {
MatrixMultiply(axis, refent->axis, tmpaxis);
AxisCopy(tmpaxis, axis);
}
}
if (itag && itag->merged != -1) {
vec3_t origin2;
vec3_t axis2[3];
mdx_tag_orientation(refent, itag->merged, origin2, axis2, withhead, 0);
/* weighted origin */
VectorSubtract(origin, origin2, origin);
VectorMA(origin2, itag->weight, origin, origin);
/* weighted axis */
mdx_lerp_matrix(axis, axis2, tmpaxis, itag->weight);
AxisCopy(tmpaxis, axis);
}
}
#endif /* BONE_HITTESTS */
/* */
int trap_R_LerpTagNumber( orientation_t *tag, /*const*/ grefEntity_t *refent, int tagNum )
{
mdm_t *model;
vec3_t axis[3];
vec3_t offset;
mdx_t *mdx;
int bone;
model = &mdm_models[QHANDLETOINDEX(refent->hModel)];
mdx = &mdx_models[QHANDLETOINDEX(refent->frameModel)];
if (tagNum < 0 || tagNum >= model->tag_count)
return -1;
bone = model->tags[tagNum].attach_bone;
mdx_calculate_bones_single(refent, bone);
mdx_bone_orientation(refent, bone, tag->origin, axis);
PointRotate(model->tags[tagNum].offset, axis, offset);
VectorAdd(tag->origin, offset, tag->origin);
MatrixMultiply(model->tags[tagNum].axis, axis, tag->axis);
return 0;
}
int trap_R_LookupTag(/*const*/ grefEntity_t *refent, const char *tagName)
{
mdm_t *model;
model = &mdm_models[QHANDLETOINDEX(refent->hModel)];
return mdm_tag_lookup(model, tagName);
}
int trap_R_LerpTag( orientation_t *tag, /*const*/ grefEntity_t *refent, const char *tagName, int startIndex )
{
int tagNum;
if (startIndex) {
G_Error(GAME_VERSION " MDX: Huh? What to do, what to do... (non-zero startIndex)\n");
}
tagNum = trap_R_LookupTag(refent, tagName);
return trap_R_LerpTagNumber(tag, refent, tagNum);
}
/**************************************************************/
/* Animations/Player stuff */
#define SWING_RIGHT 1
#define SWING_LEFT 2
/*
==================
mdx_SwingAngles, adapted from CG_SwingAngles
==================
*/
#define SERVER_FRAMETIME (1000/20)
static void mdx_SwingAngles( float destination, float swingTolerance, float clampTolerance,
float speed, float *angle, qboolean *swinging ) {
float swing;
float move;
float scale;
if ( !*swinging ) {
// see if a swing should be started
float centerAngle;
// zinx - use predictable center so server can match cgame easier
centerAngle = rint(*angle / swingTolerance) * swingTolerance;
swing = AngleSubtract( destination, *angle );
if ( swing >= swingTolerance || swing < -swingTolerance ) {
*swinging = qtrue;
}
}
if ( !*swinging ) {
return;
}
// modify the speed depending on the delta
// so it doesn't seem so linear
swing = AngleSubtract( destination, *angle );
scale = fabs( swing );
scale *= 0.05;
if (scale < 0.5)
scale = 0.5;
// swing towards the destination angle
if ( swing >= 0 ) {
move = SERVER_FRAMETIME * scale * speed;
if ( move >= swing ) {
move = swing;
*swinging = qfalse;
} else {
*swinging = (qboolean)SWING_LEFT; // left
}
*angle = AngleMod( *angle + move );
} else if ( swing < 0 ) {
move = SERVER_FRAMETIME * scale * -speed;
if ( move <= swing ) {
move = swing;
*swinging = qfalse;
} else {
*swinging = (qboolean)SWING_RIGHT; // right
}
*angle = AngleMod( *angle + move );
}
// clamp to no more than tolerance
swing = AngleSubtract( destination, *angle );
if ( swing > clampTolerance ) {
*angle = AngleMod( destination - (clampTolerance - 1) );
} else if ( swing < -clampTolerance ) {
*angle = AngleMod( destination + (clampTolerance - 1) );
}
}
/*
===============
mdx_PlayerAngles, adapted from CG_PlayerAngles
===============
*/
#define SWINGSPEED 0.1 /* Cheat protected, so we don't care if it matches. */
void mdx_PlayerAngles( gentity_t *ent, vec3_t legsAngles, vec3_t torsoAngles, vec3_t headAngles, qboolean doswing )
{
float dest;
vec3_t velocity;
float speed;
float clampTolerance;
float movementDir;
bg_character_t *character;
int legsSet;
gclient_t *client = ent->client;
character = BG_GetCharacterForPlayerstate( &client->ps );
if ( !character )
return;
legsSet = client->ps.legsAnim & ~ANIM_TOGGLEBIT;
if (client->ps.movementDir > 128)
movementDir = (float)client->ps.movementDir - 256;
else
movementDir = client->ps.movementDir;
VectorCopy(client->ps.viewangles, headAngles);
headAngles[YAW] = AngleMod( headAngles[YAW] );
VectorClear( legsAngles );
VectorClear( torsoAngles );
// --------- yaw -------------
// allow yaw to drift a bit, unless these conditions don't allow them
// rain - use clientNum instead of number, we get called for corpses.
if( !(BG_GetConditionBitFlag( ent->s.clientNum, ANIM_COND_MOVETYPE, ANIM_MT_IDLE ) ||
BG_GetConditionBitFlag( ent->s.clientNum, ANIM_COND_MOVETYPE, ANIM_MT_IDLECR ) )/*
|| (BG_GetConditionValue( cent->currentState.clientNum, ANIM_COND_MOVETYPE, qfalse ) & ((1<<ANIM_MT_STRAFELEFT) | (1<<ANIM_MT_STRAFERIGHT)) )*/) {
// always point all in the same direction
ent->torsoFrame.yawing = qtrue; // always center
ent->torsoFrame.pitching = qtrue; // always center
ent->legsFrame.yawing = qtrue; // always center
// if firing, make sure torso and head are always aligned
// rain - clientNum instead of number
} else if( BG_GetConditionValue( ent->s.clientNum, ANIM_COND_FIRING, qtrue ) ) {
ent->torsoFrame.yawing = qtrue; // always center
ent->torsoFrame.pitching = qtrue; // always center
}
// adjust legs for movement dir
if( client->ps.eFlags & (EF_DEAD | EF_MOUNTEDTANK | EF_PLAYDEAD) ) {
// don't let dead bodies twitch
legsAngles[YAW] = headAngles[YAW];
torsoAngles[YAW] = headAngles[YAW];
} else {
legsAngles[YAW] = headAngles[YAW] + movementDir;
if( !(client->ps.eFlags & EF_FIRING) ) {
torsoAngles[YAW] = headAngles[YAW] + 0.35 * movementDir;
clampTolerance = 90;
} else { // must be firing
torsoAngles[YAW] = headAngles[YAW]; // always face firing direction
//if (fabs(ent->s.angles2[YAW]) > 30)
// legsAngles[YAW] = headAngles[YAW];
clampTolerance = 60;
}
// torso
if (doswing) mdx_SwingAngles( torsoAngles[YAW], 25, clampTolerance, SWINGSPEED, &ent->torsoFrame.yawAngle, &ent->torsoFrame.yawing );
// if the legs are yawing (facing heading direction), allow them to rotate a bit, so we don't keep calling
// the legs_turn animation while an AI is firing, and therefore his angles will be randomizing according to their accuracy
clampTolerance = 150;
if( BG_GetConditionBitFlag( ent->s.clientNum, ANIM_COND_MOVETYPE, ANIM_MT_IDLE) ) {
if (doswing) {
ent->legsFrame.yawing = qfalse; // set it if they really need to swing
mdx_SwingAngles( legsAngles[YAW], 20, clampTolerance, 0.5*SWINGSPEED, &ent->legsFrame.yawAngle, &ent->legsFrame.yawing );
}
} else if( strstr( BG_GetAnimString( character->animModelInfo, legsSet ), "strafe" ) ) {
// FIXME: what is this strstr hack??
// if ( BG_GetConditionValue( ci->clientNum, ANIM_COND_MOVETYPE, qfalse ) & ((1<<ANIM_MT_STRAFERIGHT)|(1<<ANIM_MT_STRAFELEFT)) ) {
// rain - this nasty strstr hack is to apply this only to
// strafe animations, because strafing with some weapons uses
// a non-strafe animation (!@#%), e.g. strafing with the
// mobile mg42
if (doswing) {
ent->legsFrame.yawing = qfalse; // set it if they really need to swing
legsAngles[YAW] = headAngles[YAW];
mdx_SwingAngles( legsAngles[YAW], 0, clampTolerance, SWINGSPEED, &ent->legsFrame.yawAngle, &ent->legsFrame.yawing );
}
} else if(ent->legsFrame.yawing) {
if (doswing) mdx_SwingAngles( legsAngles[YAW], 0, clampTolerance, SWINGSPEED, &ent->legsFrame.yawAngle, &ent->legsFrame.yawing );
} else {
if (doswing) mdx_SwingAngles( legsAngles[YAW], 40, clampTolerance, SWINGSPEED, &ent->legsFrame.yawAngle, &ent->legsFrame.yawing );
}
torsoAngles[YAW] = ent->torsoFrame.yawAngle;
legsAngles[YAW] = ent->legsFrame.yawAngle;
}
// --------- pitch -------------
// only show a fraction of the pitch angle in the torso
if( headAngles[PITCH] > 180 ) {
dest = (-360 + headAngles[PITCH]) * 0.75;
} else {
dest = headAngles[PITCH] * 0.75;
}
// rain - zero out the head pitch when dead
if (client->ps.eFlags & (EF_DEAD | EF_PLAYDEAD)) {
headAngles[PITCH] = 0;
}
//if (doswing) mdx_SwingAngles( dest, 15, 30, 0.1, &ent->torsoFrame.pitchAngle, &ent->torsoFrame.pitching );
//torsoAngles[PITCH] = ent->torsoFrame.pitchAngle;
if( client->ps.eFlags & EF_PRONE ) {
torsoAngles[PITCH] = legsAngles[PITCH] - 3;
} else if (client->ps.eFlags & (EF_DEAD | EF_PLAYDEAD)) {
// rain - zero out the torso pitch when dead
torsoAngles[PITCH] = 0;
} else {
if (doswing) mdx_SwingAngles( dest, 15, 30, 0.1, &ent->torsoFrame.pitchAngle, &ent->torsoFrame.pitching );
torsoAngles[PITCH] = ent->torsoFrame.pitchAngle;
}
// --------- roll -------------
// lean towards the direction of travel
VectorCopy( client->ps.velocity, velocity );
speed = VectorNormalize( velocity );
if( speed ) {
vec3_t axis[3];
float side;
speed *= 0.05;
AnglesToAxis( legsAngles, axis );
side = speed * DotProduct( velocity, axis[1] );
legsAngles[ROLL] -= side;
side = speed * DotProduct( velocity, axis[0] );
legsAngles[PITCH] += side;
}
// FIXME: Do pain twitch?
// pull the angles back out of the hierarchial chain
AnglesSubtract( headAngles, torsoAngles, headAngles );
AnglesSubtract( torsoAngles, legsAngles, torsoAngles );
}
/* Adapted from CG_RunLerpFrameRate */
/* I'd rather not duplicate this much code.... */
#define CROUCHING(anim) ( (anim) && ((anim)->movetype & ((1<<ANIM_MT_IDLECR)|(1<<ANIM_MT_WALKCR)|(1<<ANIM_MT_WALKCRBK))) )
static void mdx_SetLerpFrame(gentity_t *ent, glerpFrame_t *lf, int newAnimation, bg_character_t *character)
{
animation_t *oldAnim;
animation_t *anim;
int transitionMin = -1;
qboolean firstAnim = qfalse;
if ( !lf->animation ) {
firstAnim = qtrue;
}
oldAnim = lf->animation;
lf->animationNumber = newAnimation;
anim = BG_GetAnimationForIndex(character->animModelInfo, lf->animationNumber & ~ANIM_TOGGLEBIT);
lf->animation = anim;
lf->animationTime = lf->frameTime + anim->initialLerp;
if ( !(anim->flags & ANIMFL_FIRINGANIM) || (lf != &ent->torsoFrame) ) {
if ( (lf == &ent->legsFrame) && (CROUCHING(oldAnim) != CROUCHING(anim)) ) {
if ( anim->moveSpeed || ( anim->movetype & ((1<<ANIM_MT_TURNLEFT)|(1<<ANIM_MT_TURNRIGHT)) ) ) // if unknown movetype, go there faster
transitionMin = lf->frameTime + 200; // slowly raise/drop
else
transitionMin = lf->frameTime + 350; // slowly raise/drop
} else if ( anim->moveSpeed ) {
transitionMin = lf->frameTime + 120; // always do some lerping (?)
} else // not moving, so take your time
transitionMin = lf->frameTime + 170; // always do some lerping (?)
if ( oldAnim && oldAnim->animBlend ) { //transitionMin < lf->frameTime + oldanim->animBlend) {
transitionMin = lf->frameTime + oldAnim->animBlend;
lf->animationTime = transitionMin;
} else {
// slow down transitions according to speed
if( anim->moveSpeed && lf->animSpeedScale < 1.0 )
lf->animationTime += anim->initialLerp;
if( lf->animationTime < transitionMin )
lf->animationTime = transitionMin;
}
}
// if first anim, go immediately
if ( firstAnim ) {
lf->frameTime = level.time - 1;
lf->animationTime = level.time - 1;
lf->frame = anim->firstFrame;
lf->frameModel = anim->mdxFile;
VectorCopy( ent->s.pos.trBase, lf->oldFramePos );
}
//G_Printf("[fT%6d->%-6d] NA %d%s sT %d\n", lf->oldFrameTime, lf->frameTime, lf->animationNumber, firstAnim?" (FIRST)":"", level.time);
}
static void mdx_RunLerpFrame(gentity_t *ent, glerpFrame_t *lf, int newAnimation, bg_character_t *character, int recursion)
{
int f;
animation_t *anim, *oldAnim;
animation_t *otherAnim = NULL;
qboolean isLadderAnim;
qboolean done = qfalse; // break out if we would loop forever
#define ANIM_SCALEMAX_LOW 1.1
#define ANIM_SCALEMAX_HIGH 1.6
#define ANIM_SPEEDMAX_LOW 100
#define ANIM_SPEEDMAX_HIGH 20
isLadderAnim = lf->animation && (lf->animation->flags & ANIMFL_LADDERANIM) ? qtrue : qfalse;
oldAnim = lf->animation;
if ( newAnimation != lf->animationNumber || !lf->animation ) {
mdx_SetLerpFrame(ent, lf, newAnimation, character);
}
anim = lf->animation;
// check for forcing last frame
if ( (ent->s.eFlags & EF_FORCE_END_FRAME) || ent->s.eType == ET_CORPSE ) {
lf->oldFrame = lf->frame = anim->firstFrame + anim->numFrames - 1;
lf->oldFrameModel = lf->frameModel = anim->mdxFile;
return;
}
// if we have passed the current frame, move it to
// oldFrame and calculate a new frame
while( level.time > lf->frameTime && !done ) {
// Calculate move speed
if (lf->oldFrameSnapshotTime < ent->s.pos.trTime) {
// We have a new snapshot, and thus a new speed
float serverDelta;
// calculate the speed at which we moved over the last frame
// zinx - changed to use server position instead of lerp'd position
if( isLadderAnim ) { // only use Z axis for speed
lf->oldFramePos[0] = ent->s.pos.trBase[0];
lf->oldFramePos[1] = ent->s.pos.trBase[1];
}
serverDelta = (float)(ent->s.pos.trTime - lf->oldFrameSnapshotTime) / 1000.0;
lf->moveSpeed = int( Distance( ent->s.pos.trBase, lf->oldFramePos ) / serverDelta );
VectorCopy( ent->s.pos.trBase, lf->oldFramePos );
lf->oldFrameSnapshotTime = ent->s.pos.trTime;
}
// calculate speed for new frame
if (anim->moveSpeed) {
// convert moveSpeed to a factor of this animation's movespeed
lf->animSpeedScale = lf->moveSpeed / (float)anim->moveSpeed;
} else {
// move at normal speed
lf->animSpeedScale = 1.0;
}
// restrict the speed range
if( lf->animSpeedScale < 0.25 ) { // if it's too slow, then a really slow spped, combined with a sudden take-off, can leave them playing a really slow frame while they a moving really fast
if (lf->animSpeedScale < 0.01 && isLadderAnim)
lf->animSpeedScale = 0.0;
else
lf->animSpeedScale = 0.25;
} else if( lf->animSpeedScale > ANIM_SCALEMAX_LOW ) {
if( !(anim->flags & ANIMFL_LADDERANIM) ) {
// allow slower anims to speed up more than faster anims
if( anim->moveSpeed > ANIM_SPEEDMAX_LOW ) {
lf->animSpeedScale = ANIM_SCALEMAX_LOW;
} else if( anim->moveSpeed < ANIM_SPEEDMAX_HIGH ) {
if( lf->animSpeedScale > ANIM_SCALEMAX_HIGH )
lf->animSpeedScale = ANIM_SCALEMAX_HIGH;
} else {
lf->animSpeedScale = ANIM_SCALEMAX_HIGH - (ANIM_SCALEMAX_HIGH - ANIM_SCALEMAX_LOW) * (float)(anim->moveSpeed - ANIM_SPEEDMAX_HIGH) / (float)(ANIM_SPEEDMAX_LOW - ANIM_SPEEDMAX_HIGH);
}
} else if( lf->animSpeedScale > 4.0 ) {
lf->animSpeedScale = 4.0;
}
}
// move to new frame
lf->oldFrame = lf->frame;
lf->oldFrameTime = lf->frameTime;
lf->oldFrameModel = lf->frameModel;
if ( lf == &ent->legsFrame ) {
otherAnim = ent->torsoFrame.animation;
} else if ( lf == &ent->torsoFrame ) {
otherAnim = ent->legsFrame.animation;
}
// get the next frame based on the animation
if( !lf->animSpeedScale ) {
// stopped on the ladder, so stay on the same frame
f = lf->frame - anim->firstFrame;
lf->frameTime += anim->frameLerp; // don't wait too long before starting to move again
} else if ( lf->oldAnimationNumber != lf->animationNumber &&
(!anim->moveSpeed || lf->oldFrame < anim->firstFrame || lf->oldFrame >= anim->firstFrame + anim->numFrames) ) { // Ridah, added this so walking frames don't always get reset to 0, which can happen in the middle of a walking anim, which looks wierd
lf->frameTime = lf->animationTime; // initial lerp
if (oldAnim && anim->moveSpeed) { // keep locomotions going continuously
f = (lf->frame - oldAnim->firstFrame) + 1;
while (f < 0) {
f += anim->numFrames;
}
} else {
f = 0;
}
} else if ( (lf == &ent->legsFrame) && otherAnim && !(anim->flags & ANIMFL_FIRINGANIM) && ((lf->animationNumber & ~ANIM_TOGGLEBIT) == (ent->torsoFrame.animationNumber & ~ANIM_TOGGLEBIT)) && (!anim->moveSpeed) ) {
// legs should synch with torso
f = ent->torsoFrame.frame - otherAnim->firstFrame;
if (f >= anim->numFrames || f < 0) {
f = 0; // wait at the start for the legs to catch up (assuming they are still in an old anim)
}
lf->frameTime = ent->torsoFrame.frameTime;
done = qtrue;
} else if ( (lf == &ent->torsoFrame) && otherAnim && !(anim->flags & ANIMFL_FIRINGANIM) && ((lf->animationNumber & ~ANIM_TOGGLEBIT) == (ent->legsFrame.animationNumber & ~ANIM_TOGGLEBIT)) && (otherAnim->moveSpeed) ) {
// torso needs to sync with legs
f = ent->legsFrame.frame - otherAnim->firstFrame;
if (f >= anim->numFrames || f < 0) {
f = 0; // wait at the start for the legs to catch up (assuming they are still in an old anim)
}
lf->frameTime = ent->legsFrame.frameTime;
done = qtrue;
} else {
lf->frameTime = lf->oldFrameTime + (int)((float)anim->frameLerp * (1.0 / lf->animSpeedScale));
if( anim->flags & ANIMFL_REVERSED ) {
f = (anim->numFrames - 1) - ( (lf->frame - anim->firstFrame) - 1 );
} else {
f = (lf->frame - anim->firstFrame) + 1;
}
}
//f = ( lf->frameTime - lf->animationTime ) / anim->frameLerp;
if ( f >= anim->numFrames ) {
f -= anim->numFrames;
if ( anim->loopFrames ) {
f %= anim->loopFrames;
f += anim->numFrames - anim->loopFrames;
} else {
f = anim->numFrames - 1;
// the animation is stuck at the end, so it
// can immediately transition to another sequence
lf->frameTime = level.time;
done = qtrue;
}
}
if( anim->flags & ANIMFL_REVERSED ) {
lf->frame = anim->firstFrame + anim->numFrames - 1 - f;
lf->frameModel = anim->mdxFile;
} else {
lf->frame = anim->firstFrame + f;
lf->frameModel = anim->mdxFile;
}
lf->oldAnimationNumber = lf->animationNumber;
oldAnim = anim;
//G_Printf("[fT%6d->%-6d] NF %4d->%-4d s %1.4f sT %d\n", lf->oldFrameTime, lf->frameTime, lf->oldFrame, lf->frame, lf->animSpeedScale, level.time);
}
// Gordon: BIG hack, occaisionaly (VERY occaisionally), the frametime gets totally wacked
if( lf->frameTime > level.time + 5000 ) {
lf->frameTime = level.time;
}
}
void mdx_PlayerAnimation(gentity_t *ent)
{
bg_character_t *character;
vec3_t legsAngles, torsoAngles, headAngles;
int animIndex, tempIndex;
if (ent->s.eType == ET_PLAYER) {
character = BG_GetCharacter(ent->client->sess.sessionTeam, ent->client->sess.playerType);
} else {
character = BG_GetCharacter(BODY_TEAM(ent), BODY_CLASS(ent));
}
animIndex = ent->s.legsAnim;
// do the shuffle turn frames locally
if ( !(ent->s.eFlags & (EF_DEAD | EF_PLAYDEAD)) && ent->legsFrame.yawing ) {
tempIndex = BG_GetAnimScriptAnimation( ent->s.number, character->animModelInfo, ent->s.aiState, (ent->legsFrame.yawing == SWING_RIGHT ? ANIM_MT_TURNRIGHT : ANIM_MT_TURNLEFT) );
if (tempIndex > -1) {
animIndex = tempIndex;
}
}
mdx_RunLerpFrame(ent, &ent->legsFrame, animIndex, character, 0);
mdx_RunLerpFrame(ent, &ent->torsoFrame, ent->s.torsoAnim, character, 0);
// swing angles
mdx_PlayerAngles(ent, legsAngles, torsoAngles, headAngles, qtrue);
}
/**************************************************************/
/* Hit testing */
#ifdef BONE_HITTESTS
/* Rotates and transforms everything in to the space of origin/axis/scale,
then finds the closest point to the origin on the line start<->end */
static qboolean mdx_hit_warp(
const vec3_t start, const vec3_t end,
const vec3_t origin,
/*const*/ vec3_t axis[3],
const vec3_t scale,
vec3_t tangent, vec_t *fraction
)
{
vec3_t unaxis[3];
vec3_t unstart, unend, undir;
vec3_t tmp;
/* Un-translate */
VectorSubtract(start, origin, unstart);
VectorSubtract(end, origin, unend);
/* Un-rotate */
MatrixTranspose(axis, unaxis);
PointRotate(unstart, unaxis, tmp);
VectorCopy(tmp, unstart);
PointRotate(unend, unaxis, tmp);
VectorCopy(tmp, unend);
/* Un-scale */
unstart[0] /= scale[0];
unstart[1] /= scale[1];
unstart[2] /= scale[2];
unend[0] /= scale[0];
unend[1] /= scale[1];
unend[2] /= scale[2];
VectorSubtract(unend, unstart, undir);
/* Find closest point */
VectorNegate(unstart, unstart);
*fraction = DotProduct(unstart, undir) / DotProduct(undir, undir);
VectorNegate(unstart, unstart);
if (*fraction < 0.0) {
VectorCopy(unstart, tangent);
*fraction = 0;
return qfalse; // don't shoot backwards..
} else if (*fraction >= 1.0) {
VectorCopy(unend, tangent);
*fraction = 1.0;
} else {
VectorMA(unstart, *fraction, undir, tangent);
}
if (g_debugBullets.integer >= 4) {
/* Draw line from tangent point */
vec3_t point;
VectorSubtract(end, start, point);
VectorMA(start, *fraction, point, point);
etpro_AddDebugLine(origin, point, 2, LINEMODE_LINE, LINESHADER_RAILCORE, 0, qfalse);
}
return qtrue;
}
static qboolean mdx_hit_test_cylinder(const vec3_t p1, const vec3_t p2, float *backlerp)
{
vec_t lerpt, lerp1, lerp2;
vec_t distx, disty;
/* Check ends */
if (p1[2] < 0)
return qfalse;
if (p2[2] > 0)
return qfalse;
/* Check radius */
lerpt = p1[2] + -p2[2];
lerp1 = (lerpt - p1[2]) / lerpt;
lerp2 = 1.0 - lerp1;
*backlerp = lerp1;
distx = p1[0]*lerp1 + p2[0]*lerp2;
distx *= distx;
disty = p1[1]*lerp1 + p2[1]*lerp2;
disty *= disty;
if ((distx+disty) > 1.0)
return qfalse;
return qtrue;
}
static qboolean mdx_hit_test_box2(const vec3_t p1, const vec3_t p2, float *backlerp)
{
vec_t lerpt, lerp1, lerp2;
vec_t distx, disty;
/* Check ends */
if (p1[2] < 0)
return qfalse;
if (p2[2] > 0)
return qfalse;
/* Check radius */
lerpt = p1[2] + -p2[2];
lerp1 = (lerpt - p1[2]) / lerpt;
lerp2 = 1.0 - lerp1;
*backlerp = lerp1;
distx = p1[0]*lerp1 + p2[0]*lerp2;
if (Q_fabs(distx) > 1.0)
return qfalse;
disty = p1[1]*lerp1 + p2[1]*lerp2;
if (Q_fabs(disty) > 1.0)
return qfalse;
return qtrue;
}
static qboolean mdx_hit_test_sphere(const vec3_t p1)
{
/* Check radius */
if (VectorLengthSquared(p1) > Square(1.0))
return qfalse;
/* Hit */
return qtrue;
}
static qboolean mdx_hit_test_box(const vec3_t p1)
{
/* Check radius */
if (Q_fabs(p1[0]) > 1.0) return qfalse;
if (Q_fabs(p1[1]) > 1.0) return qfalse;
if (Q_fabs(p1[2]) > 1.0) return qfalse;
/* Hit */
return qtrue;
}
qboolean mdx_hit_test(const vec3_t start, const vec3_t end, /*const*/ gentity_t *ent, /*const*/ grefEntity_t *refent, int *hit_type, vec_t *fraction, animScriptImpactPoint_t *impactpoint)
{
int i;
bg_character_t *character;
hit_t *hitModel;
vec_t best_frac;
int best_type;
animScriptImpactPoint_t best_impactpoint;
if (ent->s.eType == ET_PLAYER) {
character = BG_GetCharacter(ent->client->sess.sessionTeam, ent->client->sess.playerType);
} else {
character = BG_GetCharacter(BODY_TEAM(ent), BODY_CLASS(ent));
}
// FIXME: Need better lookup for this eventually
for (i = 0; i < hit_count; i++) {
if (hits[i].animModelInfo == character->animModelInfo)
break;
}
if (i >= hit_count)
return qfalse;
hitModel = &hits[i];
mdx_calculate_bones(refent);
best_type = MDX_NONE;
best_frac = 2.0;
best_impactpoint = IMPACTPOINT_UNUSED;
for (i = 0; i < hitModel->hit_count; i++) {
struct hit_area *hit = &hitModel->hits[i];
vec_t hit_frac;
vec3_t o1, o2;
vec3_t a1[3], a2[3];
vec3_t t1, t2;
mdx_tag_orientation(refent, hit->tag[0], o1, a1, hit->ishead[0], 0);
if (hit->tag[1] != -1) {
vec_t hit_frac1, hit_frac2;
mdx_tag_orientation(refent, hit->tag[1], o2, a2, hit->ishead[1], 0);
/* Calculate axis */
VectorSubtract(o2, o1, a1[2]);
VectorNormalize(a1[2]);
CrossProduct(a1[2], a1[0], a1[1]);
VectorNormalize(a1[1]);
CrossProduct(a1[2], a1[1], a1[0]);
/* Apply hit axis */
MatrixMultiply(a1, hit->axis, a2);
if (g_debugBullets.integer >= 3) {
etpro_AddDebugLine(o1, o2, 1, LINEMODE_LINE, LINESHADER_RAILCORE, 0, qfalse);
VectorScale(a2[0], hit->scale[0][0], a1[0]);
VectorScale(a2[1], hit->scale[0][1], a1[1]);
VectorScale(a2[2], hit->scale[0][2], a1[2]);
#ifdef DEBUG
etpro_AddDebugLine(o1, a1[0], 1, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
etpro_AddDebugLine(o1, a1[1], 2, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
etpro_AddDebugLine(o1, a1[2], 3, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
#endif
VectorScale(a2[0], hit->scale[1][0], a1[0]);
VectorScale(a2[1], hit->scale[1][1], a1[1]);
VectorScale(a2[2], hit->scale[1][2], a1[2]);
#ifdef DEBUG
etpro_AddDebugLine(o2, a1[0], 1, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
etpro_AddDebugLine(o2, a1[1], 2, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
etpro_AddDebugLine(o2, a1[2], 3, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
#endif
}
if (!mdx_hit_warp(start, end, o1, a2, hit->scale[0], t1, &hit_frac1))
continue;
if (!mdx_hit_warp(start, end, o2, a2, hit->scale[1], t2, &hit_frac2))
continue;
if (hit->isbox) {
if (!mdx_hit_test_box2(t1, t2, &hit_frac))
continue;
} else {
if (!mdx_hit_test_cylinder(t1, t2, &hit_frac))
continue;
}
hit_frac = hit_frac1*hit_frac + hit_frac2*(1.0 - hit_frac);
} else {
/* Apply hit axis */
MatrixMultiply(a1, hit->axis, a2);
if (g_debugBullets.integer >= 3) {
VectorScale(a2[0], hit->scale[0][0], a1[0]);
VectorScale(a2[1], hit->scale[0][1], a1[1]);
VectorScale(a2[2], hit->scale[0][2], a1[2]);
#ifdef DEBUG
etpro_AddDebugLine(o1, a1[0], 1, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
etpro_AddDebugLine(o1, a1[1], 2, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
etpro_AddDebugLine(o1, a1[2], 3, LINEMODE_ARROW, LINESHADER_RAILCORE, 0, qfalse);
#endif
}
if (!mdx_hit_warp(start, end, o1, a2, hit->scale[0], t1, &hit_frac))
continue;
if (hit->isbox) {
if (!mdx_hit_test_box(t1))
continue;
} else {
if (!mdx_hit_test_sphere(t1))
continue;
}
}
/* It hit. */
if (best_frac > hit_frac) {
best_type = hit->hit_type;
best_frac = hit_frac;
best_impactpoint = hit->impactpoint;
}
}
if (best_frac > 1.0) best_frac = 1.0;
if (hit_type) *hit_type = best_type;
if (fraction) *fraction = best_frac;
if (impactpoint) *impactpoint = best_impactpoint;
return qtrue;
}
#endif
/* For new old-style hit tests; returns -center- positions, to have -centered- bbox applied. */
void mdx_head_position(/*const*/ gentity_t *ent, /*const*/ grefEntity_t *refent, vec3_t org)
{
bg_character_t *character;
mdm_t *model;
orientation_t o;
vec3_t axis[3];
int i;
if (ent->s.eType == ET_PLAYER) {
character = BG_GetCharacter(ent->client->sess.sessionTeam, ent->client->sess.playerType);
} else {
character = BG_GetCharacter(BODY_TEAM(ent), BODY_CLASS(ent));
}
model = &mdm_models[QHANDLETOINDEX(refent->hModel)];
trap_R_LerpTagNumber(&o, refent, model->tag_head);
/* Tag offset */
VectorCopy(refent->origin, org);
for (i = 0; i < 3; i++)
VectorMA(org, o.origin[i], refent->axis[i], org);
/* Apply head/body rotation */
MatrixMultiply(refent->headAxis, o.axis, axis);
MatrixMultiply(axis, refent->axis, o.axis);
/* calculate center position for standard head (this offset is just a guess) */
VectorMA(org, 6.5, o.axis[2], org); // up
VectorMA(org, 0.5, o.axis[0], org); // forward
}
void mdx_legs_position(/*const*/ gentity_t *ent, /*const*/ grefEntity_t *refent, vec3_t org)
{
bg_character_t *character;
mdm_t *model;
orientation_t o;
vec3_t org1, org2;
int i;
if (ent->s.eType == ET_PLAYER) {
character = BG_GetCharacter(ent->client->sess.sessionTeam, ent->client->sess.playerType);
} else {
character = BG_GetCharacter(BODY_TEAM(ent), BODY_CLASS(ent));
}
model = &mdm_models[QHANDLETOINDEX(refent->hModel)];
trap_R_LerpTagNumber(&o, refent, model->tag_footleft);
/* Tag offset */
VectorCopy(refent->origin, org1);
for (i = 0; i < 3; i++)
VectorMA(org1, o.origin[i], refent->axis[i], org1);
trap_R_LerpTagNumber(&o, refent, model->tag_footright);
/* Tag offset */
VectorCopy(refent->origin, org2);
for (i = 0; i < 3; i++)
VectorMA(org2, o.origin[i], refent->axis[i], org2);
VectorAdd(org1, org2, org);
VectorScale(org, 0.5, org);
}
static void
mdx_taginfo( grefEntity_t& re, int tag, vec3_t& origin, orientation_t& orient )
{
trap_R_LerpTagNumber( &orient, &re, tag );
// Apply tag offset from model.
VectorCopy( re.origin, origin );
VectorMA( origin, orient.origin[0], re.axis[0], origin );
VectorMA( origin, orient.origin[1], re.axis[1], origin );
VectorMA( origin, orient.origin[2], re.axis[2], origin );
}
void
mdx_advanced_positions( gentity_t& ent, grefEntity_t& re, vec3_t* origins, orientation_t* orients )
{
mdm_t& model = mdm_models[QHANDLETOINDEX( re.hModel )];
mdx_taginfo( re, model.tag_head, origins[ MRP_NECK ], orients[ MRP_NECK ] );
mdx_taginfo( re, model.tag_armleft, origins[ MRP_ELBOW_LEFT ], orients[ MRP_ELBOW_LEFT ] );
mdx_taginfo( re, model.tag_armright, origins[ MRP_ELBOW_RIGHT ], orients[ MRP_ELBOW_RIGHT ] );
mdx_taginfo( re, model.tag_weapon2, origins[ MRP_HAND_LEFT ], orients[ MRP_HAND_LEFT ] );
mdx_taginfo( re, model.tag_weapon, origins[ MRP_HAND_RIGHT ], orients[ MRP_HAND_RIGHT ] );
mdx_taginfo( re, model.tag_back, origins[ MRP_BACK ], orients[ MRP_BACK ] );
mdx_taginfo( re, model.tag_chest, origins[ MRP_CHEST ], orients[ MRP_CHEST ] );
mdx_taginfo( re, model.tag_torso, origins[ MRP_PELVIS ], orients[ MRP_PELVIS ] );
mdx_taginfo( re, model.tag_legleft, origins[ MRP_KNEE_LEFT ], orients[ MRP_KNEE_LEFT ] );
mdx_taginfo( re, model.tag_legright, origins[ MRP_KNEE_RIGHT ], orients[ MRP_KNEE_RIGHT ] );
mdx_taginfo( re, model.tag_footleft, origins[ MRP_ANKLE_LEFT ], orients[ MRP_ANKLE_LEFT ] );
mdx_taginfo( re, model.tag_footright, origins[ MRP_ANKLE_RIGHT ], orients[ MRP_ANKLE_RIGHT ] );
}
void
mdx_weapon_positions( gentity_t& ent, grefEntity_t& re, vec3_t* origins, orientation_t* orients )
{
mdm_t& model = mdm_models[QHANDLETOINDEX( re.hModel )];
mdx_taginfo( re, model.tag_weapon, origins[ 0 ], orients[ 0 ] );
mdx_taginfo( re, model.tag_weapon2, origins[ 1 ], orients[ 1 ] );
}
| 29.60477 | 253 | 0.668618 | [
"mesh",
"vector",
"model"
] |
e446d8a5bd1d6cd07433b4ec72d3fb7fe316a5e1 | 1,386 | cpp | C++ | Days 251 - 260/Day 252/ReexpressFraction.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 251 - 260/Day 252/ReexpressFraction.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 251 - 260/Day 252/ReexpressFraction.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <utility>
#include <vector>
using Fraction = std::pair<unsigned int, unsigned int>;
std::vector<Fraction> ReexpressFraction(const Fraction& fraction)
{
const auto [a, b] = fraction;
if (a >= b)
{
throw std::invalid_argument("Fraction is improper or whole.");
}
std::vector<Fraction> subfractions;
unsigned int currentDenominator = 2;
long double currentValue = static_cast<long double>(a) / static_cast<long double>(b);
while (currentValue > std::numeric_limits<long double>::epsilon())
{
const long double currentFraction = 1.0l / static_cast<long double>(currentDenominator);
if (currentFraction <= currentValue)
{
subfractions.emplace_back(1, currentDenominator);
currentValue -= currentFraction;
}
++currentDenominator;
}
return subfractions;
}
inline std::ostream& operator <<(std::ostream& outputStream, const Fraction& fraction)
{
outputStream << fraction.first << " / " << fraction.second;
return outputStream;
}
template <typename T>
std::ostream& operator <<(std::ostream& outputStream, const std::vector<T>& values)
{
for (const auto& value : values)
{
outputStream << value << "\n";
}
return outputStream;
}
int main(int argc, char* argv[])
{
std::cout << ReexpressFraction({ 4, 13 }) << "\n";
std::cin.get();
return EXIT_SUCCESS;
} | 21.65625 | 90 | 0.703463 | [
"vector"
] |
e44de84a413bbe12b45981b765802eb459063cda | 1,324 | cpp | C++ | leetcode/sum-of-root-to-leaf-binary-numbers/solution.cpp | kpagacz/spoj | 8bff809c6c5227a6e85e9b12f808dd921f24e587 | [
"MIT"
] | 1 | 2021-12-06T16:01:55.000Z | 2021-12-06T16:01:55.000Z | leetcode/sum-of-root-to-leaf-binary-numbers/solution.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | leetcode/sum-of-root-to-leaf-binary-numbers/solution.cpp | kpagacz/comp-programming | 15482d762ede4d3b7f8ff45a193f6e6bcd85672a | [
"MIT"
] | null | null | null | // link to the problem:https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
#include <numeric>
#include <queue>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int sumUtil(TreeNode *root, int number) {
number = (number << 1) | root->val;
if (root->left == nullptr && root->right == nullptr) {
return number;
}
int sum = 0;
if (root->left != nullptr) sum += sumUtil(root->left, number);
if (root->right != nullptr) sum += sumUtil(root->right, number);
return sum;
}
int sumRootToLeaf(TreeNode *root) {
return sumUtil(root, 0);
}
};
int main(int argc, char **argv) {}
// What did I learn in this problem?
// if passed digits of a binary number in order I can use << and | to create the number in O(1) space
// instead storing all the digits in the string.
// Although string might be more performant (paradoxically).
| 28.782609 | 101 | 0.664653 | [
"vector"
] |
e44eb2984d2509edbf756fefb539115518bf3358 | 819 | cpp | C++ | samples/KeywordSpotting/test/DecoderTest.cpp | Srivathsav-max/armnn-clone | af2daa6526623c91ee97f7141be4d1b07de92a48 | [
"MIT"
] | 1 | 2022-03-31T18:21:59.000Z | 2022-03-31T18:21:59.000Z | samples/KeywordSpotting/test/DecoderTest.cpp | Elm8116/armnn | e571cde8411803aec545b1070ed677e481f46f3f | [
"MIT"
] | null | null | null | samples/KeywordSpotting/test/DecoderTest.cpp | Elm8116/armnn | e571cde8411803aec545b1070ed677e481f46f3f | [
"MIT"
] | null | null | null | //
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <catch.hpp>
#include <map>
#include "Decoder.hpp"
TEST_CASE("Test KWS decoder")
{
// Actual output probability: [0.0, 0.06, 0.02, 0.03, 0.0, 0.0, 0.05, 0.0, 0.83, 0.0, 0.1, 0.0]
// int8 quantised Model output [1, 4, 2, 3, 1, 1, 3, 1, 43, 1, 6, 1]
// Reconstructed dequantised probability [0.0, 0.06, 0.02, 0.04, 0.0, 0.0, 0.04, 0.0, 0.84, 0.0, 0.1, 0.0]
int quantisationOffset = 1;
float quantisationScale = 0.02;
std::vector<int8_t> modelOutput = {1, 4, 2, 3, 1, 1, 3, 1, 43, 1, 6, 1};
kws::Decoder decoder(quantisationOffset,quantisationScale);
std::pair<int,float> result = decoder.decodeOutput(modelOutput);
CHECK(result == std::pair<int,float>(8,0.84));
}
| 28.241379 | 110 | 0.625153 | [
"vector",
"model"
] |
e45166fc5d6ced3a733cfe29d969e994c2466692 | 1,049 | cpp | C++ | Codeforces/1141F/greedy_prefix_array.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2019-07-28T11:26:01.000Z | 2021-06-29T09:50:08.000Z | Codeforces/1141F/greedy_prefix_array.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | null | null | null | Codeforces/1141F/greedy_prefix_array.cpp | codgician/ACM | 391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4 | [
"MIT"
] | 2 | 2017-12-30T02:46:35.000Z | 2018-03-28T03:30:49.000Z | #include <bits/stdc++.h>
using namespace std;
#define SIZE 1510
int pfx[SIZE];
map<int, vector<pair<int, int> > > mp;
vector<pair<int, int> > ans, cnt;
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int len;
cin >> len;
pfx[0] = 0;
for (int i = 1; i <= len; i++) {
cin >> pfx[i];
pfx[i] += pfx[i - 1];
}
for (int i = 1; i <= len; i++) {
for (int j = i; j <= len; j++) {
int val = pfx[j] - pfx[i - 1];
mp[val].push_back(make_pair(i, j));
}
}
for (auto p : mp) {
sort(p.second.begin(), p.second.end(), [](auto fst, auto snd) {
return fst.second < snd.second;
});
cnt.clear();
for (auto i : p.second)
if (cnt.empty() || i.first > cnt.back().second)
cnt.push_back(i);
if (cnt.size() > ans.size())
ans = cnt;
}
cout << ans.size() << endl;
for (auto i : ans)
cout << i.first << " " << i.second << endl;
return 0;
} | 22.319149 | 71 | 0.452812 | [
"vector"
] |
e451bccf9c29f8730a77445ca93f0efa6a76161f | 11,562 | hpp | C++ | test/matrix_vector/MemoryBase.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | 2 | 2018-07-04T16:44:04.000Z | 2021-01-03T07:26:27.000Z | test/matrix_vector/MemoryBase.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | test/matrix_vector/MemoryBase.hpp | spraetor/amdis2 | 53c45c81a65752a8fafbb54f9ae6724a86639dcd | [
"MIT"
] | null | null | null | #pragma once
// AMDiS headers
#include "Config.hpp"
#include "Log.hpp" // TEST_EXIT_DBG
#include "operations/generic_loops.hpp" // meta::FOR
#include "utility/aligned_alloc.hpp" // ALIGNED_ALLOC, ALIGNED_FREE, ...
namespace AMDiS
{
/// Memory base for vector types using static storage
/** The template parameter \p T describes the value-type of the
* data elements. The maximal size (capacity) of the container
* ist set by the non-type template parameter \p N. In the case
* that the container is a matrix, a second dimension can be
* specified by the non-type template parameter \p M. Then the
* total size is N*M.
**/
template <class T, small_t N, small_t M = 1>
struct MemoryBaseStatic
{
static_assert( N*M > 0 , "Container size must be > 0" );
using value_type = T;
using size_type = small_t;
using pointer = value_type*;
using const_pointer = value_type const*;
// static sizes
static constexpr int _SIZE = N*M;
static constexpr int _ROWS = N;
static constexpr int _COLS = M;
protected:
static constexpr size_type _size = _SIZE;
static constexpr size_type _capacity = _SIZE; // TODO: eventuell aufrunden
AMDIS_ALIGNED(T, _elements, _capacity); // T _elements[N];
protected:
/// default constructor
explicit MemoryBaseStatic(size_type DBG_VAR( s ) = 0)
{
TEST_EXIT_DBG(s == 0 || s == _SIZE, "Size must be equal to capacity!\n");
}
/// destructor
~MemoryBaseStatic() = default;
public:
// use default implementations for copy and move operations
MemoryBaseStatic(MemoryBaseStatic const&) = default;
MemoryBaseStatic(MemoryBaseStatic&&) = default;
MemoryBaseStatic& operator=(MemoryBaseStatic const&) = default;
MemoryBaseStatic& operator=(MemoryBaseStatic&&) = default;
public:
/// return the \ref _size of the vector.
size_type getSize() const
{
return _size;
}
/// return the \ref _capacity of the vector.
static constexpr size_type getCapacity()
{
return _capacity;
}
/// return the amount of memory in Bytes allocated by this vector.
size_type getMemoryUsage() const
{
return _capacity*sizeof(T) + sizeof(size_type);
}
/// return address of contiguous memory block \ref _elements
pointer data()
{
return _elements;
}
/// return address of contiguous memory block \ref _elements (const version)
const_pointer data() const
{
return _elements;
}
/// resize the vector. Only possible, if \p s <= _capacity
void resize(size_type s)
{
TEST_EXIT(s != _size, "Resize of static-size containers not allowed!\n");
}
protected:
template <class Target, class Source, class Assigner>
void assign_aux(Target& target, Source const& src, Assigner assigner)
{
using meta::FOR;
FOR<0,_SIZE>::assign(target, src, assigner);
// for (size_type i = 0; i < _size; ++i)
// Assigner::apply(target(i), src(i));
}
template <class Functor>
void for_each_aux(Functor f)
{
using meta::FOR;
FOR<0,_SIZE>::for_each(_elements, f);
// for (size_type i = 0; i < _size; ++i)
// f(_elements[i]);
}
};
// ===========================================================================
/// Memory base for vector types using dynamic storage
/** The template parameter \p T describes the value-type of the
* data elements. The memory is allocated on the heap. When
* \p aligned is set to true an 16-Byte alignement of the data
* is enforced, in order to use vectorization methods.
**/
template <class T, bool aligned = false>
struct MemoryBaseDynamic
{
using Self = MemoryBaseDynamic;
using value_type = T;
using size_type = small_t;
using pointer = value_type*;
using const_pointer = value_type const*;
// static sizes (by default -1 := dynamic size)
static constexpr int _SIZE = -1;
static constexpr int _ROWS = -1;
static constexpr int _COLS = -1;
protected:
size_type _size;
size_type _capacity;
T* _elements;
protected:
/// default constructor
explicit MemoryBaseDynamic(size_type s = 0)
: _size(s),
_capacity(s),
_elements(_size ? (aligned ? AMDIS_ALIGNED_ALLOC(T, s) : new T[s]) : NULL)
{}
/// destructor
~MemoryBaseDynamic()
{
if (_elements)
{
if (aligned)
{
AMDIS_ALIGNED_FREE(_elements);
}
else
{
delete [] _elements;
}
_elements = NULL;
}
}
public:
/// copy constructor
MemoryBaseDynamic(Self const& other)
: _size(other._size),
_capacity(other._capacity),
_elements(_size ? (aligned ? AMDIS_ALIGNED_ALLOC(T, _size) : new T[_size]) : NULL)
{
std::copy(other._elements, other._elements + _size, _elements);
}
/// copy assignment operator
MemoryBaseDynamic& operator=(Self const& other)
{
if (this != &other) {
resize(other._size);
std::copy(other._elements, other._elements + other._size, _elements);
}
return *this;
}
/// move constructor
MemoryBaseDynamic(Self&& other)
: _size(other._size),
_capacity(other._capacity),
_elements(other._elements)
{
other._elements = NULL;
other._size = 0;
}
// move assignment operator
MemoryBaseDynamic& operator=(Self&& other)
{
if (this != &other)
{
if (_elements)
{
if (aligned)
{
AMDIS_ALIGNED_FREE(_elements);
}
else
{
delete [] _elements;
}
_elements = NULL;
}
_size = other._size;
_capacity = other._capacity;
_elements = other._elements;
other._elements = NULL;
other._size = 0;
}
return *this;
}
public:
/// return the \ref _size of the vector.
size_type getSize() const
{
return _size;
}
/// return the \ref _capacity of the vector.
size_type getCapacity() const
{
return _capacity;
}
/// return the amount of memory in Bytes allocated by this vector.
size_type getMemoryUsage() const
{
return (aligned ? AMDIS_ALIGNED_SIZE(_capacity*sizeof(T), CACHE_LINE)
: _capacity*sizeof(T))
+ 2*sizeof(size_type);
}
/// return address of contiguous memory block \ref _elements
pointer data()
{
return _elements;
}
/// return address of contiguous memory block \ref _elements (const version)
const_pointer data() const
{
return _elements;
}
/// resize the vector. If \p s <= \ref _capacity simply set the \ref _size
/// attribute the s, otherwise realloc memory
void resize(size_type s)
{
if (s <= _capacity)
{
_size = s;
// TODO: (maybe) set unused entries to NULL
}
else
{
if (_elements)
{
if (aligned)
{
AMDIS_ALIGNED_FREE(_elements);
}
else
{
delete [] _elements;
}
}
_elements = aligned ? AMDIS_ALIGNED_ALLOC(T, s) : new T[s];
_size = s;
}
}
protected:
template <class Target, class Source, class Assigner>
void assign_aux(Target& target, Source const& src, Assigner assigner)
{
assign_aux(target, src, assigner, bool_<aligned>());
}
template <class Target, class Source, class Assigner> // not assume aligned
void assign_aux(Target& target, Source const& src, Assigner, false_)
{
for (size_type i = 0; i < _size; ++i)
Assigner::apply(target(i), src(i));
}
template <class Target, class Source, class Assigner> // assume aligned
void assign_aux(Target& /*target*/, Source const& src, Assigner, true_)
{
value_type* var = (value_type*)AMDIS_ASSUME_ALIGNED(_elements);
for (size_type i = 0; i < _size; ++i)
Assigner::apply(var[i], src(i));
}
template <class Functor>
void for_each_aux(Functor f)
{
for (size_type i = 0; i < _size; ++i)
f(_elements[i]);
}
};
// ===========================================================================
/// Memory base for vector types using static storage, with dynamic size
/** The template parameter \p T describes the value-type of the
* data elements. The maximal size (capacity) of the container
* ist set by the non-type template parameter \p N. In the case
* that the container is a matrix, a second dimension can be
* specified by the non-type template parameter \p M. Then the
* total size allocated is N*M. The internal size used is set in the
* constructor or the \ref resize function.
**/
template <class T, small_t N, small_t M=1>
struct MemoryBaseHybrid
{
static_assert( N*M > 0 , "Container size must be > 0" );
using value_type = T;
using size_type = small_t;
using pointer = value_type*;
using const_pointer = value_type const*;
// static sizes
static constexpr int _SIZE = -1;
static constexpr int _ROWS = -1;
static constexpr int _COLS = -1;
protected:
size_type _size;
static constexpr size_type _capacity = N*M;
AMDIS_ALIGNED(T, _elements, _capacity); // T _elements[N];
protected:
/// default constructor
explicit MemoryBaseHybrid(size_type s = 0)
: _size(s)
{
TEST_EXIT_DBG(s <= _capacity, "Size must be <= capacity!\n");
}
/// destructor
~MemoryBaseHybrid() = default;
public:
// use default implementations for copy and move operations
MemoryBaseHybrid(MemoryBaseHybrid const&) = default;
MemoryBaseHybrid(MemoryBaseHybrid&&) = default;
MemoryBaseHybrid& operator=(MemoryBaseHybrid const&) = default;
MemoryBaseHybrid& operator=(MemoryBaseHybrid&&) = default;
public:
/// return the \ref _size of the vector.
size_type getSize() const
{
return _size;
}
/// return the \ref _capacity of the vector.
size_type getCapacity() const
{
return _capacity;
}
/// return the amount of memory in Bytes allocated by this vector.
size_type getMemoryUsage() const
{
return _capacity*sizeof(T) + sizeof(size_type);
}
/// return address of contiguous memory block \ref _elements
pointer data()
{
return _elements;
}
/// return address of contiguous memory block \ref _elements (const version)
const_pointer data() const
{
return _elements;
}
/// resize the vector. If \p s <= \ref _capacity simply set the \ref _size
/// attribute the s, otherwise realloc memory
void resize(size_type s)
{
TEST_EXIT(s <= _capacity,
"Resize above capacity not supported for MemoryBaseHybrid.\n");
_size = s;
}
protected:
template <class Target, class Source, class Assigner>
void assign_aux(Target& target, Source const& src, Assigner /*assigner*/)
{
for (size_type i = 0; i < _size; ++i)
Assigner::apply(target(i), src(i));
}
template <class Functor>
void for_each_aux(Functor f)
{
for (size_type i = 0; i < _size; ++i)
f(_elements[i]);
}
};
} // end namespace AMDiS
| 27.140845 | 90 | 0.600415 | [
"vector"
] |
e45292a8b92c902a690778a78cee41206f82b531 | 364 | cpp | C++ | Protein_search_engine.cpp | duming/Protein-3D-Search | a12af1bc47d77906a70b124a5c71d6dd15635c03 | [
"MIT"
] | null | null | null | Protein_search_engine.cpp | duming/Protein-3D-Search | a12af1bc47d77906a70b124a5c71d6dd15635c03 | [
"MIT"
] | null | null | null | Protein_search_engine.cpp | duming/Protein-3D-Search | a12af1bc47d77906a70b124a5c71d6dd15635c03 | [
"MIT"
] | null | null | null | #include "Protein_search_engine.hpp"
/*
void Index_query::desQuery(std::vector<std::pair<float, unsigned> > & result, INDEX_DATA_TYPE *query)
{
scanner->reset(query);
lshIndex.query(query, *scanner);
lshbox::Topk & tpk = scanner->topk();
//tpk.genTopk();
std::vector<std::pair<float, unsigned> > & tops = tpk.getTopk();
result = tops;
}*/
| 28 | 101 | 0.653846 | [
"vector"
] |
e455ae9d4450773de5e1d87e178376b20b9877ad | 663 | cpp | C++ | application/source/Ass1/PointLightNode.cpp | jacoblammert/CGLab_Bu-mann120117_Lammert121796 | cd958a3b00e24bb7986fbb5493127a54bc1a88d2 | [
"MIT"
] | 1 | 2021-12-12T12:43:53.000Z | 2021-12-12T12:43:53.000Z | application/source/Ass1/PointLightNode.cpp | jacoblammert/CGLab_Bu-mann120117_Lammert121796 | cd958a3b00e24bb7986fbb5493127a54bc1a88d2 | [
"MIT"
] | null | null | null | application/source/Ass1/PointLightNode.cpp | jacoblammert/CGLab_Bu-mann120117_Lammert121796 | cd958a3b00e24bb7986fbb5493127a54bc1a88d2 | [
"MIT"
] | null | null | null | //
// Created by Jacob on 03.11.2021.
//
#include "PointLightNode.h"
#include <utility>
/**
*
* @return color as vector with 3 values
* glm:vector?
*/
std::vector<float> PointLightNode::getColor() {
return lightColor_;
}
/**
* set the values of the color for the light
* @param color
*/
void PointLightNode::setColor(std::vector<float> color) {
lightColor_ = std::move(color);
}
/**
* getter for the brightness
* @return
*/
float PointLightNode::getIntensity() {
return lightIntensity_;
}
/**
* getter for the brightness
* @param brightness
*/
void PointLightNode::setIntensity(float intensity) {
lightIntensity_ = intensity;
}
| 16.170732 | 57 | 0.675716 | [
"vector"
] |
e4571f86706581f8355c5693c8bfb4e9066800b7 | 9,496 | cpp | C++ | src/xrGame/alife_trader_abstract.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/xrGame/alife_trader_abstract.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/xrGame/alife_trader_abstract.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : alife_trader_abstract.cpp
// Created : 27.10.2005
// Modified : 27.10.2005
// Author : Dmitriy Iassenev
// Description : ALife trader abstract class
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "xrServer_Objects_ALife_Monsters.h"
#include "alife_simulator.h"
#include "specific_character.h"
#include "ai_space.h"
#include "alife_object_registry.h"
#include "ai_debug.h"
#include "alife_graph_registry.h"
#include "xrServer.h"
#include "alife_schedule_registry.h"
#include "xrServerEntities/xrMessages.h"
#ifdef DEBUG
extern Flags32 psAI_Flags;
#endif
void CSE_ALifeTraderAbstract::spawn_supplies()
{
CSE_ALifeDynamicObject* dynamic_object = smart_cast<CSE_ALifeDynamicObject*>(this);
VERIFY(dynamic_object);
CSE_Abstract* abstract = dynamic_object->alife().spawn_item(
"device_pda", base()->o_Position, dynamic_object->m_tNodeID, dynamic_object->m_tGraphID, base()->ID);
CSE_ALifeItemPDA* pda = smart_cast<CSE_ALifeItemPDA*>(abstract);
pda->m_original_owner = base()->ID;
#ifdef XRGAME_EXPORTS
character_profile();
m_SpecificCharacter = shared_str();
m_community_index = NO_COMMUNITY_INDEX;
pda->m_specific_character = specific_character();
#endif
if (m_SpecificCharacter.size())
{
//если в custom data объекта есть
//секция [dont_spawn_character_supplies]
//то не вызывать spawn из selected_char.SupplySpawn()
bool specific_character_supply = true;
if (xr_strlen(dynamic_object->m_ini_string))
{
#pragma warning(push)
#pragma warning(disable : 4238)
IReader reader((void*)(*dynamic_object->m_ini_string), xr_strlen(dynamic_object->m_ini_string));
CInifile ini(&reader, FS.get_path("$game_config$")->m_Path);
#pragma warning(pop)
if (ini.section_exist("dont_spawn_character_supplies"))
specific_character_supply = false;
}
if (specific_character_supply)
{
CSpecificCharacter selected_char;
selected_char.Load(m_SpecificCharacter);
dynamic_object->spawn_supplies(selected_char.SupplySpawn());
}
}
}
void CSE_ALifeTraderAbstract::vfInitInventory()
{
// m_fCumulativeItemMass = 0.f;
// m_iCumulativeItemVolume = 0;
}
#if 0 // def DEBUG
bool CSE_ALifeTraderAbstract::check_inventory_consistency ()
{
int volume = 0;
float mass = 0.f;
xr_vector<ALife::_OBJECT_ID>::const_iterator I = base()->children.begin();
xr_vector<ALife::_OBJECT_ID>::const_iterator E = base()->children.end();
for ( ; I != E; ++I) {
CSE_ALifeDynamicObject *object = ai().alife().objects().object(*I,true);
if (!object)
continue;
CSE_ALifeInventoryItem *item = smart_cast<CSE_ALifeInventoryItem*>(object);
if (!item)
continue;
volume += item->m_iVolume;
mass += item->m_fMass;
}
R_ASSERT2 (fis_zero(m_fCumulativeItemMass - mass,EPS_L),base()->name_replace());
if (!fis_zero(m_fCumulativeItemMass - mass,EPS_L))
return (false);
R_ASSERT2 (m_iCumulativeItemVolume == volume,base()->name_replace());
if (m_iCumulativeItemVolume != volume)
return (false);
#ifdef DEBUG
// if (psAI_Flags.test(aiALife)) {
// Msg ("[LSS] [%s] inventory is consistent [%f][%d]",base()->name_replace(),mass,volume);
// }
#endif
return (true);
}
#endif
void CSE_ALifeDynamicObject::attach(CSE_ALifeInventoryItem* tpALifeInventoryItem, bool bALifeRequest, bool bAddChildren)
{
if (!bALifeRequest)
return;
tpALifeInventoryItem->base()->ID_Parent = ID;
if (!bAddChildren)
return;
R_ASSERT2(std::find(children.begin(), children.end(), tpALifeInventoryItem->base()->ID) == children.end(),
"Item is already inside the inventory");
children.push_back(tpALifeInventoryItem->base()->ID);
}
void CSE_ALifeDynamicObject::detach(
CSE_ALifeInventoryItem* tpALifeInventoryItem, ALife::OBJECT_IT* I, bool bALifeRequest, bool bRemoveChildren)
{
CSE_ALifeDynamicObject* l_tpALifeDynamicObject1 = smart_cast<CSE_ALifeDynamicObject*>(tpALifeInventoryItem);
R_ASSERT2(l_tpALifeDynamicObject1, "Invalid children objects");
l_tpALifeDynamicObject1->o_Position = o_Position;
l_tpALifeDynamicObject1->m_tNodeID = m_tNodeID;
l_tpALifeDynamicObject1->m_tGraphID = m_tGraphID;
l_tpALifeDynamicObject1->m_fDistance = m_fDistance;
if (!bALifeRequest)
return;
tpALifeInventoryItem->base()->ID_Parent = 0xffff;
if (I)
{
children.erase(*I);
return;
}
if (!bRemoveChildren)
return;
ALife::OBJECT_IT i = std::find(children.begin(), children.end(), tpALifeInventoryItem->base()->ID);
R_ASSERT2(children.end() != i, "Can't detach an item which is not on my own");
children.erase(i);
}
void add_online_impl(CSE_ALifeDynamicObject* object, const bool& update_registries)
{
NET_Packet tNetPacket;
ClientID clientID;
clientID.set(
object->alife().server().GetServerClient() ? object->alife().server().GetServerClient()->ID.value() : 0);
for (auto& it : object->children)
{
//Alundaio:
if (it == ai().alife().graph().actor()->ID)
continue;
//-Alundaio
CSE_ALifeDynamicObject* l_tpALifeDynamicObject = ai().alife().objects().object(it);
if (!l_tpALifeDynamicObject)
continue;
CSE_ALifeInventoryItem* l_tpALifeInventoryItem = smart_cast<CSE_ALifeInventoryItem*>(l_tpALifeDynamicObject);
if (!l_tpALifeInventoryItem)
continue;
//R_ASSERT2(l_tpALifeInventoryItem, "Non inventory item object has parent?!");
l_tpALifeInventoryItem->base()->s_flags._or (M_SPAWN_UPDATE);
CSE_Abstract* l_tpAbstract = smart_cast<CSE_Abstract*>(l_tpALifeInventoryItem);
object->alife().server().entity_Destroy(l_tpAbstract);
#ifdef DEBUG
// if (psAI_Flags.test(aiALife))
// Msg ("[LSS] Spawning item
//[%s][%s][%d]",l_tpALifeInventoryItem->base()->name_replace(),*l_tpALifeInventoryItem->base()->s_name,l_tpALifeDynamicObject->ID);
Msg("[LSS][%d] Going online [%d][%s][%d] with parent [%d][%s] on '%s'", Device.dwFrame, Device.dwTimeGlobal,
l_tpALifeInventoryItem->base()->name_replace(), l_tpALifeInventoryItem->base()->ID, object->ID,
object->name_replace(), "*SERVER*");
#endif
// R_ASSERT3
//(ai().level_graph().valid_vertex_id(l_tpALifeDynamicObject->m_tNodeID),"Invalid
// vertex for object ",l_tpALifeInventoryItem->name_replace());
l_tpALifeDynamicObject->o_Position = object->o_Position;
l_tpALifeDynamicObject->m_tNodeID = object->m_tNodeID;
object->alife().server().Process_spawn(tNetPacket, clientID, FALSE, l_tpALifeInventoryItem->base());
l_tpALifeDynamicObject->s_flags._and (u16(-1) ^ M_SPAWN_UPDATE);
l_tpALifeDynamicObject->m_bOnline = true;
}
if (!update_registries)
return;
object->alife().scheduled().remove(object);
object->alife().graph().remove(object, object->m_tGraphID, false);
}
void CSE_ALifeTraderAbstract::add_online(const bool& update_registries)
{
CSE_ALifeDynamicObject* object = smart_cast<CSE_ALifeDynamicObject*>(this);
VERIFY(object);
add_online_impl(object, update_registries);
}
void add_offline_impl(
CSE_ALifeDynamicObject* object, const xr_vector<ALife::_OBJECT_ID>& saved_children, const bool& update_registries)
{
for (u32 i = 0, n = saved_children.size(); i < n; ++i)
{
CSE_ALifeDynamicObject* child =
smart_cast<CSE_ALifeDynamicObject*>(ai().alife().objects().object(saved_children[i], true));
R_ASSERT(child);
child->m_bOnline = false;
CSE_ALifeInventoryItem* inventory_item = smart_cast<CSE_ALifeInventoryItem*>(child);
VERIFY2(inventory_item, "Non inventory item object has parent?!");
#ifdef DEBUG
// if (psAI_Flags.test(aiALife))
// Msg ("[LSS] Destroying item
//[%s][%s][%d]",inventory_item->base()->name_replace(),*inventory_item->base()->s_name,inventory_item->base()->ID);
Msg("[LSS][%d] Going offline [%d][%s][%d] with parent [%d][%s] on '%s'", Device.dwFrame, Device.dwTimeGlobal,
inventory_item->base()->name_replace(), inventory_item->base()->ID, object->ID, object->name_replace(),
"*SERVER*");
#endif
ALife::_OBJECT_ID item_id = inventory_item->base()->ID;
inventory_item->base()->ID = object->alife().server().PerformIDgen(item_id);
if (!child->can_save())
{
object->alife().release(child);
--i;
--n;
continue;
}
child->clear_client_data();
object->alife().graph().add(child, child->m_tGraphID, false);
object->alife().graph().attach(*object, inventory_item, child->m_tGraphID, true);
}
if (!update_registries)
return;
object->alife().scheduled().add(object);
object->alife().graph().add(object, object->m_tGraphID, false);
}
void CSE_ALifeTraderAbstract::add_offline(
const xr_vector<ALife::_OBJECT_ID>& saved_children, const bool& update_registries)
{
CSE_ALifeDynamicObject* object = smart_cast<CSE_ALifeDynamicObject*>(this);
VERIFY(object);
add_offline_impl(object, saved_children, update_registries);
}
| 35.301115 | 139 | 0.665859 | [
"object"
] |
e4639af4cfe4f7b5331a7e5ccf7ca0209398229f | 1,705 | hpp | C++ | data.hpp | altosaar/gmm_cpp | e418387f4c7e5d841034f33f2cad68386311fba5 | [
"MIT"
] | 2 | 2017-10-21T17:04:25.000Z | 2018-07-16T02:03:19.000Z | data.hpp | altosaar/gmm_cpp | e418387f4c7e5d841034f33f2cad68386311fba5 | [
"MIT"
] | null | null | null | data.hpp | altosaar/gmm_cpp | e418387f4c7e5d841034f33f2cad68386311fba5 | [
"MIT"
] | 3 | 2018-07-05T21:16:55.000Z | 2021-01-30T17:12:33.000Z | #pragma once
#include "utils.hpp"
// a general data base class
class Data {
public:
// sp_mat || mat
virtual string get_data_type() = 0;
virtual shared_ptr<arma::sp_mat> get_sp_mat() {
throw runtime_error("get_sp_mat() not implemented in Data");
return NULL;
}
virtual shared_ptr<arma::mat> get_mat() {
throw runtime_error("get_mat() not implemented in Data");
return NULL;
}
// returns NULL by ault, not NULL means there is a
// training/testing split
virtual shared_ptr<arma::mat> get_train_filter() { return NULL; }
virtual int n_examples() = 0;
virtual int n_dim_y() = 0;
virtual shared_ptr<Data> transpose() const = 0;
virtual shared_ptr<arma::mat> slice_data(const ExampleIds &example_ids) = 0;
virtual void transform(function<double(double)> func) = 0;
};
shared_ptr<Data> build_data(const string &data_type, const pt::ptree &options,
const string &fname);
class DenseData : public Data {
private:
pt::ptree options;
shared_ptr<arma::mat> data;
DenseData() {}
public:
string get_data_type() { return "mat"; }
shared_ptr<arma::mat> get_mat() { return data; }
int n_examples() { return data->n_cols; }
int n_dim_y() { return data->n_rows; }
shared_ptr<Data> transpose() const;
DenseData(const pt::ptree &options, const string &fname);
shared_ptr<arma::mat> slice_data(const ExampleIds &example_ids) {
shared_ptr<arma::mat> batch(
new arma::mat(data->n_rows, example_ids.size()));
for (size_t i = 0; i < example_ids.size(); ++i)
batch->col(i) = data->col(example_ids[i]);
return batch;
}
void transform(function<double(double)> func) { data->transform(func); }
};
| 27.063492 | 78 | 0.672141 | [
"transform"
] |
e47066d65db2b9747fd3fb636504e647949d1c00 | 5,807 | cc | C++ | Dragon/src/operators/loss/softmax_focal_loss_op.cc | awesome-archive/Dragon | b35f9320909d07d138c2f6b345a4c24911f7c521 | [
"BSD-2-Clause"
] | null | null | null | Dragon/src/operators/loss/softmax_focal_loss_op.cc | awesome-archive/Dragon | b35f9320909d07d138c2f6b345a4c24911f7c521 | [
"BSD-2-Clause"
] | null | null | null | Dragon/src/operators/loss/softmax_focal_loss_op.cc | awesome-archive/Dragon | b35f9320909d07d138c2f6b345a4c24911f7c521 | [
"BSD-2-Clause"
] | null | null | null | #include "core/workspace.h"
#include "utils/op_kernel.h"
#include "utils/math_functions.h"
#include "utils/proto_utils.h"
#include "operators/loss/softmax_focal_loss_op.h"
namespace dragon {
#define DETERMINE_RUNTIME_ARGUMENTS(X) \
axis = OperatorBase::Arg<int64_t>("axis", 1); \
axis = axis < 0 ? axis + X.ndim() : axis; \
CHECK(axis >= 0 && axis < X.ndim()) \
<< "\nExcepted the axis in [-" << X.ndim() << ", " << X.ndim() \
<< "), got " << OperatorBase::Arg<int64_t>("axis", 1) << ".";
template <class Context> template <typename Tx, typename Ty>
void SoftmaxFocalLossOp<Context>::RunWithType() {
auto* Pdata = this->prob->template data<Tx, Context>();
auto* Tdata = Input(1).template data<Ty, Context>();
auto* Idata = !this->ignores.count() ? nullptr :
this->ignores.template data<int, Context>();
auto* Ldata = losses.template mutable_data<Tx, Context>();
auto* Fdata = flags.template mutable_data<int, Context>();
kernel::SoftmaxFocalLoss(
outer_dim, Input(0).dim(axis), inner_dim, this->ignores.count(),
pos_alpha, neg_alpha, gamma, neg_id,
Pdata, Tdata, Idata, Ldata, Fdata, ctx());
if (normalization == "UNIT") {
Output(0)->ReshapeLike(losses);
Output(0)->template CopyFrom<Context>(
losses, ctx()); return;
}
double normalizer = 1.;
if (normalization == "VALID") {
normalizer = std::max(
math::Sum(flags.count(),
1.f, Fdata, ctx()), 1);
} else if (normalization == "BATCH_SIZE") {
normalizer = Input(0).dim(0);
} else if (normalization == "FULL"){
normalizer = outer_dim * inner_dim;
}
Output(0)->Reshape(vector<int64_t>());
auto* Ydata = Output(0)->template mutable_data<Tx, Context>();
math::Sum(losses.count(), 1. / normalizer, Ldata, Ydata, ctx());
}
template <class Context>
void SoftmaxFocalLossOp<Context>::RunOnDevice() {
DETERMINE_RUNTIME_ARGUMENTS(Input(0));
outer_dim = Input(0).count(0, axis);
inner_dim = Input(0).count(axis + 1);
CHECK_EQ(outer_dim * inner_dim, Input(1).count())
<< "\nNumber of predictions must match the number of labels.";
flags.Reshape({ outer_dim * inner_dim });
losses.Reshape({ outer_dim * inner_dim });
this->SoftmaxRun();
if (XIsType(Input(0), float)) {
if (XIsType(Input(1), float)) RunWithType<float, float>();
else if (XIsType(Input(1), int64_t)) RunWithType<float, int64_t>();
else LOG(FATAL) << DTypeHelper(Input(1), { "float32", "int64" });
} else LOG(FATAL) << DTypeHelper(Input(0), { "float32" });
}
DEPLOY_CPU(SoftmaxFocalLoss);
#ifdef WITH_CUDA
DEPLOY_CUDA(SoftmaxFocalLoss);
#endif
OPERATOR_SCHEMA(SoftmaxFocalLoss).NumInputs(2).NumOutputs(1);
template <class Context> template <typename Tx, typename Ty>
void SoftmaxFocalLossGradientOp<Context>::RunWithType() {
auto* Pdata = this->prob->template mutable_data<Tx, Context>();
auto* Tdata = Input(1).template data<Ty, Context>();
auto* Idata = !this->ignores.count() ? nullptr :
this->ignores.template data<int, Context>();
auto* dXdata = Output(0)->template mutable_data<Tx, Context>();
auto* Fdata = flags.template mutable_data<int, Context>();
kernel::SoftmaxFocalLossGrad(
outer_dim, Output(0)->dim(axis), inner_dim, this->ignores.count(),
pos_alpha, neg_alpha, gamma, neg_id,
Pdata, Tdata, Idata, dXdata, Fdata, ctx());
if (normalization == "UNIT") {
auto* dYdata = Input(-1).template data<Tx, Context>();
kernel::Repeat(outer_dim, 1, inner_dim,
Input(0).dim(axis), dYdata, Pdata, ctx());
math::Mul(Output(0)->count(),
Pdata, dXdata, dXdata, ctx()); return;
}
double normalizer = 1.;
if (normalization == "VALID") {
normalizer = std::max(
math::Sum(flags.count(),
1.f, Fdata, ctx()), 1);
} else if (normalization == "BATCH_SIZE") {
normalizer = Input(0).dim(0);
} else if (normalization == "FULL") {
normalizer = outer_dim * inner_dim;
}
auto* dYdata = Input(-1).template data<Tx, Context>();
Tx dYHost; ctx()->template Copy
<Tx, CPUContext, Context>(
1, &dYHost, dYdata);
ctx()->FinishDeviceCompution();
math::Scale(
Output(0)->count(),
dYHost / normalizer,
dXdata, dXdata, ctx());
}
template <class Context>
void SoftmaxFocalLossGradientOp<Context>::RunOnDevice() {
DETERMINE_RUNTIME_ARGUMENTS(Input(0));
outer_dim = Input(0).count(0, axis);
inner_dim = Input(0).count(axis + 1);
Output(0)->ReshapeLike(Input(0));
flags.Reshape({ outer_dim * inner_dim });
this->prob = ws()->GetTensor(
mount_name("softmax/prob"));
if (XIsType(Input(0), float)) {
if (XIsType(Input(1), float)) RunWithType<float, float>();
else if (XIsType(Input(1), int64_t)) RunWithType<float, int64_t>();
else LOG(FATAL) << DTypeHelper(Input(1), { "float32", "int64" });
} else LOG(FATAL) << DTypeHelper(Input(0), { "float32" });
}
DEPLOY_CPU(SoftmaxFocalLossGradient);
#ifdef WITH_CUDA
DEPLOY_CUDA(SoftmaxFocalLossGradient);
#endif
OPERATOR_SCHEMA(SoftmaxFocalLossGradient)
.NumInputs(3).NumOutputs(1);
class GetSoftmaxFocalLossGradient
final : public GradientMakerBase {
public:
GRADIENT_MAKER_CTOR(GetSoftmaxFocalLossGradient);
vector<OperatorDef> MakeDefs() override {
return SingleDef(def.type() + "Gradient", "",
vector<string>({ I(0), I(1), GO(0) }),
vector<string>({ GI(0) }));
}
};
REGISTER_GRADIENT(
SoftmaxFocalLoss,
GetSoftmaxFocalLossGradient
);
#undef DETERMINE_RUNTIME_ARGUMENTS
} // namespace dragon | 34.565476 | 75 | 0.623386 | [
"vector"
] |
e4747fec5887a373d294e1063d2804dff0d1b1e3 | 3,177 | hpp | C++ | src/dss_cell_group.hpp | kabicm/arbor | cfab5fd6a2e6a211c097659c96dcc098ee806e68 | [
"BSD-3-Clause"
] | null | null | null | src/dss_cell_group.hpp | kabicm/arbor | cfab5fd6a2e6a211c097659c96dcc098ee806e68 | [
"BSD-3-Clause"
] | null | null | null | src/dss_cell_group.hpp | kabicm/arbor | cfab5fd6a2e6a211c097659c96dcc098ee806e68 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <cell_group.hpp>
#include <dss_cell_description.hpp>
#include <recipe.hpp>
#include <util/span.hpp>
#include <util/unique_any.hpp>
namespace arb {
/// Cell_group to collect spike sources
class dss_cell_group: public cell_group {
public:
dss_cell_group(std::vector<cell_gid_type> gids, const recipe& rec):
gids_(std::move(gids))
{
for (auto gid: gids_) {
auto desc = util::any_cast<dss_cell_description>(rec.get_cell_description(gid));
// store spike times from description
auto times = desc.spike_times;
util::sort(times);
spike_times_.push_back(std::move(times));
// Take a reference to the first spike time
not_emit_it_.push_back(spike_times_.back().begin());
}
}
cell_kind get_cell_kind() const override {
return cell_kind::data_spike_source;
}
void reset() override {
// Reset the pointers to the next undelivered spike to the start
// of the input range.
auto it = not_emit_it_.begin();
auto times = spike_times_.begin();
for (;it != not_emit_it_.end(); ++it, times++) {
*it = times->begin();
}
clear_spikes();
}
void set_binning_policy(binning_kind policy, time_type bin_interval) override {}
void advance(epoch ep, time_type dt, const event_lane_subrange& event_lanes) override {
for (auto i: util::make_span(0, not_emit_it_.size())) {
// The first potential spike_time to emit for this cell
auto spike_time_it = not_emit_it_[i];
// Find the first spike past tfinal
not_emit_it_[i] = std::find_if(
spike_time_it, spike_times_[i].end(),
[ep](time_type t) {return t >= ep.tfinal; }
);
// Loop over the range and create spikes
for (; spike_time_it != not_emit_it_[i]; ++spike_time_it) {
spikes_.push_back({ {gids_[i], 0u}, *spike_time_it });
}
}
};
const std::vector<spike>& spikes() const override {
return spikes_;
}
void clear_spikes() override {
spikes_.clear();
}
void add_sampler(sampler_association_handle h, cell_member_predicate probe_ids, schedule sched, sampler_function fn, sampling_policy policy) override {
std::logic_error("The dss_cells do not support sampling of internal state!");
}
void remove_sampler(sampler_association_handle h) override {}
void remove_all_samplers() override {}
private:
// Spikes that are generated.
std::vector<spike> spikes_;
// Map of local index to gid
std::vector<cell_gid_type> gids_;
// The dss_cell is simple: Put all logic in the cellgroup cause accelerator support
// is not expected. We need storage for the cell state
// The times the cells should spike, one for each cell, sorted in time
std::vector<std::vector<time_type> > spike_times_;
// Each cell needs its own itterator to the first spike not yet emitted
std::vector<std::vector<time_type>::iterator > not_emit_it_;
};
} // namespace arb
| 31.77 | 155 | 0.636764 | [
"vector"
] |
e4781001859b82589f6bea8cd0eff0dbf4607d38 | 6,306 | cpp | C++ | branches/g3d-8.0-64ffmpeg-win/scratch-morgan/App.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | branches/g3d-8.0-64ffmpeg-win/scratch-morgan/App.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | branches/g3d-8.0-64ffmpeg-win/scratch-morgan/App.cpp | brown-ccv/VRG3D | 0854348453ac150b27a8ae89024ef57360f15d45 | [
"BSD-3-Clause"
] | null | null | null | /** \file App.cpp */
#include "App.h"
// Tells C++ to invoke command-line main() function even on OS X and Win32.
G3D_START_AT_MAIN();
int main(int argc, char** argv) {
(void)argc; (void)argv;
GApp::Settings settings;
// Change the window and other startup parameters by modifying the
// settings class. For example:
settings.window.width = 960;
settings.window.height = 600;
settings.film.enabled =false;
# ifdef G3D_WIN32
if (FileSystem::exists("data-files", false)) {
// Running on Windows, building inside the starter directory
chdir("data-files");
} else if (FileSystem::exists("../samples/starter/data-files", false)) {
// Running on Windows, building from the G3D.sln project (TODO: remove this from your program!)
chdir("../samples/starter/data-files");
}
# endif
return App(settings).run();
}
App::App(const GApp::Settings& settings) : GApp(settings) {
# ifdef G3D_DEBUG
// Let the debugger catch unhandled exceptions
catchCommonExceptions = false;
# endif
}
void App::onInit() {
// Called before the application loop beings. Load data here and
// not in the constructor so that common exceptions will be
// automatically caught.
// Turn on the developer HUD
debugWindow->setVisible(true);
developerWindow->cameraControlWindow->setVisible(true);
developerWindow->videoRecordDialog->setEnabled(true);
showRenderingStats = true;
/////////////////////////////////////////////////////////////
// Example of how to add debugging controls
debugPane->addButton("Exit", this, &App::endProgram);
debugPane->addLabel("Add more debug controls");
debugPane->addLabel("in App::onInit().");
// More examples of debugging GUI controls:
// debugPane->addCheckBox("Use explicit checking", &explicitCheck);
// debugPane->addTextBox("Name", &myName);
// debugPane->addNumberBox("height", &height, "m", GuiTheme::LINEAR_SLIDER, 1.0f, 2.5f);
// button = debugPane->addButton("Run Simulator");
// Example of using a callback; you can also listen for events in onEvent or bind controls to data
m_sceneDropDownList = debugPane->addDropDownList("Scene", Scene::sceneNames(), NULL, GuiControl::Callback(this, &App::loadScene));
debugPane->addButton(GuiText("q", GFont::fromFile(System::findDataFile("icon.fnt")), 14), this, &App::loadScene, GuiTheme::TOOL_BUTTON_STYLE)->moveRightOf(m_sceneDropDownList);
debugWindow->pack();
debugWindow->moveTo(Vector2(0, window()->height() - debugWindow->rect().height()));
// Start wherever the developer HUD last marked as "Home"
defaultCamera.setCoordinateFrame(bookmark("Home"));
m_shadowMap = ShadowMap::create();
loadScene();
}
void App::loadScene() {
const std::string& sceneName = m_sceneDropDownList->selectedValue().text();
// Use immediate mode rendering to force a simple message onto the screen
drawMessage("Loading " + sceneName + "...");
// Load the scene
m_scene = Scene::create(sceneName, defaultCamera);
}
void App::onAI() {
// Add non-simulation game logic and AI code here
}
void App::onNetwork() {
// Poll net messages here
}
void App::onSimulation(RealTime rdt, SimTime sdt, SimTime idt) {
(void)idt; (void)sdt; (void)rdt;
// Add physical simulation here. You can make your time
// advancement based on any of the three arguments.
m_scene->onSimulation(sdt);
}
bool App::onEvent(const GEvent& e) {
if (GApp::onEvent(e)) {
return true;
}
// If you need to track individual UI events, manage them here.
// Return true if you want to prevent other parts of the system
// from observing this specific event.
//
// For example,
// if ((e.type == GEventType::GUI_ACTION) && (e.gui.control == m_button)) { ... return true;}
// if ((e.type == GEventType::KEY_DOWN) && (e.key.keysym.sym == GKey::TAB)) { ... return true; }
return false;
}
void App::onUserInput(UserInput* ui) {
(void)ui;
// Add key handling here based on the keys currently held or
// ones that changed in the last frame.
}
void App::onPose(Array<Surface::Ref>& surfaceArray, Array<Surface2D::Ref>& surface2D) {
// Append any models to the arrays that you want to later be rendered by onGraphics()
m_scene->onPose(surfaceArray);
(void)surface2D;
}
void App::onGraphics3D(RenderDevice* rd, Array<Surface::Ref>& surface3D) {
if (m_scene->lighting()->environmentMap.notNull()) {
Draw::skyBox(rd, m_scene->lighting()->environmentMap);
}
// Render all objects (or, you can call Surface methods on the
// elements of posed3D directly to customize rendering. Pass a
// ShadowMap as the final argument to create shadows.)
Surface::sortAndRender(rd, defaultCamera, surface3D, m_scene->lighting(), m_shadowMap);
//////////////////////////////////////////////////////
// Sample immediate-mode rendering code
rd->enableLighting();
for (int i = 0; i < m_scene->lighting()->lightArray.size(); ++i) {
rd->setLight(i, m_scene->lighting()->lightArray[i]);
}
for (int i = 0; i < m_scene->lighting()->shadowedLightArray.size(); ++i) {
rd->setLight(i + m_scene->lighting()->lightArray.size(), m_scene->lighting()->shadowedLightArray[i]);
}
rd->setAmbientLightColor(m_scene->lighting()->ambientAverage());
Draw::axes(CoordinateFrame(Vector3(0, 0, 0)), rd);
Draw::sphere(Sphere(Vector3(2.5f, 0.5f, 0), 0.5f), rd, Color3::white(), Color4::clear());
Draw::box(AABox(Vector3(-2.0f, 0.0f, -0.5f), Vector3(-1.0f, 1.0f, 0.5f)), rd, Color4(Color3::orange(), 0.25f),
Color3::black());
// Call to make the GApp show the output of debugDraw
drawDebugShapes();
}
void App::onGraphics2D(RenderDevice* rd, Array<Surface2D::Ref>& posed2D) {
// Render 2D objects like Widgets. These do not receive tone mapping or gamma correction
Surface2D::sortAndRender(rd, posed2D);
}
void App::onCleanup() {
// Called after the application loop ends. Place a majority of cleanup code
// here instead of in the constructor so that exceptions can be caught
}
void App::endProgram() {
m_endProgram = true;
}
| 34.459016 | 180 | 0.652395 | [
"render"
] |
e47876c09e556bb015e592befaefbc5da0ee38db | 17,679 | hpp | C++ | fc_malloc/fc_heap.hpp | r-lyeh/malloc-survey | 6da5aca6aa2720d64bff709c111a5d8a5fa7a1be | [
"Zlib"
] | 16 | 2015-06-26T20:58:23.000Z | 2017-11-05T09:46:45.000Z | fc_malloc/fc_heap.hpp | r-lyeh/test-allocators | 6da5aca6aa2720d64bff709c111a5d8a5fa7a1be | [
"Zlib"
] | 1 | 2015-07-22T22:48:56.000Z | 2015-07-22T22:48:56.000Z | fc_malloc/fc_heap.hpp | r-lyeh/test-allocators | 6da5aca6aa2720d64bff709c111a5d8a5fa7a1be | [
"Zlib"
] | 2 | 2015-09-26T17:40:20.000Z | 2016-06-23T17:15:23.000Z | #pragma once
#include "mmap_alloc.hpp"
#include <iostream>
#include <sstream>
#include <assert.h>
#include <string.h>
#include <vector>
#include <unordered_set>
#define CHECK_SIZE( x ) assert(((x) != 0) && !((x) & ((x) - 1)))
#define PAGE_SIZE (2*1024*1024)
#define LOG2(X) ((unsigned) (8*sizeof (unsigned long long) - __builtin_clzll((X)) - 1))
#define LZERO(X) (__builtin_clzll((X)) )
#define NUM_BINS 32 // log2(PAGE_SIZE)
class block_header
{
public:
block_header()
:_prev_size(0),_size(-PAGE_SIZE),_flags(0)
{
//fprintf( stderr, "constructor... size: %d\n", _size );
//memset( data(), 0, size() - 8 );
assert( page_size() == PAGE_SIZE );
}
void* operator new (size_t s) { return malloc(PAGE_SIZE);/*mmap_alloc( PAGE_SIZE );*/ }
void operator delete( void* p ) { free(p); /*mmap_free( p, PAGE_SIZE );*/ }
void dump( const char* label )
{
fprintf( stderr, "%s ] _prev_size: %d _size: %d\n", label, _prev_size, _size);//, int(_flags) );
}
/** size of the block header including the header, data size is size()-8 */
uint32_t size()const { return abs(_size); }
char* data() { return reinterpret_cast<char*>(((char*)this)+8); }
block_header* next()const
{
return _size <= 0 ? nullptr : reinterpret_cast<block_header*>(((char*)this)+size());
}
block_header* prev()const
{
return _prev_size <= 0 ? nullptr : reinterpret_cast<block_header*>(((char*)this)-_prev_size);
}
/**
* creates a new block of size S at the end of this block.
*
* @pre size is a power of 2
* @return a pointer to the new block, or null if no split was possible
*/
block_header* split( uint32_t sz )
{
assert( sz >= 32 );
assert( size() >= 32 );
assert( sz <= (size() - 32) );
assert( page_size() == PAGE_SIZE );
assert( _size != 0xbad );
CHECK_SIZE(sz);
int32_t old_size = _size;
block_header* old_nxt = next();
_size = size() - sz;
assert( _size != 0 );
block_header* nxt = next();
assert( nxt != 0 );
nxt->_prev_size = _size;
nxt->_size = old_size < 0 ? -sz : sz;
assert( _size != 0 );
if( old_nxt ) old_nxt->_prev_size = nxt->_size;
//memset( data(), 0, size()-8 );
assert( size() + nxt->size() == uint32_t(abs(old_size)) );
assert( nxt->next() == old_nxt );
assert( nxt->prev() == this );
assert( next() == nxt );
assert( page_size() == PAGE_SIZE );
assert( nxt->page_size() == PAGE_SIZE );
assert( nxt != this );
nxt->_flags = 0;
return nxt;
}
/**
* @return the merged node, if any
*/
block_header* merge_next()
{
assert( _size != 0xbad );
block_header* cur_next = next();
if( !cur_next ) return this;
assert( cur_next->_size != 0xbad );
assert( cur_next->size() > 0 );
// if( !cur_next->is_idle() ) return this;
auto s = size();
assert( _size > 0 );
_size += cur_next->size();
assert( _size != 0 );
if( cur_next->_size > 0 )
{
block_header* new_next = next();
new_next->_prev_size = size();
}
else
{
_size = -_size; // we are at the end.
assert( _size != 0 );
}
assert( cur_next->_size = 0xbad );
// memset( data(), 0, size()-8 );
assert( size() > s );
if( next() )
{
assert( size()/8 == next() - this );
assert( next()->_prev_size == size() );
assert( page_size() == PAGE_SIZE );
}
return this;
}
/**
* @return the merged node, or this.
*/
block_header* merge_prev()
{
assert( page_size() == PAGE_SIZE );
block_header* pre = prev();
if( !pre ) return this;
return prev()->merge_next();
}
block_header* head()
{
if( !prev() ) return this;
return prev()->head();
}
block_header* tail()
{
if( !next() ) return this;
return next()->tail();
}
size_t page_size()
{
auto t = tail();
auto h = head();
return ((char*)t-(char*)h) + t->size();
}
struct queue_state // the block is serving as a linked-list node
{
block_header* qnext;
block_header* qprev;
block_header** head;
block_header** tail;
};
enum flag_enum
{
queued = 1,
idle = 2,
active = 4
};
bool is_idle()const { return _flags & idle; }
bool is_active()const { return _flags & active; }
bool is_queued()const { return _flags & queued; }
void set_active( bool s )
{
if( s ) _flags |= active;
else _flags &= ~active;
}
void set_queued( bool s )
{
if( s ) _flags |= queued;
else _flags &= ~queued;
// anytime we change state it should be reset..
if( is_queued() )
{
as_queue().qnext = nullptr;
as_queue().qprev = nullptr;
}
}
/** removes this node from any queue it is in */
void dequeue()
{
block_header* pre = as_queue().qprev;
block_header* nxt = as_queue().qnext;
if( pre ) pre->as_queue().qnext = nxt;
if( nxt ) nxt->as_queue().qprev = pre;
set_queued(false);
}
void set_idle( bool s )
{
if( s ) _flags |= idle;
else _flags &= ~idle;
assert( is_idle() == s );
}
queue_state& as_queue()
{
// assert( is_queued() );
return *reinterpret_cast<queue_state*>(data());
}
// private:
int32_t _prev_size; // size of previous header.
int32_t _size:24; // offset to next, negitive indicates tail, 8 MB max, it could be neg
int32_t _flags:8; // offset to next, negitive indicates tail
};
static_assert( sizeof(block_header) == 8, "Compiler is not packing data" );
typedef block_header* block_header_ptr;
struct block_stack
{
public:
block_stack():_head(nullptr){}
void push( block_header* h )
{
h->as_queue().qnext = _head;
if( _head ) _head->as_queue().qprev = h;
_head = h;
//_head.push_back(h);
}
void push_all( block_header* h )
{
assert( h->is_queued() );
assert( _head == nullptr );
_head = h;
}
/*
bool pop( block_header* h )
{
if( _head == nullptr ) return null;
return _head.erase(h) != 0;
}
*/
/** returns all blocks */
block_header* pop_all()
{
block_header* h = _head;
_head = nullptr;
return h;
}
block_header* pop()
{
if( _head )
{
auto tmp = _head;
_head = _head->as_queue().qnext;
if( _head )
_head->as_queue().qprev = nullptr;
return tmp;
}
return nullptr;
/*
if( _head.size() == 0 ) return nullptr;
auto f = _head.begin();
auto h = *f;
_head.erase(f);
return h;
*/
}
block_header* head(){ return _head; }
//int size() { return int(_head.size()); }
private:
//std::unordered_set<block_header*> _head;
block_header* _head;
};
/**
* Single threaded heap implementation, foundation
* for multi-threaded version;
*/
class fc_heap
{
public:
block_header* alloc( size_t s );
void free( block_header* h );
fc_heap()
{
memset(_bins, 0, sizeof(_bins) );
_free_32_data = mmap_alloc( PAGE_SIZE );
_free_64_data = mmap_alloc( PAGE_SIZE );
_free_32_data_end = _free_32_data + PAGE_SIZE;
_free_64_data_end = _free_64_data + PAGE_SIZE;
_free_32_scan_end = &_free_32_state[PAGE_SIZE/32/64];
_free_64_scan_end = &_free_64_state[PAGE_SIZE/64/64];
_free_32_scan_pos = _free_32_state;
_free_64_scan_pos = _free_64_state;
memset( _free_32_state, 0xff, sizeof(_free_32_state ) );
memset( _free_64_state, 0xff, sizeof(_free_64_state ) );
}
~fc_heap()
{
mmap_free( _free_64_data, PAGE_SIZE );
mmap_free( _free_32_data, PAGE_SIZE );
}
// private:
char* alloc32()
{
uint32_t c = 0;
while( 0 == *_free_32_scan_pos )
{
++_free_32_scan_pos;
if( _free_32_scan_pos == _free_32_scan_end )
{
_free_32_scan_pos = _free_32_state;
}
if( ++c == sizeof(_free_32_state)/sizeof(int64_t) )
{
return alloc64();
}
}
int bit = LZERO(*_free_32_scan_pos);
int offset = (_free_32_scan_pos - _free_32_state)*64;
*_free_32_scan_pos ^= (1ll<<(63-bit)); // flip the bit
// fprintf( stderr, "alloc offset: %d bit %d pos %d\n", offset,bit,(offset+bit) );
return _free_32_data + (offset+bit)*32;
}
char* alloc64()
{
uint32_t c = 0;
while( 0 == *_free_64_scan_pos )
{
++_free_64_scan_pos;
if( _free_64_scan_pos == _free_64_scan_end )
{
_free_64_scan_pos = _free_64_state;
}
if( ++c == sizeof(_free_64_state)/sizeof(int64_t) )
{
return nullptr;
}
}
int bit = LZERO(*_free_64_scan_pos);
int offset = (_free_64_scan_pos - _free_64_state)*64;
*_free_64_scan_pos ^= (1ll<<(63-bit)); // flip the bit
return _free_64_data + (offset+bit)*64;
}
bool free32( char* p )
{
if( p >= _free_32_data &&
_free_32_data_end > p )
{
uint32_t offset = (p - _free_32_data)/32;
uint32_t bit = offset & (64-1);
uint32_t idx = offset/64;
_free_32_state[idx] ^= (1ll<<((63-bit)));
return true;
}
return false;
}
bool free64( char* p )
{
if( p >= _free_64_data &&
_free_64_data_end > p )
{
uint32_t offset = (p - _free_64_data)/64;
uint32_t bit = offset & (64-1);
uint32_t idx = offset/64;
_free_64_state[idx] ^= (1ll<<((63-bit)));
return true;
}
return false;
}
char* _free_32_data;
char* _free_64_data;
char* _free_32_data_end;
char* _free_64_data_end;
uint64_t* _free_32_scan_pos;
uint64_t* _free_64_scan_pos;
uint64_t* _free_32_scan_end;
uint64_t* _free_64_scan_end;
uint64_t _free_32_state[PAGE_SIZE/32/64];
uint64_t _free_64_state[PAGE_SIZE/64/64];
block_stack _bins[NUM_BINS]; // anything less than 1024 bytes
};
/**
* Return a block of size s or greater
* @pre size >= 32
* @pre size is power of 2
*/
block_header* fc_heap::alloc( size_t s )
{
assert( s >= 32 );
CHECK_SIZE( s ); // make sure it is a power of 2
uint32_t min_bin = LOG2(s); // find the min bin for it.
while( min_bin < 32 )
{
block_header* h = _bins[min_bin].pop();
if( h )
{
assert( h->_size != 0 );
assert( h->_size != 0xbad );
assert( h->is_queued() );
h->set_queued(false);
if( h->size() - 32 < s )
{
h->set_active(true);
return h;
}
block_header* tail = h->split(s);
assert( h->_size != 0 );
h->set_active(true);
this->free(h);
tail->set_active(true);
return tail;
}
++min_bin;
}
// mmap a new page
block_header* h = new block_header();
block_header* t = h->split(s);
h->set_active(true);
free(h);
t->set_active(true);
return t;
}
void fc_heap::free( block_header* h )
{
assert( h != nullptr );
assert( h->is_active() );
assert( h->_size != 0 );
assert( h->size() < PAGE_SIZE );
auto pre = h->prev();
auto nxt = h->next();
if( nxt && !nxt->is_active() && nxt->is_queued() )
{
auto nxt_bin = LOG2(nxt->size());
if( _bins[nxt_bin].head() == nxt )
{
_bins[nxt_bin].pop();
nxt->set_queued(false);
}
else
{
nxt->dequeue();
}
h = h->merge_next();
}
if( pre && !pre->is_active() && pre->is_queued() )
{
auto pre_bin = LOG2(pre->size());
if( _bins[pre_bin].head() == pre )
{
_bins[pre_bin].pop();
pre->set_queued(false);
}
else
{
pre->dequeue();
}
h = pre->merge_next();
}
if( h->size() == PAGE_SIZE )
{
delete h;
return;
}
h->set_active(false);
h->set_queued(true );
auto hbin = LOG2(h->size());
_bins[hbin].push(h);
}
class thread_heap;
class garbage_thread
{
public:
static garbage_thread& get();
uint64_t avail( int bin );
int64_t claim( int bin, int64_t num );
block_header* get_claim( int bin, int64_t pos );
protected:
void register_thread_heap( thread_heap* h );
friend class thread_heap;
static void run();
};
class thread_heap
{
public:
static thread_heap& get();
block_header* allocate( size_t s )
{
if( s >= PAGE_SIZE )
{
// TODO: allocate special mmap region...
}
uint32_t min_bin = LOG2(s); // find the min bin for it.
while( min_bin < NUM_BINS )
{
block_header* h = cache_alloc(min_bin, s);
if( h ) return h;
garbage_thread& gc = garbage_thread::get();
if( auto av = gc.avail( min_bin ) )
{
int64_t claim_num = std::min<int64_t>(4,av);
int64_t claim = gc.claim( min_bin, claim_num );
int64_t end = claim + claim_num;
while( claim < end )
{
block_header* h = gc.get_claim(min_bin,claim);
if( h )
{
cache(h);
}
++claim;
}
h = cache_alloc(min_bin, s);
if( h ) return h; // else... we actually didn't get our claim
}
++min_bin;
}
block_header* h = new block_header();
h->set_active(true);
if( s <= PAGE_SIZE - 32 )
{
block_header* t = h->split(s);
t->set_active(true);
cache( h );
return t;
}
return h;
}
block_header* cache_alloc( int bin, size_t s )
{
block_header* c = pop_cache(bin);
if( c && (c->size() - 32) > s )
{
block_header* t = c->split(s);
c->set_active(true);
if( !cache( c ) )
{
this->free(c);
}
t->set_active(true);
return t;
}
return nullptr;
}
bool cache( block_header* h )
{
uint32_t b = LOG2( h->size() );
if( _cache_size[b] < 4 )
{
h->set_queued(true);
_cache[b].push(h);
_cache_size[b]++;
return true;
}
return false;
}
block_header* pop_cache( int bin )
{
block_header* h = _cache[bin].pop();
if( h )
{
_cache_size[bin]--;
h->set_queued(false);
return h;
}
return nullptr;
}
void free( block_header* h )
{
h->set_queued(true);
_gc_on_deck.push( h );
if( !_gc_at_bat.head() )
_gc_at_bat.push_all( _gc_on_deck.pop_all() );
}
private:
thread_heap();
friend garbage_thread;
block_stack _gc_at_bat; // waiting for gc to empty
block_stack _gc_on_deck; // caching until gc pickups at bat
block_stack _cache[NUM_BINS];
int16_t _cache_size[NUM_BINS];
};
static fc_heap static_heap;
void* fc_malloc( size_t s )
{
if( s <= 64 )
{
if( s <= 32 )
return static_heap.alloc32();
else
return static_heap.alloc64();
}
// round up to nearest power of 2 > 32
s += 8; // room for header.
if( s < 32 ) s = 32; // min size
s = (1<<(LOG2(s-1)+1)); // round up to nearest power of 2
if( s < 24 ) s = 24;
block_header* h = static_heap.alloc( s );
assert( h->is_active() );
// h->set_idle(false);
// assert( h->page_size() == PAGE_SIZE );
return h->data();
}
void fc_free( void* f )
{
if( static_heap.free32((char*)f) || static_heap.free64((char*)f) ) return;
block_header* bh = (block_header*)(((char*)f)-8);
// fprintf( stderr, "fc_free(block: %p)\n", bh );
// assert( bh->is_active() );
//assert( bh->page_size() == PAGE_SIZE );
static_heap.free(bh);
}
| 25.547688 | 107 | 0.491883 | [
"vector"
] |
e4796106908158d0f4fc4bfd7257c0f59f834165 | 1,301 | cpp | C++ | 654. Maximum Binary Tree/main.cpp | shenzheyu/LeetCode | 08478996f9c41a526ea8560233b4e91ed04c9682 | [
"MIT"
] | 6 | 2018-04-20T14:43:06.000Z | 2021-01-17T21:51:22.000Z | 654. Maximum Binary Tree/main.cpp | shenzheyu/LeetCode | 08478996f9c41a526ea8560233b4e91ed04c9682 | [
"MIT"
] | 1 | 2018-04-29T13:10:02.000Z | 2018-04-29T14:47:44.000Z | 654. Maximum Binary Tree/main.cpp | shenzheyu/LeetCode | 08478996f9c41a526ea8560233b4e91ed04c9682 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode *root = build(nums, 0, nums.size() - 1);
return root;
}
private:
// construct tree with nums[lo, hi]
TreeNode* build(vector<int>& nums, int lo, int hi) {
// base case
if (lo > hi) {
return NULL;
}
// find the max value and index in nums
int rootVal = INT_MIN;
int rootInd = -1;
for (int i = lo; i <= hi; i++) {
if (nums[i] > rootVal) {
rootVal = nums[i];
rootInd = i;
}
}
TreeNode *root = new TreeNode(rootVal);
// construct the left tree and right tree recursively
root->left = build(nums, lo, rootInd - 1);
root->right = build(nums, rootInd + 1, hi);
return root;
}
};
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
| 24.54717 | 90 | 0.539585 | [
"vector"
] |
e47c7748bb6fb2a0f39ce4183a1ebd990354bfc6 | 5,319 | cpp | C++ | GUIWidgets/BasicStreamEditor/DistrFunctionDialog.cpp | FlowsheetSimulation/Dyssol-open | 557d57d959800868e1b3fd161b26cad16481382b | [
"BSD-3-Clause"
] | 7 | 2020-12-02T02:54:31.000Z | 2022-03-08T20:37:46.000Z | GUIWidgets/BasicStreamEditor/DistrFunctionDialog.cpp | FlowsheetSimulation/Dyssol-open | 557d57d959800868e1b3fd161b26cad16481382b | [
"BSD-3-Clause"
] | 33 | 2021-03-26T12:20:18.000Z | 2022-02-23T11:37:56.000Z | GUIWidgets/BasicStreamEditor/DistrFunctionDialog.cpp | FlowsheetSimulation/Dyssol-open | 557d57d959800868e1b3fd161b26cad16481382b | [
"BSD-3-Clause"
] | 6 | 2020-07-17T08:17:37.000Z | 2022-02-24T13:45:16.000Z | /* Copyright (c) 2020, Dyssol Development Team. All rights reserved. This file is part of Dyssol. See LICENSE file for license information. */
#include "DistrFunctionDialog.h"
#include "DyssolUtilities.h"
#include "DyssolStringConstants.h"
#include <QMessageBox>
#include "MultidimensionalGrid.h"
CDistrFunctionDialog::CDistrFunctionDialog(QWidget* parent /*= nullptr*/) : QDialog(parent)
{
ui.setupUi(this);
setModal(true);
m_distrFun = EDistrFunction::Normal;
m_PSDGridType = EPSDGridType::DIAMETER;
m_nDimType = DISTR_SIZE;
m_pGrid = nullptr;
m_dParam1 = 0;
m_dParam2 = 0;
SetDistributionsGrid(m_pGrid, m_nDimType, m_PSDGridType);
CreateDistrFunCombo();
connect(ui.comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CDistrFunctionDialog::FunctionChanged);
connect(ui.pushButtonOk, &QPushButton::clicked, this, &CDistrFunctionDialog::OKClicked);
connect(ui.pushButtonCancel, &QPushButton::clicked, this, &CDistrFunctionDialog::CancelClicked);
}
void CDistrFunctionDialog::setVisible(bool _bVisible)
{
if (_bVisible && !this->isVisible())
UpdateWholeView();
QDialog::setVisible(_bVisible);
}
void CDistrFunctionDialog::SetDistributionsGrid(const CMultidimensionalGrid* _pGrid, EDistrTypes _nType, EPSDGridType _nPSDGridType)
{
m_nDimType = _nType;
if (!_pGrid) return;
m_pGrid = _pGrid;
m_PSDGridType = _nPSDGridType;
if (m_nDimType != DISTR_SIZE)
m_vSizes = _pGrid->GetGridDimensionNumeric(_nType)->GetClassesMeans();
else
m_vSizes = _pGrid->GetPSDMeans(_nPSDGridType);
}
std::vector<double> CDistrFunctionDialog::GetDistribution() const
{
return m_vDistr;
}
void CDistrFunctionDialog::CreateDistrFunCombo() const
{
QSignalBlocker blocker(ui.comboBox);
ui.comboBox->insertItem(static_cast<int>(EDistrFunction::Normal), StrConst::FUN_NormalName);
ui.comboBox->insertItem(static_cast<int>(EDistrFunction::RRSB), StrConst::FUN_RRSBName);
ui.comboBox->insertItem(static_cast<int>(EDistrFunction::GGS), StrConst::FUN_GGSName);
ui.comboBox->insertItem(static_cast<int>(EDistrFunction::LogNormal), StrConst::FUN_LogNormalName);
ui.comboBox->setCurrentIndex(static_cast<int>(m_distrFun));
}
void CDistrFunctionDialog::UpdateWholeView() const
{
UpdateDistrFunction();
UpdateUnits();
UpdateParamLabels();
UpdateParams();
}
void CDistrFunctionDialog::UpdateDistrFunction() const
{
ui.comboBox->setCurrentIndex(static_cast<int>(m_distrFun) - 1);
}
void CDistrFunctionDialog::UpdateUnits() const
{
const QString sUnits = m_nDimType != DISTR_SIZE ? StrConst::FUN_EmptyUnits : m_PSDGridType == EPSDGridType::DIAMETER ? StrConst::FUN_DiameterUnits : StrConst::FUN_VolumeUnits;
ui.labelUnits1->setText(sUnits);
if (m_distrFun == EDistrFunction::Normal)
ui.labelUnits2->setText(sUnits);
else
ui.labelUnits2->setText(QString(StrConst::FUN_EmptyUnits));
}
void CDistrFunctionDialog::UpdateParamLabels() const
{
switch (m_distrFun)
{
case EDistrFunction::Normal:
ui.labelParam1->setText(StrConst::FUN_NormalParam1);
ui.labelParam2->setText(StrConst::FUN_NormalParam2);
break;
case EDistrFunction::RRSB:
ui.labelParam1->setText(StrConst::FUN_RRSBParam1);
ui.labelParam2->setText(StrConst::FUN_RRSBParam2);
break;
case EDistrFunction::GGS:
ui.labelParam1->setText(StrConst::FUN_GGSParam1);
ui.labelParam2->setText(StrConst::FUN_GGSParam2);
break;
case EDistrFunction::LogNormal:
ui.labelParam1->setText(StrConst::FUN_LogNormalParam1);
ui.labelParam2->setText(StrConst::FUN_LogNormalParam2);
break;
case EDistrFunction::Manual:
ui.labelParam1->setText(StrConst::FUN_UndefinedParam);
ui.labelParam2->setText(StrConst::FUN_UndefinedParam);
break;
}
}
void CDistrFunctionDialog::UpdateParams() const
{
ui.lineEditParam1->setText(QString::number(m_dParam1));
ui.lineEditParam2->setText(QString::number(m_dParam2));
}
void CDistrFunctionDialog::FunctionChanged(int _index)
{
m_distrFun = static_cast<EDistrFunction>(_index + 1);
UpdateParamLabels();
UpdateUnits();
}
void CDistrFunctionDialog::OKClicked()
{
m_dParam1 = ui.lineEditParam1->text().toDouble();
m_dParam2 = ui.lineEditParam2->text().toDouble();
m_distrFun = static_cast<EDistrFunction>(ui.comboBox->currentIndex() + 1);
switch (m_distrFun)
{
case EDistrFunction::Normal:
if (m_dParam2 == 0) { QMessageBox::critical(this, StrConst::FUN_ErrorName, QString::fromStdString(StrConst::FUN_ErrorZeroParameter(StrConst::FUN_NormalParam2))); return; }
break;
case EDistrFunction::RRSB:
if (m_dParam1 == 0) { QMessageBox::critical(this, StrConst::FUN_ErrorName, QString::fromStdString(StrConst::FUN_ErrorZeroParameter(StrConst::FUN_RRSBParam1))); return; }
break;
case EDistrFunction::GGS:
if (m_dParam1 == 0) { QMessageBox::critical(this, StrConst::FUN_ErrorName, QString::fromStdString(StrConst::FUN_ErrorZeroParameter(StrConst::FUN_GGSParam1))); return; }
break;
case EDistrFunction::LogNormal:
if (m_dParam2 == 0) { QMessageBox::critical(this, StrConst::FUN_ErrorName, QString::fromStdString(StrConst::FUN_ErrorZeroParameter(StrConst::FUN_LogNormalParam2))); return; }
break;
case EDistrFunction::Manual:
break;
}
m_vDistr = CreateDistribution(m_distrFun, m_vSizes, m_dParam1, m_dParam2);
Normalize(m_vDistr);
QDialog::accept();
}
void CDistrFunctionDialog::CancelClicked()
{
QDialog::reject();
}
| 32.631902 | 176 | 0.772138 | [
"vector"
] |
e47cfee9fa69bcb849b9a4c36147d0c0223718d2 | 1,700 | cpp | C++ | Samples/Tests/Shapes/CapsuleShapeTest.cpp | All8Up/JoltPhysics | 751d13891f5bd8850863ad236eaa3c340e90de9a | [
"MIT"
] | 1,311 | 2021-08-16T07:37:05.000Z | 2022-03-31T21:13:39.000Z | Samples/Tests/Shapes/CapsuleShapeTest.cpp | All8Up/JoltPhysics | 751d13891f5bd8850863ad236eaa3c340e90de9a | [
"MIT"
] | 102 | 2021-08-28T14:41:32.000Z | 2022-03-31T20:25:55.000Z | Samples/Tests/Shapes/CapsuleShapeTest.cpp | All8Up/JoltPhysics | 751d13891f5bd8850863ad236eaa3c340e90de9a | [
"MIT"
] | 65 | 2021-08-16T07:59:04.000Z | 2022-03-28T06:18:49.000Z | // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#include <TestFramework.h>
#include <Tests/Shapes/CapsuleShapeTest.h>
#include <Physics/Collision/Shape/CapsuleShape.h>
#include <Physics/Body/BodyCreationSettings.h>
#include <Layers.h>
JPH_IMPLEMENT_RTTI_VIRTUAL(CapsuleShapeTest)
{
JPH_ADD_BASE_CLASS(CapsuleShapeTest, Test)
}
void CapsuleShapeTest::Initialize()
{
// Floor
CreateFloor();
RefConst<Shape> big_capsule = new CapsuleShape(2.5f, 2);
// Capsule on outer sphere
Body &body1 = *mBodyInterface->CreateBody(BodyCreationSettings(big_capsule, Vec3(0, 10, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING));
mBodyInterface->AddBody(body1.GetID(), EActivation::Activate);
// Capsule on cylinder
Body &body2 = *mBodyInterface->CreateBody(BodyCreationSettings(big_capsule, Vec3(10, 10, 0), Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), EMotionType::Dynamic, Layers::MOVING));
mBodyInterface->AddBody(body2.GetID(), EActivation::Activate);
RefConst<Shape> long_capsule = new CapsuleShape(5, 1);
// Tower of capsules
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 2; ++j)
{
Vec3 position;
Quat rotation;
if (i & 1)
{
position = Vec3(-4.0f + 8.0f * j, 2.0f + 3.0f * i, -20.0f);
rotation = Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI);
}
else
{
position = Vec3(0, 2.0f + 3.0f * i, -20.0f - 4.0f + 8.0f * j);
rotation = Quat::sRotation(Vec3::sAxisZ(), 0.5f * JPH_PI);
}
Body &body = *mBodyInterface->CreateBody(BodyCreationSettings(long_capsule, position, rotation, EMotionType::Dynamic, Layers::MOVING));
mBodyInterface->AddBody(body.GetID(), EActivation::Activate);
}
}
} | 31.481481 | 181 | 0.692941 | [
"shape"
] |
6b0583fcb8f1151271ae1bbb965c485bbe605608 | 3,490 | cc | C++ | google/cloud/resourcemanager/projects_connection_idempotency_policy.cc | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | null | null | null | google/cloud/resourcemanager/projects_connection_idempotency_policy.cc | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | null | null | null | google/cloud/resourcemanager/projects_connection_idempotency_policy.cc | joezqren/google-cloud-cpp | 325d312b0a21569f3c57515aec7d91f3540d3b48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/resourcemanager/v3/projects.proto
#include "google/cloud/resourcemanager/projects_connection_idempotency_policy.h"
#include "absl/memory/memory.h"
#include <memory>
namespace google {
namespace cloud {
namespace resourcemanager {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
using ::google::cloud::internal::Idempotency;
ProjectsConnectionIdempotencyPolicy::~ProjectsConnectionIdempotencyPolicy() =
default;
namespace {
class DefaultProjectsConnectionIdempotencyPolicy
: public ProjectsConnectionIdempotencyPolicy {
public:
~DefaultProjectsConnectionIdempotencyPolicy() override = default;
/// Create a new copy of this object.
std::unique_ptr<ProjectsConnectionIdempotencyPolicy> clone() const override {
return absl::make_unique<DefaultProjectsConnectionIdempotencyPolicy>(*this);
}
Idempotency GetProject(
google::cloud::resourcemanager::v3::GetProjectRequest const&) override {
return Idempotency::kIdempotent;
}
Idempotency ListProjects(
google::cloud::resourcemanager::v3::ListProjectsRequest) override {
return Idempotency::kIdempotent;
}
Idempotency SearchProjects(
google::cloud::resourcemanager::v3::SearchProjectsRequest) override {
return Idempotency::kIdempotent;
}
Idempotency CreateProject(
google::cloud::resourcemanager::v3::CreateProjectRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency UpdateProject(
google::cloud::resourcemanager::v3::UpdateProjectRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency MoveProject(
google::cloud::resourcemanager::v3::MoveProjectRequest const&) override {
return Idempotency::kNonIdempotent;
}
Idempotency DeleteProject(
google::cloud::resourcemanager::v3::DeleteProjectRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency UndeleteProject(
google::cloud::resourcemanager::v3::UndeleteProjectRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency GetIamPolicy(
google::iam::v1::GetIamPolicyRequest const&) override {
return Idempotency::kNonIdempotent;
}
Idempotency SetIamPolicy(
google::iam::v1::SetIamPolicyRequest const&) override {
return Idempotency::kNonIdempotent;
}
Idempotency TestIamPermissions(
google::iam::v1::TestIamPermissionsRequest const&) override {
return Idempotency::kNonIdempotent;
}
};
} // namespace
std::unique_ptr<ProjectsConnectionIdempotencyPolicy>
MakeDefaultProjectsConnectionIdempotencyPolicy() {
return absl::make_unique<DefaultProjectsConnectionIdempotencyPolicy>();
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace resourcemanager
} // namespace cloud
} // namespace google
| 30.614035 | 80 | 0.758166 | [
"object"
] |
6b08c6843f85631a9d0a790b0eaa8bca68b90487 | 3,329 | cpp | C++ | src/core/coloring_algorithms/LubyColoringAlgorithm.cpp | mrgalopes/sdp_project_q1 | 6d79891ff50eef31158fe1eea3f27d92b60810bf | [
"BSL-1.0"
] | null | null | null | src/core/coloring_algorithms/LubyColoringAlgorithm.cpp | mrgalopes/sdp_project_q1 | 6d79891ff50eef31158fe1eea3f27d92b60810bf | [
"BSL-1.0"
] | null | null | null | src/core/coloring_algorithms/LubyColoringAlgorithm.cpp | mrgalopes/sdp_project_q1 | 6d79891ff50eef31158fe1eea3f27d92b60810bf | [
"BSL-1.0"
] | null | null | null |
#include <chrono>
#include <functional>
#include <memory>
#include <mutex>
#include <numeric>
#include <random>
#include <thread>
#include <unordered_set>
#include "LubyColoringAlgorithm.h"
namespace {
std::mutex mtx;
void independentSetWorker(const std::vector<Vertex>& vertices, const std::unordered_set<int>& A,
std::shared_ptr<std::vector<int>> r_p,
const std::unordered_set<int>::const_iterator A_begin,
const std::unordered_set<int>::const_iterator A_end,
std::unordered_set<int>& i_set, std::unordered_set<int>& x_set) {
std::unordered_set<int> i_set_prime;
std::unordered_set<int> x_set_prime;
for (auto v = A_begin; v != A_end; v++) {
bool peak = true;
const auto& edge_list = vertices.at(*v - 1).getEdgeList();
for (auto vx : edge_list) {
if (A.contains(vx) && r_p->at(vx - 1) > r_p->at(*v - 1)) {
peak = false;
break;
}
}
if (peak) {
i_set_prime.insert(*v);
x_set_prime.insert(edge_list.cbegin(), edge_list.cend());
}
}
mtx.lock();
i_set.merge(i_set_prime);
x_set.merge(x_set_prime);
mtx.unlock();
}
} // Anonymous namespace
// uses time-based seed by default
LubyColoringAlgorithm::LubyColoringAlgorithm()
: ColoringStrategy(), _num_workers(default_workers),
_seed(std::chrono::system_clock::now().time_since_epoch().count()) {}
void LubyColoringAlgorithm::colorGraph(std::vector<Vertex>& vertices) {
std::size_t size_u = vertices.size();
int lowest_available_color = 1;
auto r_p = std::make_shared<std::vector<int>>(size_u); // random permutation
std::iota(r_p->begin(), r_p->end(), 1);
std::unordered_set<int> U{r_p->begin(), r_p->end()}; // U contains the IDs of uncolored vertices
std::unordered_set<int> A{r_p->begin(), r_p->end()}; // A contains the IDs of undecided vertices
std::unordered_set<int> i_set{};
std::unordered_set<int> x_set{};
while (!U.empty()) {
A = U;
i_set.clear();
while (!A.empty()) {
std::shuffle(r_p->begin(), r_p->end(), std::default_random_engine(_seed));
x_set.clear();
// choose independent set
std::vector<std::thread> workers;
for (int i = 0; i < this->_num_workers; i++) {
auto A_begin = A.cbegin();
std::advance(A_begin, (i * A.size() / this->_num_workers));
auto A_end = A.cbegin();
std::advance(A_end, ((i + 1) * A.size() / this->_num_workers));
workers.emplace_back(independentSetWorker, std::ref(vertices), std::ref(A), r_p,
A_begin, A_end, std::ref(i_set), std::ref(x_set));
}
for (auto& t : workers) {
t.join();
}
for (auto& i : i_set) {
A.erase(i);
}
for (auto& x : x_set) {
A.erase(x);
}
}
for (auto v : i_set) {
vertices.at(v - 1).setColor(lowest_available_color);
}
lowest_available_color += 1;
for (auto& i : i_set) {
U.erase(i);
}
}
} | 32.960396 | 100 | 0.544608 | [
"vector"
] |
6b09306b184428d758ee7d5a8059ed0e0adacb4a | 518 | cpp | C++ | C++/tests/problems/0149_count_servers_communicate_test.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 6 | 2019-03-20T22:23:26.000Z | 2020-08-28T03:10:27.000Z | C++/tests/problems/0149_count_servers_communicate_test.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 15 | 2019-10-13T20:53:53.000Z | 2022-03-31T02:01:35.000Z | C++/tests/problems/0149_count_servers_communicate_test.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 3 | 2019-03-11T10:57:46.000Z | 2020-02-26T21:13:21.000Z | #include "../../problems/0149_count_servers_communicate.hpp"
#include <bits/stdc++.h>
#include "../../frameworks/catch.hpp"
using namespace std;
TEST_CASE( "Count Servers that Communicate" ) {
Solution sol;
vector<vector<int>> grid1 = {{1,0},{0,1}};
vector<vector<int>> grid2 = {{1,1},{0,1}};
vector<vector<int>> grid3 = {{1,1,0,0},{0,0,1,0},{0,0,1,0},{0,0,0,1}};
REQUIRE( sol.countServers(grid1) == 0 );
REQUIRE( sol.countServers(grid2) == 3 );
REQUIRE( sol.countServers(grid3) == 4 );
} | 34.533333 | 74 | 0.619691 | [
"vector"
] |
6b0f6e3c7e31340f7d6bc28df3342b840fc0f390 | 689 | hpp | C++ | src/imgtogb/Tilemap.hpp | SimonLarsen/imgtogb | 2a5c7d4925677b9959cb06f72f893db067996142 | [
"MIT"
] | 5 | 2017-02-07T11:48:03.000Z | 2019-02-21T18:07:37.000Z | src/imgtogb/Tilemap.hpp | SimonLarsen/imgtogb | 2a5c7d4925677b9959cb06f72f893db067996142 | [
"MIT"
] | 1 | 2015-07-20T15:40:46.000Z | 2015-07-20T15:40:46.000Z | src/imgtogb/Tilemap.hpp | SimonLarsen/imgtogb | 2a5c7d4925677b9959cb06f72f893db067996142 | [
"MIT"
] | null | null | null | #ifndef IMGTOGB_TILEMAP_HPP
#define IMGTOGB_TILEMAP_HPP
#include <map>
#include <ostream>
#include <string>
#include <boost/numeric/ublas/matrix.hpp>
#include <imgtogb/Image.hpp>
#include <imgtogb/Tile.hpp>
namespace imgtogb {
class Tilemap {
public:
Tilemap(const Image &img, int offset);
size_t getTilesX() const;
size_t getTilesY() const;
size_t getTileDataSize() const;
void getTileMap(std::vector<unsigned char> &out) const;
void getTileData(std::vector<unsigned char> &out) const;
private:
const Image *img;
int offset;
size_t tiles_x, tiles_y, ntiles;
boost::numeric::ublas::matrix<int> tilemap;
std::multimap<int, Tile> map;
};
}
#endif
| 21.53125 | 59 | 0.71553 | [
"vector"
] |
6b0ff32a5a8b6809df361c76ff2d58ec4c2dfc37 | 6,097 | hpp | C++ | algorithms/Krylov/iter_solver_op_CombBLAS.hpp | wangg12/libskylark | e8836190be854d0284d38772c48e110b3c6d5e51 | [
"Apache-2.0"
] | 86 | 2015-01-20T03:12:46.000Z | 2022-01-10T04:05:21.000Z | algorithms/Krylov/iter_solver_op_CombBLAS.hpp | cjiyer/libskylark | e8836190be854d0284d38772c48e110b3c6d5e51 | [
"Apache-2.0"
] | 48 | 2015-05-12T09:31:23.000Z | 2018-12-05T14:45:46.000Z | algorithms/Krylov/iter_solver_op_CombBLAS.hpp | cjiyer/libskylark | e8836190be854d0284d38772c48e110b3c6d5e51 | [
"Apache-2.0"
] | 25 | 2015-01-18T23:02:11.000Z | 2021-06-12T07:30:35.000Z | #ifndef SKYLARK_ITER_SOLVER_OP_COMBBLAS_HPP
#define SKYLARK_ITER_SOLVER_OP_COMBBLAS_HPP
/*****
***** NOTE: THIS CLASS IS NOT USED ANYMORE!
***** It is kept until the useful code can be transfered
***** as functions in namespace base.
*****/
#include <functional>
#include <algorithm>
#include <CombBLAS.h>
namespace skylark { namespace nla {
template <typename IndexType,
typename ValueType>
struct iter_solver_op_t <SpParMat<IndexType,
ValueType,
SpDCCols<IndexType, ValueType> >,
FullyDistMultiVec<IndexType, ValueType> > {
/** A class that allows us to compute power of values */
template <int p, bool invert>
struct pow_t {
typedef ValueType argument_type;
typedef ValueType result_type;
static result_type apply(const argument_type& arg) {
return ((false==invert) ? pow(arg,p):pow(arg,1./p));
}
result_type operator()(const argument_type& arg) const {
return apply(arg);
}
};
struct scale_t {
typedef ValueType argument_type;
typedef ValueType result_type;
const argument_type scaling_factor;
scale_t (argument_type scaling_factor): scaling_factor(scaling_factor) {}
result_type operator()(const argument_type& arg) const {
return scaling_factor*arg;
}
};
template <typename BinaryOperation>
struct scaled_bin_op_t {
typedef ValueType argument_type;
typedef ValueType result_type;
BinaryOperation bin_op;
argument_type scale_arg_1;
argument_type scale_arg_2;
scaled_bin_op_t (argument_type scale_arg_1,
argument_type scale_arg_2) : scale_arg_1(scale_arg_1),
scale_arg_2(scale_arg_2) {}
result_type operator()(const argument_type& arg_1,
const argument_type& arg_2) {
return bin_op(scale_arg_1*arg_1, scale_arg_2*arg_2);
}
};
/** Typedefs for some variables */
typedef IndexType index_t;
typedef ValueType value_t;
typedef SpDCCols<IndexType, ValueType> seq_matrix_t;
typedef FullyDistMultiVec<IndexType, ValueType> mpi_multi_vector_t;
typedef typename mpi_multi_vector_t::mpi_vector_t mpi_vector_t;
typedef SpParMat<IndexType,
ValueType,
SpDCCols<IndexType, ValueType> > mpi_matrix_t;
typedef PlusTimesSRing<ValueType,ValueType> semi_ring_t;
typedef pow_t<2, false> square_t;
typedef pow_t<2, true> square_root_t;
typedef scaled_bin_op_t<std::plus<value_t> > ax_plus_by_t;
/************************************************************************/
/* TYPEDEFs -- if needed externally */
/************************************************************************/
typedef index_t index_type;
typedef value_t value_type;
typedef mpi_matrix_t matrix_type;
typedef mpi_vector_t vector_type;
typedef mpi_multi_vector_t multi_vector_type;
/*************************************************************************/
/* Operations between a matrix and a multi-vector */
/* UNOPTIMIZED */
/*************************************************************************/
static mpi_matrix_t transpose (const mpi_matrix_t& A) {
mpi_matrix_t AT = A;
AT.Transpose();
return AT;
}
static void mat_vec (const mpi_matrix_t& A,
const mpi_multi_vector_t& X,
mpi_multi_vector_t& AX) {
/** Get the dimensions and make sure that they agree */
index_t m = A.getnrow();
index_t n = A.getncol();
if (n != X.dim) { /* error */ }
/** As SpMM is not provided, do the multiplication one at a time */
for (index_t i=0; i<X.size; ++i) AX[i] = SpMV<semi_ring_t>(A,X[i]);
}
template <typename RandomAccessContainer>
static void ax_plus_by (const RandomAccessContainer& a,
mpi_multi_vector_t& X,
const RandomAccessContainer& b,
const mpi_multi_vector_t& Y) {
/** Basic error checking on the dimensions for the multi-vectors */
if (X.dim != Y.dim) { /* error */ }
if (X.size != Y.size) { /* error */ }
if (a.size() != X.size) { /* error */ }
if (b.size() != Y.size) { /* error */ }
/** Perform all the required element-wise operations one by one */
for (index_t i=0; i<X.size; ++i)
X[i].EWiseApply(Y[i], ax_plus_by_t(a[i], b[i]));
}
template <typename RandomAccessContainer>
static void scale (const RandomAccessContainer& a,
mpi_multi_vector_t& X) {
if (a.size() != X.size) { /* error */ }
for (index_t i=0; i<X.size; ++i) X[i].Apply(scale_t(a[i]));
}
template <typename RandomAccessContainer>
static void norm (const mpi_multi_vector_t& X,
RandomAccessContainer& norms) {
for (index_t i=0; i<X.size; ++i) norms[i] = square_root_t::apply
(X[i].Reduce(std::plus<double>(), 0.0, square_t()));
}
static void get_dim (const mpi_multi_vector_t& X, index_t& M, index_t& N) {
M = X.dim;
N = X.size;
}
static void get_dim (const mpi_matrix_t& A, index_t& M, index_t& N) {
M = A.getnrow();
N = A.getncol();
}
template <typename RandomAccessContainer>
static void residual_norms (const mpi_matrix_t& A,
const mpi_multi_vector_t& B,
const mpi_multi_vector_t& X,
RandomAccessContainer& r_norms) {
mpi_multi_vector_t R(B);
/** 1. Compute AX so that we can subtract B from it */
mat_vec (A, X, R);
/** 2. Subtract AX from B to form R */
RandomAccessContainer ONES(X.size, 1.0);
RandomAccessContainer MINUS_ONES(X.size, -1.0);
ax_plus_by (MINUS_ONES, R, ONES, B);
/** 3. Compute the norms of the residual */
norm (R, r_norms);
}
};
} } /** namespace skylark::nla */
#endif // SKYLARK_ITER_SOLVER_OP_COMBBLAS_HPP
| 34.252809 | 77 | 0.586846 | [
"vector"
] |
6b1757cdf418e2a41a9bdf3d923ba3af6c22593c | 1,388 | hpp | C++ | master/master_handler.hpp | husky-team/PyHusky | ac3638101d9147890f9360bcfd18293f2ec1a9a3 | [
"Apache-2.0"
] | 9 | 2017-02-28T08:14:42.000Z | 2019-07-16T19:20:12.000Z | master/master_handler.hpp | husky-team/PyHusky | ac3638101d9147890f9360bcfd18293f2ec1a9a3 | [
"Apache-2.0"
] | 13 | 2017-01-03T08:29:05.000Z | 2017-06-05T11:03:57.000Z | master/master_handler.hpp | husky-team/PyHusky | ac3638101d9147890f9360bcfd18293f2ec1a9a3 | [
"Apache-2.0"
] | 6 | 2017-01-05T02:14:19.000Z | 2020-01-22T04:07:17.000Z | // Copyright 2016 Husky Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <list>
#include <string>
#include <utility>
#include "husky/master/master.hpp"
namespace husky {
class FrontendMasterHandlers;
class PyHuskyMasterHandlers {
friend FrontendMasterHandlers;
public:
void init_master();
void session_begin_handler();
void session_end_handler();
void new_task_handler();
void query_task_handler();
void task_end_handler();
void request_instruction_handler();
protected:
int need_session_begin_py = 0;
int need_session_end_py = 0;
// int cur_generation = 0;
bool py_started = false;
// std::vector<int> daemon_generation;
std::list<std::pair<int, std::string>> task_results; // {int,sting}:{from python/cpp, content}
FrontendMasterHandlers* parent;
};
} // namespace husky
| 24.785714 | 99 | 0.721182 | [
"vector"
] |
6b19d5f3469faf229fb984bc71b641a279a4d033 | 164 | cpp | C++ | 30_days_of_code/generics.cpp | williamfdevine/hackerrank | 80045f708d84feafd9af9094c02ce5b08ba43797 | [
"MIT"
] | null | null | null | 30_days_of_code/generics.cpp | williamfdevine/hackerrank | 80045f708d84feafd9af9094c02ce5b08ba43797 | [
"MIT"
] | null | null | null | 30_days_of_code/generics.cpp | williamfdevine/hackerrank | 80045f708d84feafd9af9094c02ce5b08ba43797 | [
"MIT"
] | null | null | null | /**
@file generics.cpp
*/
template<class T>
void printArray(std::vector<T> vec)
{
for(int i = 0; i < vec.size(); i++)
{
std::cout << vec[i] << std::endl;
}
} | 13.666667 | 36 | 0.554878 | [
"vector"
] |
6b1e80fba78e6601cc361b107aca60088bc2c92a | 3,982 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/hardware/camera2/CameraCaptureSession.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/hardware/camera2/CameraCaptureSession.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/hardware/camera2/CameraCaptureSession.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/hardware/camera2/CameraCaptureSession.h"
using Elastos::IO::EIID_ICloseable;
namespace Elastos {
namespace Droid {
namespace Hardware {
namespace Camera2 {
CAR_INTERFACE_IMPL(CameraCaptureSession::StateCallback, Object, ICameraCaptureSessionStateCallback)
ECode CameraCaptureSession::StateCallback::OnReady(
/* [in] */ ICameraCaptureSession* session)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::StateCallback::OnActive(
/* [in] */ ICameraCaptureSession* session)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::StateCallback::OnClosed(
/* [in] */ ICameraCaptureSession* session)
{
// default empty implementation
return NOERROR;
}
CAR_INTERFACE_IMPL(CameraCaptureSession::StateListener, StateCallback, ICameraCaptureSessionStateListener)
CAR_INTERFACE_IMPL(CameraCaptureSession::CaptureCallback, Object, ICameraCaptureSessionCaptureCallback)
ECode CameraCaptureSession::CaptureCallback::OnCaptureStarted(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ ICaptureRequest* request,
/* [in] */ Int64 timestamp,
/* [in] */ Int64 frameNumber)
{
// Temporary trampoline for API change transition
return OnCaptureStarted(session, request, timestamp);
}
ECode CameraCaptureSession::CaptureCallback::OnCaptureStarted(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ ICaptureRequest* request,
/* [in] */ Int64 timestamp)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::CaptureCallback::OnCapturePartial(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ ICaptureRequest* request,
/* [in] */ ICaptureResult* result)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::CaptureCallback::OnCaptureProgressed(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ ICaptureRequest* request,
/* [in] */ ICaptureResult* partialResult)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::CaptureCallback::OnCaptureCompleted(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ ICaptureRequest* request,
/* [in] */ ITotalCaptureResult* result)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::CaptureCallback::OnCaptureFailed(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ ICaptureRequest* request,
/* [in] */ ICaptureFailure* failure)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::CaptureCallback::OnCaptureSequenceCompleted(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ Int32 sequenceId,
/* [in] */ Int64 frameNumber)
{
// default empty implementation
return NOERROR;
}
ECode CameraCaptureSession::CaptureCallback::OnCaptureSequenceAborted(
/* [in] */ ICameraCaptureSession* session,
/* [in] */ Int32 sequenceId)
{
// default empty implementation
return NOERROR;
}
CAR_INTERFACE_IMPL_2(CameraCaptureSession, Object, ICameraCaptureSession, ICloseable)
} // namespace Camera2
} // namespace Hardware
} // namepsace Droid
} // namespace Elastos | 30.630769 | 106 | 0.700402 | [
"object"
] |
6b2843fc7dd082c25cc724f3ec48cf9787ad527e | 2,856 | hpp | C++ | cpp/oneapi/dal/algo/pca/common.hpp | YarShev/daal | 9ca5d848176ab1c6b3493c805ddf745273e934ab | [
"Apache-2.0"
] | null | null | null | cpp/oneapi/dal/algo/pca/common.hpp | YarShev/daal | 9ca5d848176ab1c6b3493c805ddf745273e934ab | [
"Apache-2.0"
] | null | null | null | cpp/oneapi/dal/algo/pca/common.hpp | YarShev/daal | 9ca5d848176ab1c6b3493c805ddf745273e934ab | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2020 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#pragma once
#include "oneapi/dal/detail/common.hpp"
#include "oneapi/dal/table/common.hpp"
namespace oneapi::dal::pca {
namespace task {
struct dim_reduction {};
using by_default = dim_reduction;
} // namespace task
namespace detail {
struct tag {};
template <typename Task = task::by_default>
class descriptor_impl;
template <typename Task = task::by_default>
class model_impl;
} // namespace detail
namespace method {
struct cov {};
struct svd {};
using by_default = cov;
} // namespace method
template <typename Task = task::by_default>
class ONEAPI_DAL_EXPORT descriptor_base : public base {
public:
using tag_t = detail::tag;
using task_t = Task;
using float_t = float;
using method_t = method::by_default;
descriptor_base();
auto get_component_count() const -> std::int64_t;
auto get_is_deterministic() const -> bool;
protected:
void set_component_count_impl(std::int64_t value);
void set_is_deterministic_impl(bool value);
dal::detail::pimpl<detail::descriptor_impl<task_t>> impl_;
};
template <typename Float = descriptor_base<task::by_default>::float_t,
typename Method = descriptor_base<task::by_default>::method_t,
typename Task = task::by_default>
class descriptor : public descriptor_base<Task> {
public:
using float_t = Float;
using method_t = Method;
auto& set_component_count(int64_t value) {
descriptor_base<Task>::set_component_count_impl(value);
return *this;
}
auto& set_is_deterministic(bool value) {
descriptor_base<Task>::set_is_deterministic_impl(value);
return *this;
}
};
template <typename Task = task::by_default>
class ONEAPI_DAL_EXPORT model : public base {
friend dal::detail::pimpl_accessor;
public:
using task_t = Task;
model();
table get_eigenvectors() const;
auto& set_eigenvectors(const table& value) {
set_eigenvectors_impl(value);
return *this;
}
private:
void set_eigenvectors_impl(const table&);
dal::detail::pimpl<detail::model_impl<task_t>> impl_;
};
} // namespace oneapi::dal::pca
| 26.943396 | 80 | 0.677521 | [
"model"
] |
6b336e0c1f54d02da8ba3656b0d6d25e27d74ed9 | 8,923 | hpp | C++ | DemoFramework/FslSimpleUI/Base/include/FslSimpleUI/Base/Control/Experimental/Histogram.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoFramework/FslSimpleUI/Base/include/FslSimpleUI/Base/Control/Experimental/Histogram.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoFramework/FslSimpleUI/Base/include/FslSimpleUI/Base/Control/Experimental/Histogram.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #ifndef FSLSIMPLEUI_BASE_CONTROL_EXPERIMENTAL_HISTOGRAM_HPP
#define FSLSIMPLEUI_BASE_CONTROL_EXPERIMENTAL_HISTOGRAM_HPP
/****************************************************************************************************************************************************
* Copyright 2020 NXP
* 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 NXP. 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 <FslBase/Log/Log3Core.hpp>
#include <FslBase/Math/MathHelper_Clamp.hpp>
#include <FslBase/Math/Pixel/TypeConverter.hpp>
#include <FslBase/UncheckedNumericCast.hpp>
#include <FslGraphics/Color.hpp>
#include <FslGraphics/Render/NineSliceAtlasTexture2D.hpp>
#include <FslSimpleUI/Base/Control/Util/Draw9SliceUtil.hpp>
#include <FslSimpleUI/Base/BaseWindow.hpp>
#include <FslSimpleUI/Base/DefaultValues.hpp>
#include <FslSimpleUI/Base/PropertyTypeFlags.hpp>
#include <FslSimpleUI/Base/UIDrawContext.hpp>
#include <FslSimpleUI/Base/WindowContext.hpp>
#include <algorithm>
#include <cassert>
#include <vector>
namespace Fsl
{
namespace UI
{
class WindowContext;
//! Experimental histogram rendering.
//! The next revision of this should probably just take a list of bars and their height instead!
template <typename T>
class Histogram : public BaseWindow
{
struct BarGraphics
{
NineSliceAtlasTexture2D NineSliceTexture;
Color PrimaryColor{DefaultColor::Palette::Primary};
};
struct BarRecord
{
uint32_t Entries{};
};
public:
using value_type = T;
private:
struct HistogramInfo
{
value_type Min{};
value_type Max{};
uint32_t MaxEntriesInOneBar{};
HistogramInfo() = default;
HistogramInfo(const value_type min, const value_type max, const uint32_t maxEntriesInOneBar)
: Min(min)
, Max(std::max(max, min))
, MaxEntriesInOneBar(maxEntriesInOneBar)
{
}
};
std::shared_ptr<WindowContext> m_windowContext;
BarGraphics m_bar;
std::vector<value_type> m_values;
std::vector<BarRecord> m_bars;
HistogramInfo m_info;
public:
explicit Histogram(const std::shared_ptr<WindowContext>& context)
: BaseWindow(context)
, m_windowContext(context)
, m_bars(10)
{
// We need to be draw enabled
Enable(WindowFlags::DrawEnabled);
}
const NineSliceAtlasTexture2D& GetBarTexture() const
{
return m_bar.Texture;
}
void SetBarTexture(const NineSliceAtlasTexture2D& value)
{
if (value != m_bar.NineSliceTexture)
{
m_bar.NineSliceTexture = value;
PropertyUpdated(PropertyType::Content);
}
}
const Color& GetBarColor() const
{
return m_bar.PrimaryColor;
}
void SetBarColor(const Color& value)
{
if (value != m_bar.PrimaryColor)
{
m_bar.PrimaryColor = value;
PropertyUpdated(PropertyType::Other);
}
}
const std::vector<value_type>& GetData() const
{
return m_values;
}
bool SetData(const std::vector<value_type>& values, const uint16_t barCount)
{
const uint16_t cappedBarCount = std::max(barCount, uint16_t(1u));
if (cappedBarCount != m_bars.size() || values != m_values)
{
m_values = values;
{ // now build the histogram for the data
const auto range = std::minmax_element(m_values.begin(), m_values.end());
BuildHistogram(*range.first, *range.second, cappedBarCount);
}
return true;
}
return false;
}
bool SetData(const std::vector<value_type>& values, const value_type minValue, const value_type maxValue, const uint16_t barCount)
{
const uint16_t cappedBarCount = std::max(barCount, uint16_t(1u));
if (cappedBarCount != m_bars.size() || values != m_values)
{
m_values = values;
// now build the histogram for the data
BuildHistogram(minValue, maxValue, cappedBarCount);
return true;
}
return false;
}
void WinDraw(const UIDrawContext& context) final
{
const auto renderSizePx = TypeConverter::UncheckedTo<PxPoint2>(RenderExtentPx());
if (renderSizePx.Y < 1)
{
return;
}
const int32_t barWidthPx = renderSizePx.X / int32_t(m_bars.size());
const int32_t barBottomPx = renderSizePx.Y - 1;
const int32_t finalBarWidthPx = barWidthPx * int32_t(m_bars.size());
if (m_bar.NineSliceTexture.IsValid() && m_info.MaxEntriesInOneBar > 0u)
{
int32_t xPosPx = renderSizePx.X >= finalBarWidthPx ? renderSizePx.X - finalBarWidthPx : 0;
PxAreaRectangleF cursorDstRectPxf(context.TargetRect.Left(), context.TargetRect.Top(), float(barWidthPx), context.TargetRect.Height());
for (uint32_t i = 0; i < m_bars.size(); ++i)
{
assert(m_info.MaxEntriesInOneBar > 0u);
int32_t ySizePx = MathHelper::Clamp(
int32_t(std::round((float(renderSizePx.Y) / float(m_info.MaxEntriesInOneBar)) * float(m_bars[i].Entries))), 0, renderSizePx.Y);
cursorDstRectPxf.MoveLeft(context.TargetRect.Left() + float(xPosPx));
cursorDstRectPxf.SetTopBottom(context.TargetRect.Top() + float(barBottomPx - ySizePx), context.TargetRect.Top() + float(barBottomPx));
Draw9SliceUtil::WinDraw(m_windowContext->Batch2D, cursorDstRectPxf, m_bar.NineSliceTexture.Texture, m_bar.NineSliceTexture.NSlice,
ThicknessF(), m_bar.PrimaryColor);
xPosPx += barWidthPx;
}
}
}
protected:
// PxSize2D ArrangeOverride(const PxSize2D& finalSizePx) final
//{
//}
PxSize2D MeasureOverride(const PxAvailableSize& /*availableSizePx*/) final
{
auto minBarExtent = m_bar.NineSliceTexture.Texture.GetExtent();
auto width = m_bars.size() * minBarExtent.Width;
return {UncheckedNumericCast<int32_t>(width), UncheckedNumericCast<int32_t>(minBarExtent.Height)};
}
private:
void BuildHistogram(const value_type min, const value_type max, const uint16_t cappedBarCount)
{
m_info = HistogramInfo(min, max, 0u);
if (cappedBarCount != m_bars.size())
{
m_bars.resize(cappedBarCount);
}
// Clear the counters
std::fill(m_bars.begin(), m_bars.end(), BarRecord());
if (m_bars.size() > 0u)
{
// Then put each entry into its bucket
const value_type interval = (m_info.Max - m_info.Min) / value_type(m_bars.size() - 1);
for (const auto& entry : m_values)
{
auto bucket = static_cast<value_type>(std::round((entry - m_info.Min) / interval));
const uint32_t bucketIndex = MathHelper::Clamp(uint32_t(bucket), 0u, uint32_t(m_bars.size()));
++m_bars[bucketIndex].Entries;
if (m_bars[bucketIndex].Entries > m_info.MaxEntriesInOneBar)
{
m_info.MaxEntriesInOneBar = m_bars[bucketIndex].Entries;
}
}
}
}
};
}
}
#endif
| 35.692 | 150 | 0.630057 | [
"render",
"vector"
] |
6b34682007d7aa38a797b23ca8eefa60651e2ee8 | 2,043 | cpp | C++ | src/atom.cpp | robashaw/gamma | 26fba31be640c9bc429f8c22d5c61c0f8e9215e6 | [
"MIT"
] | 8 | 2019-09-13T10:35:26.000Z | 2022-03-26T13:20:54.000Z | src/atom.cpp | robashaw/gamma | 26fba31be640c9bc429f8c22d5c61c0f8e9215e6 | [
"MIT"
] | null | null | null | src/atom.cpp | robashaw/gamma | 26fba31be640c9bc429f8c22d5c61c0f8e9215e6 | [
"MIT"
] | null | null | null | /*
*
* PURPOSE: Implements atom.hpp, defining class Atom
*
* DATE AUTHOR CHANGES
* =======================================================================
* 27/08/15 Robert Shaw Original code.
* 05/09/15 Robert Shaw Added function to count number of cgbfs
* in spherical basis.
*/
// Includes
#include "atom.hpp"
#include <iostream>
//Constructors
Atom::Atom(const Vector& coords, int q, double m)
{
x = coords(0);
y = coords(1);
z = coords(2);
core = 0;
pos = new double[3];
pos[0] = x;
pos[1] = y;
pos[2] = z;
charge = q;
mass = m;
}
// Copy constructor
Atom::Atom(const Atom& other)
{
x = other.x;
y = other.y;
z = other.z;
core = other.core;
pos = new double[3];
pos[0] = x;
pos[1] = y;
pos[2] = z;
mass = other.mass;
charge = other.charge;
}
// Coordinate accessor
Vector Atom::getCoords() const
{
Vector v(3);
v[0] = x; v[1] = y; v[2] = z;
return v;
}
void Atom::setCore(libecpint::ECPBasis& ecpset) {
core = ecpset.getECPCore(charge);
}
// Routines
// Translate(dx, dy, dz) translates the coordinates by [dx, dy, dz]
// while rotate(Matrix U) applies the unitary transformation U to the coords
void Atom::rotate(const Matrix& U)
{
// Brute force is quicker than matrix-vector multiplication for
// a 3x3 situation such as this
x = U(0, 0)*x + U(0, 1)*y + U(0, 2)*z;
y = U(1, 0)*x + U(1, 1)*y + U(1, 2)*z;
z = U(2, 0)*x + U(2, 1)*y + U(2, 2)*z;
pos[0] = x; pos[1] = y; pos[2] = z;
}
void Atom::translate(double dx, double dy, double dz)
{
x += dx; y += dy; z += dz;
pos[0] = x; pos[1] = y; pos[2] = z;
}
// Overloaded operators
// Overload the assignment operator, =
Atom& Atom::operator=(const Atom& other)
{
// Assign attributes
charge = other.charge;
core = other.core;
x = other.x; y = other.y; z = other.z;
pos = new double[3];
pos[0] = other.pos[0];
pos[1] = other.pos[1];
pos[2] = other.pos[2];
mass = other.mass;
return *this;
}
| 21.28125 | 77 | 0.548213 | [
"vector"
] |
6b3ad412e7b00838f3b5bb296881452f94027d31 | 7,239 | cc | C++ | trt/src/tests/spdk_test.cc | nik-io/uDepot | 06b94b7f2438b38b46572ede28072e24997e40c6 | [
"BSD-3-Clause"
] | null | null | null | trt/src/tests/spdk_test.cc | nik-io/uDepot | 06b94b7f2438b38b46572ede28072e24997e40c6 | [
"BSD-3-Clause"
] | null | null | null | trt/src/tests/spdk_test.cc | nik-io/uDepot | 06b94b7f2438b38b46572ede28072e24997e40c6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020 International Business Machines
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* Authors: Kornilios Kourtis (kou@zurich.ibm.com, kornilios@gmail.com)
*
*/
// vim: set expandtab softtabstop=4 tabstop:4 shiftwidth:4:
// A test for "test_util/spdk.hh"
//
// write a bunch of data into a device
// read them, and make sure they have the same checksum
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "trt_util/spdk.hh"
#define TOTAL_BYTES (1024*4096)
struct XorCsum {
unsigned long csum;
uint64_t len;
XorCsum() : csum(0), len(0) {}
void add(char *buff, size_t buff_size) {
for (size_t i = 0; i < buff_size; i++) {
csum ^= buff[i];
}
len += buff_size;
}
bool operator!=(XorCsum &c) { return csum != c.csum || len != c.len; }
};
struct SpdkOp {
SpdkQpair *qp_;
const size_t dev_sectors_;
const size_t sector_size_;
SpdkOp(SpdkQpair *qp)
: qp_(qp),
dev_sectors_(qp->sqp_namespace->get_nsectors()),
sector_size_(qp->sqp_namespace->get_sector_size()) {}
virtual bool finished(void) = 0;
virtual void submit_op(void) = 0;
virtual void op_done(void) = 0;
static void callback_(void *arg, const struct spdk_nvme_cpl *);
virtual void run_op() {
submit_op();
while (!finished()) {
qp_->execute_completions();
}
}
};
void SpdkOp::callback_(void *arg, const struct spdk_nvme_cpl *)
{
SpdkOp *op = static_cast<SpdkOp *>(arg);
op->qp_->npending_dec(1);
op->op_done();
if (!op->finished())
op->submit_op();
}
struct SpdkWrite : SpdkOp {
size_t total_bytes_, bytes_written_;
SpdkPtr buff_;
size_t buff_size_;
size_t last_write_size_;
size_t nwrites_;
XorCsum csum_;
SpdkWrite(SpdkQpair *qp, size_t nbytes)
: SpdkOp(qp),
total_bytes_(nbytes),
bytes_written_(0),
buff_size_(4096),
last_write_size_(0),
nwrites_(0) {
size_t buff_nlbas = buff_size_ / qp->get_sector_size();
assert(buff_size_ % qp->get_sector_size() == 0);
buff_ = std::move(qp->alloc_buffer(buff_nlbas));
if (!buff_.ptr_m) {
fprintf(stderr, "malloc failed");
exit(1);
}
srand(time(NULL));
}
~SpdkWrite() {
if (buff_.ptr_m)
qp_->free_buffer(std::move(buff_));
}
bool finished(void) override {
return total_bytes_ <= bytes_written_;
}
void op_done() override {
bytes_written_ += last_write_size_;
}
void submit_op() override {
for (unsigned i=0; i<buff_size_; i++) {
char *p = (char *)buff_.ptr_m;
p[i] = rand();
}
uint64_t lba = bytes_written_ / sector_size_;
uint64_t bytes_remaining = (lba - dev_sectors_) * sector_size_;
uint64_t op_bytes = std::min(buff_size_, bytes_remaining);
assert(op_bytes % sector_size_ == 0);
last_write_size_ = op_bytes;
csum_.add((char *)buff_.ptr_m, op_bytes);
qp_->submit_write(buff_, lba, op_bytes / sector_size_, callback_, this);
}
};
struct SpdkCsum : SpdkOp {
size_t bytes_read_;
XorCsum csum_;
SpdkPtr spdk_buff;
size_t spdk_buff_size;
size_t last_read_size;
SpdkCsum(SpdkQpair *qp)
: SpdkOp(qp),
bytes_read_(0),
spdk_buff_size(4096),
last_read_size(0) {
size_t buff_nlbas = spdk_buff_size / qp->get_sector_size();
assert(spdk_buff_size % qp->get_sector_size() == 0);
spdk_buff = std::move(qp->alloc_buffer(buff_nlbas));
if (spdk_buff.ptr_m == nullptr) {
fprintf(stderr, "rte_malloc failed\n");
exit(1);
}
assert(spdk_buff_size % sector_size_ == 0);
}
~SpdkCsum(void) {
if (spdk_buff.ptr_m)
qp_->free_buffer(std::move(spdk_buff));
}
bool finished(void) override {
//return bytes_read_ == sector_size_ * dev_sectors_;
return bytes_read_ == TOTAL_BYTES;
}
void op_done(void) override {
csum_.add((char *)spdk_buff.ptr_m, last_read_size);
bytes_read_ += last_read_size;
}
void submit_op() override {
uint64_t lba = bytes_read_ / sector_size_;
uint64_t bytes_remaining = (lba - dev_sectors_) * sector_size_;
uint64_t op_bytes = std::min(spdk_buff_size, bytes_remaining);
assert(op_bytes % sector_size_ == 0);
//printf("submitting (read:%lu)\n", bytes_read_);
last_read_size = op_bytes;
qp_->submit_read(spdk_buff, lba, op_bytes / sector_size_, callback_, this);
}
};
XorCsum spdk_xor_checksum() {
SpdkGlobalState sg;
sg.init();
SpdkState spdk(sg);
auto qp = spdk.getQpair(std::string());
if (qp == nullptr) {
fprintf(stderr, "did not find queue pair\n");
abort();
}
printf("dev_sectors: %zd\n", qp->sqp_namespace->get_nsectors());
printf("sector_size: %u\n", qp->sqp_namespace->get_sector_size());
// execute write operations
SpdkWrite wr(qp.get(), TOTAL_BYTES);
wr.run_op();
// execute read operations
SpdkCsum rd(qp.get());
rd.run_op();
if (wr.csum_ != rd.csum_) {
fprintf(stderr, "%s: checksums differ!\n", __PRETTY_FUNCTION__);
fprintf(stderr, "Write: len=%lu csum=%lu\n", wr.csum_.len, wr.csum_.csum);
fprintf(stderr, "Read : len=%lu csum=%lu\n", rd.csum_.len, rd.csum_.csum);
}
spdk.stop();
return rd.csum_;
}
XorCsum file_xor_checksum(const char *device) {
uint64_t bytes_read;
char buff[4096];
XorCsum csum;
int fd = open(device, O_RDONLY /* | O_DIRECT */);
if (fd == -1) {
perror(device);
exit(1);
}
bytes_read = 0;
while (bytes_read != TOTAL_BYTES) {
int r = read(fd, buff, sizeof(buff));
if (r == 0) {
break;
} else if (r < 0) {
perror("read");
abort();
}
csum.add(buff, r);
bytes_read += r;
}
return csum;
}
void usage(FILE *f) {
fprintf(f, "-f filename: filename to use\n");
//fprintf(f, "-l length of file to use\n");
fprintf(f, "-s Use spdk\n");
}
int main(int argc, char *argv[]) {
int opt;
XorCsum x;
char *filename = (char *)(uintptr_t)-1;
//size_t len = TOTAL_BYTES;
while ((opt = getopt(argc, argv, "f:l:s")) != -1) {
switch (opt) {
case 'f':
filename = optarg;
break;
/*
case 'l':
len = atol(optarg);
break;
*/
case 's':
filename = NULL;
break;
default:
usage(stderr);
exit(1);
}
}
if (filename == (char *)(uintptr_t)-1) {
usage(stdout);
exit(0);
} else if (filename) {
x = file_xor_checksum(filename);
} else {
x = spdk_xor_checksum();
}
printf("csum:%lu len:%lu\nTerminating normally.\n", x.csum, x.len);
return 0;
}
| 24.373737 | 83 | 0.571764 | [
"vector"
] |
6b3cdc06679beb2be665571a047087377979598b | 9,478 | cpp | C++ | src/bindings/Main.cpp | FabianTerhorst/altv-js-module | 3585b56a31cfa108e00f17058c7943c398b65931 | [
"MIT"
] | 1 | 2020-06-01T23:53:29.000Z | 2020-06-01T23:53:29.000Z | src/bindings/Main.cpp | FabianTerhorst/altv-js-module | 3585b56a31cfa108e00f17058c7943c398b65931 | [
"MIT"
] | null | null | null | src/bindings/Main.cpp | FabianTerhorst/altv-js-module | 3585b56a31cfa108e00f17058c7943c398b65931 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "helpers/V8Module.h"
#include "CNodeResourceImpl.h"
using namespace alt;
static void OnClient(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 2, "2 args expected");
V8_CHECK(info[0]->IsString(), "string expected");
V8_CHECK(info[1]->IsFunction(), "function expected");
V8ResourceImpl* resource = V8ResourceImpl::Get(isolate->GetEnteredContext());
V8_CHECK(resource, "invalid resource");
v8::String::Utf8Value evName(isolate, info[0]);
resource->SubscribeRemote(*evName, info[1].As<v8::Function>(), V8::SourceLocation::GetCurrent(isolate));
}
static void OffClient(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 2, "2 args expected");
V8_CHECK(info[0]->IsString(), "string expected");
V8_CHECK(info[1]->IsFunction(), "function expected");
V8ResourceImpl* resource = V8ResourceImpl::Get(isolate->GetEnteredContext());
V8_CHECK(resource, "invalid resource");
v8::String::Utf8Value evName(isolate, info[0]);
resource->UnsubscribeRemote(*evName, info[1].As<v8::Function>());
}
static void EmitClient(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() >= 2, "at least 2 args expected");
V8_CHECK(info[0]->IsObject() || info[0]->IsNull(), "player or null expected");
V8_CHECK(info[1]->IsString(), "string expected");
V8ResourceImpl* resource = V8ResourceImpl::Get(isolate->GetEnteredContext());
V8_CHECK(resource, "invalid resource");
v8::String::Utf8Value evName(isolate, info[1]);
Ref<IPlayer> player;
if (!info[0]->IsNull())
{
V8Entity* v8Player = V8Entity::Get(info[0]);
V8_CHECK(v8Player && v8Player->GetHandle()->GetType() == alt::IBaseObject::Type::PLAYER, "player or null expected");
player = v8Player->GetHandle().As<IPlayer>();
}
MValueArgs mvArgs;
for (int i = 2; i < info.Length(); ++i)
mvArgs.Push(V8Helpers::V8ToMValue(info[i]));
ICore::Instance().TriggerClientEvent(player, *evName, mvArgs);
}
static void SetSyncedMeta(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 2, "2 args expected");
v8::Local<v8::String> key = info[0]->ToString(isolate);
alt::ICore::Instance().SetSyncedMetaData(*v8::String::Utf8Value(isolate, key), V8Helpers::V8ToMValue(info[1]));
}
static void DeleteSyncedMeta(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
v8::Local<v8::String> key = info[0]->ToString(isolate);
alt::ICore::Instance().DeleteSyncedMetaData(*v8::String::Utf8Value(isolate, key));
}
static void GetPlayersByName(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
Log::Warning << "alt.getPlayersByName is deprecated and will be removed in future versions, "
<< "consider using alt.Player.all.filter(p => p.name == name)" << Log::Endl;
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
V8ResourceImpl* resource = V8ResourceImpl::Get(isolate->GetEnteredContext());
V8_CHECK(resource, "invalid resource");
v8::String::Utf8Value name(isolate, info[0]);
alt::Array<Ref<alt::IPlayer>> players = alt::ICore::Instance().GetPlayersByName(*name);
v8::Local<v8::Array> arr = v8::Array::New(isolate, players.GetSize());
for (uint32_t i = 0; i < players.GetSize(); ++i)
{
arr->Set(i, resource->GetOrCreateEntity(players[i].Get(), "Player")->GetJSVal());
}
info.GetReturnValue().Set(arr);
}
static void GetNetTime(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8ResourceImpl* resource = V8ResourceImpl::Get(isolate->GetEnteredContext());
V8_CHECK(resource, "invalid resource");
uint32_t netTime = alt::ICore::Instance().GetNetTime();
info.GetReturnValue().Set(v8::Integer::NewFromUnsigned(isolate, netTime));
}
static void StartResource(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
v8::String::Utf8Value name(isolate, info[0]);
alt::ICore::Instance().StartResource(*name);
}
static void StopResource(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
v8::String::Utf8Value name(isolate, info[0]);
alt::ICore::Instance().StopResource(*name);
}
static void RestartResource(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
v8::String::Utf8Value name(isolate, info[0]);
alt::ICore::Instance().RestartResource(*name);
}
static void GetResourceMain(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
v8::String::Utf8Value name(isolate, info[0]);
alt::IResource* resource = alt::ICore::Instance().GetResource(*name);
if (resource)
info.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, resource->GetMain().CStr()));
}
static void GetResourcePath(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
v8::String::Utf8Value name(isolate, info[0]);
alt::IResource* resource = alt::ICore::Instance().GetResource(*name);
if (resource)
info.GetReturnValue().Set(v8::String::NewFromUtf8(isolate, resource->GetPath().CStr()));
}
static void HasResource(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
v8::String::Utf8Value name(isolate, info[0]);
alt::IResource* resource = alt::ICore::Instance().GetResource(*name);
if (resource && resource->IsStarted())
info.GetReturnValue().Set(v8::True(isolate));
else
info.GetReturnValue().Set(v8::False(isolate));
}
static void GetResourceExports(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 1, "1 arg expected");
V8_CHECK(info[0]->IsString(), "string expected");
V8ResourceImpl* resource = V8ResourceImpl::Get(isolate->GetEnteredContext());
V8_CHECK(resource, "invalid resource");
v8::String::Utf8Value name(isolate, info[0]);
alt::IResource* _resource = alt::ICore::Instance().GetResource(*name);
if (_resource)
{
v8::Local<v8::Value> exports = V8Helpers::MValueToV8(_resource->GetExports());
info.GetReturnValue().Set(exports);
}
}
static void ResourceLoaded(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
V8_CHECK(info.Length() == 2, "2 args expected");
V8_CHECK(info[0]->IsString(), "string expected");
v8::String::Utf8Value name(isolate, info[0]);
alt::IResource* resource = alt::ICore::Instance().GetResource(*name);
if (resource && resource->GetType() == "js")
{
CNodeResourceImpl* _resource = static_cast<CNodeResourceImpl*>(resource->GetImpl());
_resource->Started(info[1]);
}
}
static V8Module v8Alt("alt",
{
"Vector3",
"RGBA",
"File",
"BaseObject",
"WorldObject",
"Entity",
"Player",
"Vehicle",
"Blip",
"PointBlip",
"Checkpoint",
"VoiceChannel",
"Colshape",
"ColshapeCylinder",
"ColshapeSphere",
"ColshapeCircle",
"ColshapeCuboid",
"ColshapeRectangle"
},
[](v8::Local<v8::Context> ctx, v8::Local<v8::Object> exports) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
V8::RegisterSharedMain(ctx, exports);
V8Helpers::RegisterFunc(exports, "getResourceMain", &GetResourceMain);
V8Helpers::RegisterFunc(exports, "getResourcePath", &GetResourcePath);
V8Helpers::RegisterFunc(exports, "resourceLoaded", &ResourceLoaded);
V8Helpers::RegisterFunc(exports, "hasResource", &HasResource);
V8Helpers::RegisterFunc(exports, "getResourceExports", &GetResourceExports);
V8Helpers::RegisterFunc(exports, "startResource", &StartResource);
V8Helpers::RegisterFunc(exports, "stopResource", &StopResource);
V8Helpers::RegisterFunc(exports, "restartResource", &RestartResource);
V8Helpers::RegisterFunc(exports, "onClient", &OnClient);
V8Helpers::RegisterFunc(exports, "offClient", &OffClient);
V8Helpers::RegisterFunc(exports, "emitClient", &EmitClient);
V8Helpers::RegisterFunc(exports, "setSyncedMeta", &SetSyncedMeta);
V8Helpers::RegisterFunc(exports, "deleteSyncedMeta", &DeleteSyncedMeta);
V8Helpers::RegisterFunc(exports, "getPlayersByName", &GetPlayersByName);
V8Helpers::RegisterFunc(exports, "getNetTime", &GetNetTime);
alt::StringView rootDir = alt::ICore::Instance().GetRootDirectory();
exports->Set(isolate->GetEnteredContext(), v8::String::NewFromUtf8(isolate, "rootDir"), v8::String::NewFromUtf8(isolate, rootDir.CStr()));
alt::IResource* resource = V8ResourceImpl::GetResource(ctx);
V8_CHECK(resource, "invalid resource");
exports->Set(isolate->GetEnteredContext(), v8::String::NewFromUtf8(isolate, "resourceName"), v8::String::NewFromUtf8(isolate, resource->GetName().CStr()));
});
| 31.488372 | 156 | 0.715446 | [
"object"
] |
6b4b5f39a4f9c756190f8e81d130d3beaec74b01 | 20,618 | cpp | C++ | device_support/raptor/cygnet.cpp | zack-vii/mdsplus | 7c631281d22e993599dbdf7bd31782035af92688 | [
"BSD-2-Clause"
] | 1 | 2019-09-02T13:40:23.000Z | 2019-09-02T13:40:23.000Z | device_support/raptor/cygnet.cpp | zack-vii/mdsplus | 7c631281d22e993599dbdf7bd31782035af92688 | [
"BSD-2-Clause"
] | 4 | 2019-10-29T09:06:32.000Z | 2020-03-26T22:09:39.000Z | device_support/raptor/cygnet.cpp | zack-vii/mdsplus | 7c631281d22e993599dbdf7bd31782035af92688 | [
"BSD-2-Clause"
] | 2 | 2019-10-29T08:54:27.000Z | 2020-05-18T09:59:39.000Z | /*
Copyright (c) 2017, Massachusetts Institute of Technology 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.
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.
*/
#define FORMATFILE "/home/mdsplus/cygnet.dat"
#define FORMAT "default" // NSTC S-Video on input 1
#define UNITS 1
#define UNITSMAP ((1<<UNITS)-1) // shorthand - bitmap of all units
#define DRIVERPARMS "" // default
//#undef DEBUG
#include <math.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <stdarg.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <poll.h>
#include <time.h>
#include <sys/time.h>
#include <xcliball.h> // driver function prototypes
#include <cammdsutils.h> //Camera MDSplus support
#include "cygnet.h"
#ifdef DEBUG
static void printFrameInfo(void);
static void printImageInfo(void);
#endif
static bool isOpen = false;
static double dSecPerTick = 1E-3;
/*
* SUPPORT STUFF:
*
* Catch CTRL+C and floating point exceptions so that
* once opened, the PIXCI(R) driver and frame grabber
* are always closed before exit.
* In most environments, this isn't critical; the operating system
* advises the PIXCI(R) driver that the program has terminated.
* In other environments, such as DOS, the operating system
* isn't as helpful and the driver & frame grabber would remain open.
*/
void sigintfunc(int sig)
{
/*
* Some languages/environments don't allow
* use of printf from a signal catcher.
* Printing the message isn't important anyhow.
*
if (sig == SIGINT)
printf("Break\n");
if (sig == SIGFPE)
printf("Float\n");
*/
pxd_PIXCIclose();
exit(1);
}
/*
* Video 'interrupt' callback function.
*/
static int fieldirqcount = 0;
static void videoirqfunc(int sig)
{
fieldirqcount++;
}
/*
* Open the XCLIB C Library for use.
*/
int epixOpen(char *pcConfFile)
{
int status;
if(isOpen) return 0;
#ifdef DEBUG
printf("Opening EPIX(R) PIXCI(R) Frame Grabber,\n");
printf("using configuration parameters '%s',\n", DRIVERPARMS? DRIVERPARMS: "default");
#endif
status = pxd_PIXCIopen(DRIVERPARMS, "", pcConfFile); // ConfFile includes exposure time which seems to take precedence over later serial commands
if (status >= 0)
{
#ifdef DEBUG
printf("Open OK\n");
#endif
isOpen = true;
}
else
{
printf("Open Error %d\a\a\n", status);
pxd_mesgFault(UNITSMAP);
return status;
}
#ifdef DEBUG
printFrameInfo();
printImageInfo();
#endif
uint32 ticku[2];
if(pxd_infoSysTicksUnits(ticku) == 0)
{
dSecPerTick = (double)ticku[0] / (double)ticku[1] * 1E-6;
#ifdef DEBUG
printf("Microseconds per tick: %f\n", dSecPerTick * 1E6);
#endif
}
return status;
}
void epixClose(void)
{
pxd_PIXCIclose();
isOpen = false;
}
#ifdef DEBUG
/*
* Report image frame buffer memory size
*/
static void printFrameInfo(void)
{
printf("Image frame buffer memory size: %.3f Kbytes\n", (double)pxd_infoMemsize(UNITSMAP)/1024);
printf("Image frame buffers : %d\n", pxd_imageZdim());
printf("Number of boards : %d\n", pxd_infoUnits());
}
/*
* Report image resolution.
*/
static void printImageInfo(void)
{
printf("Image resolution:\n");
printf("xdim = %d\n", pxd_imageXdim());
printf("ydim = %d\n", pxd_imageYdim());
printf("colors = %d\n", pxd_imageCdim());
printf("bits per pixel = %d\n", pxd_imageCdim()*pxd_imageBdim());
}
#endif
/*
* Capture
*/
void epixStartVideoCapture(int iID)
{
pxd_goLivePair(iID, 1, 2); // should iID be converted to a unitmap?
#ifdef DEBUG
printf("Video capture started.\n");
#endif
}
void epixStopVideoCapture(int iID)
{
pxd_goUnLive(iID); // should iID be converted to a unitmap?
#ifdef DEBUG
printf("Video capture stopped.\n");
#endif
}
//Capture either a single frame or timeouts.
//Returns 1 on capture and 0 on timeout
//Return the tick count of the last frame or the passed baseTicks in case of timeout
//iID: device iID (1)
//dataNid: nid number of target data node
//timeNid: nid number of associated timestamp node. If -1, the time is put directly in the segmented data, else a reference to the timebase is put
//timeoutMs: timeout in milliseconds
//*treePtr: pointer to Tree object
//*listPtr: pointer to Internal List object for saving frames
//*bufIdx: index of the last captured frame grabber buffer (initialize with -1 !!!)
//*frameIdx: frame index (from 0 onwards)
//*baseTicks: last 32 bits of system time when the first frame has been taken
//*currtime: returns time since reference t=0
int epixCaptureFrame(int iID, int iFramesNid, double dTriggerTime, int iTimeoutMs, void *pTree, void *pList, int *piBufIdx, int *piFrameIdx, int *piBaseTicks, double *pdCurrTime)
{
int iUnitMap = 1 << (iID - 1);
int iLastBufIdx, iCurrTicks;
int iPixelsRead, iPixelsToRead, iPixelsX, iPixelsY;
struct timespec waitTime;
pxbuffer_t lastbuf = 0;
iPixelsX = pxd_imageXdim();
iPixelsY = pxd_imageYdim();
iPixelsToRead = iPixelsX * iPixelsY;
waitTime.tv_sec = 0;
waitTime.tv_nsec = 5000000; //5ms delay
if(*piBufIdx < 0)
{
iLastBufIdx = pxd_capturedBuffer(iUnitMap); //The first time captureFrame is called
*piFrameIdx = 0;
}
else
iLastBufIdx = *piBufIdx;
int iMaxCount = iTimeoutMs/5; //Maximum number of iterations before timing out
for(int i = 0; i < iMaxCount; i++)
{
int iLastCaptured = pxd_capturedBuffer(iUnitMap);
if(iLastCaptured != iLastBufIdx) //A new frame arrived
{
iCurrTicks = pxd_capturedSysTicks(iUnitMap);//internal clock
if ( *piFrameIdx == 0) //first frame
*piBaseTicks = iCurrTicks;
*pdCurrTime = (iCurrTicks - (*piBaseTicks)) * dSecPerTick + dTriggerTime;
unsigned short *piFrame = new unsigned short[iPixelsToRead];//allocate frame
iPixelsRead = pxd_readushort(iUnitMap, iLastCaptured, 0, 0, iPixelsX, iPixelsY, piFrame, iPixelsToRead, (char *)"Grey");//get frame
#ifdef DEBUG
printf("FRAME %d READ AT TIME %f\n", *piFrameIdx, *pdCurrTime);
#endif
if(iPixelsRead != iPixelsToRead)
{
if (iPixelsRead < 0)
printf("pxd_readushort: %s\n", pxd_mesgErrorCode(iPixelsRead));
else
printf("pxd_readushort error: %d != %d\n", iPixelsRead, iPixelsToRead);
return 0;
}
camSaveFrameDirect(piFrame, iPixelsX, iPixelsY, *pdCurrTime, 12, pTree, iFramesNid, -1, *piFrameIdx, pList);
*piBufIdx = iLastCaptured;
*piFrameIdx += 1;
return 1;
}
else //No new frame
nanosleep(&waitTime, NULL);
}
//If code arrives here timeout occurred
return 0;
}
int doTransaction(int iID, const char *pcOutBufIn, int iOutBytes, char *pcReadBuf, int iBytesToRead)
{
int iBytesRead;
int iUnitMap = 1 << (iID-1);
struct timespec waitTime;
static bool isInitialized = false;
char *pcOutBuf = new char[iOutBytes+1];
pcOutBuf[iOutBytes] = 0;
for(int i = 0; i < iOutBytes; i++)
{
pcOutBuf[i] = pcOutBufIn[i];
pcOutBuf[iOutBytes] ^= pcOutBuf[i];
}
waitTime.tv_sec = 0;
waitTime.tv_nsec = 20000000; //20ms
if(!isInitialized)
{
iBytesRead = pxd_serialConfigure(iUnitMap, 0, 115200, 8, 0, 1, 0, 0, 0);
if (iBytesRead < 0)
{
printf("ERROR CONFIGURING SERIAL CAMERALINK PORT\n");
return iBytesRead; // error
}
isInitialized = true;
}
nanosleep(&waitTime, NULL);
iBytesRead = pxd_serialWrite(iUnitMap, 0, pcOutBuf, iOutBytes+1);
if (iBytesRead < 0)
{
printf("ERROR IN SERIAL WRITE\n");
return iBytesRead; // error
}
nanosleep(&waitTime, NULL);
iBytesRead = pxd_serialRead(iUnitMap, 0, pcReadBuf, iBytesToRead);
if (iBytesRead < 0)
printf("ERROR IN SERIAL READ\n");
else if(iBytesRead != iBytesToRead)
printf("ERROR IN SERIAL READ: LESS BYTES READ THAN EXPECTED %d %d\n", iBytesRead, iBytesToRead);
return iBytesRead;
}
short epixGetCMOSTemp(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xF3, 0x7E, 0x50};
const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0x72, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf5[] = {0x53, 0xE0, 0x02, 0xF3, 0x7F, 0x50};
const char queryBuf6[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50};
const char queryBuf7[] = {0x53, 0xE0, 0x01, 0x73, 0x50};
const char queryBuf8[] = {0x53, 0xE1, 0x01, 0x50};
short sTemp = 0;
char cRetBuf[2];
doTransaction(iID, queryBuf1, 6, cRetBuf, 1);
doTransaction(iID, queryBuf2, 6, cRetBuf, 1);
doTransaction(iID, queryBuf3, 5, cRetBuf, 1);
doTransaction(iID, queryBuf4, 4, cRetBuf, 2);
sTemp = (cRetBuf[0] & 0x00FF);
doTransaction(iID, queryBuf5, 6, cRetBuf, 1);
doTransaction(iID, queryBuf6, 6, cRetBuf, 1);
doTransaction(iID, queryBuf7, 5, cRetBuf, 1);
doTransaction(iID, queryBuf8, 4, cRetBuf, 2);
sTemp |= (cRetBuf[0] & 0x00FF) << 8;
return sTemp;
}
short epixGetPCBTemp(int iID)
{
// const char queryBuf[] = {0x4F, 0x56, 0x50};
const char queryBuf1[] = {0x53, 0xE0, 0x02, 0x70, 0x00, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x02, 0x71, 0x00, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
short sTemp = 0;
char cRetBuf[2];
//doTransaction(iID, queryBuf, 3, cRetBuf, 2);
doTransaction(iID, queryBuf1, 6, cRetBuf, 1);
doTransaction(iID, queryBuf2, 4, cRetBuf, 2);
sTemp = (cRetBuf[0] & 0x3) << 8;
doTransaction(iID, queryBuf3, 6, cRetBuf, 1);
doTransaction(iID, queryBuf4, 4, cRetBuf, 2);
sTemp |= (cRetBuf[0] & 0x00FF);
return sTemp;
}
static double getFrameRate(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xDD, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xDE, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf5[] = {0x53, 0xE0, 0x01, 0xDF, 0x50};
const char queryBuf6[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf7[] = {0x53, 0xE0, 0x01, 0xE0, 0x50};
const char queryBuf8[] = {0x53, 0xE1, 0x01, 0x50};
int iFrameRate = 0;
char cRetBuf[3];
doTransaction(iID, queryBuf1, 5, cRetBuf, 2);
doTransaction(iID, queryBuf2, 4, cRetBuf, 3);
iFrameRate |= ((cRetBuf[0] & 0x000000FF) << 24);
doTransaction(iID, queryBuf3, 5, cRetBuf, 2);
doTransaction(iID, queryBuf4, 4, cRetBuf, 3);
iFrameRate |= ((cRetBuf[0] & 0x000000FF) << 16);
doTransaction(iID, queryBuf5, 5, cRetBuf, 2);
doTransaction(iID, queryBuf6, 4, cRetBuf, 3);
iFrameRate |= ((cRetBuf[0] & 0x000000FF) << 8);
doTransaction(iID, queryBuf7, 5, cRetBuf, 2);
doTransaction(iID, queryBuf8, 4, cRetBuf, 3);
iFrameRate |= (cRetBuf[0] & 0x000000FF);
return (double)iFrameRate / 6E7;
}
static void setFrameRate(int iID, double dFrameRate)
{
int iFrameRate = fabs(6E7 * dFrameRate);
const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xDD, (iFrameRate & 0xFF000000) >> 24, 0x50};
const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xDE, (iFrameRate & 0x00FF0000) >> 16, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x02, 0xDF, (iFrameRate & 0x0000FF00) >> 8, 0x50};
const char queryBuf4[] = {0x53, 0xE0, 0x02, 0xE0, (iFrameRate & 0x000000FF), 0x50};
char cRetBuf[1];
doTransaction(iID, queryBuf1, 6, cRetBuf, 1);
doTransaction(iID, queryBuf2, 6, cRetBuf, 1);
doTransaction(iID, queryBuf3, 6, cRetBuf, 1);
doTransaction(iID, queryBuf4, 6, cRetBuf, 1);
}
static double getExposure(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xED, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xEE, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf5[] = {0x53, 0xE0, 0x01, 0xEF, 0x50};
const char queryBuf6[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf7[] = {0x53, 0xE0, 0x01, 0xF0, 0x50};
const char queryBuf8[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf9[] = {0x53, 0xE0, 0x01, 0xF1, 0x50};
const char queryBuf10[]= {0x53, 0xE1, 0x01, 0x50};
long lExposure = 0;
char cRetBuf[2];
doTransaction(iID, queryBuf1, 5, cRetBuf, 1);
doTransaction(iID, queryBuf2, 4, cRetBuf, 2);
lExposure |= ((cRetBuf[0] & 0x00000000000000FFL) << 32);
doTransaction(iID, queryBuf3, 5, cRetBuf, 1);
doTransaction(iID, queryBuf4, 4, cRetBuf, 2);
lExposure |= ((cRetBuf[0] & 0x000000FF) << 24);
doTransaction(iID, queryBuf5, 5, cRetBuf, 1);
doTransaction(iID, queryBuf6, 4, cRetBuf, 2);
lExposure |= ((cRetBuf[0] & 0x000000FF) << 16);
doTransaction(iID, queryBuf7, 5, cRetBuf, 1);
doTransaction(iID, queryBuf8, 4, cRetBuf, 2);
lExposure |= ((cRetBuf[0] & 0x000000FF) << 8);
doTransaction(iID, queryBuf9, 5, cRetBuf, 1);
doTransaction(iID, queryBuf10,4, cRetBuf, 2);
lExposure |= (cRetBuf[0] & 0x000000FF);
return (double)lExposure / 6E4;
}
static void setExposure(int iID, double dExposureMs)
{
long lExposure = fabs(6E4 * dExposureMs);//60MHz: 1E6/16.6666 = 6e4
// long lExposure = fabs(6E7 * dExposure);
const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xED, (lExposure & 0x000000FF00000000L) >> 32, 0x50};
const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xEE, (lExposure & 0xFF000000) >> 24, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x02, 0xEF, (lExposure & 0x00FF0000) >> 16, 0x50};
const char queryBuf4[] = {0x53, 0xE0, 0x02, 0xF0, (lExposure & 0x0000FF00) >> 8, 0x50};
const char queryBuf5[] = {0x53, 0xE0, 0x02, 0xF1, (lExposure & 0x000000FF), 0x50};
char cRetBuf[1];
doTransaction(iID, queryBuf1, 6, cRetBuf, 1);
doTransaction(iID, queryBuf2, 6, cRetBuf, 1);
doTransaction(iID, queryBuf3, 6, cRetBuf, 1);
doTransaction(iID, queryBuf4, 6, cRetBuf, 1);
}
static float getGain(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD5, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xD6, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
short sGain = 0;
char cRetBuf[3];
doTransaction(iID, queryBuf1, 5, cRetBuf, 2);
doTransaction(iID, queryBuf2, 4, cRetBuf, 3);
sGain |= ((cRetBuf[0] & 0x00FF) << 8);
doTransaction(iID, queryBuf3, 5, cRetBuf, 2);
doTransaction(iID, queryBuf4, 4, cRetBuf, 3);
sGain |= (cRetBuf[0] & 0x00FF);
return sGain/512.;
}
static char getTrigMode(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD4, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
char cRetBuf[3];
doTransaction(iID, queryBuf1, 5, cRetBuf, 2);
doTransaction(iID, queryBuf2, 4, cRetBuf, 3);
return cRetBuf[0];
}
static void setTrigMode(int iID, char cTrigMode)
{
const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xD4, cTrigMode, 0x50};
char cRetBuf[1];
doTransaction(iID, queryBuf1, 6, cRetBuf, 1);
}
static char getBinning(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xDB, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
char cRetBuf[2];
doTransaction(iID, queryBuf1, 5, cRetBuf, 1);
doTransaction(iID, queryBuf2, 4, cRetBuf, 2);
return cRetBuf[0];
}
static short getRoiXSize(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD7, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xD8, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
short sSize = 0;
char cRetBuf[2];
doTransaction(iID, queryBuf1, 5, cRetBuf, 1);
doTransaction(iID, queryBuf2, 4, cRetBuf, 2);
sSize |= ((cRetBuf[0] & 0x000F) << 8);
doTransaction(iID, queryBuf3, 5, cRetBuf, 1);
doTransaction(iID, queryBuf4, 4, cRetBuf, 2);
sSize |= (cRetBuf[0] & 0x00FF);
return sSize;
}
static short getRoiXOffset(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x01, 0xD9, 0x50};
const char queryBuf2[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0xDA, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
short sOffset = 0;
char cRetBuf[2];
doTransaction(iID, queryBuf1, 5, cRetBuf, 1);
doTransaction(iID, queryBuf2, 4, cRetBuf, 2);
sOffset |= ((cRetBuf[0] & 0x000F) << 8);
doTransaction(iID, queryBuf3, 5, cRetBuf, 1);
doTransaction(iID, queryBuf4, 4, cRetBuf, 2);
sOffset |= (cRetBuf[0] & 0x00FF);
return sOffset;
}
static short getRoiYSize(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xF3, 0x01, 0x50};
const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0x73, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf5[] = {0x53, 0xE0, 0x02, 0xF3, 0x02, 0x50};
const char queryBuf6[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50};
const char queryBuf7[] = {0x53, 0xE0, 0x01, 0x73, 0x50};
const char queryBuf8[] = {0x53, 0xE1, 0x01, 0x50};
short sSize = 0;
char cRetBuf[2];
doTransaction(iID, queryBuf1, 6, cRetBuf, 1);
doTransaction(iID, queryBuf2, 6, cRetBuf, 1);
doTransaction(iID, queryBuf3, 5, cRetBuf, 1);
doTransaction(iID, queryBuf4, 4, cRetBuf, 2);
sSize |= (cRetBuf[0] & 0x00FF);
doTransaction(iID, queryBuf5, 6, cRetBuf, 1);
doTransaction(iID, queryBuf6, 6, cRetBuf, 1);
doTransaction(iID, queryBuf7, 5, cRetBuf, 1);
doTransaction(iID, queryBuf8, 4, cRetBuf, 2);
sSize |= ((cRetBuf[0] & 0x000F) << 8);
return sSize;
}
static short getRoiYOffset(int iID)
{
const char queryBuf1[] = {0x53, 0xE0, 0x02, 0xF3, 0x03, 0x50};
const char queryBuf2[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50};
const char queryBuf3[] = {0x53, 0xE0, 0x01, 0x73, 0x50};
const char queryBuf4[] = {0x53, 0xE1, 0x01, 0x50};
const char queryBuf5[] = {0x53, 0xE0, 0x02, 0xF3, 0x04, 0x50};
const char queryBuf6[] = {0x53, 0xE0, 0x02, 0xF4, 0x00, 0x50};
const char queryBuf7[] = {0x53, 0xE0, 0x01, 0x73, 0x50};
const char queryBuf8[] = {0x53, 0xE1, 0x01, 0x50};
short sSize = 0;
char cRetBuf[2];
doTransaction(iID, queryBuf1, 6, cRetBuf, 1);
doTransaction(iID, queryBuf2, 6, cRetBuf, 1);
doTransaction(iID, queryBuf3, 5, cRetBuf, 1);
doTransaction(iID, queryBuf4, 4, cRetBuf, 2);
sSize |= (cRetBuf[0] & 0x00FF);
doTransaction(iID, queryBuf5, 6, cRetBuf, 1);
doTransaction(iID, queryBuf6, 6, cRetBuf, 1);
doTransaction(iID, queryBuf7, 5, cRetBuf, 1);
doTransaction(iID, queryBuf8, 4, cRetBuf, 2);
sSize |= ((cRetBuf[0] & 0x000F) << 8);
return sSize;
}
void epixSetConfiguration(int iID, double dFrameRate, char cTrigMode)
{
setFrameRate(iID, dFrameRate);
setTrigMode(iID, cTrigMode);
}
void epixGetConfiguration(int iID, char *pcBinning, short *psRoiXSize, short *psRoiXOffset, short *psRoiYSize, short *psRoiYOffset)
{
*pcBinning = getBinning(iID);
*psRoiXSize = getRoiXSize(iID);
*psRoiXOffset = getRoiXOffset(iID);
*psRoiYSize = getRoiYSize(iID);
*psRoiYOffset = getRoiYOffset(iID);
#ifdef DEBUG
printf("EXPOSURE READ AS %f\n", getExposure(iID));
#endif
}
void epixGetTemp(int iID, float *pfPcbTemp, short *psCmosTemp)
{
*pfPcbTemp = epixGetPCBTemp(iID)/16.;
*psCmosTemp = epixGetCMOSTemp(iID);
} | 34.827703 | 178 | 0.664516 | [
"object"
] |
6b51c30a54f2f387d4b4d2572e95ac094914a898 | 151 | hpp | C++ | engine/include/Graphic/Transform.hpp | BigETI/NoLifeNoCry | 70ac2498b5e740b2b348771ef9617dea1eed7f9c | [
"MIT"
] | 5 | 2020-11-07T23:38:48.000Z | 2021-12-07T11:03:22.000Z | engine/include/Graphic/Transform.hpp | BigETI/NoLifeNoCry | 70ac2498b5e740b2b348771ef9617dea1eed7f9c | [
"MIT"
] | null | null | null | engine/include/Graphic/Transform.hpp | BigETI/NoLifeNoCry | 70ac2498b5e740b2b348771ef9617dea1eed7f9c | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Graphics/Transform.hpp>
namespace DirtMachine::Graphic
{
// TODO: Make better API!
using Transform = sf::Transform;
}
| 13.727273 | 38 | 0.728477 | [
"transform"
] |
6b51f109b1f249c63a28c2d7be573884130e3cfe | 503 | cpp | C++ | src/2000/2252.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | 8 | 2018-04-12T15:54:09.000Z | 2020-06-05T07:41:15.000Z | src/2000/2252.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | src/2000/2252.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> adj[32001];
int in[32001];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
while (m--)
{
int a, b;
cin >> a >> b;
adj[a].push_back(b);
in[b]++;
}
queue<int> Q;
for (int i = 1; i <= n; i++)
if (in[i] == 0) Q.push(i);
while (Q.size())
{
int cur = Q.front();
cout << cur << " ";
Q.pop();
for (int i : adj[cur])
{
if (!--in[i])
Q.push(i);
}
}
} | 13.972222 | 30 | 0.50497 | [
"vector"
] |
6b56f1d523a79881cde8afdb92330d8a93b9069f | 11,031 | cpp | C++ | Parser/Parser.cpp | ronchauhan/scil | e3644c55decc46a09a773a9e4598ac277bd898b1 | [
"MIT"
] | null | null | null | Parser/Parser.cpp | ronchauhan/scil | e3644c55decc46a09a773a9e4598ac277bd898b1 | [
"MIT"
] | null | null | null | Parser/Parser.cpp | ronchauhan/scil | e3644c55decc46a09a773a9e4598ac277bd898b1 | [
"MIT"
] | null | null | null | #include "Parser/Parser.h"
#include "IR/CFG.h"
#include "IR/Instruction.h"
#include <cassert>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
void Parser::parseFile() {
std::ifstream file(fileName);
std::string instString;
std::vector<Token> tokens;
unsigned lineNo = 1;
while (std::getline(file, instString)) {
tokenizeInstString(instString, tokens);
if (tokens.empty()) {
++lineNo;
continue;
}
bool success = parseInstruction(tokens);
if (!success) {
errGlobalState = true;
std::cerr << "Error in parsing line " << lineNo << '\n';
}
++lineNo;
tokens.clear();
}
}
bool Parser::isValidCharacter(char c) const {
return std::isspace(c) || std::isalnum(c) || c == '=' || c == ',' ||
c == '.' || c == '>' || c == '<';
}
bool Parser::tryRecognizeOpCode(Token &token) {
if (token.string.length() != 3 && token.string.length() != 2)
return false;
if (token.string == "add")
token.kind = Token::Add;
else if (token.string == "sub")
token.kind = Token::Sub;
else if (token.string == "mul")
token.kind = Token::Mul;
else if (token.string == "div")
token.kind = Token::Div;
else if (token.string == "jmp")
token.kind = Token::Jmp;
else if (token.string == "br")
token.kind = Token::Br;
return token.isOpCode();
}
void Parser::tokenizeInstString(std::string instString,
std::vector<Token> &tokens) {
Token token;
int i = 0;
while (i < instString.length()) {
if (!isValidCharacter(instString[i])) {
token.kind = Token::Invalid;
token.string.push_back(instString[i]);
++i;
}
// whitespace
else if (std::isspace(instString[i])) {
while (std::isspace(instString[i]))
++i;
continue;
}
// identifier or opcode
else if (std::isalpha(instString[i])) {
token.kind = Token::Ident;
while (std::isalnum(instString[i])) {
token.string.push_back(instString[i]);
++i;
}
tryRecognizeOpCode(token);
}
else if (instString[i] == '=') {
token.kind = Token::Assign;
++i;
}
else if (instString[i] == '>') {
token.kind = Token::GreaterThan;
++i;
}
else if (instString[i] == '<') {
token.kind = Token::LessThan;
++i;
}
else if (instString[i] == ',') {
token.kind = Token::Comma;
++i;
}
else if (instString[i] == '.') {
token.kind = Token::Dot;
++i;
}
// integer literal
else if (std::isdigit(instString[i])) {
token.kind = Token::IntLiteral;
while (std::isdigit(instString[i])) {
token.string.push_back(instString[i]);
++i;
}
}
tokens.push_back(token);
token.clear();
}
}
bool Parser::parseInstruction(std::vector<Token> &tokens) {
switch (tokens[0].kind) {
case Token::Ident:
return parseDef(tokens);
case Token::Dot:
return parseLabelDef(tokens);
case Token::Br:
return parseBranchInst(tokens);
case Token::Jmp:
return parseJumpInst(tokens);
default:
return false;
}
}
bool Parser::parseLabelDef(std::vector<Token> &tokens) {
assert(tokens[0].kind == Token::Dot && "Expected Token::Dot");
if (tokens.size() != 2)
return false;
if (tokens[1].kind != Token::Ident)
return false;
if (!errGlobalState) {
Value labelName(Value::Label, tokens[1].string.c_str());
instList.emplace_back(new Instruction(Instruction::LabelDef, labelName));
}
return true;
}
bool Parser::parseDef(std::vector<Token> &tokens) {
assert(tokens[0].kind == Token::Ident && "Expected Token::Ident");
switch (tokens.size()) {
case 3:
return parseRegDef(tokens);
case 5:
return parseRelationalOpInst(tokens);
case 6:
return parseBinaryOpInst(tokens);
default:
return false;
}
}
bool Parser::parseRegDef(std::vector<Token> &tokens) {
assert(tokens.size() == 3 && "RegDef must have 3 tokens");
assert(tokens[0].kind == Token::Ident && "Expected Token::Ident");
if (tokens[1].kind != Token::Assign)
return false;
if (tokens[2].kind != Token::IntLiteral && tokens[2].kind != Token::Ident)
return false;
if (!errGlobalState) {
Value dest(Value::Register, tokens[0].string.c_str());
unsigned srcKind = tokens[2].kind;
Value src;
if (srcKind == Token::IntLiteral)
src = Value(Value::Immediate, std::stoll(tokens[2].string));
else
src = Value(Value::Register, tokens[2].string.c_str());
instList.emplace_back(new Instruction(Instruction::RegDef, dest, src));
}
return true;
}
unsigned Parser::getInstBinaryOpCode(unsigned tokenKind) const {
assert(tokenKind >= Token::Add && tokenKind <= Token::Div &&
"Expected a binary opcode");
switch (tokenKind) {
case Token::Add:
return Instruction::Add;
case Token::Sub:
return Instruction::Sub;
case Token::Mul:
return Instruction::Mul;
case Token::Div:
return Instruction::Div;
}
}
unsigned Parser::getInstRelationalOpCode(unsigned tokenKind) const {
assert(tokenKind >= Token::GreaterThan && tokenKind <= Token::LessThan &&
"Expected a relational opcode");
switch (tokenKind) {
case Token::GreaterThan:
return Instruction::Gt;
case Token::LessThan:
return Instruction::Lt;
}
}
bool Parser::parseBinaryOpInst(std::vector<Token> &tokens) {
assert(tokens.size() == 6 && "BinaryOp inst has 6 tokens");
assert(tokens[0].kind == Token::Ident && "Expected Token::Ident");
if (tokens[1].kind != Token::Assign)
return false;
if (!tokens[2].isBinaryOpCode())
return false;
if (tokens[3].kind != Token::Ident && tokens[3].kind != Token::IntLiteral)
return false;
if (tokens[4].kind != Token::Comma)
return false;
if (tokens[5].kind != Token::Ident && tokens[5].kind != Token::IntLiteral)
return false;
if (!errGlobalState) {
Value dest(Value::Register, tokens[0].string.c_str());
unsigned srcKind = tokens[3].kind;
Value src1;
if (srcKind == Token::IntLiteral)
src1 = Value(Value::Immediate, std::stoll(tokens[3].string));
else
src1 = Value(Value::Register, tokens[3].string.c_str());
srcKind = tokens[5].kind;
Value src2;
if (srcKind == Token::IntLiteral)
src2 = Value(Value::Immediate, std::stoll(tokens[5].string));
else
src2 = Value(Value::Register, tokens[5].string.c_str());
unsigned opCode = getInstBinaryOpCode(tokens[2].kind);
instList.emplace_back(new Instruction(opCode, dest, src1, src2));
}
return true;
}
bool Parser::parseRelationalOpInst(std::vector<Token> &tokens) {
assert(tokens.size() == 5 && "BinaryOp inst has 5 tokens");
assert(tokens[0].kind == Token::Ident && "Expected Token::Ident");
if (tokens[1].kind != Token::Assign)
return false;
if (tokens[2].kind != Token::Ident && tokens[2].kind != Token::IntLiteral)
return false;
if (!tokens[3].isRelationalOpCode())
return false;
if (tokens[4].kind != Token::Ident && tokens[4].kind != Token::IntLiteral)
return false;
if (!errGlobalState) {
Value dest(Value::Register, tokens[0].string.c_str());
unsigned srcKind = tokens[2].kind;
Value src1;
if (srcKind == Token::IntLiteral)
src1 = Value(Value::Immediate, std::stoll(tokens[2].string));
else
src1 = Value(Value::Register, tokens[2].string.c_str());
srcKind = tokens[4].kind;
Value src2;
if (srcKind == Token::IntLiteral)
src2 = Value(Value::Immediate, std::stoll(tokens[4].string));
else
src2 = Value(Value::Register, tokens[4].string.c_str());
unsigned opCode = getInstRelationalOpCode(tokens[3].kind);
instList.emplace_back(new Instruction(opCode, dest, src1, src2));
}
return true;
}
bool Parser::parseBranchInst(std::vector<Token> &tokens) {
assert(tokens[0].kind == Token::Br && "Expected Token::Br");
if (tokens.size() != 4)
return false;
for (int i = 1; i < tokens.size(); ++i) {
if (tokens[i].kind != Token::Ident)
return false;
}
if (!errGlobalState) {
Value cond(Value::Register, tokens[1].string.c_str());
Value trueLabel(Value::Label, tokens[2].string.c_str());
Value falseLabel(Value::Label, tokens[3].string.c_str());
instList.emplace_back(
new Instruction(Instruction::Br, cond, trueLabel, falseLabel));
}
return true;
}
bool Parser::parseJumpInst(std::vector<Token> &tokens) {
assert(tokens[0].kind == Token::Jmp && "Expected Token::Jmp");
if (tokens.size() != 2)
return false;
if (tokens[1].kind != Token::Ident)
return false;
if (!errGlobalState) {
Value targetLabel(Value::Label, tokens[1].string.c_str());
instList.emplace_back(new Instruction(Instruction::Jmp, targetLabel));
}
return true;
}
//------------------------------ CFG routines --------------------------------//
CFG *Parser::getCFG() {
if (theCFG)
return theCFG;
parseFile();
buildCFG();
return theCFG;
}
void Parser::buildCFG() {
theCFG = new CFG();
std::vector<unsigned> labelIndices;
std::vector<unsigned> terminatorIndices;
std::map<Instruction *, CFGBlock *> inst2BB;
for (int i = 0; i < instList.size(); ++i) {
if (instList[i]->isLabelDef())
labelIndices.push_back(i);
else if (instList[i]->isTerminator())
terminatorIndices.push_back(i);
}
// Basic blocks
for (auto i : labelIndices) {
auto currentIdx = i;
CFGBlock *B = new CFGBlock(instList[currentIdx]->getOperand(0).getName());
++currentIdx;
if (currentIdx == instList.size())
continue;
while (currentIdx < instList.size() &&
!instList[currentIdx]->isTerminator()) {
inst2BB[instList[currentIdx]] = B;
B->addInst(instList[currentIdx]);
++currentIdx;
}
if (currentIdx < instList.size() && instList[currentIdx]->isTerminator()) {
B->addInst(instList[currentIdx]);
inst2BB[instList[currentIdx]] = B;
}
if (i == 0)
theCFG->addBlock(B, /*isEntryBlock=*/true);
else
theCFG->addBlock(B);
}
// TODO : jmp and br instructions require target labels, so anything after a
// terminator that isn't a LabelDef must be a dead block. Don't allow the text
// to have such dead blocks. In essence, all blocks must start with a label
// and end with a terminator.
// Add the edges.
for (auto i : terminatorIndices) {
auto terminator = instList[i];
auto currentBlock = inst2BB[terminator];
unsigned operandIdx = terminator->isBranch() ? 1 : 0;
const char *targetName = terminator->getOperand(operandIdx).getName();
CFGBlock *target = theCFG->getBlockWithName(targetName);
target->addPredecessor(currentBlock);
currentBlock->addSuccessor(target);
if (terminator->isBranch()) {
const char *target2Name = terminator->getOperand(2).getName();
CFGBlock *target2 = theCFG->getBlockWithName(target2Name);
target2->addPredecessor(currentBlock);
currentBlock->addSuccessor(target2);
}
}
}
| 26.97066 | 80 | 0.624785 | [
"vector"
] |
6b5a6be5cbc97f131caf0a6a3b79876345e3e5c2 | 27,754 | cc | C++ | chrome/browser/nearby_sharing/client/nearby_share_client_impl_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/nearby_sharing/client/nearby_share_client_impl_unittest.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/nearby_sharing/client/nearby_share_client_impl_unittest.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 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 <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/gtest_util.h"
#include "base/test/null_task_runner.h"
#include "base/test/task_environment.h"
#include "chrome/browser/nearby_sharing/client/nearby_share_api_call_flow.h"
#include "chrome/browser/nearby_sharing/client/nearby_share_api_call_flow_impl.h"
#include "chrome/browser/nearby_sharing/client/nearby_share_client.h"
#include "chrome/browser/nearby_sharing/client/nearby_share_client_impl.h"
#include "chrome/browser/nearby_sharing/client/nearby_share_http_notifier.h"
#include "chrome/browser/nearby_sharing/common/nearby_share_http_result.h"
#include "chrome/browser/nearby_sharing/common/nearby_share_switches.h"
#include "chrome/browser/nearby_sharing/proto/certificate_rpc.pb.h"
#include "chrome/browser/nearby_sharing/proto/contact_rpc.pb.h"
#include "chrome/browser/nearby_sharing/proto/device_rpc.pb.h"
#include "chrome/browser/nearby_sharing/proto/rpc_resources.pb.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace {
const char kGet[] = "GET";
const char kPost[] = "POST";
const char kPatch[] = "PATCH";
const char kAccessToken[] = "access_token";
const char kAccountName1[] = "accountname1";
const char kContactId1[] = "contactid1";
const char kDeviceIdPath[] = "users/me/devices/deviceid";
const char kEmail[] = "test@gmail.com";
const char kEncryptedMetadataBytes1[] = "encryptedmetadatabytes1";
const char kImageUrl1[] = "https://example.com/image.jpg";
const char kMetadataEncryptionKey1[] = "metadataencryptionkey1";
const char kMetadataEncryptionKeyTag1[] = "metadataencryptionkeytag1";
const char kObfuscatedGaia1[] = "obfuscatedgaia1";
const char kPageToken1[] = "pagetoken1";
const char kPageToken2[] = "pagetoken2";
const char kPersonName1[] = "personname1";
const char kPhoneNumber1[] = "1231231234";
const char kPublicKey1[] = "publickey1";
const char kSecretId1[] = "secretid1";
const char kSecretId2[] = "secretid2";
const char kSecretId1Encoded[] = "c2VjcmV0aWQx";
const char kSecretId2Encoded[] = "c2VjcmV0aWQy";
const char kSecretKey1[] = "secretkey1";
const char kTestGoogleApisUrl[] = "https://nearbysharing-pa.testgoogleapis.com";
const int32_t kNanos1 = 123123123;
const int32_t kNanos2 = 321321321;
const int32_t kPageSize1 = 1000;
const int64_t kSeconds1 = 1594392109;
const int64_t kSeconds2 = 1623336109;
class FakeNearbyShareApiCallFlow : public NearbyShareApiCallFlow {
public:
FakeNearbyShareApiCallFlow() = default;
~FakeNearbyShareApiCallFlow() override = default;
FakeNearbyShareApiCallFlow(FakeNearbyShareApiCallFlow&) = delete;
FakeNearbyShareApiCallFlow& operator=(FakeNearbyShareApiCallFlow&) = delete;
void StartPostRequest(
const GURL& request_url,
const std::string& serialized_request,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const std::string& access_token,
ResultCallback&& result_callback,
ErrorCallback&& error_callback) override {
http_method_ = kPost;
request_url_ = request_url;
serialized_request_ = serialized_request;
url_loader_factory_ = url_loader_factory;
result_callback_ = std::move(result_callback);
error_callback_ = std::move(error_callback);
EXPECT_EQ(kAccessToken, access_token);
}
void StartPatchRequest(
const GURL& request_url,
const std::string& serialized_request,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const std::string& access_token,
ResultCallback&& result_callback,
ErrorCallback&& error_callback) override {
http_method_ = kPatch;
request_url_ = request_url;
serialized_request_ = serialized_request;
url_loader_factory_ = url_loader_factory;
result_callback_ = std::move(result_callback);
error_callback_ = std::move(error_callback);
EXPECT_EQ(kAccessToken, access_token);
}
void StartGetRequest(
const GURL& request_url,
const QueryParameters& request_as_query_parameters,
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
const std::string& access_token,
ResultCallback&& result_callback,
ErrorCallback&& error_callback) override {
http_method_ = kGet;
request_url_ = request_url;
request_as_query_parameters_ = request_as_query_parameters;
url_loader_factory_ = url_loader_factory;
result_callback_ = std::move(result_callback);
error_callback_ = std::move(error_callback);
EXPECT_EQ(kAccessToken, access_token);
}
void SetPartialNetworkTrafficAnnotation(
const net::PartialNetworkTrafficAnnotationTag& partial_traffic_annotation)
override {
// Do nothing
}
std::string http_method_;
GURL request_url_;
std::string serialized_request_;
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
ResultCallback result_callback_;
ErrorCallback error_callback_;
QueryParameters request_as_query_parameters_;
};
// Return the values associated with |key|, or fail the test if |key| isn't in
// |query_parameters|
std::vector<std::string> ExpectQueryStringValues(
const NearbyShareApiCallFlow::QueryParameters& query_parameters,
const std::string& key) {
std::vector<std::string> values;
for (const std::pair<std::string, std::string>& pair : query_parameters) {
if (pair.first == key) {
values.push_back(pair.second);
}
}
EXPECT_TRUE(values.size() > 0);
return values;
}
// Callback that should never be invoked.
template <class T>
void NotCalled(T type) {
EXPECT_TRUE(false);
}
// Callback that should never be invoked.
template <class T>
void NotCalledConstRef(const T& type) {
EXPECT_TRUE(false);
}
// Callback that saves the result returned by NearbyShareClient.
template <class T>
void SaveResult(T* out, T result) {
*out = result;
}
// Callback that saves the result returned by NearbyShareClient.
template <class T>
void SaveResultConstRef(T* out, const T& result) {
*out = result;
}
} // namespace
class NearbyShareClientImplTest : public testing::Test,
public NearbyShareHttpNotifier::Observer {
protected:
NearbyShareClientImplTest() {
shared_factory_ =
base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>(
base::BindOnce([]() -> network::mojom::URLLoaderFactory* {
ADD_FAILURE() << "Did not expect this to actually be used";
return nullptr;
}));
}
void SetUp() override {
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kNearbyShareHTTPHost, kTestGoogleApisUrl);
identity_test_environment_.MakeUnconsentedPrimaryAccountAvailable(kEmail);
std::unique_ptr<FakeNearbyShareApiCallFlow> api_call_flow =
std::make_unique<FakeNearbyShareApiCallFlow>();
api_call_flow_ = api_call_flow.get();
client_ = std::make_unique<NearbyShareClientImpl>(
std::move(api_call_flow), identity_test_environment_.identity_manager(),
shared_factory_, ¬ifier_);
notifier_.AddObserver(this);
}
void TearDown() override { notifier_.RemoveObserver(this); }
// NearbyShareHttpNotifier::Observer:
void OnUpdateDeviceRequest(
const nearbyshare::proto::UpdateDeviceRequest& request) override {
update_device_request_from_notifier_ = request;
}
void OnUpdateDeviceResponse(
const nearbyshare::proto::UpdateDeviceResponse& response) override {
update_device_response_from_notifier_ = response;
}
void OnListContactPeopleRequest(
const nearbyshare::proto::ListContactPeopleRequest& request) override {
list_contact_people_request_from_notifier_ = request;
}
void OnListContactPeopleResponse(
const nearbyshare::proto::ListContactPeopleResponse& response) override {
list_contact_people_response_from_notifier_ = response;
}
void OnListPublicCertificatesRequest(
const nearbyshare::proto::ListPublicCertificatesRequest& request)
override {
list_public_certificate_request_from_notifier_ = request;
}
void OnListPublicCertificatesResponse(
const nearbyshare::proto::ListPublicCertificatesResponse& response)
override {
list_public_certificate_response_from_notifier_ = response;
}
const std::string& http_method() { return api_call_flow_->http_method_; }
const GURL& request_url() { return api_call_flow_->request_url_; }
const std::string& serialized_request() {
return api_call_flow_->serialized_request_;
}
const NearbyShareApiCallFlow::QueryParameters& request_as_query_parameters() {
return api_call_flow_->request_as_query_parameters_;
}
// Returns |response_proto| as the result to the current API request.
void FinishApiCallFlow(const google::protobuf::MessageLite* response_proto) {
std::move(api_call_flow_->result_callback_)
.Run(response_proto->SerializeAsString());
}
// Returns |serialized_proto| as the result to the current API request.
void FinishApiCallFlowRaw(const std::string& serialized_proto) {
std::move(api_call_flow_->result_callback_).Run(serialized_proto);
}
// Ends the current API request with |error|.
void FailApiCallFlow(NearbyShareHttpError error) {
std::move(api_call_flow_->error_callback_).Run(error);
}
void VerifyRequestNotification(
const nearbyshare::proto::UpdateDeviceRequest& expected_request) const {
ASSERT_TRUE(update_device_request_from_notifier_);
EXPECT_EQ(expected_request.SerializeAsString(),
update_device_request_from_notifier_->SerializeAsString());
}
void VerifyResponseNotification(
const nearbyshare::proto::UpdateDeviceResponse& expected_response) const {
ASSERT_TRUE(update_device_response_from_notifier_);
EXPECT_EQ(expected_response.SerializeAsString(),
update_device_response_from_notifier_->SerializeAsString());
}
void VerifyRequestNotification(
const nearbyshare::proto::ListContactPeopleRequest& expected_request)
const {
ASSERT_TRUE(list_contact_people_request_from_notifier_);
EXPECT_EQ(expected_request.SerializeAsString(),
list_contact_people_request_from_notifier_->SerializeAsString());
}
void VerifyResponseNotification(
const nearbyshare::proto::ListContactPeopleResponse& expected_response)
const {
ASSERT_TRUE(list_contact_people_response_from_notifier_);
EXPECT_EQ(expected_response.SerializeAsString(),
list_contact_people_response_from_notifier_->SerializeAsString());
}
void VerifyRequestNotification(
const nearbyshare::proto::ListPublicCertificatesRequest& expected_request)
const {
ASSERT_TRUE(list_public_certificate_request_from_notifier_);
EXPECT_EQ(
expected_request.SerializeAsString(),
list_public_certificate_request_from_notifier_->SerializeAsString());
}
void VerifyResponseNotification(
const nearbyshare::proto::ListPublicCertificatesResponse&
expected_response) const {
ASSERT_TRUE(list_public_certificate_response_from_notifier_);
EXPECT_EQ(
expected_response.SerializeAsString(),
list_public_certificate_response_from_notifier_->SerializeAsString());
}
protected:
base::Optional<nearbyshare::proto::UpdateDeviceRequest>
update_device_request_from_notifier_;
base::Optional<nearbyshare::proto::UpdateDeviceResponse>
update_device_response_from_notifier_;
base::Optional<nearbyshare::proto::ListContactPeopleRequest>
list_contact_people_request_from_notifier_;
base::Optional<nearbyshare::proto::ListContactPeopleResponse>
list_contact_people_response_from_notifier_;
base::Optional<nearbyshare::proto::ListPublicCertificatesRequest>
list_public_certificate_request_from_notifier_;
base::Optional<nearbyshare::proto::ListPublicCertificatesResponse>
list_public_certificate_response_from_notifier_;
base::test::TaskEnvironment task_environment_;
signin::IdentityTestEnvironment identity_test_environment_;
FakeNearbyShareApiCallFlow* api_call_flow_;
scoped_refptr<network::SharedURLLoaderFactory> shared_factory_;
NearbyShareHttpNotifier notifier_;
std::unique_ptr<NearbyShareClient> client_;
};
TEST_F(NearbyShareClientImplTest, UpdateDeviceSuccess) {
nearbyshare::proto::UpdateDeviceResponse result_proto;
nearbyshare::proto::UpdateDeviceRequest request_proto;
request_proto.mutable_device()->set_name(kDeviceIdPath);
client_->UpdateDevice(
request_proto,
base::BindOnce(
&SaveResultConstRef<nearbyshare::proto::UpdateDeviceResponse>,
&result_proto),
base::BindOnce(&NotCalled<NearbyShareHttpError>));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
VerifyRequestNotification(request_proto);
EXPECT_EQ(kPatch, http_method());
EXPECT_EQ(request_url(), GURL(std::string(kTestGoogleApisUrl) + "/v1/" +
std::string(kDeviceIdPath)));
nearbyshare::proto::UpdateDeviceRequest expected_request;
EXPECT_TRUE(expected_request.ParseFromString(serialized_request()));
EXPECT_EQ(kDeviceIdPath, expected_request.device().name());
nearbyshare::proto::UpdateDeviceResponse response_proto;
nearbyshare::proto::Device& device = *response_proto.mutable_device();
device.set_name(kDeviceIdPath);
device.add_contacts();
device.mutable_contacts(0)->mutable_identifier()->set_phone_number(
kPhoneNumber1);
device.mutable_contacts(0)->set_is_selected(false);
device.add_contacts();
device.mutable_contacts(1)->mutable_identifier()->set_account_name(
kAccountName1);
device.mutable_contacts(1)->set_is_selected(true);
device.add_contacts();
device.mutable_contacts(2)->mutable_identifier()->set_obfuscated_gaia(
kObfuscatedGaia1);
device.mutable_contacts(2)->set_is_selected(true);
FinishApiCallFlow(&response_proto);
VerifyResponseNotification(response_proto);
// Check that the result received in callback is the same as the response.
ASSERT_EQ(3, result_proto.device().contacts_size());
EXPECT_EQ(nearbyshare::proto::Contact::Identifier::kPhoneNumber,
result_proto.device().contacts(0).identifier().identifier_case());
EXPECT_EQ(kPhoneNumber1,
result_proto.device().contacts(0).identifier().phone_number());
EXPECT_EQ(nearbyshare::proto::Contact::Identifier::kAccountName,
result_proto.device().contacts(1).identifier().identifier_case());
EXPECT_EQ(kAccountName1,
result_proto.device().contacts(1).identifier().account_name());
EXPECT_EQ(nearbyshare::proto::Contact::Identifier::kObfuscatedGaia,
result_proto.device().contacts(2).identifier().identifier_case());
EXPECT_EQ(kObfuscatedGaia1,
result_proto.device().contacts(2).identifier().obfuscated_gaia());
}
TEST_F(NearbyShareClientImplTest, UpdateDeviceFailure) {
nearbyshare::proto::UpdateDeviceRequest request;
request.mutable_device()->set_name(kDeviceIdPath);
NearbyShareHttpError error;
client_->UpdateDevice(
request,
base::BindOnce(
&NotCalledConstRef<nearbyshare::proto::UpdateDeviceResponse>),
base::BindOnce(&SaveResult<NearbyShareHttpError>, &error));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
EXPECT_EQ(kPatch, http_method());
EXPECT_EQ(request_url(), GURL(std::string(kTestGoogleApisUrl) + "/v1/" +
std::string(kDeviceIdPath)));
FailApiCallFlow(NearbyShareHttpError::kInternalServerError);
EXPECT_EQ(NearbyShareHttpError::kInternalServerError, error);
}
TEST_F(NearbyShareClientImplTest, ListContactPeopleSuccess) {
nearbyshare::proto::ListContactPeopleResponse result_proto;
nearbyshare::proto::ListContactPeopleRequest request_proto;
request_proto.set_page_size(kPageSize1);
request_proto.set_page_token(kPageToken1);
client_->ListContactPeople(
request_proto,
base::BindOnce(
&SaveResultConstRef<nearbyshare::proto::ListContactPeopleResponse>,
&result_proto),
base::BindOnce(&NotCalled<NearbyShareHttpError>));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
VerifyRequestNotification(request_proto);
EXPECT_EQ(kGet, http_method());
EXPECT_EQ(request_url(),
std::string(kTestGoogleApisUrl) + "/v1/contactRecords");
EXPECT_EQ(
std::vector<std::string>{base::NumberToString(kPageSize1)},
ExpectQueryStringValues(request_as_query_parameters(), "page_size"));
EXPECT_EQ(
std::vector<std::string>{kPageToken1},
ExpectQueryStringValues(request_as_query_parameters(), "page_token"));
nearbyshare::proto::ListContactPeopleResponse response_proto;
response_proto.add_contact_records();
response_proto.mutable_contact_records(0)->set_id(kContactId1);
response_proto.mutable_contact_records(0)->set_person_name(kPersonName1);
response_proto.mutable_contact_records(0)->set_image_url(kImageUrl1);
response_proto.mutable_contact_records(0)->add_identifiers();
response_proto.mutable_contact_records(0)
->mutable_identifiers(0)
->set_obfuscated_gaia(kObfuscatedGaia1);
response_proto.set_next_page_token(kPageToken2);
FinishApiCallFlow(&response_proto);
VerifyResponseNotification(response_proto);
EXPECT_EQ(1, result_proto.contact_records_size());
EXPECT_EQ(kContactId1, result_proto.contact_records(0).id());
EXPECT_EQ(kPersonName1, result_proto.contact_records(0).person_name());
EXPECT_EQ(kImageUrl1, result_proto.contact_records(0).image_url());
EXPECT_EQ(1, result_proto.contact_records(0).identifiers_size());
EXPECT_EQ(
nearbyshare::proto::Contact::Identifier::IdentifierCase::kObfuscatedGaia,
result_proto.contact_records(0).identifiers(0).identifier_case());
EXPECT_EQ(kObfuscatedGaia1,
result_proto.contact_records(0).identifiers(0).obfuscated_gaia());
}
TEST_F(NearbyShareClientImplTest, ListPublicCertificatesSuccess) {
nearbyshare::proto::ListPublicCertificatesResponse result_proto;
nearbyshare::proto::ListPublicCertificatesRequest request_proto;
request_proto.set_parent(kDeviceIdPath);
request_proto.set_page_size(kPageSize1);
request_proto.set_page_token(kPageToken1);
request_proto.add_secret_ids();
request_proto.set_secret_ids(0, kSecretId1);
request_proto.add_secret_ids();
request_proto.set_secret_ids(1, kSecretId2);
client_->ListPublicCertificates(
request_proto,
base::BindOnce(&SaveResultConstRef<
nearbyshare::proto::ListPublicCertificatesResponse>,
&result_proto),
base::BindOnce(&NotCalled<NearbyShareHttpError>));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
VerifyRequestNotification(request_proto);
EXPECT_EQ(kGet, http_method());
EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" +
std::string(kDeviceIdPath) +
"/publicCertificates");
EXPECT_EQ(
std::vector<std::string>{base::NumberToString(kPageSize1)},
ExpectQueryStringValues(request_as_query_parameters(), "page_size"));
EXPECT_EQ(
std::vector<std::string>{kPageToken1},
ExpectQueryStringValues(request_as_query_parameters(), "page_token"));
EXPECT_EQ(
(std::vector<std::string>{kSecretId1Encoded, kSecretId2Encoded}),
ExpectQueryStringValues(request_as_query_parameters(), "secret_ids"));
nearbyshare::proto::ListPublicCertificatesResponse response_proto;
response_proto.set_next_page_token(kPageToken2);
response_proto.add_public_certificates();
response_proto.mutable_public_certificates(0)->set_secret_id(kSecretId1);
response_proto.mutable_public_certificates(0)->set_secret_key(kSecretKey1);
response_proto.mutable_public_certificates(0)->set_public_key(kPublicKey1);
response_proto.mutable_public_certificates(0)
->mutable_start_time()
->set_seconds(kSeconds1);
response_proto.mutable_public_certificates(0)
->mutable_start_time()
->set_nanos(kNanos1);
response_proto.mutable_public_certificates(0)
->mutable_end_time()
->set_seconds(kSeconds2);
response_proto.mutable_public_certificates(0)->mutable_end_time()->set_nanos(
kNanos2);
response_proto.mutable_public_certificates(0)->set_for_selected_contacts(
false);
response_proto.mutable_public_certificates(0)->set_metadata_encryption_key(
kMetadataEncryptionKey1);
response_proto.mutable_public_certificates(0)->set_encrypted_metadata_bytes(
kEncryptedMetadataBytes1);
response_proto.mutable_public_certificates(0)
->set_metadata_encryption_key_tag(kMetadataEncryptionKeyTag1);
FinishApiCallFlow(&response_proto);
VerifyResponseNotification(response_proto);
EXPECT_EQ(kPageToken2, result_proto.next_page_token());
EXPECT_EQ(1, result_proto.public_certificates_size());
EXPECT_EQ(kSecretId1, result_proto.public_certificates(0).secret_id());
EXPECT_EQ(kSecretKey1, result_proto.public_certificates(0).secret_key());
EXPECT_EQ(kSeconds1,
result_proto.public_certificates(0).start_time().seconds());
EXPECT_EQ(kNanos1, result_proto.public_certificates(0).start_time().nanos());
EXPECT_EQ(kSeconds2,
result_proto.public_certificates(0).end_time().seconds());
EXPECT_EQ(kNanos2, result_proto.public_certificates(0).end_time().nanos());
EXPECT_EQ(false, result_proto.public_certificates(0).for_selected_contacts());
EXPECT_EQ(kMetadataEncryptionKey1,
result_proto.public_certificates(0).metadata_encryption_key());
EXPECT_EQ(kEncryptedMetadataBytes1,
result_proto.public_certificates(0).encrypted_metadata_bytes());
EXPECT_EQ(kMetadataEncryptionKeyTag1,
result_proto.public_certificates(0).metadata_encryption_key_tag());
}
TEST_F(NearbyShareClientImplTest, FetchAccessTokenFailure) {
NearbyShareHttpError error;
client_->UpdateDevice(
nearbyshare::proto::UpdateDeviceRequest(),
base::BindOnce(
&NotCalledConstRef<nearbyshare::proto::UpdateDeviceResponse>),
base::BindOnce(&SaveResult<NearbyShareHttpError>, &error));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithError(
GoogleServiceAuthError(GoogleServiceAuthError::SERVICE_UNAVAILABLE));
EXPECT_EQ(NearbyShareHttpError::kAuthenticationError, error);
}
TEST_F(NearbyShareClientImplTest, ParseResponseProtoFailure) {
nearbyshare::proto::UpdateDeviceRequest request_proto;
request_proto.mutable_device()->set_name(kDeviceIdPath);
NearbyShareHttpError error;
client_->UpdateDevice(
request_proto,
base::BindOnce(
&NotCalledConstRef<nearbyshare::proto::UpdateDeviceResponse>),
base::BindOnce(&SaveResult<NearbyShareHttpError>, &error));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
EXPECT_EQ(kPatch, http_method());
EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" +
std::string(kDeviceIdPath));
FinishApiCallFlowRaw("Not a valid serialized response message.");
EXPECT_EQ(NearbyShareHttpError::kResponseMalformed, error);
}
TEST_F(NearbyShareClientImplTest, MakeSecondRequestBeforeFirstRequestSucceeds) {
nearbyshare::proto::UpdateDeviceRequest request_proto;
request_proto.mutable_device()->set_name(kDeviceIdPath);
// Make first request.
nearbyshare::proto::UpdateDeviceResponse result_proto;
client_->UpdateDevice(
request_proto,
base::BindOnce(
&SaveResultConstRef<nearbyshare::proto::UpdateDeviceResponse>,
&result_proto),
base::BindOnce(&NotCalled<NearbyShareHttpError>));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
EXPECT_EQ(kPatch, http_method());
EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" +
std::string(kDeviceIdPath));
// With request pending, make second request.
{
NearbyShareHttpError error;
EXPECT_DCHECK_DEATH(client_->ListPublicCertificates(
nearbyshare::proto::ListPublicCertificatesRequest(),
base::BindOnce(&NotCalledConstRef<
nearbyshare::proto::ListPublicCertificatesResponse>),
base::BindOnce(&SaveResult<NearbyShareHttpError>, &error)));
}
// Complete first request.
{
nearbyshare::proto::UpdateDeviceResponse response_proto;
response_proto.mutable_device()->set_name(kDeviceIdPath);
FinishApiCallFlow(&response_proto);
}
EXPECT_EQ(kDeviceIdPath, result_proto.device().name());
}
TEST_F(NearbyShareClientImplTest, MakeSecondRequestAfterFirstRequestSucceeds) {
// Make first request successfully.
{
nearbyshare::proto::UpdateDeviceResponse result_proto;
nearbyshare::proto::UpdateDeviceRequest request_proto;
request_proto.mutable_device()->set_name(kDeviceIdPath);
client_->UpdateDevice(
request_proto,
base::BindOnce(
&SaveResultConstRef<nearbyshare::proto::UpdateDeviceResponse>,
&result_proto),
base::BindOnce(&NotCalled<NearbyShareHttpError>));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
EXPECT_EQ(kPatch, http_method());
EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" +
std::string(kDeviceIdPath));
nearbyshare::proto::UpdateDeviceResponse response_proto;
response_proto.mutable_device()->set_name(kDeviceIdPath);
FinishApiCallFlow(&response_proto);
EXPECT_EQ(kDeviceIdPath, result_proto.device().name());
}
// Second request fails.
{
NearbyShareHttpError error;
EXPECT_DCHECK_DEATH(client_->ListPublicCertificates(
nearbyshare::proto::ListPublicCertificatesRequest(),
base::BindOnce(&NotCalledConstRef<
nearbyshare::proto::ListPublicCertificatesResponse>),
base::BindOnce(&SaveResult<NearbyShareHttpError>, &error)));
}
}
TEST_F(NearbyShareClientImplTest, GetAccessTokenUsed) {
EXPECT_TRUE(client_->GetAccessTokenUsed().empty());
nearbyshare::proto::UpdateDeviceResponse result_proto;
nearbyshare::proto::UpdateDeviceRequest request_proto;
request_proto.mutable_device()->set_name(kDeviceIdPath);
client_->UpdateDevice(
request_proto,
base::BindOnce(
&SaveResultConstRef<nearbyshare::proto::UpdateDeviceResponse>,
&result_proto),
base::BindOnce(&NotCalled<NearbyShareHttpError>));
identity_test_environment_
.WaitForAccessTokenRequestIfNecessaryAndRespondWithToken(
kAccessToken, base::Time::Max());
EXPECT_EQ(kPatch, http_method());
EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" +
std::string(kDeviceIdPath));
EXPECT_EQ(kAccessToken, client_->GetAccessTokenUsed());
}
| 40.164978 | 81 | 0.756972 | [
"vector"
] |
6b5c12b1b41d1945f7a2abf582fc75850e2fe930 | 355 | cpp | C++ | #1306.jump-game-iii.cpp | hosomi/LeetCode | aba8fae8e37102b33dba8fd4adf1f018c395a4db | [
"MIT"
] | null | null | null | #1306.jump-game-iii.cpp | hosomi/LeetCode | aba8fae8e37102b33dba8fd4adf1f018c395a4db | [
"MIT"
] | null | null | null | #1306.jump-game-iii.cpp | hosomi/LeetCode | aba8fae8e37102b33dba8fd4adf1f018c395a4db | [
"MIT"
] | null | null | null | class Solution {
public:
bool canReach(vector<int>& arr, int start) {
if (start >= 0 && start < arr.size() && arr[start] >= 0) {
arr[start] *= -1;
return arr[start] == 0
|| canReach(arr, start + arr[start])
|| canReach(arr, start - arr[start]);
}
return false;
}
};
| 25.357143 | 66 | 0.459155 | [
"vector"
] |
6b5df1f472e0a2a98ce4698978127678dc3f60da | 4,259 | cpp | C++ | decoder/source/pkt_printers/trc_print_fact.cpp | rossburton/OpenCSD | 01d44a34f8fc057f4b041c01f8d9502d77fe612f | [
"BSD-3-Clause"
] | 84 | 2015-08-07T09:40:59.000Z | 2022-03-14T09:04:33.000Z | decoder/source/pkt_printers/trc_print_fact.cpp | rossburton/OpenCSD | 01d44a34f8fc057f4b041c01f8d9502d77fe612f | [
"BSD-3-Clause"
] | 41 | 2016-07-28T09:14:06.000Z | 2022-03-04T10:47:42.000Z | decoder/source/pkt_printers/trc_print_fact.cpp | rossburton/OpenCSD | 01d44a34f8fc057f4b041c01f8d9502d77fe612f | [
"BSD-3-Clause"
] | 37 | 2016-06-08T15:40:47.000Z | 2022-02-18T09:29:35.000Z | /*
* \file trc_print_fact.cpp
* \brief OpenCSD : Trace Packet printer factory.
*
* \copyright Copyright (c) 2017, ARM Limited. All Rights Reserved.
*/
/*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of 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 "pkt_printers/trc_print_fact.h"
RawFramePrinter * PktPrinterFact::createRawFramePrinter(std::vector<ItemPrinter *> &printer_list, ocsdMsgLogger *pMsgLogger /*= 0*/)
{
RawFramePrinter *pPrinter = 0;
pPrinter = new (std::nothrow)RawFramePrinter();
SavePrinter(printer_list, pPrinter, pMsgLogger);
return pPrinter;
}
TrcGenericElementPrinter *PktPrinterFact::createGenElemPrinter(std::vector<ItemPrinter *> &printer_list, ocsdMsgLogger *pMsgLogger /*= 0*/)
{
TrcGenericElementPrinter *pPrinter = 0;
pPrinter = new (std::nothrow)TrcGenericElementPrinter();
SavePrinter(printer_list, pPrinter, pMsgLogger);
return pPrinter;
}
ItemPrinter *PktPrinterFact::createProtocolPrinter(std::vector<ItemPrinter *> &printer_list, ocsd_trace_protocol_t protocol, uint8_t CSID, ocsdMsgLogger *pMsgLogger /*= 0*/)
{
ItemPrinter *pPrinter = 0;
switch (protocol)
{
case OCSD_PROTOCOL_ETMV4I:
case OCSD_PROTOCOL_ETE:
pPrinter = new (std::nothrow) PacketPrinter<EtmV4ITrcPacket>(CSID);
break;
case OCSD_PROTOCOL_ETMV3:
pPrinter = new (std::nothrow) PacketPrinter<EtmV3TrcPacket>(CSID);
break;
case OCSD_PROTOCOL_PTM:
pPrinter = new (std::nothrow) PacketPrinter<PtmTrcPacket>(CSID);
break;
case OCSD_PROTOCOL_STM:
pPrinter = new (std::nothrow) PacketPrinter<StmTrcPacket>(CSID);
break;
default:
break;
}
SavePrinter(printer_list, pPrinter, pMsgLogger);
return pPrinter;
}
const int PktPrinterFact::numPrinters(std::vector<ItemPrinter *> &printer_list)
{
return printer_list.size();
}
void PktPrinterFact::SavePrinter(std::vector<ItemPrinter *> &printer_list, ItemPrinter *pPrinter, ocsdMsgLogger *pMsgLogger)
{
if (pPrinter)
{
pPrinter->setMessageLogger(pMsgLogger);
printer_list.push_back((ItemPrinter *)pPrinter);
}
}
void PktPrinterFact::destroyAllPrinters(std::vector<ItemPrinter *> &printer_list)
{
std::vector<ItemPrinter *>::iterator it;
it = printer_list.begin();
while (it != printer_list.end())
{
delete *it;
it++;
}
printer_list.clear();
}
void PktPrinterFact::destroyPrinter(std::vector<ItemPrinter *> &printer_list, ItemPrinter *pPrinter)
{
std::vector<ItemPrinter *>::iterator it;
it = printer_list.begin();
while (it != printer_list.end())
{
if (*it == pPrinter)
{
printer_list.erase(it);
delete pPrinter;
return;
}
else
it++;
}
}
/* end of file trc_print_fact.cpp */
| 34.072 | 173 | 0.712609 | [
"vector"
] |
6b5e1127ab831ccbb701271e0f63c9d46ffe69ee | 13,324 | cc | C++ | L1Trigger/L1TCalorimeter/src/CaloTools.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | L1Trigger/L1TCalorimeter/src/CaloTools.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | L1Trigger/L1TCalorimeter/src/CaloTools.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | #include "L1Trigger/L1TCalorimeter/interface/CaloTools.h"
#include "L1Trigger/L1TCalorimeter/interface/CaloStage2Nav.h"
const l1t::CaloTower l1t::CaloTools::nullTower_;
const l1t::CaloCluster l1t::CaloTools::nullCluster_;
const float l1t::CaloTools::kGTEtaLSB = 0.0435;
const float l1t::CaloTools::kGTPhiLSB = 0.0435;
const float l1t::CaloTools::kGTEtLSB = 0.5;
const int64_t l1t::CaloTools::cos_coeff[72] = {1023, 1019, 1007, 988, 961, 927, 886, 838, 784, 723, 658, 587, 512, 432, 350, 265, 178, 89, 0, -89, -178, -265, -350, -432, -512, -587, -658, -723, -784, -838, -886, -927, -961, -988, -1007, -1019, -1023, -1019, -1007, -988, -961, -927, -886, -838, -784, -723, -658, -587, -512, -432, -350, -265, -178, -89, 0, 89, 178, 265, 350, 432, 511, 587, 658, 723, 784, 838, 886, 927, 961, 988, 1007, 1019};
const int64_t l1t::CaloTools::sin_coeff[72] = {0, 89, 178, 265, 350, 432, 512, 587, 658, 723, 784, 838, 886, 927, 961, 988, 1007, 1019, 1023, 1019, 1007, 988, 961, 927, 886, 838, 784, 723, 658, 587, 512, 432, 350, 265, 178, 89, 0, -89, -178, -265, -350, -432, -512, -587, -658, -723, -784, -838, -886, -927, -961, -988, -1007, -1019, -1023, -1019, -1007, -988, -961, -927, -886, -838, -784, -723, -658, -587, -512, -432, -350, -265, -178, -89};
bool l1t::CaloTools::insertTower(std::vector<l1t::CaloTower>& towers, const l1t::CaloTower& tower) {
size_t towerIndex = CaloTools::caloTowerHash(tower.hwEta(), tower.hwPhi());
if (towers.size() > towerIndex) {
towers.at(towerIndex) = tower;
return true;
}
else return false;
}
//currently implemented as a brute force search but this will hopefully change in the future
//with standarising the layout of std::vector<l1t::CaloTower>
const l1t::CaloTower& l1t::CaloTools::getTower(const std::vector<l1t::CaloTower>& towers,int iEta,int iPhi)
{
if(abs(iEta) > CaloTools::kHFEnd) return nullTower_;
size_t towerIndex = CaloTools::caloTowerHash(iEta, iPhi);
if(towerIndex<towers.size()){
if(towers[towerIndex].hwEta()!=iEta || towers[towerIndex].hwPhi()!=iPhi){ //it failed, this is bad, but we will not log the error due to policy and silently attempt to do a brute force search instead
//std::cout <<"error, tower "<<towers[towerIndex].hwEta()<<" "<<towers[towerIndex].hwPhi()<<" does not match "<<iEta<<" "<<iPhi<<" index "<<towerIndex<<" nr towrs "<<towers.size()<<std::endl;
for(size_t towerNr=0;towerNr<towers.size();towerNr++){
if(towers[towerNr].hwEta()==iEta && towers[towerNr].hwPhi()==iPhi) return towers[towerNr];
}
}else return towers[towerIndex];
}
else{// in case the vector of towers do not contain all the towers (towerIndex can be > towers.size())
for(size_t towerNr=0;towerNr<towers.size();towerNr++){
if(towers[towerNr].hwEta()==iEta && towers[towerNr].hwPhi()==iPhi) return towers[towerNr];
}
}
return nullTower_;
}
const l1t::CaloCluster& l1t::CaloTools::getCluster(const std::vector<l1t::CaloCluster>& clusters,int iEta,int iPhi)
{
for(size_t clusterNr=0;clusterNr<clusters.size();clusterNr++){
if(clusters[clusterNr].hwEta()==iEta && clusters[clusterNr].hwPhi()==iPhi) return clusters[clusterNr];
}
return nullCluster_;
}
//this implimentation has not all the necessary info yet, we need to check the exact HF numbering
//(iEta=-28,iPhi=1)=index 0 to (iEta=28,iPhi=72)=index 28*72*2-1
//HF then runs after that so -32,1 = 28*72*2
size_t l1t::CaloTools::caloTowerHash(int iEta,int iPhi)
{
if(!isValidIEtaIPhi(iEta,iPhi)) return caloTowerHashMax();
else{
const int absIEta = abs(iEta);
if(absIEta>kHFEnd) return kNrTowers;
else if(absIEta<=kHBHEEnd){ //HBHE
int iEtaNoZero=iEta;
if(iEta>0) iEtaNoZero--;
return (iEtaNoZero+kHBHEEnd)*kHBHENrPhi+iPhi-1;
}else{ //HF
int iEtaIndex = iEta+kHFEnd; //iEta=-32 is 0
if(iEta>0) iEtaIndex= iEta-kHBHEEnd+(kHFEnd-kHBHEEnd)-1; //but iEta=29 is 4
return iEtaIndex*kHFNrPhi+iPhi/kHFPhiSeg + kNrHBHETowers;
}
}
}
size_t l1t::CaloTools::caloTowerHashMax()
{
return kNrTowers;
}
bool l1t::CaloTools::isValidIEtaIPhi(int iEta,int iPhi)
{
size_t absIEta = abs(iEta);
if(iPhi<=0 || iPhi>kNPhi) return false;
if(absIEta==0 || absIEta>kHFEnd) return false;
//if(absIEta>kHBHEEnd && iPhi%kHFPhiSeg!=1) return false;
return true;
}
int l1t::CaloTools::calHwEtSum(int iEta,int iPhi,const std::vector<l1t::CaloTower>& towers,
int localEtaMin,int localEtaMax,int localPhiMin,int localPhiMax,
SubDet etMode)
{
return calHwEtSum(iEta,iPhi,towers,localEtaMin,localEtaMax,localPhiMin,localPhiMax,kHFEnd,etMode);
}
int l1t::CaloTools::calHwEtSum(int iEta,int iPhi,const std::vector<l1t::CaloTower>& towers,
int localEtaMin,int localEtaMax,int localPhiMin,int localPhiMax,
int iEtaAbsMax,SubDet etMode)
{
int hwEtSum=0;
for(int etaNr=localEtaMin;etaNr<=localEtaMax;etaNr++){
for(int phiNr=localPhiMin;phiNr<=localPhiMax;phiNr++){
int towerIEta = l1t::CaloStage2Nav::offsetIEta(iEta,etaNr);
int towerIPhi = l1t::CaloStage2Nav::offsetIPhi(iPhi,phiNr);
if(abs(towerIEta)<=iEtaAbsMax){
const l1t::CaloTower& tower = getTower(towers,towerIEta,towerIPhi);
if(etMode==ECAL) hwEtSum+=tower.hwEtEm();
else if(etMode==HCAL) hwEtSum+=tower.hwEtHad();
else if(etMode==CALO) hwEtSum+=tower.hwPt();
}
}
}
return hwEtSum;
}
size_t l1t::CaloTools::calNrTowers(int iEtaMin,int iEtaMax,int iPhiMin,int iPhiMax,const std::vector<l1t::CaloTower>& towers,int minHwEt,int maxHwEt,SubDet etMode)
{
size_t nrTowers=0;
l1t::CaloStage2Nav nav(iEtaMin,iPhiMin);
while(nav.currIEta()<=iEtaMax){
bool finishPhi = false;
while(!finishPhi){
const l1t::CaloTower& tower = l1t::CaloTools::getTower(towers,CaloTools::caloEta(nav.currIEta()),nav.currIPhi());
int towerHwEt =0;
if(etMode==ECAL) towerHwEt+=tower.hwEtEm();
else if(etMode==HCAL) towerHwEt+=tower.hwEtHad();
else if(etMode==CALO) towerHwEt+=tower.hwPt();
if(towerHwEt>=minHwEt && towerHwEt<=maxHwEt) nrTowers++;
finishPhi = (nav.currIPhi() == iPhiMax);
nav.north();
}
nav.east();
nav.resetIPhi();
}
return nrTowers;
}
std::pair<float,float> l1t::CaloTools::towerEtaBounds(int ieta)
{
if(ieta==0) ieta = 1;
if(ieta>kHFEnd) ieta = kHFEnd;
if(ieta<(-1*kHFEnd)) ieta = -1*kHFEnd;
//const float towerEtas[33] = {0,0.087,0.174,0.261,0.348,0.435,0.522,0.609,0.696,0.783,0.870,0.957,1.044,1.131,1.218,1.305,1.392,1.479,1.566,1.653,1.740,1.830,1.930,2.043,2.172,2.322,2.5,2.650,3.000,3.5,4.0,4.5,5.0};
const float towerEtas[42] = {0,0.087,0.174,0.261,0.348,0.435,0.522,0.609,0.696,0.783,0.870,0.957,1.044,1.131,1.218,1.305,1.392,1.479,1.566,1.653,1.740,1.830,1.930,2.043,2.172,2.322,2.5,2.650,2.853,3.139,3.314,3.489,3.664,3.839,4.013,4.191,4.363,4.538,4.716,4.889,5.191,5.191};
return std::make_pair( towerEtas[abs(ieta)-1],towerEtas[abs(ieta)] );
}
float l1t::CaloTools::towerEta(int ieta)
{
std::pair<float,float> bounds = towerEtaBounds(ieta);
float eta = (bounds.second+bounds.first)/2.;
float sign = ieta>0 ? 1. : -1.;
return sign*eta;
}
float l1t::CaloTools::towerPhi(int ieta, int iphi)
{
float phi = (float(iphi)-0.5)*towerPhiSize(ieta);
if (phi > M_PI) phi = phi - (2*M_PI);
return phi;
}
float l1t::CaloTools::towerEtaSize(int ieta)
{
std::pair<float,float> bounds = towerEtaBounds(ieta);
float size = (bounds.second-bounds.first);
return size;
}
float l1t::CaloTools::towerPhiSize(int ieta)
{
return 2.*M_PI/kNPhi;
}
// convert from calo ieta to internal MP ieta
int l1t::CaloTools::mpEta(int ieta) {
if (ieta>kHFBegin) return ieta-1;
else if (ieta<-1*kHFBegin) return ieta+1;
else return ieta;
}
// convert from internal MP ieta to calo ieta
int l1t::CaloTools::caloEta(int mpEta) {
if (mpEta>=kHFBegin) return mpEta+1;
else if (mpEta<=-1*kHFBegin) return mpEta-1;
else return mpEta;
}
// convert calorimeter ieta to RCT region index
int l1t::CaloTools::regionEta(int ieta)
{
// outside HF
if (abs(ieta) > kHFEnd)
return (ieta<0 ? 0 : 21);
// inside HBHE
if (abs(ieta) <= kHFBegin)
{
if (ieta<0)
return 11 - ceil( double (abs(ieta) /4.) );
else
return ceil( double (abs(ieta) /4.) ) + 10;
}
// in HF
if (ieta<0)
return 4 - ceil( double (abs(ieta)-29) /4. );
else
return ceil( double (abs(ieta)-29) /4. ) + 17;
}
// convert calorimeter ieta to etaBin16 index
int l1t::CaloTools::bin16Eta(int ieta)
{
int absIEta = abs(ieta);
if (absIEta>0 && absIEta<=5) return 0;
else if (absIEta<=9) return 1;
else if (absIEta<=13) return 2;
else if (absIEta<=15) return 3;
else if (absIEta<=17) return 4;
else if (absIEta<=19) return 5;
else if (absIEta<=21) return 6;
else if (absIEta==22) return 7;
else if (absIEta==23) return 8;
else if (absIEta==24) return 9;
else if (absIEta==25) return 10;
else if (absIEta==26) return 11;
else if (absIEta<=28) return 12;
else if (absIEta<=32) return 13;
else if (absIEta<=36) return 14;
else if (absIEta<=41) return 15;
else return -1; // error
}
int l1t::CaloTools::gtEta(int ieta) {
double eta = towerEta(ieta);
return round ( eta / kGTEtaLSB );
}
int l1t::CaloTools::gtPhi(int ieta, int iphi) {
double phi = towerPhi(ieta, iphi);
if (phi<0) phi = phi + 2*M_PI;
return round ( phi / kGTPhiLSB );
}
// this conversion is based on GT input definitions in CMS DN-2014/029
math::PtEtaPhiMLorentzVector l1t::CaloTools::p4Demux(l1t::L1Candidate* cand) {
return math::PtEtaPhiMLorentzVector( cand->hwPt() * kGTEtLSB + 1.E-6,
cand->hwEta() * kGTEtaLSB,
cand->hwPhi() * kGTPhiLSB,
0. ) ;
}
l1t::EGamma l1t::CaloTools::egP4Demux(l1t::EGamma& eg) {
l1t::EGamma tmpEG( p4Demux(&eg),
eg.hwPt(),
eg.hwEta(),
eg.hwPhi(),
eg.hwQual(),
eg.hwIso() );
tmpEG.setTowerIPhi(eg.towerIPhi());
tmpEG.setTowerIEta(eg.towerIEta());
tmpEG.setRawEt(eg.rawEt());
tmpEG.setIsoEt(eg.isoEt());
tmpEG.setFootprintEt(eg.footprintEt());
tmpEG.setNTT(eg.nTT());
tmpEG.setShape(eg.shape());
tmpEG.setTowerHoE(eg.towerHoE());
return tmpEG;
}
l1t::Tau l1t::CaloTools::tauP4Demux(l1t::Tau& tau) {
l1t::Tau tmpTau ( p4Demux(&tau),
tau.hwPt(),
tau.hwEta(),
tau.hwPhi(),
tau.hwQual(),
tau.hwIso());
tmpTau.setTowerIPhi(tau.towerIPhi());
tmpTau.setTowerIEta(tau.towerIEta());
tmpTau.setRawEt(tau.rawEt());
tmpTau.setIsoEt(tau.isoEt());
tmpTau.setNTT(tau.nTT());
tmpTau.setHasEM(tau.hasEM());
tmpTau.setIsMerged(tau.isMerged());
return tmpTau;
}
l1t::Jet l1t::CaloTools::jetP4Demux(l1t::Jet& jet) {
l1t::Jet tmpJet ( p4Demux(&jet),
jet.hwPt(),
jet.hwEta(),
jet.hwPhi(),
jet.hwQual() );
tmpJet.setTowerIPhi(jet.towerIPhi());
tmpJet.setTowerIEta(jet.towerIEta());
tmpJet.setRawEt(jet.rawEt());
tmpJet.setSeedEt(jet.seedEt());
tmpJet.setPUEt(jet.puEt());
tmpJet.setPUDonutEt(0,jet.puDonutEt(0));
tmpJet.setPUDonutEt(1,jet.puDonutEt(1));
tmpJet.setPUDonutEt(2,jet.puDonutEt(2));
tmpJet.setPUDonutEt(3,jet.puDonutEt(3));
return tmpJet;
}
l1t::EtSum l1t::CaloTools::etSumP4Demux(l1t::EtSum& etsum) {
return l1t::EtSum( p4Demux(&etsum),
etsum.getType(),
etsum.hwPt(),
etsum.hwEta(),
etsum.hwPhi(),
etsum.hwQual() );
}
//
math::PtEtaPhiMLorentzVector l1t::CaloTools::p4MP(l1t::L1Candidate* cand) {
return math::PtEtaPhiMLorentzVector( cand->hwPt() * 0.5 + 1.E-6,
towerEta(cand->hwEta()),
towerPhi(cand->hwEta(), cand->hwPhi()),
0. ) ;
}
l1t::EGamma l1t::CaloTools::egP4MP(l1t::EGamma& eg) {
l1t::EGamma tmpEG( p4MP(&eg),
eg.hwPt(),
eg.hwEta(),
eg.hwPhi(),
eg.hwQual(),
eg.hwIso() );
tmpEG.setTowerIPhi(eg.towerIPhi());
tmpEG.setTowerIEta(eg.towerIEta());
tmpEG.setRawEt(eg.rawEt());
tmpEG.setIsoEt(eg.isoEt());
tmpEG.setFootprintEt(eg.footprintEt());
tmpEG.setNTT(eg.nTT());
tmpEG.setShape(eg.shape());
tmpEG.setTowerHoE(eg.towerHoE());
return tmpEG;
}
l1t::Tau l1t::CaloTools::tauP4MP(l1t::Tau& tau) {
l1t::Tau tmpTau ( p4MP(&tau),
tau.hwPt(),
tau.hwEta(),
tau.hwPhi(),
tau.hwQual(),
tau.hwIso());
tmpTau.setTowerIPhi(tau.towerIPhi());
tmpTau.setTowerIEta(tau.towerIEta());
tmpTau.setRawEt(tau.rawEt());
tmpTau.setIsoEt(tau.isoEt());
tmpTau.setNTT(tau.nTT());
tmpTau.setHasEM(tau.hasEM());
tmpTau.setIsMerged(tau.isMerged());
return tmpTau;
}
l1t::Jet l1t::CaloTools::jetP4MP(l1t::Jet& jet) {
l1t::Jet tmpJet ( p4MP(&jet),
jet.hwPt(),
jet.hwEta(),
jet.hwPhi(),
jet.hwQual() );
tmpJet.setTowerIPhi(jet.towerIPhi());
tmpJet.setTowerIEta(jet.towerIEta());
tmpJet.setRawEt(jet.rawEt());
tmpJet.setSeedEt(jet.seedEt());
tmpJet.setPUEt(jet.puEt());
tmpJet.setPUDonutEt(0,jet.puDonutEt(0));
tmpJet.setPUDonutEt(1,jet.puDonutEt(1));
tmpJet.setPUDonutEt(2,jet.puDonutEt(2));
tmpJet.setPUDonutEt(3,jet.puDonutEt(3));
return tmpJet;
}
l1t::EtSum l1t::CaloTools::etSumP4MP(l1t::EtSum& etsum) {
return l1t::EtSum( p4MP(&etsum),
etsum.getType(),
etsum.hwPt(),
etsum.hwEta(),
etsum.hwPhi(),
etsum.hwQual() );
}
| 29.283516 | 444 | 0.654983 | [
"shape",
"vector"
] |
6b5e9f8ba0922bb714459513258acf11b733538b | 17,638 | cpp | C++ | src/Factory/Module/Modem/Modem.cpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Factory/Module/Modem/Modem.cpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Factory/Module/Modem/Modem.cpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | #include "Tools/Exception/exception.hpp"
#include "Tools/Code/SCMA/modem_SCMA_functions.hpp"
#include "Module/Modem/OOK/Modem_OOK.hpp"
#include "Module/Modem/BPSK/Modem_BPSK.hpp"
#include "Module/Modem/BPSK/Modem_BPSK_fast.hpp"
#include "Module/Modem/PAM/Modem_PAM.hpp"
#include "Module/Modem/QAM/Modem_QAM.hpp"
#include "Module/Modem/PSK/Modem_PSK.hpp"
#include "Module/Modem/CPM/Modem_CPM.hpp"
#include "Module/Modem/SCMA/Modem_SCMA.hpp"
#include "Module/Modem/User/Modem_user.hpp"
#include "Modem.hpp"
using namespace aff3ct;
using namespace aff3ct::factory;
const std::string aff3ct::factory::Modem_name = "Modem";
const std::string aff3ct::factory::Modem_prefix = "mdm";
Modem::parameters
::parameters(const std::string &prefix)
: Factory::parameters(Modem_name, Modem_name, prefix)
{
}
Modem::parameters
::~parameters()
{
}
Modem::parameters* Modem::parameters
::clone() const
{
return new Modem::parameters(*this);
}
void Modem::parameters
::get_description(arg_map &req_args, arg_map &opt_args) const
{
auto p = this->get_prefix();
// ----------------------------------------------------------------------------------------------------- modulator
req_args[{p+"-fra-size", "N"}] =
{"strictly_positive_int",
"number of symbols by frame."};
opt_args[{p+"-fra", "F"}] =
{"strictly_positive_int",
"set the number of inter frame level to process."};
opt_args[{p+"-type"}] =
{"string",
"type of the modulation to use in the simulation.",
"BPSK, BPSK_FAST, OOK, PSK, PAM, QAM, CPM, USER, SCMA"};
opt_args[{p+"-bps"}] =
{"strictly_positive_int",
"select the number of bits per symbol (default is 1)."};
opt_args[{p+"-ups"}] =
{"strictly_positive_int",
"select the symbol sampling factor (default is 1)."};
opt_args[{p+"-const-path"}] =
{"string",
"path to the ordered modulation symbols (constellation), to use with \"--mod-type USER\"."};
opt_args[{p+"-cpm-std"}] =
{"string",
"the selection of a default CPM standard hardly implemented (any of those parameters is "
"overwritten if the argument is given by the user)",
"GSM"};
opt_args[{p+"-cpm-L"}] =
{"strictly_positive_int",
"CPM pulse width or CPM memory (default is 2)"};
opt_args[{p+"-cpm-k"}] =
{"strictly_positive_int",
"modulation index numerator (default is 1)"};
opt_args[{p+"-cpm-p"}] =
{"strictly_positive_int",
"modulation index denominator (default is 2)"};
opt_args[{p+"-cpm-map"}] =
{"string",
"symbols mapping layout (default is NATURAL)",
"NATURAL, GRAY"};
opt_args[{p+"-cpm-ws"}] =
{"string",
"wave shape (default is GMSK)",
"GMSK, REC, RCOS"};
// --------------------------------------------------------------------------------------------------- demodulator
opt_args[{p+"-max"}] =
{"string",
"select the type of the max operation to use in the demodulator.",
"MAX, MAXL, MAXS, MAXSS"};
opt_args[{p+"-sigma"}] =
{"strictly_posive_float",
"noise variance value for the demodulator."};
opt_args[{p+"-no-sig2"}] =
{"",
"turn off the division by sigma square in the demodulator."};
opt_args[{p+"-psi"}] =
{"string",
"select the type of the psi function to use in the SCMA demodulator.",
"PSI0, PSI1, PSI2, PSI3"};
opt_args[{p+"-ite"}] =
{"strictly_positive_int",
"select the number of iteration in the demodulator."};
}
void Modem::parameters
::store(const arg_val_map &vals)
{
auto p = this->get_prefix();
// ----------------------------------------------------------------------------------------------------- modulator
if(exist(vals, {p+"-type" })) this->type = vals.at({p+"-type" });
if(exist(vals, {p+"-cpm-std" })) this->cpm_std = vals.at({p+"-cpm-std" });
if (this->type == "CPM")
{
if (!this->cpm_std.empty())
{
if (this->cpm_std == "GSM")
{
this->cpm_L = 3;
this->cpm_k = 1;
this->cpm_p = 2;
this->bps = 1;
this->upf = 5;
this->mapping = "NATURAL";
this->wave_shape = "GMSK";
}
else
{
std::stringstream message;
message << "Unknown CPM standard ('cpm_std' = " << this->cpm_std << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
}
}
if(exist(vals, {p+"-fra-size", "N"})) this->N = std::stoi(vals.at({p+"-fra-size", "N"}));
if(exist(vals, {p+"-fra", "F"})) this->n_frames = std::stoi(vals.at({p+"-fra", "F"}));
if(exist(vals, {p+"-bps" })) this->bps = std::stoi(vals.at({p+"-bps" }));
if(exist(vals, {p+"-ups" })) this->upf = std::stoi(vals.at({p+"-ups" }));
if(exist(vals, {p+"-const-path" })) this->const_path = vals.at({p+"-const-path" });
if(exist(vals, {p+"-cpm-L" })) this->cpm_L = std::stoi(vals.at({p+"-cpm-L" }));
if(exist(vals, {p+"-cpm-p" })) this->cpm_p = std::stoi(vals.at({p+"-cpm-p" }));
if(exist(vals, {p+"-cpm-k" })) this->cpm_k = std::stoi(vals.at({p+"-cpm-k" }));
if(exist(vals, {p+"-cpm-map" })) this->mapping = vals.at({p+"-cpm-map" });
if(exist(vals, {p+"-cpm-ws" })) this->wave_shape = vals.at({p+"-cpm-ws" });
if (this->type.find("BPSK") != std::string::npos || this->type == "PAM")
this->complex = false;
// force the number of bits per symbol to 1 when BPSK mod
if (this->type == "BPSK" || this->type == "BPSK_FAST" || this->type == "OOK")
this->bps = 1;
// force the number of bits per symbol to 3 when SCMA mod
if (this->type == "SCMA")
this->bps = 3;
this->N_mod = get_buffer_size_after_modulation(this->type,
this->N,
this->bps,
this->upf,
this->cpm_L,
this->cpm_p);
this->N_fil = get_buffer_size_after_filtering (this->type,
this->N,
this->bps,
this->cpm_L,
this->cpm_p);
// --------------------------------------------------------------------------------------------------- demodulator
if(exist(vals, {p+"-no-sig2"})) this->no_sig2 = true;
if(exist(vals, {p+"-sigma" })) this->sigma = std::stof(vals.at({p+"-sigma"}));
if(exist(vals, {p+"-ite" })) this->n_ite = std::stoi(vals.at({p+"-ite" }));
if(exist(vals, {p+"-max" })) this->max = vals.at({p+"-max" });
if(exist(vals, {p+"-psi" })) this->psi = vals.at({p+"-psi" });
}
void Modem::parameters
::get_headers(std::map<std::string,header_list>& headers, const bool full) const
{
auto p = this->get_prefix();
// ----------------------------------------------------------------------------------------------------- modulator
headers[p].push_back(std::make_pair("Type", this->type));
if (full) headers[p].push_back(std::make_pair("Frame size (N)", std::to_string(this->N)));
if (full) headers[p].push_back(std::make_pair("Inter frame level", std::to_string(this->n_frames)));
if (this->type == "CPM")
{
if(this->cpm_std.size())
headers[p].push_back(std::make_pair("CPM standard", this->cpm_std));
headers[p].push_back(std::make_pair("CPM L memory", std::to_string(this->cpm_L)));
headers[p].push_back(std::make_pair("CPM h index", (std::to_string(this->cpm_k) + std::string("/") +
std::to_string(this->cpm_p))));
headers[p].push_back(std::make_pair("CPM wave shape", this->wave_shape));
headers[p].push_back(std::make_pair("CPM mapping", this->mapping));
}
headers[p].push_back(std::make_pair("Bits per symbol", std::to_string(this->bps)));
headers[p].push_back(std::make_pair("Sampling factor", std::to_string(this->upf)));
// --------------------------------------------------------------------------------------------------- demodulator
std::string demod_sig2 = (this->no_sig2) ? "off" : "on";
std::string demod_max = (this->type == "BPSK" ) ||
(this->type == "BPSK_FAST") ||
(this->type == "OOK" ) ||
(this->type == "SCMA" ) ?
"unused" : this->max;
std::string demod_ite = std::to_string(this->n_ite);
std::string demod_psi = this->psi;
if (this->sigma != -1.f && full)
headers[p].push_back(std::make_pair("Sigma value", std::to_string(this->sigma)));
headers[p].push_back(std::make_pair("Sigma square", demod_sig2));
if (demod_max != "unused")
headers[p].push_back(std::make_pair("Max type", demod_max));
if (this->type == "SCMA")
{
headers[p].push_back(std::make_pair("Number of iterations", demod_ite));
headers[p].push_back(std::make_pair("Psi function", demod_psi));
}
}
template <typename B, typename R, typename Q, tools::proto_max<Q> MAX>
module::Modem<B,R,Q>* Modem::parameters
::_build() const
{
if (this->type == "BPSK" ) return new module::Modem_BPSK <B,R,Q >(this->N, this->sigma, this->no_sig2, this->n_frames);
else if (this->type == "BPSK_FAST") return new module::Modem_BPSK_fast<B,R,Q >(this->N, this->sigma, this->no_sig2, this->n_frames);
else if (this->type == "OOK" ) return new module::Modem_OOK <B,R,Q >(this->N, this->sigma, this->no_sig2, this->n_frames);
else if (this->type == "PAM" ) return new module::Modem_PAM <B,R,Q,MAX>(this->N, this->sigma, this->bps, this->no_sig2, this->n_frames);
else if (this->type == "QAM" ) return new module::Modem_QAM <B,R,Q,MAX>(this->N, this->sigma, this->bps, this->no_sig2, this->n_frames);
else if (this->type == "PSK" ) return new module::Modem_PSK <B,R,Q,MAX>(this->N, this->sigma, this->bps, this->no_sig2, this->n_frames);
else if (this->type == "USER" ) return new module::Modem_user <B,R,Q,MAX>(this->N, this->const_path, this->sigma, this->bps, this->no_sig2, this->n_frames);
else if (this->type == "CPM" ) return new module::Modem_CPM <B,R,Q,MAX>(this->N, this->sigma, this->bps, this->upf, this->cpm_L, this->cpm_k, this->cpm_p, this->mapping, this->wave_shape, this->no_sig2, this->n_frames);
throw tools::cannot_allocate(__FILE__, __LINE__, __func__);
}
template <typename B, typename R, typename Q>
module::Modem<B,R,Q>* Modem::parameters
::_build_scma() const
{
if (this->psi == "PSI0") return new module::Modem_SCMA <B,R,Q,tools::psi_0<Q>>(this->N, this->sigma, this->bps, this->no_sig2, this->n_ite, this->n_frames);
else if (this->psi == "PSI1") return new module::Modem_SCMA <B,R,Q,tools::psi_1<Q>>(this->N, this->sigma, this->bps, this->no_sig2, this->n_ite, this->n_frames);
else if (this->psi == "PSI2") return new module::Modem_SCMA <B,R,Q,tools::psi_2<Q>>(this->N, this->sigma, this->bps, this->no_sig2, this->n_ite, this->n_frames);
else if (this->psi == "PSI3") return new module::Modem_SCMA <B,R,Q,tools::psi_3<Q>>(this->N, this->sigma, this->bps, this->no_sig2, this->n_ite, this->n_frames);
throw tools::cannot_allocate(__FILE__, __LINE__, __func__);
}
template <typename B, typename R, typename Q>
module::Modem<B,R,Q>* Modem::parameters
::build() const
{
if (this->type == "SCMA")
{
return _build_scma<B,R,Q>();
}
else
{
if (this->max == "MAX" ) return _build<B,R,Q,tools::max <Q>>();
else if (this->max == "MAXL" ) return _build<B,R,Q,tools::max_linear <Q>>();
else if (this->max == "MAXS" ) return _build<B,R,Q,tools::max_star <Q>>();
else if (this->max == "MAXSS") return _build<B,R,Q,tools::max_star_safe<Q>>();
}
throw tools::cannot_allocate(__FILE__, __LINE__, __func__);
}
template <typename B, typename R, typename Q>
module::Modem<B,R,Q>* Modem
::build(const parameters ¶ms)
{
return params.template build<B,R,Q>();
}
int Modem
::get_buffer_size_after_modulation(const std::string &type,
const int N,
const int bps,
const int upf,
const int cpm_L,
const int cpm_p)
{
if (type == "BPSK" ) return module::Modem_BPSK <>::size_mod(N );
else if (type == "BPSK_FAST") return module::Modem_BPSK_fast<>::size_mod(N );
else if (type == "OOK" ) return module::Modem_OOK <>::size_mod(N );
else if (type == "SCMA" ) return module::Modem_SCMA <>::size_mod(N, bps );
else if (type == "PAM" ) return module::Modem_PAM <>::size_mod(N, bps );
else if (type == "QAM" ) return module::Modem_QAM <>::size_mod(N, bps );
else if (type == "PSK" ) return module::Modem_PSK <>::size_mod(N, bps );
else if (type == "USER" ) return module::Modem_user <>::size_mod(N, bps );
else if (type == "CPM" ) return module::Modem_CPM <>::size_mod(N, bps, cpm_L, cpm_p, upf);
throw tools::cannot_allocate(__FILE__, __LINE__, __func__);
}
int Modem
::get_buffer_size_after_filtering(const std::string &type,
const int N,
const int bps,
const int cpm_L,
const int cpm_p)
{
if (type == "BPSK" ) return module::Modem_BPSK <>::size_fil(N );
else if (type == "BPSK_FAST") return module::Modem_BPSK_fast<>::size_fil(N );
else if (type == "OOK" ) return module::Modem_OOK <>::size_fil(N );
else if (type == "SCMA" ) return module::Modem_SCMA <>::size_fil(N, bps );
else if (type == "PAM" ) return module::Modem_PAM <>::size_fil(N, bps );
else if (type == "QAM" ) return module::Modem_QAM <>::size_fil(N, bps );
else if (type == "PSK" ) return module::Modem_PSK <>::size_fil(N, bps );
else if (type == "USER" ) return module::Modem_user <>::size_fil(N, bps );
else if (type == "CPM" ) return module::Modem_CPM <>::size_fil(N, bps, cpm_L, cpm_p);
throw tools::cannot_allocate(__FILE__, __LINE__, __func__);
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template aff3ct::module::Modem<B_8 ,R_8 ,Q_8 >* aff3ct::factory::Modem::parameters::build<B_8 ,R_8 ,Q_8 >() const;
template aff3ct::module::Modem<B_8 ,R_8 ,R_8 >* aff3ct::factory::Modem::parameters::build<B_8 ,R_8 ,R_8 >() const;
template aff3ct::module::Modem<B_16,R_16,Q_16>* aff3ct::factory::Modem::parameters::build<B_16,R_16,Q_16>() const;
template aff3ct::module::Modem<B_16,R_16,R_16>* aff3ct::factory::Modem::parameters::build<B_16,R_16,R_16>() const;
template aff3ct::module::Modem<B_32,R_32,Q_32>* aff3ct::factory::Modem::parameters::build<B_32,R_32,Q_32>() const;
template aff3ct::module::Modem<B_64,R_64,Q_64>* aff3ct::factory::Modem::parameters::build<B_64,R_64,Q_64>() const;
template aff3ct::module::Modem<B_8 ,R_8 ,Q_8 >* aff3ct::factory::Modem::build<B_8 ,R_8 ,Q_8 >(const aff3ct::factory::Modem::parameters&);
template aff3ct::module::Modem<B_8 ,R_8 ,R_8 >* aff3ct::factory::Modem::build<B_8 ,R_8 ,R_8 >(const aff3ct::factory::Modem::parameters&);
template aff3ct::module::Modem<B_16,R_16,Q_16>* aff3ct::factory::Modem::build<B_16,R_16,Q_16>(const aff3ct::factory::Modem::parameters&);
template aff3ct::module::Modem<B_16,R_16,R_16>* aff3ct::factory::Modem::build<B_16,R_16,R_16>(const aff3ct::factory::Modem::parameters&);
template aff3ct::module::Modem<B_32,R_32,Q_32>* aff3ct::factory::Modem::build<B_32,R_32,Q_32>(const aff3ct::factory::Modem::parameters&);
template aff3ct::module::Modem<B_64,R_64,Q_64>* aff3ct::factory::Modem::build<B_64,R_64,Q_64>(const aff3ct::factory::Modem::parameters&);
#else
template aff3ct::module::Modem<B,R,Q>* aff3ct::factory::Modem::parameters::build<B,R,Q>() const;
template aff3ct::module::Modem<B,R,Q>* aff3ct::factory::Modem::build<B,R,Q>(const aff3ct::factory::Modem::parameters&);
#if !defined(PREC_32_BIT) && !defined(PREC_64_BIT)
template aff3ct::module::Modem<B,R,R>* aff3ct::factory::Modem::parameters::build<B,R,R>() const;
template aff3ct::module::Modem<B,R,R>* aff3ct::factory::Modem::build<B,R,R>(const aff3ct::factory::Modem::parameters&);
#endif
#endif
// ==================================================================================== explicit template instantiation
| 48.723757 | 248 | 0.537703 | [
"shape"
] |
6b610e92672fd7f399cc18460f3455d928441c48 | 709 | cpp | C++ | library/Methods/Structure/union-find/weighted-union-find.cpp | sarafanshul/KACTL | fa14ed34e93cd32d8625ed3729ba2eee55838340 | [
"MIT"
] | 127 | 2019-07-22T03:52:01.000Z | 2022-03-11T07:20:21.000Z | library/Methods/Structure/union-find/weighted-union-find.cpp | sarafanshul/KACTL | fa14ed34e93cd32d8625ed3729ba2eee55838340 | [
"MIT"
] | 39 | 2019-09-16T12:04:53.000Z | 2022-03-29T15:43:35.000Z | library/Methods/Structure/union-find/weighted-union-find.cpp | sarafanshul/KACTL | fa14ed34e93cd32d8625ed3729ba2eee55838340 | [
"MIT"
] | 29 | 2019-08-10T11:27:06.000Z | 2022-03-11T07:02:43.000Z | template< typename T >
struct WeightedUnionFind {
vector< int > data;
vector< T > ws;
WeightedUnionFind() {}
WeightedUnionFind(int sz) : data(sz, -1), ws(sz) {}
int find(int k) {
if(data[k] < 0) return k;
auto par = find(data[k]);
ws[k] += ws[data[k]];
return data[k] = par;
}
T weight(int t) {
find(t);
return ws[t];
}
bool unite(int x, int y, T w) {
w += weight(x);
w -= weight(y);
x = find(x), y = find(y);
if(x == y) return false;
if(data[x] > data[y]) {
swap(x, y);
w *= -1;
}
data[x] += data[y];
data[y] = x;
ws[y] = w;
return true;
}
T diff(int x, int y) {
return weight(y) - weight(x);
}
};
| 17.292683 | 53 | 0.490832 | [
"vector"
] |
6b613e3929c50aac6293ddb9a4f0549faee17845 | 8,509 | cpp | C++ | inject-hook-linux/hook/hook.cpp | maxcompston/inject-hook-linux | 226d5df9df5234ee1dbdee8fb8bb91b929558f23 | [
"BSD-3-Clause"
] | 2 | 2021-02-05T12:23:19.000Z | 2022-01-23T12:34:42.000Z | inject-hook-linux/hook/hook.cpp | maxcompston/inject-hook-linux | 226d5df9df5234ee1dbdee8fb8bb91b929558f23 | [
"BSD-3-Clause"
] | null | null | null | inject-hook-linux/hook/hook.cpp | maxcompston/inject-hook-linux | 226d5df9df5234ee1dbdee8fb8bb91b929558f23 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2015, Simone 'evilsocket' Margaritelli
Copyright (c) 2015, Jorrit 'Chainfire' Jongma
Copyright (c) 2019, Max Compston, Embedded Software Solutions
See LICENSE file for details
Modifications:
-- Adapted this code from Android to Linux
-- Linking and loading for Linux differs from Android
-- Hybrid adaptation to Android Interface
*/
#include <sys/mman.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include <dlfcn.h> // Adds dladdr and dlvsym
#include "plthook.h"
#include "ndklog.h"
#include "hook.h"
typedef struct ld_module {
uintptr_t address_exec_start;
uintptr_t address_exec_end;
uintptr_t address_ro_start = 0;
uintptr_t address_ro_end = 0;
uintptr_t address_rw_start = 0;
uintptr_t address_rw_end = 0;
std::string name;
ld_module(uintptr_t start, uintptr_t end, const std::string& name) :
address_exec_start(start), address_exec_end(end), name(name) {
}
void set_data_ro(uintptr_t start, uintptr_t end)
{
this->address_ro_start = start;
this->address_ro_end = end;
}
void set_data_rw(uintptr_t start, uintptr_t end)
{
this->address_rw_start = start;
this->address_rw_end = end;
}
} ld_module_t;
typedef std::vector<ld_module_t> ld_modules_t;
typedef struct hook_t {
const char *name;
uintptr_t *original;
uintptr_t hook;
hook_t(const char* n, uintptr_t* o, uintptr_t h) :
name(n), original(o), hook(h) {
}
} hook_t;
typedef std::vector<hook_t> hooks_t;
hooks_t hooks;
static ld_modules_t get_modules()
{
ld_modules_t modules;
char szPath[PATH_MAX];
char buffer[1024] = { 0 };
uintptr_t address;
uintptr_t address_end;
std::string name;
FILE *fp = fopen("/proc/self/maps", "rt");
if (fp == NULL)
{
perror("fopen");
return modules;
}
// get the Executable Path
readlink("/proc/self/exe", szPath, PATH_MAX);
std::string strPath = std::string(szPath);
// HOOKLOG("strPath: %s", strPath.c_str());
while (fgets(buffer, sizeof(buffer), fp))
{
address = (uintptr_t) strtoul(buffer, NULL, 16);
address_end = (uintptr_t) strtoul(strchr(buffer, '-') + 1, NULL, 16);
if (strchr(buffer, '/') != NULL)
{
name = strchr(buffer, '/');
}
else
{
name = strrchr(buffer, ' ') + 1;
}
name.resize(name.size() - 1);
// Skip Non Module Name
if (strchr(name.c_str(), '[') != NULL)
{
// HOOKLOG("module name: %s", name.c_str());
continue;
}
// Check if Base Name Exists
if (strrchr(buffer, '/') != NULL)
{
std::string base;
base = strrchr(buffer, '/');
base.resize(base.size());
// HOOKLOG("base name: %s", base.c_str());
std::size_t found = base.find("/ld-");
// Check if Base Name is the Link / Loader, Skip It
if (found != std::string::npos)
{
// HOOKLOG("skipping, base name: %s", base.c_str());
continue;
}
}
// If Module is the executable, skip this module
if (!name.compare(strPath))
{
continue;
}
if (strstr(buffer, "r-xp"))
{
// HOOKLOG("module[%s] exec [0x%lx]-[0x%lx]", name.c_str(), (long unsigned int)address, (long unsigned int)address_end);
modules.push_back(ld_module_t(address, address_end, name));
}
else if (strstr(buffer, "r--p"))
{
for (ld_modules_t::iterator i = modules.begin(), ie = modules.end(); i != ie; ++i)
{
if (i->name == name)
{
// HOOKLOG("module[%s] r/o [0x%lx]-[0x%lx]", name.c_str(), (long unsigned int)address, (long unsigned int)address_end);
i->set_data_ro(address, address_end);
}
}
}
else if (strstr(buffer, "rw-p"))
{
for (ld_modules_t::iterator i = modules.begin(), ie = modules.end(); i != ie; ++i)
{
if (i->name == name)
{
// HOOKLOG("module[%s] r/w [0x%lx]-[0x%lx]", name.c_str(), (long unsigned int)address, (long unsigned int)address_end);
i->set_data_rw(address, address_end);
}
}
}
}
if (fp)
{
fclose(fp);
}
return modules;
}
void _libhook_register(const char* name, uintptr_t* original, uintptr_t hook)
{
hooks.push_back(hook_t(name, original, hook));
}
void libhook_hook(int patch_module_ro, int patch_module_rw)
{
HOOKLOG("LIBRARY LOADED FROM PID %d", getpid());
plthook_t *plthook;
const char* libself = NULL;
Dl_info info;
if (dladdr((void*) &_libhook_register, &info) != 0)
{
libself = info.dli_fname;
}
HOOKLOG("LIBRARY NAME %s", libself == NULL ? "UNKNOWN" : libself);
// get a list of all loaded modules inside this process.
ld_modules_t modules = get_modules();
HOOKLOG("Found %u modules", (unsigned int)modules.size());
HOOKLOG("Installing %u hooks", (unsigned int)hooks.size());
uint32_t flags_min = FLAG_NEW_SOINFO | FLAG_LINKED;
uint32_t flags_max = (FLAG_NEW_SOINFO | FLAG_GNU_HASH | FLAG_LINKER | FLAG_EXE | FLAG_LINKED) + 0x1000 /* future */;
for (ld_modules_t::iterator i = modules.begin(), ie = modules.end(); i != ie; ++i)
{
// since we know the module is already loaded and mostly
// we DO NOT want its constructors to be called again,
// use RTLD_NOLOAD to just get its soinfo address.
// void* soinfo_base = dlopen(i->name.c_str(), 4, /*RTLD_NOLOAD*/);
HOOKLOG("i->name.c_str(): %s", i->name.c_str());
// Open the Shared Library, Check if Error Returned
if (plthook_open(&plthook, i->name.c_str()) != 0)
{
HOOKLOG("error: %s\n", plthook_error());
}
unsigned int pos = 0;
const char *symbol;
void **addr;
int rv;
while ((rv = plthook_enum(plthook, &pos, &symbol, &addr)) == 0)
{
// HOOKLOG("symbol = %s, address = %p at %p", symbol, *addr, addr);
for (hooks_t::iterator j = hooks.begin(), je = hooks.end(); j != je; ++j)
{
size_t funcnamelen = strlen(j->name);
if (strncmp(symbol, j->name, funcnamelen) == 0)
{
HOOKLOG("Found symbol = %s, address = %p at %p", symbol, *addr, addr);
// Check if symbol Valid
if (symbol[funcnamelen] == '\0' || symbol[funcnamelen] == '@')
{
int prot = get_memory_permission(addr);
if (prot == 0)
{
HOOKLOG("Plt Hook Internal Error");
}
// Set Memory Protection to Read / Write
if (!(prot & PROT_WRITE))
{
if (mprotect(ALIGN_ADDR(addr), page_size, PROT_READ | PROT_WRITE) != 0)
{
HOOKLOG("Could not change the process memory permission at %p: %s",
ALIGN_ADDR(addr), strerror(errno));
}
}
// Get the Original Function Pointer
*(j->original) = *(uintptr_t *)addr;
// Set the Address to the Hooked Function
*addr = (void *)j->hook;
HOOKLOG("Library: %s, Symbol: %s - Original: %p -> Hook: %p", i->name.c_str(), j->name, *(j->original), j->hook);
// If Protction was Write Only Set Protection Back
if (!(prot & PROT_WRITE))
{
mprotect(ALIGN_ADDR(addr), page_size, prot);
}
}
}
}
}
plthook_close(plthook);
}
// HOOKLOG("Done");
}
| 31.514815 | 138 | 0.511811 | [
"vector"
] |
6b6351ccfd4ff1741369b275f984de6bd41edf5d | 12,795 | hpp | C++ | include/ear/dsp/gain_interpolator.hpp | valnoel/libear | 1e9c162f00bff20c66adc1e75c3014ed919a6ed4 | [
"Apache-2.0"
] | null | null | null | include/ear/dsp/gain_interpolator.hpp | valnoel/libear | 1e9c162f00bff20c66adc1e75c3014ed919a6ed4 | [
"Apache-2.0"
] | null | null | null | include/ear/dsp/gain_interpolator.hpp | valnoel/libear | 1e9c162f00bff20c66adc1e75c3014ed919a6ed4 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "ear/helpers/assert.hpp"
namespace ear {
namespace dsp {
/// \file
/// Utilities for applying interpoalted gain vectors to audio samples; see
/// ear::dsp::GainInterpolator for details.
/// Type used to index into sample bufers.
using SampleIndex = long int;
/// Gain interpolator, templated over an interpolation type which defines
/// the type of interpolation (linear, cosine etc.), the type of the values
/// to interpolate between (floats, vectors, matrices), and therefore
/// restrictions on the input and output channel sizes.
///
/// An interpolation curve is defined by the points in #interp_points. Each
/// of these is a pair of the sample index and the gain values at that time.
/// These must be sorted in time order. Duplicate times can be used to
/// specify steps.
///
/// See LinearInterpSingle, LinearInterpVector and LinearInterpMatrix for
/// possible interpolation types. See InterpType for the interface that
/// interpolation types define.
//
// Internally, blocks of samples between two interpolation points are
// referred to by the 'block index', which is the index of the end of the
// block in interp_points, except for interp_points.size(), which doesn't
// have an end. An example with 3 interpolation points:
//
// interp_points: 0 1 2
// block_idx: 0 | 1 | 2 | 3
template <typename InterpType>
class GainInterpolator {
public:
std::vector<std::pair<SampleIndex, typename InterpType::Point>>
interp_points;
/// Process n samples.
/// \param block_start the index of the first sample relative to the
/// sample indices in #interp_points
/// \param nsamples number of samples in \p in and \p out
/// \param in input samples with a number of channels compatible with the
/// interpolation type and points used
/// \param out output samples with a number of channels compatible with
/// the interpolation type and points used
void process(SampleIndex block_start, size_t nsamples,
const float *const *in, float *const *out) {
SampleIndex block_end = block_start + nsamples;
SampleIndex this_block_start = block_start;
while (this_block_start < block_end) {
size_t block_idx = find_block(this_block_start);
SampleIndex this_block_end =
block_idx == interp_points.size()
? block_end
: std::min(interp_points[block_idx].first, block_end);
ear_assert(this_block_start < this_block_end,
"found block ends before processed block starts");
if (block_idx == 0 || block_idx == interp_points.size() ||
InterpType::constant_interp(interp_points[block_idx - 1].second,
interp_points[block_idx].second)) {
size_t point_with_value =
block_idx == interp_points.size() ? block_idx - 1 : block_idx;
InterpType::apply_constant(in, out, this_block_start - block_start,
this_block_end - block_start,
interp_points[point_with_value].second);
} else {
InterpType::apply_interp(in, out, this_block_start - block_start,
this_block_end - block_start, block_start,
interp_points[block_idx - 1].first,
interp_points[block_idx].first,
interp_points[block_idx - 1].second,
interp_points[block_idx].second);
}
this_block_start = this_block_end;
}
}
private:
// find whether a sample is before, after or inside a block:
// 0: sample is inside the block
// -1: sample is before the start of the block
// 1: sample is after the end of the block
int block_cmp(size_t block_idx, SampleIndex sample_idx) {
if (block_idx > 0) {
SampleIndex block_start = interp_points[block_idx - 1].first;
if (sample_idx < block_start) return -1;
}
if (block_idx < interp_points.size()) {
SampleIndex block_end = interp_points[block_idx].first;
if (sample_idx >= block_end) return 1;
}
return 0;
}
// find the block index for a sample; the last block returned is cached,
// so in common cases we don't have to look at many blocks
size_t last_block = 0;
size_t find_block(SampleIndex sample_idx) {
// last_block could be outside the allowed range if interp_points
// changed since the last call
if (last_block > interp_points.size()) last_block = 0;
// move in the direction given by block_cmp until we find the right
// block (cmp == 0); this is slightly complicated by checking that we
// are making progress.
int cmp = block_cmp(last_block, sample_idx);
int first_cmp = cmp;
while (cmp != 0) {
last_block += cmp;
if (cmp != first_cmp)
throw invalid_argument("interpolation points are not sorted");
cmp = block_cmp(last_block, sample_idx);
}
return last_block;
}
};
/// Base type for interpolation types.
template <typename PointT>
struct InterpType {
/// Type of points on the interpolation curve, for example float, vector,
/// matrix.
using Point = PointT;
/// Are the two points the same (and therefore constant/no interpolation
/// should be used between them)?
static bool constant_interp(const Point &a, const Point &b) {
return a == b;
}
/// Apply interpolated gains to \p in, writing to \p out.
///
/// For example, if an interpolation curve goes from x to y between
/// sample 5 and 15, these calls would occur for the first and second
/// 10-sample blocks:
///
/// \code
/// apply_interp(in_a, out_a, 5, 10, 0, 5, 15, x, y);
/// apply_interp(in_b, out_b, 0, 5, 10, 5, 15, x, y);
/// \endcode
///
/// \param in input samples
/// \param out output samples
/// \param range_start offset in \p in and \p out to start processing
/// \param range_end offset in \p in and \p out to end processing
/// \param block_start: start sample index of this block, i.e. in[0][0]
/// \param start: start sample index of interpolation curve
/// \param end: end sample index of interpolation curve
/// \param start_point: gain values at \p start
/// \param end_point: gain values at \p end
static void apply_interp(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
SampleIndex block_start, SampleIndex start,
SampleIndex end, const Point &start_point,
const Point &end_point);
/// Apply constnt gain gains to \p in, writing to \p out.
///
/// \param in input samples
/// \param out output samples
/// \param range_start offset in \p in and \p out to start processing
/// \param range_end offset in \p in and \p out to end processing
/// \param point: gain values to apply
static void apply_constant(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
const Point &point);
};
// interpolation implementations
/// Linear interpolation of a single channel for use in GainInterpolator.
struct LinearInterpSingle : public InterpType<float> {
static void apply_interp(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
SampleIndex block_start, SampleIndex start,
SampleIndex end, const Point &start_point,
const Point &end_point) {
float scale = 1.0f / (end - start);
for (SampleIndex i = range_start; i < range_end; i++) {
float p = (float)((block_start + i) - start) * scale;
float gain = (1.0f - p) * start_point + p * end_point;
out[0][i] = in[0][i] * gain;
}
}
static void apply_constant(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
const Point &point) {
for (SampleIndex i = range_start; i < range_end; i++) {
out[0][i] = in[0][i] * point;
}
}
};
/// Linear interpolation with one channel in and multiple out for use in
/// GainInterpolator.
struct LinearInterpVector : public InterpType<std::vector<float>> {
static void apply_interp(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
SampleIndex block_start, SampleIndex start,
SampleIndex end, const Point &start_point,
const Point &end_point) {
float scale = 1.0f / (end - start);
for (SampleIndex i = range_start; i < range_end; i++) {
float p = (float)((block_start + i) - start) * scale;
for (size_t channel = 0; channel < start_point.size(); channel++) {
float gain =
(1.0f - p) * start_point[channel] + p * end_point[channel];
out[channel][i] = in[0][i] * gain;
}
}
}
static void apply_constant(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
const Point &point) {
for (SampleIndex i = range_start; i < range_end; i++) {
for (size_t channel = 0; channel < point.size(); channel++) {
out[channel][i] = in[0][i] * point[channel];
}
}
}
};
/// Linear interpolation with multiple input and output channels, with a
/// matrix of coefficients for use in GainInterpolator.
///
/// Points contain one vector of per-output gains per input channel.
struct LinearInterpMatrix
: public InterpType<std::vector<std::vector<float>>> {
static void apply_interp(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
SampleIndex block_start, SampleIndex start,
SampleIndex end, const Point &start_point,
const Point &end_point) {
float scale = 1.0f / (end - start);
for (SampleIndex i = range_start; i < range_end; i++) {
for (size_t out_channel = 0;
out_channel < start_point.size() ? start_point[0].size() : 0;
out_channel++) {
out[out_channel][i] = 0.0;
}
float p = (float)((block_start + i) - start) * scale;
for (size_t in_channel = 0; in_channel < start_point.size();
in_channel++) {
for (size_t out_channel = 0;
out_channel < start_point[in_channel].size(); out_channel++) {
float gain = (1.0f - p) * start_point[in_channel][out_channel] +
p * end_point[in_channel][out_channel];
out[out_channel][i] += in[in_channel][i] * gain;
}
}
}
}
static void apply_constant(const float *const *in, float *const *out,
SampleIndex range_start, SampleIndex range_end,
const Point &point) {
for (SampleIndex i = range_start; i < range_end; i++) {
for (size_t out_channel = 0;
out_channel < point.size() ? point[0].size() : 0;
out_channel++) {
out[out_channel][i] = 0.0;
}
for (size_t in_channel = 0; in_channel < point.size(); in_channel++) {
for (size_t out_channel = 0; out_channel < point[in_channel].size();
out_channel++) {
out[out_channel][i] +=
in[in_channel][i] * point[in_channel][out_channel];
}
}
}
}
};
} // namespace dsp
} // namespace ear
| 43.372881 | 80 | 0.571317 | [
"vector"
] |
6b782fabeb43ea87546d848c1a6fe17729f4c653 | 679 | hpp | C++ | src/model.hpp | wojtex/songbook-generator | 5ed4a901587231b75a79a54286793bf1de1ad0e9 | [
"MIT"
] | null | null | null | src/model.hpp | wojtex/songbook-generator | 5ed4a901587231b75a79a54286793bf1de1ad0e9 | [
"MIT"
] | null | null | null | src/model.hpp | wojtex/songbook-generator | 5ed4a901587231b75a79a54286793bf1de1ad0e9 | [
"MIT"
] | null | null | null | #pragma once
#include "source.hpp"
#include <vector>
#include <QAbstractItemModel>
namespace Cantionale
{
class Model : public QAbstractTableModel
{
Q_OBJECT
public:
Model(QObject *parent);
~Model();
int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE ;
int columnCount(const QModelIndex& parent = QModelIndex()) const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE;
std::vector<Source*> getSources() const;
Source * getSource(int index) const;
private:
std::vector<Source*> sources;
};
} | 26.115385 | 98 | 0.656848 | [
"vector",
"model"
] |
6b7e098b38115129a4657620667e8bdf46f82b34 | 7,941 | cpp | C++ | src/utilprocess.cpp | dendisuhubdy/BitcoinUnlimited | 68d87c9d637583e8b89218f969caf624a76141cc | [
"MIT"
] | 3 | 2019-11-28T13:45:44.000Z | 2021-05-22T07:18:15.000Z | src/utilprocess.cpp | dendisuhubdy/BitcoinUnlimited | 68d87c9d637583e8b89218f969caf624a76141cc | [
"MIT"
] | null | null | null | src/utilprocess.cpp | dendisuhubdy/BitcoinUnlimited | 68d87c9d637583e8b89218f969caf624a76141cc | [
"MIT"
] | 3 | 2019-10-26T03:34:45.000Z | 2021-08-17T15:35:30.000Z | // Copyright (c) 2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "utilprocess.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <boost/predef/os.h>
#include <sstream>
#if BOOST_OS_LINUX
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <spawn.h>
#include <sys/wait.h>
#endif
unsupported_platform_error::unsupported_platform_error(const std::string &func_name)
: std::runtime_error("Function '" + func_name + "' is not implemented on this platform")
{
}
std::string this_process_path()
{
// this could be implemented with boost::dll::program_location, however
// with current boost version on linux this adds a linker dependency to libdl.
#if BOOST_OS_LINUX
// TODO: Replaced with std::read_symlink with C++17
return boost::filesystem::read_symlink("/proc/self/exe").string();
#else
throw unsupported_platform_error(__func__);
#endif
}
#if BOOST_OS_LINUX
class posix_error : public subprocess_error
{
public:
//! fetches error number from (thread-local) global errno
posix_error(const std::string &operation) : subprocess_error(operation + ": " + std::string(strerror(errno))) {}
posix_error(const std::string &operation, int _errno)
: subprocess_error(operation + ": " + std::string(strerror(_errno)))
{
}
};
#define THROW_IF_RETERROR(cond) \
{ \
int errno_ = cond; \
if (errno_ != 0) \
{ \
throw posix_error(#cond, errno_); \
} \
}
#define THROW_CHECK_ERRNO(cond) \
{ \
if ((cond) != 0) \
{ \
throw posix_error(#cond); \
} \
}
#endif
SubProcess::SubProcess(const std::string &path_,
const std::vector<std::string> &args_,
getline_callb stdout_callb_,
getline_callb stderr_callb_)
: path(path_), args(args_), stdout_callb(stdout_callb_), stderr_callb(stderr_callb_), pid(-1), is_running(false),
run_started(false)
{
#if !BOOST_OS_LINUX
throw unsupported_platform_error(__func__);
#endif
}
SubProcess::~SubProcess()
{
#ifdef DEBUG_ASSERTION
assert(!run_started);
#endif
if (!run_started)
{
return;
}
LOGA("CRITICAL ERROR: ~SubProcess called while process is running.");
try
{
// Try to recover
Terminate();
while (run_started)
{
std::this_thread::yield();
}
}
catch (...)
{
LOGA("~SubProcess failed to terminate process");
}
}
void extract_line(std::string &buffer, getline_callb &callb)
{
size_t pos = 0;
while ((pos = buffer.find('\n')) != std::string::npos)
{
callb(buffer.substr(0, pos));
buffer.erase(0, pos + 1);
}
}
#if BOOST_OS_LINUX
struct RunCleanupRAII
{
std::atomic<bool> &is_running;
std::atomic<bool> &run_started;
posix_spawn_file_actions_t *action;
~RunCleanupRAII()
{
run_started.store(false);
is_running.store(false);
if (action != nullptr)
{
posix_spawn_file_actions_destroy(action);
}
}
};
#endif
void SubProcess::Run()
{
DbgAssert(!run_started, return );
#if BOOST_OS_LINUX
run_started.store(true);
RunCleanupRAII cleanup{is_running, run_started, nullptr};
const size_t PARENT = 0;
const size_t CHILD = 1;
int cout_pipe[2];
int cerr_pipe[2];
THROW_CHECK_ERRNO(pipe(cout_pipe));
THROW_CHECK_ERRNO(pipe(cerr_pipe));
// Plumbing to access the child process' stdout and stderr
posix_spawn_file_actions_t action;
THROW_IF_RETERROR(posix_spawn_file_actions_init(&action));
cleanup.action = &action;
THROW_IF_RETERROR(posix_spawn_file_actions_addclose(&action, cout_pipe[PARENT]));
THROW_IF_RETERROR(posix_spawn_file_actions_addclose(&action, cerr_pipe[PARENT]));
THROW_IF_RETERROR(posix_spawn_file_actions_adddup2(&action, cout_pipe[CHILD], 1));
THROW_IF_RETERROR(posix_spawn_file_actions_adddup2(&action, cerr_pipe[CHILD], 2));
THROW_IF_RETERROR(posix_spawn_file_actions_addclose(&action, cout_pipe[CHILD]));
THROW_IF_RETERROR(posix_spawn_file_actions_addclose(&action, cerr_pipe[CHILD]));
// Spawn the child process
std::string filename = boost::filesystem::path(path).filename().string();
std::vector<char *> cmdargs(1 + args.size() + 1);
cmdargs[0] = const_cast<char *>(filename.c_str());
for (size_t i = 0; i < args.size(); ++i)
{
cmdargs[i + 1] = const_cast<char *>(args[i].c_str());
}
cmdargs[cmdargs.size() - 1] = nullptr;
pid_t child_pid;
THROW_IF_RETERROR(posix_spawnp(&child_pid, path.c_str(), &action, nullptr, &cmdargs[0], nullptr));
pid.store(child_pid);
is_running.store(true);
// Close child side of pipes
THROW_CHECK_ERRNO(close(cout_pipe[CHILD]));
THROW_CHECK_ERRNO(close(cerr_pipe[CHILD]));
// Read stdin, stdout
std::string buffer(1024, '\0');
std::vector<pollfd> plist = {{cout_pipe[PARENT], POLLIN, 0}, {cerr_pipe[PARENT], POLLIN, 0}};
std::string stdout_buffer;
std::string stderr_buffer;
while (true)
{
const int timeout = -1;
int rc = poll(&plist[0], plist.size(), timeout);
if (rc == -1)
{
LOGA("%s: poll error %s", __func__, strerror(errno));
break;
}
if (rc == 0)
{
// timeout, this shouldn't happen
LOGA("%s: unexpected poll timeout", __func__);
break;
}
const size_t PIPE_STDOUT = 0;
const size_t PIPE_STDERR = 1;
if (plist[PIPE_STDOUT].revents & POLLIN)
{
int bytes_read = read(cout_pipe[PARENT], &buffer[0], buffer.length());
stdout_buffer += buffer.substr(0, static_cast<size_t>(bytes_read));
extract_line(stdout_buffer, stdout_callb);
continue;
}
if (plist[PIPE_STDERR].revents & POLLIN)
{
int bytes_read = read(cerr_pipe[PARENT], &buffer[0], buffer.length());
stderr_buffer += buffer.substr(0, static_cast<size_t>(bytes_read));
extract_line(stderr_buffer, stderr_callb);
continue;
}
// nothing left to read
break;
}
int status;
if (waitpid(pid, &status, 0) == -1)
{
throw subprocess_error("waitpid failed");
}
if (WIFEXITED(status))
{
int exit_status = WEXITSTATUS(status);
if (exit_status != 0)
{
subprocess_error err("exited with error");
err.exit_status = exit_status;
throw err;
}
}
else if (WIFSIGNALED(status))
{
subprocess_error err("terminated by signal");
err.termination_signal = WTERMSIG(status);
throw err;
}
else
{
throw subprocess_error("unknown termination reason");
}
#endif
}
void SubProcess::SendSignal(int signal)
{
#if BOOST_OS_LINUX
int curr_pid = pid; // copy to avoid a race
if (curr_pid == -1)
{
std::stringstream err;
err << "Cannot signal " << signal << " to " << path << ", process is not running.";
throw subprocess_error(err.str());
}
if (kill(static_cast<pid_t>(curr_pid), signal) != 0)
{
std::stringstream err;
err << "Failed to send signal " << signal << " to pid " << curr_pid;
throw subprocess_error(err.str());
}
#endif
}
void SubProcess::Interrupt()
{
#if BOOST_OS_LINUX
SendSignal(SIGINT);
#endif
}
void SubProcess::Terminate()
{
#if BOOST_OS_LINUX
SendSignal(SIGKILL);
#endif
}
| 27.961268 | 117 | 0.607984 | [
"vector"
] |
6b843cc1c4efba869ee6a7f059d160f3c2ec721a | 5,677 | cpp | C++ | tests/qi/test_bind.cpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 61 | 2015-01-08T08:05:28.000Z | 2022-01-07T16:47:47.000Z | tests/qi/test_bind.cpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 30 | 2015-04-06T21:41:18.000Z | 2021-08-18T13:24:51.000Z | tests/qi/test_bind.cpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 64 | 2015-02-23T20:01:11.000Z | 2022-03-14T13:31:20.000Z | #include <gtest/gtest.h>
#include <boost/thread.hpp>
#include <ka/macro.hpp>
KA_WARNING_PUSH()
KA_WARNING_DISABLE(4996, deprecated-declarations) // ignore use of deprecated overloads.
#include <qi/trackable.hpp>
KA_WARNING_POP()
#include <qi/future.hpp>
#include <qi/actor.hpp>
#include "test_future.hpp"
qiLogCategory("test");
int exchange(int& target, int value)
{
int old = target;
target = value;
return old;
}
// wrap a call, waiting before, and notifying state
void wrap(boost::function<void()> op, qi::MilliSeconds delay, std::atomic<int>& notify)
{
notify = 1;
if (delay != qi::MilliSeconds::zero())
boost::this_thread::sleep_for(delay);
notify = 2;
try {
op();
}
catch (const qi::PointerLockException&)
{}
notify = 3;
}
TEST(TestBind, Simple)
{
int v = 0;
KA_WARNING_PUSH()
KA_WARNING_DISABLE(4996, deprecated-declarations) // ignore use of deprecated overloads
qi::bind<void(int)>(&exchange, std::ref(v), _1)(15);
EXPECT_EQ(15, v);
qi::bind<void(void)>(&exchange, std::ref(v), 16)();
KA_WARNING_POP()
EXPECT_EQ(16, v);
qi::bind(&exchange, std::ref(v), _1)(15);
EXPECT_EQ(15, v);
qi::bind(&exchange, std::ref(v), 16)();
EXPECT_EQ(16, v);
}
TEST(TestBind, MemFun)
{
std::atomic<int> v{0};
SetValue s1(v);
qi::bind(&SetValue::exchange, &s1, _1)(1);
EXPECT_EQ(1, v);
qi::bind(&SetValue::exchange, &s1, 2)();
EXPECT_EQ(2, v);
qi::bind(&SetValue::exchange, boost::ref(s1), _1)(3);
EXPECT_EQ(3, v);
qi::bind(&SetValue::exchange, boost::ref(s1), 4)();
EXPECT_EQ(4, v);
}
TEST(TestBind, SharedPtr)
{
std::atomic<int> v{0};
boost::shared_ptr<SetValue> s(new SetValue(v));
qi::bind(&SetValue::exchange, s, _1)(1);
EXPECT_EQ(1, v);
qi::bind(&SetValue::exchange, s, 2)();
EXPECT_EQ(2, v);
boost::function<void(void)> f = qi::bind(&SetValue::exchange, s, 3);
s.reset();
f();
EXPECT_EQ(3, v);
}
TEST(TestBind, WeakPtr)
{
std::atomic<int> v{0};
boost::shared_ptr<SetValue> s(new SetValue(v));
boost::weak_ptr<SetValue> w(s);
qi::bind(&SetValue::exchange, w, _1)(1);
EXPECT_EQ(1, v);
qi::bind(&SetValue::exchange, w, 2)();
EXPECT_EQ(2, v);
boost::function<void(void)> f = qi::bind(&SetValue::exchange, w, 3);
s.reset();
EXPECT_ANY_THROW(f());
EXPECT_EQ(2, v);
}
TEST(TestBind, Trackable)
{
std::atomic<int> v{0};
{
KA_WARNING_PUSH()
KA_WARNING_DISABLE(4996, deprecated-declarations) // ignore use of deprecated overloads
SetValue2 s1(v);
qi::bind<void(int)>(&SetValue2::exchange, &s1, _1)(1);
EXPECT_EQ(1, v);
qi::bind<void(void)>(&SetValue2::exchange, &s1, 2)();
EXPECT_EQ(2, v);
qi::bind<void(int)>(&SetValue2::exchange, boost::ref(s1), _1)(3);
EXPECT_EQ(3, v);
qi::bind<void(void)>(&SetValue2::exchange, boost::ref(s1), 4)();
EXPECT_EQ(4, v);
KA_WARNING_POP()
}
v = 0;
{
SetValue2 s1(v);
qi::bind(&SetValue2::exchange, &s1, _1)(1);
EXPECT_EQ(1, v);
qi::bind(&SetValue2::exchange, &s1, 2)();
EXPECT_EQ(2, v);
qi::bind(&SetValue2::exchange, boost::ref(s1), _1)(3);
EXPECT_EQ(3, v);
qi::bind(&SetValue2::exchange, boost::ref(s1), 4)();
EXPECT_EQ(4, v);
}
boost::function<void(void)> f;
{
SetValue2 s1(v);
f = qi::bind(&SetValue2::exchange, &s1, 5);
}
EXPECT_ANY_THROW(f()); // s1 is trackable, bound and deleted: callback not executed
EXPECT_EQ(4, v);
// check waiting behavior of destroy
std::atomic<int> notify{0};
{
SetValue2 s1(v);
KA_WARNING_PUSH()
KA_WARNING_DISABLE(4996, deprecated-declarations) // ignore use of deprecated overloads
boost::thread(wrap,
qi::bind<void(void)>(&SetValue2::delayExchange, &s1, qi::MilliSeconds{100}, 10),
qi::MilliSeconds{ 0 },
std::ref(notify));
KA_WARNING_POP()
// wait enough for operation to start
while (!notify)
std::this_thread::sleep_for(std::chrono::milliseconds{10});
// exit scope, deleting s1, which should block until operation terminates
}
EXPECT_EQ(10, v);
// check disable-call behavior again in our more complex threaded setup
{
notify = 0;
SetValue2 s1(v);
boost::thread(wrap,
qi::bind(&SetValue2::delayExchange, &s1, qi::MilliSeconds{100}, 11),
qi::MilliSeconds{ 50 },
std::ref(notify));
}
while (notify != 3)
std::this_thread::sleep_for(std::chrono::milliseconds{10});
EXPECT_EQ(10, v); //call not made
}
TEST(TestBind, BindLambda)
{
auto f = qi::bind<int>([](int i){ return i; }, 18);
ASSERT_EQ(18, f());
}
namespace {
using SomeData = std::vector<int>;
struct ActorType : public qi::Actor
{
~ActorType()
{
qi::Actor::joinTasks();
}
// must return a future for the test to reproduce real common use case
qi::Future<int> run(const SomeData&) { return qi::Future<int>{42}; }
};
struct NotActorType
{
// must return a future for the test to reproduce real common use case
qi::Future<int> run(const SomeData&) { return qi::Future<int>{42}; }
};
template<typename T>
struct TestBindActor : ::testing::Test {};
using ObjectTypeList = ::testing::Types<ActorType, NotActorType>;
TYPED_TEST_CASE(TestBindActor, ObjectTypeList);
}
TYPED_TEST(TestBindActor, BindObjectWrappedFunc)
{
auto p = std::make_shared<TypeParam>();
const SomeData data;
static auto f = [](TypeParam* self, const SomeData& data) { return self->run(data); };
using ReturnType = decltype(f(p.get(), data));
static std::function<ReturnType(TypeParam*, const SomeData&)> sf{ f };
auto fu = qi::bind(sf, p.get(), data);
auto result = qi::detail::tryUnwrap(qi::async(fu));
static_assert(std::is_same<decltype(result), ::qi::Future<int>>::value, "");
}
| 25.922374 | 88 | 0.644354 | [
"vector"
] |
6b84bbf616aaaa3ad5a91a0be3550300c3b73096 | 17,762 | cc | C++ | frameworks/tf/layer_norm_lstm.cc | nammingi/haste | 459608cfdb4de4d28d2213df8e71f005be8d0f35 | [
"Apache-2.0"
] | 291 | 2020-01-29T19:46:28.000Z | 2022-03-31T22:41:27.000Z | frameworks/tf/layer_norm_lstm.cc | nammingi/haste | 459608cfdb4de4d28d2213df8e71f005be8d0f35 | [
"Apache-2.0"
] | 43 | 2020-02-24T22:25:13.000Z | 2022-03-07T20:08:43.000Z | frameworks/tf/layer_norm_lstm.cc | nammingi/haste | 459608cfdb4de4d28d2213df8e71f005be8d0f35 | [
"Apache-2.0"
] | 28 | 2020-02-07T02:51:19.000Z | 2022-01-12T08:44:15.000Z | // Copyright 2020 LMNT, Inc. 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 <cuda_runtime_api.h>
#include "arena.h"
#include "haste.h"
#include "support.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/util/stream_executor_util.h"
#include "tensorflow/stream_executor/stream.h"
using namespace tensorflow;
using tensorflow::se::Stream;
using tensorflow::shape_inference::DimensionHandle;
using tensorflow::shape_inference::InferenceContext;
using tensorflow::shape_inference::ShapeHandle;
namespace layer_norm = haste::v0::layer_norm;
namespace layer_norm_lstm = haste::v0::layer_norm_lstm;
// Define the interface and shape function for the op.
REGISTER_OP("HasteLayerNormLstm")
.Attr("R: {float, double}") // Some real number type.
.Attr("training: bool")
.Attr("zoneout_prob: float")
.Input("x: R") // [T,N,C]
.Input("kernel: R") // [C,H*4]
.Input("recurrent_kernel: R") // [H,H*4]
.Input("bias: R") // [H*4]
.Input("gamma: R")
.Input("gamma_h: R")
.Input("beta_h: R")
.Input("zoneout_mask: R") // [T,N,H]
.Output("h: R") // [T,N,H]
.Output("c: R") // [T,N,H]
.Output("cache: R") // [?] (activations cache)
.SetShapeFn([](InferenceContext* c) {
ShapeHandle input_shape;
ShapeHandle kernel_shape;
ShapeHandle recurrent_shape;
ShapeHandle bias_shape;
ShapeHandle gamma_shape;
ShapeHandle gamma_h_shape;
ShapeHandle beta_h_shape;
ShapeHandle zoneout_mask_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 3, &input_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &kernel_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &recurrent_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &bias_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &gamma_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(5), 1, &gamma_h_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(6), 1, &beta_h_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(7), 3, &zoneout_mask_shape));
const DimensionHandle time_steps = c->Dim(input_shape, 0);
const DimensionHandle batch_size = c->Dim(input_shape, 1);
const DimensionHandle hidden_size = c->Dim(recurrent_shape, 0);
DimensionHandle time_steps_plus_1;
TF_RETURN_IF_ERROR(c->Add(time_steps, 1, &time_steps_plus_1));
c->set_output(0, c->MakeShape({ time_steps_plus_1, batch_size, hidden_size }));
c->set_output(1, c->MakeShape({ time_steps_plus_1, batch_size, hidden_size }));
c->set_output(2, c->UnknownShapeOfRank(1));
return Status::OK();
});
template<typename T>
struct HasteLayerNormLstmOp : public OpKernel {
explicit HasteLayerNormLstmOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("training", &training_));
OP_REQUIRES_OK(context, context->GetAttr("zoneout_prob", &zoneout_prob_));
}
// When running on GPU, TF backs all inputs and outputs with device memory
// and not host memory. We don't need to do explicit memory copies or allocations
// for the inputs and outputs.
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
const Tensor& kernel = context->input(1);
const Tensor& recurrent_kernel = context->input(2);
const Tensor& bias = context->input(3);
const Tensor& gamma = context->input(4);
const Tensor& gamma_h = context->input(5);
const Tensor& beta_h = context->input(6);
const Tensor& zoneout_mask = context->input(7);
const auto time_steps = input.shape().dim_size(0);
const auto batch_size = input.shape().dim_size(1);
const auto input_size = input.shape().dim_size(2);
const auto hidden_size = recurrent_kernel.shape().dim_size(0);
const bool has_zoneout = zoneout_prob_ && zoneout_mask.NumElements();
const auto data_type = DataTypeToEnum<T>::value;
OP_REQUIRES(context, input_size == kernel.shape().dim_size(0),
errors::InvalidArgument("input[2] and kernel[0] dimensions must match. Found ",
input_size, " and ", kernel.shape().dim_size(0)));
const TensorShape output_shape = { time_steps + 1, batch_size, hidden_size };
const TensorShape activations_shape = { time_steps, batch_size, hidden_size * 4 };
const TensorShape norm_cache_shape = { time_steps, batch_size, 2 };
Tensor* output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
Tensor* output_cell_state = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(1, output_shape, &output_cell_state));
const ArenaLayout<T> memory_layout = {
{ "act_Wx", activations_shape },
{ "act_Wx_norm", activations_shape },
{ "act_Wx_norm_cache", norm_cache_shape },
{ "act_Rh", activations_shape },
{ "act_Rh_norm_cache", norm_cache_shape },
{ "act_c_norm", { time_steps, batch_size, hidden_size } },
{ "act_c_norm_cache", norm_cache_shape },
};
Tensor* output_cache = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(2, { memory_layout.NumElements() }, &output_cache));
Arena<T> memory = memory_layout.Realize(output_cache->flat<T>().data());
TensorView<T> act_Wx = memory["act_Wx"];
TensorView<T> act_Wx_norm = memory["act_Wx_norm"];
TensorView<T> act_Wx_norm_cache = memory["act_Wx_norm_cache"];
TensorView<T> act_Rh = memory["act_Rh"];
TensorView<T> act_Rh_norm_cache = memory["act_Rh_norm_cache"];
TensorView<T> act_c_norm = memory["act_c_norm"];
TensorView<T> act_c_norm_cache = memory["act_c_norm_cache"];
Tensor tmp_Rh;
const TensorShape tmp_Rh_shape = { batch_size, 4 * hidden_size };
OP_REQUIRES_OK(context, context->allocate_temp(data_type, tmp_Rh_shape, &tmp_Rh));
cudaMemset(output->flat<T>().data(), 0, output->AllocatedBytes());
cudaMemset(output_cell_state->flat<T>().data(), 0, output_cell_state->AllocatedBytes());
layer_norm::ForwardPass<T> layer_norm1(
time_steps * batch_size,
hidden_size * 4,
gamma.SubSlice(0).unaligned_flat<T>().data(),
nullptr,
act_Wx_norm_cache.data());
layer_norm::ForwardPass<T> layer_norm2(
time_steps * batch_size,
hidden_size * 4,
gamma.SubSlice(1).unaligned_flat<T>().data(),
nullptr,
act_Rh_norm_cache.data());
layer_norm::ForwardPass<T> layer_norm3(
time_steps * batch_size,
hidden_size,
gamma_h.flat<T>().data(),
beta_h.flat<T>().data(),
act_c_norm_cache.data());
layer_norm_lstm::ForwardPass<T> lstm(
training_,
batch_size,
input_size,
hidden_size,
GetCublasHandle(context));
lstm.Run(
time_steps,
kernel.flat<T>().data(),
recurrent_kernel.flat<T>().data(),
bias.flat<T>().data(),
input.flat<T>().data(),
output->flat<T>().data(),
output_cell_state->flat<T>().data(),
act_Wx.data(),
tmp_Rh.flat<T>().data(),
layer_norm1,
act_Wx_norm.data(),
act_Rh.data(),
layer_norm2,
layer_norm3,
act_c_norm.data(),
has_zoneout ? zoneout_prob_ : 0.0f,
has_zoneout ? zoneout_mask.flat<T>().data() : nullptr);
}
private:
bool training_;
float zoneout_prob_;
};
REGISTER_GPU_KERNEL(HasteLayerNormLstm, float);
REGISTER_GPU_KERNEL(HasteLayerNormLstm, double);
REGISTER_OP("HasteLayerNormLstmGrad")
.Attr("R: {float, double}")
.Input("x_t: R") // [C,N,T]
.Input("kernel_t: R") // [H*4,C]
.Input("recurrent_kernel_t: R") // [H*4,H]
.Input("bias: R") // [H*4]
.Input("gamma: R")
.Input("gamma_h: R")
.Input("beta_h: R")
.Input("h: R") // [T,N,H]
.Input("c: R") // [T,N,H]
.Input("cache: R")
.Input("dh_new: R") // [T,N,H]
.Input("dc_new: R") // [T,N,H]
.Input("zoneout_mask: R") // [T,N,H]
.Output("dx: R") // [T,N,C]
.Output("dw: R") // [C,H*4]
.Output("dr: R") // [H,H*4]
.Output("db: R") // [H*4]
.Output("dgamma: R")
.Output("dgamma_h: R")
.Output("dbeta_h: R")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle x_shape;
ShapeHandle kernel_shape;
ShapeHandle recurrent_kernel_shape;
ShapeHandle bias_shape;
ShapeHandle gamma_shape;
ShapeHandle gamma_h_shape;
ShapeHandle beta_h_shape;
ShapeHandle h_shape;
ShapeHandle c_shape;
ShapeHandle cache_shape;
ShapeHandle dh_new_shape;
ShapeHandle dc_new_shape;
ShapeHandle zoneout_mask_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 3, &x_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &kernel_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &recurrent_kernel_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &bias_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 2, &gamma_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(5), 1, &gamma_h_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(6), 1, &beta_h_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(7), 3, &h_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(8), 3, &c_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(9), 1, &cache_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(10), 3, &dh_new_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(11), 3, &dc_new_shape));
TF_RETURN_IF_ERROR(c->WithRank(c->input(12), 3, &zoneout_mask_shape));
DimensionHandle input_size = c->Dim(x_shape, 0);
DimensionHandle time_steps = c->Dim(x_shape, 1);
DimensionHandle batch_size = c->Dim(x_shape, 2);
DimensionHandle hidden_size = c->Dim(recurrent_kernel_shape, 1);
DimensionHandle hidden_size_4;
TF_RETURN_IF_ERROR(c->Multiply(hidden_size, 4, &hidden_size_4));
c->set_output(0, c->MakeShape({ time_steps, batch_size, input_size }));
c->set_output(1, c->MakeShape({ input_size, hidden_size_4 }));
c->set_output(2, c->MakeShape({ hidden_size, hidden_size_4 }));
c->set_output(3, bias_shape);
c->set_output(4, gamma_shape);
c->set_output(5, gamma_h_shape);
c->set_output(6, beta_h_shape);
return Status::OK();
});
template<typename T>
struct HasteLayerNormLstmGradOp : public OpKernel {
explicit HasteLayerNormLstmGradOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
const Tensor& kernel = context->input(1);
const Tensor& recurrent_kernel = context->input(2);
const Tensor& bias = context->input(3);
const Tensor& gamma = context->input(4);
const Tensor& gamma_h = context->input(5);
const Tensor& beta_h = context->input(6);
const Tensor& h_vector = context->input(7);
const Tensor& c_vector = context->input(8);
const Tensor& cache_input = context->input(9);
const Tensor& dh_new = context->input(10);
const Tensor& dc_new = context->input(11);
const Tensor& zoneout_mask = context->input(12);
const auto input_size = input.shape().dim_size(0);
const auto time_steps = input.shape().dim_size(1);
const auto batch_size = input.shape().dim_size(2);
const auto hidden_size = recurrent_kernel.shape().dim_size(1);
const bool has_zoneout = !!zoneout_mask.NumElements();
const auto data_type = DataTypeToEnum<T>::value;
// Can be uninitialized. Output only, no accumulation.
const TensorShape dx_shape = { time_steps, batch_size, input_size };
Tensor* dx = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, dx_shape, &dx));
// Needs to be initialized to 0.
const TensorShape dW_shape = { input_size, hidden_size * 4 };
Tensor* dW = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(1, dW_shape, &dW));
// Needs to be initialized to 0.
const TensorShape dR_shape = { hidden_size, hidden_size * 4 };
Tensor* dR = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(2, dR_shape, &dR));
// Needs to be initialized to 0.
const TensorShape db_shape = { hidden_size * 4 };
Tensor* db = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(3, db_shape, &db));
// Needs to be initialized to 0.
Tensor* dgamma = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(4, gamma.shape(), &dgamma));
// Needs to be initialized to 0.
Tensor* dgamma_h = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(5, gamma_h.shape(), &dgamma_h));
// Needs to be initialized to 0.
Tensor* dbeta_h = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(6, beta_h.shape(), &dbeta_h));
// Needs to be initialized to 0.
const TensorShape dh_shape = { batch_size, hidden_size };
Tensor dh;
OP_REQUIRES_OK(context, context->allocate_temp(data_type, dh_shape, &dh));
// Needs to be initialized to 0.
const TensorShape dc_shape = { batch_size, hidden_size };
Tensor dc;
OP_REQUIRES_OK(context, context->allocate_temp(data_type, dc_shape, &dc));
const TensorShape activations_shape = { time_steps, batch_size, hidden_size * 4 };
const TensorShape norm_cache_shape = { time_steps, batch_size, 2 };
const ArenaLayout<T> memory_layout = {
{ "act_Wx", activations_shape },
{ "act_Wx_norm", activations_shape },
{ "act_Wx_norm_cache", norm_cache_shape },
{ "act_Rh", activations_shape },
{ "act_Rh_norm_cache", norm_cache_shape },
{ "act_c_norm", { time_steps, batch_size, hidden_size } },
{ "act_c_norm_cache", norm_cache_shape },
};
assert(cache_input.shape().num_elements() == memory_layout.NumElements());
Arena<T> memory = memory_layout.Realize(const_cast<T*>(cache_input.flat<T>().data()));
TensorView<T> act_Wx = memory["act_Wx"];
TensorView<T> act_Wx_norm = memory["act_Wx_norm"];
TensorView<T> act_Wx_norm_cache = memory["act_Wx_norm_cache"];
TensorView<T> act_Rh = memory["act_Rh"];
TensorView<T> act_Rh_norm_cache = memory["act_Rh_norm_cache"];
TensorView<T> act_c_norm = memory["act_c_norm"];
TensorView<T> act_c_norm_cache = memory["act_c_norm_cache"];
cudaMemset(dW->flat<T>().data(), 0, dW->AllocatedBytes());
cudaMemset(dR->flat<T>().data(), 0, dR->AllocatedBytes());
cudaMemset(db->flat<T>().data(), 0, db->AllocatedBytes());
cudaMemset(dgamma->flat<T>().data(), 0, dgamma->AllocatedBytes());
cudaMemset(dgamma_h->flat<T>().data(), 0, dgamma_h->AllocatedBytes());
cudaMemset(dbeta_h->flat<T>().data(), 0, dbeta_h->AllocatedBytes());
cudaMemset(dh.flat<T>().data(), 0, dh.AllocatedBytes());
cudaMemset(dc.flat<T>().data(), 0, dc.AllocatedBytes());
layer_norm::BackwardPass<T> layer_norm1(
time_steps * batch_size,
hidden_size * 4,
gamma.SubSlice(0).unaligned_flat<T>().data(),
nullptr,
act_Wx.data(),
dgamma->SubSlice(0).unaligned_flat<T>().data(),
nullptr,
act_Wx_norm_cache.data());
layer_norm::BackwardPass<T> layer_norm2(
time_steps * batch_size,
hidden_size * 4,
gamma.SubSlice(1).unaligned_flat<T>().data(),
nullptr,
act_Rh.data(),
dgamma->SubSlice(1).unaligned_flat<T>().data(),
nullptr,
act_Rh_norm_cache.data());
layer_norm::BackwardPass<T> layer_norm3(
time_steps * batch_size,
hidden_size,
gamma_h.flat<T>().data(),
beta_h.flat<T>().data(),
c_vector.SubSlice(1).unaligned_flat<T>().data(),
dgamma_h->flat<T>().data(),
dbeta_h->flat<T>().data(),
act_c_norm_cache.data());
layer_norm_lstm::BackwardPass<T> lstm(
batch_size,
input_size,
hidden_size,
GetCublasHandle(context));
lstm.Run(
time_steps,
kernel.flat<T>().data(),
recurrent_kernel.flat<T>().data(),
bias.flat<T>().data(),
input.flat<T>().data(),
h_vector.flat<T>().data(),
c_vector.flat<T>().data(),
dh_new.flat<T>().data(),
dc_new.flat<T>().data(),
dx->flat<T>().data(),
dW->flat<T>().data(),
dR->flat<T>().data(),
db->flat<T>().data(),
dh.flat<T>().data(),
dc.flat<T>().data(),
act_Wx.data(),
layer_norm1,
act_Wx_norm.data(),
act_Rh.data(),
layer_norm2,
layer_norm3,
act_c_norm.data(),
has_zoneout ? zoneout_mask.flat<T>().data() : nullptr);
}
};
REGISTER_GPU_KERNEL(HasteLayerNormLstmGrad, float);
REGISTER_GPU_KERNEL(HasteLayerNormLstmGrad, double);
| 39.914607 | 105 | 0.643283 | [
"shape"
] |
6b873a536e7b1fb8afd8fba3076529bf83d31b58 | 917 | cpp | C++ | src/lib/Analysis/AnalysisManager.cpp | cgsdfc/Optimize | f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3 | [
"MIT"
] | 1 | 2019-07-13T16:40:47.000Z | 2019-07-13T16:40:47.000Z | src/lib/Analysis/AnalysisManager.cpp | cgsdfc/simplecc | f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3 | [
"MIT"
] | null | null | null | src/lib/Analysis/AnalysisManager.cpp | cgsdfc/simplecc | f3a28ccd5caf01d2a306859d641a1cb5aa0d36f3 | [
"MIT"
] | null | null | null | #include "simplecc/Analysis/AnalysisManager.h"
#include "simplecc/AST/ASTVerifier.h"
#include "simplecc/Analysis/ArrayBoundChecker.h"
#include "simplecc/Analysis/ImplicitCallTransformer.h"
#include "simplecc/Analysis/SymbolTableBuilder.h"
#include "simplecc/Analysis/SyntaxChecker.h"
#include "simplecc/Analysis/TypeChecker.h"
using namespace simplecc;
AnalysisManager::~AnalysisManager() = default;
bool AnalysisManager::runAllAnalyses(ProgramAST *P) {
if (SyntaxChecker().Check(P)) {
return true;
}
if (SymbolTableBuilder().Build(P, TheTable)) {
return true;
}
ImplicitCallTransformer().Transform(P, TheTable);
if (TypeChecker().Check(P, TheTable)) {
return true;
}
if (ArrayBoundChecker().Check(P, TheTable)) {
return true;
}
if (ASTVerifier().Check(P)) {
PrintErrs("ProgramAST should be well-formed after all analyses run!");
return true;
}
return false;
} | 24.131579 | 74 | 0.726281 | [
"transform"
] |
6b8d41fb203d77aeee30a006ccc497e1cc778c8d | 10,634 | cpp | C++ | src/multi_sampling/sample_space.cpp | zetian/ltl_sampling | 223d225c852469c893078ced7ebc3da81cb1630c | [
"MIT"
] | 11 | 2018-03-12T06:44:43.000Z | 2022-03-10T06:44:51.000Z | src/multi_sampling/sample_space.cpp | zetian/ltl_sampling | 223d225c852469c893078ced7ebc3da81cb1630c | [
"MIT"
] | null | null | null | src/multi_sampling/sample_space.cpp | zetian/ltl_sampling | 223d225c852469c893078ced7ebc3da81cb1630c | [
"MIT"
] | 4 | 2018-06-13T18:00:59.000Z | 2021-07-13T05:58:20.000Z | #include <cmath>
#include <utility>
#include <algorithm>
#include <queue>
#include "multi_sampling/sample_space.h"
#include "trajectory/dubins_steer.h"
SampleSpace::SampleSpace(int num_ba) {
num_ba_ = num_ba;
for (int i = 0; i < num_ba; i++) {
SubSampleSpace new_sub_space;
sub_sample_space_.push_back(new_sub_space);
sample_space_ltl_map_[i] = new_sub_space;
}
}
double SampleSpace::get_dist(std::vector<double> states_1, std::vector<double> states_2) {
double dist = sqrt(pow(states_1[0] - states_2[0], 2) + pow(states_1[1] - states_2[1], 2));
return dist;
}
double SampleSpace::get_dist_dubins(std::vector<double> states_1, std::vector<double> states_2, double min_radius) {
double min_length = DubinsPath::GetDubinsPathLength(states_1, states_2, min_radius);
return min_length;
}
double SampleSpace::get_dist(MultiSampleNode multi_sample_1, MultiSampleNode multi_sample_2){
std::vector<std::vector<double>> states_1 = multi_sample_1.get_all_states();
std::vector<std::vector<double>> states_2 = multi_sample_2.get_all_states();
if (states_1.size() != states_2.size()){
return -1;
}
double dist = 0;
for (int i = 0; i < states_1.size(); i++) {
dist = dist + sqrt(pow(states_1[i][0] - states_2[i][0], 2) + pow(states_1[i][1] - states_2[i][1], 2));
}
return dist;
}
double SampleSpace::get_dist(std::vector<std::vector<double>> states_1, std::vector<std::vector<double>> states_2){
if (states_1.size() != states_2.size()){
return -1;
}
double dist = 0;
for (int i = 0; i < states_1.size(); i++) {
dist = dist + sqrt(pow(states_1[i][0] - states_2[i][0], 2) + pow(states_1[i][1] - states_2[i][1], 2));
}
return dist;
}
double SampleSpace::get_dist_dubins(std::vector<std::vector<double>> states_1, std::vector<std::vector<double>> states_2, double min_radius){
if (states_1.size() != states_2.size()){
return -1;
}
double dist = 0;
for (int i = 0; i < states_1.size(); i++) {
dist = dist + DubinsPath::GetDubinsPathLength(states_1[i], states_2[i], min_radius);
}
return dist;
}
SubSampleSpace& SampleSpace::get_sub_space(int num_ba) {
return sample_space_ltl_map_.find(num_ba)->second;
}
void SampleSpace::set_space(int num_ba) {
num_ba_ = num_ba;
for (int i = 0; i < num_ba; i++) {
SubSampleSpace new_sub_space;
sub_sample_space_.push_back(new_sub_space);
sample_space_ltl_map_[i] = new_sub_space;
}
}
void SampleSpace::insert_sample(MultiSampleNode new_sample, int sub_space_id) {
sample_space_ltl_map_.find(sub_space_id)->second.insert_sample(new_sample);
}
uint64_t SampleSpace::total_sample_num() {
uint64_t total_num = 0;
for (int i = 0; i < num_ba_; i++) {
total_num = total_num + sample_space_ltl_map_[i].num_samples();
}
return total_num;
}
void SampleSpace::rewire(uint64_t new_sample_id, int new_sample_ba, std::vector<Region> obstacles, double RADIUS) {
MultiSampleNode &new_sample = sample_space_ltl_map_.find(new_sample_ba)->second.get_sample(new_sample_id);
std::vector<MultiSampleNode>& all_sub_samples = sample_space_ltl_map_.find(new_sample_ba)->second.get_all_samples();
for (int i = 0; i < all_sub_samples.size(); i++) {
if (all_sub_samples[i].get_id() != new_sample.get_parent_id() &&
get_dist(all_sub_samples[i].get_all_states(), new_sample.get_all_states()) < RADIUS &&
get_dist(all_sub_samples[i].get_all_states(), new_sample.get_all_states()) + new_sample.get_cost() <
all_sub_samples[i].get_cost() ) {
MultiSampleNode &rewire_sample = all_sub_samples[i];
if (Region::collision_check_multi_simple(rewire_sample.get_all_states(), new_sample.get_all_states(), obstacles)) {
continue;
}
uint64_t old_parent_id = rewire_sample.get_parent_id();
int old_parent_ba = rewire_sample.get_parent_ba();
std::vector<std::pair<int, uint64_t>>& children_from_old_parent = sample_space_ltl_map_.find(old_parent_ba)->second.get_sample(old_parent_id).get_children_id();
std::pair <int, uint64_t> rewire_sample_id (rewire_sample.get_ba(), rewire_sample.get_id());
children_from_old_parent.erase(std::remove(children_from_old_parent.begin(), children_from_old_parent.end(), rewire_sample_id), children_from_old_parent.end());
rewire_sample.set_parent_ba(new_sample_ba);
rewire_sample.set_parent_id(new_sample_id);
double old_cost_of_rewire = rewire_sample.get_cost();
rewire_sample.set_cost(new_sample.get_cost() + get_dist(rewire_sample.get_all_states(), new_sample.get_all_states()));
double decreased_cost = old_cost_of_rewire - rewire_sample.get_cost();
new_sample.add_children_id(rewire_sample_id);
std::queue<std::pair <int, uint64_t>> Q_cost_update;
std::vector<std::pair<int, uint64_t>> current_children = rewire_sample.get_children_id();
for (int i = 0; i < current_children.size(); i++) {
Q_cost_update.push(current_children[i]);
}
while (!Q_cost_update.empty()) {
std::pair<int, uint64_t> child_need_fix_id = Q_cost_update.front();
Q_cost_update.pop();
MultiSampleNode &child_need_fix_sample = sample_space_ltl_map_.find(child_need_fix_id.first)->second.get_sample(child_need_fix_id.second);
child_need_fix_sample.set_cost(child_need_fix_sample.get_cost() - decreased_cost);
current_children = child_need_fix_sample.get_children_id();
for (int i = 0; i < current_children.size(); i++) {
Q_cost_update.push(current_children[i]);
}
}
}
}
}
void SampleSpace::rewire_dubins(int num_agent, uint64_t new_sample_id, int new_sample_ba, std::vector<Region> obstacles, double work_space_size_x, double work_space_size_y, double RADIUS, double min_radius, double path_step, double collision_check_rate) {
MultiSampleNode &new_sample = sample_space_ltl_map_.find(new_sample_ba)->second.get_sample(new_sample_id);
std::vector<MultiSampleNode>& all_sub_samples = sample_space_ltl_map_.find(new_sample_ba)->second.get_all_samples();
for (int i = 0; i < all_sub_samples.size(); i++) {
if (all_sub_samples[i].get_id() != new_sample.get_parent_id() &&
get_dist_dubins(all_sub_samples[i].get_all_states(), new_sample.get_all_states(), min_radius) < RADIUS &&
get_dist_dubins(all_sub_samples[i].get_all_states(), new_sample.get_all_states(), min_radius) + new_sample.get_cost() <
all_sub_samples[i].get_cost() ) {
MultiSampleNode &rewire_sample = all_sub_samples[i];
std::vector<DubinsPath::PathData> multi_dubins_steer_data_new;
for (int k = 0; k < num_agent; k++){
DubinsPath::PathData dubins_steer_data_new = DubinsPath::GetDubinsPathPointWise(rewire_sample.get_all_states()[k], new_sample.get_all_states()[k], min_radius, path_step);
multi_dubins_steer_data_new.push_back(dubins_steer_data_new);
}
// DubinsSteer::SteerData dubins_steer_data_new = DubinsSteer::GetDubinsTrajectoryPointWise(rewire_sample.get_all_states(), new_sample.get_state(), radius_L, radius_R);
if (Region::collision_check_multi_dubins(multi_dubins_steer_data_new, obstacles, work_space_size_x, work_space_size_y, collision_check_rate)) {
continue;
}
uint64_t old_parent_id = rewire_sample.get_parent_id();
int old_parent_ba = rewire_sample.get_parent_ba();
std::vector<std::pair<int, uint64_t>>& children_from_old_parent = sample_space_ltl_map_.find(old_parent_ba)->second.get_sample(old_parent_id).get_children_id();
std::pair <int, uint64_t> rewire_sample_id (rewire_sample.get_ba(), rewire_sample.get_id());
children_from_old_parent.erase(std::remove(children_from_old_parent.begin(), children_from_old_parent.end(), rewire_sample_id), children_from_old_parent.end());
rewire_sample.set_parent_ba(new_sample_ba);
rewire_sample.set_parent_id(new_sample_id);
double old_cost_of_rewire = rewire_sample.get_cost();
double all_traj_length = 0;
std::vector<std::vector<std::vector<double>>> multi_traj_point_wise;
for (int k = 0; k < multi_dubins_steer_data_new.size(); k++){
all_traj_length = all_traj_length + multi_dubins_steer_data_new[k].traj_length;
multi_traj_point_wise.push_back(multi_dubins_steer_data_new[k].traj_point_wise);
}
// rewire_sample.set_cost(new_sample.get_cost() + get_dist_dubins(rewire_sample.get_all_states(), new_sample.get_all_states(), radius_L, radius_R));
rewire_sample.set_cost(new_sample.get_cost() + all_traj_length);
double decreased_cost = old_cost_of_rewire - rewire_sample.get_cost();
new_sample.add_children_id(rewire_sample_id);
new_sample.set_multi_traj(multi_traj_point_wise);
new_sample.set_traj_data(multi_dubins_steer_data_new);
std::queue<std::pair <int, uint64_t>> Q_cost_update;
std::vector<std::pair<int, uint64_t>> current_children = rewire_sample.get_children_id();
for (int i = 0; i < current_children.size(); i++) {
Q_cost_update.push(current_children[i]);
}
while (!Q_cost_update.empty()) {
std::pair<int, uint64_t> child_need_fix_id = Q_cost_update.front();
Q_cost_update.pop();
MultiSampleNode &child_need_fix_sample = sample_space_ltl_map_.find(child_need_fix_id.first)->second.get_sample(child_need_fix_id.second);
child_need_fix_sample.set_cost(child_need_fix_sample.get_cost() - decreased_cost);
current_children = child_need_fix_sample.get_children_id();
for (int i = 0; i < current_children.size(); i++) {
Q_cost_update.push(current_children[i]);
}
}
}
}
}
| 53.17 | 255 | 0.657043 | [
"vector"
] |
6b9573307ed41021d756d044abf32255d9070a02 | 11,473 | cpp | C++ | sal/program_options/config_reader.cpp | svens/sal.lib | 8dee6a0ace5a5e4e8616f9cff98ea86ee8c4761c | [
"MIT"
] | 3 | 2017-03-21T20:39:25.000Z | 2018-03-27T10:45:45.000Z | sal/program_options/config_reader.cpp | svens/sal.lib | 8dee6a0ace5a5e4e8616f9cff98ea86ee8c4761c | [
"MIT"
] | 49 | 2016-04-17T10:48:35.000Z | 2018-12-29T10:00:55.000Z | sal/program_options/config_reader.cpp | svens/sal.lib | 8dee6a0ace5a5e4e8616f9cff98ea86ee8c4761c | [
"MIT"
] | 1 | 2017-03-21T20:48:24.000Z | 2017-03-21T20:48:24.000Z | #include <sal/program_options/config_reader.hpp>
#include <sal/program_options/error.hpp>
#include <sal/assert.hpp>
#include <cctype>
#include <deque>
#include <istream>
__sal_begin
namespace program_options {
namespace {
constexpr bool is_json_punct (int ch)
{
return ch == ','
|| ch == ':'
|| ch == '='
|| ch == '['
|| ch == ']'
|| ch == '{'
|| ch == '}'
;
}
constexpr bool is_bare_key_char (int it)
{
return it == '-'
|| it == '_'
|| (it >= 'A' && it <= 'Z')
|| (it >= 'a' && it <= 'z')
|| (it >= '0' && it <= '9')
;
}
} // namespace
struct config_reader_t::impl_t
{
std::istream &input;
std::string cache{};
std::string::const_iterator cache_it = cache.end();
size_t line = 0;
int it = 0;
struct node_t
{
using stack_t = std::deque<node_t>;
bool(impl_t::*context)(node_t &) = &impl_t::any;
std::string key{};
bool allow_comma = false;
node_t () = default;
node_t (bool(impl_t::*context)(node_t &))
: context(context)
{}
node_t (bool(impl_t::*context)(node_t &), const std::string &key)
: context(context)
, key(key)
{}
void set (bool(impl_t::*to)(node_t &))
{
context = to;
}
};
node_t::stack_t objects{};
std::string current_value{};
impl_t (std::istream &input);
impl_t (const impl_t &) = delete;
impl_t &operator= (const impl_t &) = delete;
// extract option/argument
// returns true if has more, false otherwise
bool extract (std::string *option, std::string *argument);
bool key_and_value (std::string *option, std::string *argument);
// return current column number
size_t column () const
{
return cache_it - cache.begin();
}
// read next character, caching line if necessary
bool next ();
std::string next_line ();
// peek at following char
int peek () const noexcept
{
return *cache_it;
}
int unescape (int ch) const
{
switch (ch)
{
case '"': return '"';
case '\\': return '\\';
case 'b': return '\b';
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
}
throw_unexpected("escaped character");
}
//
// state handlers
//
bool any (node_t &node);
bool object (node_t &node);
bool array (node_t &node);
bool assign (node_t &node);
bool value (node_t &node);
//
// token extractors
//
bool skip_spaces_and_comments ();
// different kind of extractors
std::string extract_string (bool is_key);
std::string extract_bare_key ();
std::string extract_quoteless_string ();
std::string extract_basic_string (bool allow_multiline);
std::string extract_literal_string (bool allow_multiline);
std::string extract_basic_multiline_string ();
std::string extract_literal_multiline_string ();
//
// errors
//
void throw_not_supported [[noreturn]] (const char *what) const
{
throw_error<parser_error>(what, " is not supported ",
'(', line, ',', column(), ')'
);
}
void throw_expected [[noreturn]] (const char *what) const
{
throw_error<parser_error>("expected ", what, ' ',
'(', line, ',', column(), ')'
);
}
void throw_unexpected [[noreturn]] (const char *what) const
{
throw_error<parser_error>("unexpected ", what, ' ',
'(', line, ',', column(), ')'
);
}
};
config_reader_t::config_reader_t (std::istream &input)
: impl_(std::make_unique<impl_t>(input))
{}
config_reader_t::~config_reader_t () = default;
bool config_reader_t::operator() (const option_set_t &,
std::string *option,
std::string *argument)
{
return impl_->extract(option, argument);
}
config_reader_t::impl_t::impl_t (std::istream &input)
: input(input)
{
objects.emplace_back();
if (next() && skip_spaces_and_comments() && it == '{')
{
object(objects.back());
}
}
bool config_reader_t::impl_t::extract (std::string *option,
std::string *argument)
{
while (skip_spaces_and_comments())
{
if (objects.empty())
{
throw_unexpected("end of object");
}
auto &node = objects.back();
if (!(this->*node.context)(node))
{
return key_and_value(option, argument);
}
}
while (objects.size())
{
const auto &node = objects.back();
if (node.context == &impl_t::value)
{
return key_and_value(option, argument);
}
else if (node.context != &impl_t::any)
{
throw_unexpected("end of input");
}
objects.pop_back();
}
return false;
}
bool config_reader_t::impl_t::key_and_value (std::string *option,
std::string *argument)
{
std::string key;
for (const auto &object: objects)
{
if (object.key.size()
&& (object.context == &impl_t::object
|| object.context == &impl_t::array
|| object.context == &impl_t::value))
{
key += object.key;
key += '.';
}
}
if (key.size() && key.back() == '.')
{
key.pop_back();
}
*sal_check_ptr(argument) = std::move(current_value);
*sal_check_ptr(option) = std::move(key);
auto &back = objects.back();
if (back.context != &impl_t::array)
{
back.set(&impl_t::any);
}
back.allow_comma = true;
return true;
}
bool config_reader_t::impl_t::any (node_t &node)
{
if (it == '}')
{
objects.pop_back();
return true;
}
else if (it == ',')
{
if (!node.allow_comma)
{
throw_unexpected("comma");
}
node.allow_comma = false;
}
else if (it == '"' || it == '\'' || is_bare_key_char(it))
{
node.key = extract_string(true);
node.set(&impl_t::assign);
return true;
}
else
{
throw_unexpected("character");
}
return next();
}
bool config_reader_t::impl_t::object (node_t &node)
{
if (it == '{')
{
node.set(&impl_t::object);
objects.emplace_back();
return next();
}
else if (it == '}')
{
objects.pop_back();
next();
if (objects.size())
{
return true;
}
}
objects.emplace_back();
objects.back().allow_comma = true;
return true;
}
bool config_reader_t::impl_t::array (node_t &node)
{
if (it == ']')
{
objects.back().set(&impl_t::any);
return next();
}
else if (it == ',')
{
if (!node.allow_comma)
{
throw_unexpected("comma");
}
node.allow_comma = false;
return next();
}
else if (it == '[' || it == '{')
{
throw_not_supported("array of arrays or objects");
}
else if (is_json_punct(it))
{
throw_unexpected("character");
}
current_value = extract_string(false);
node.allow_comma = true;
return false;
}
bool config_reader_t::impl_t::assign (node_t &node)
{
if (it == '=' || it == ':')
{
node.set(&impl_t::value);
return next();
}
throw_expected("':' or '='");
}
bool config_reader_t::impl_t::value (node_t &node)
{
if (it == '{')
{
node.set(&impl_t::object);
objects.emplace_back();
return next();
}
else if (it == '[')
{
node.set(&impl_t::array);
return next();
}
current_value = extract_string(false);
return false;
}
std::string config_reader_t::impl_t::extract_string (bool is_key)
{
if (it == '"')
{
return extract_basic_string(is_key == false);
}
else if (it == '\'')
{
return extract_literal_string(is_key == false);
}
else
{
return is_key ? extract_bare_key() : extract_quoteless_string();
}
}
std::string config_reader_t::impl_t::extract_bare_key ()
{
std::string result;
while (is_bare_key_char(it))
{
result += static_cast<char>(it);
next();
}
return result;
}
std::string config_reader_t::impl_t::extract_quoteless_string ()
{
std::string result;
while (!is_json_punct(it) && !std::isspace(it))
{
if (it == '/')
{
auto ch = peek();
if (ch == '/' || ch == '*')
{
break;
}
}
result += static_cast<char>(it);
next();
}
return result;
}
std::string config_reader_t::impl_t::extract_basic_string (bool allow_multiline)
{
next();
if (allow_multiline && it == '"' && peek() == '"')
{
next(), next();
return extract_basic_multiline_string();
}
std::string result;
while (it != '"')
{
if (it == '\n')
{
throw_unexpected("newline");
}
else if (it == '\\')
{
next();
it = unescape(it);
}
result += static_cast<char>(it);
next();
}
next();
return result;
}
std::string config_reader_t::impl_t::extract_literal_string (bool allow_multiline)
{
next();
if (allow_multiline && it == '\'' && peek() == '\'')
{
next(), next();
return extract_literal_multiline_string();
}
std::string result;
while (it != '\'')
{
if (it == '\n')
{
throw_unexpected("newline");
}
result += static_cast<char>(it);
next();
}
next();
return result;
}
std::string config_reader_t::impl_t::extract_basic_multiline_string ()
{
std::string result;
if (it == '\n')
{
next();
}
bool skip_whitespaces = false;
for (auto consecutive_quotes = 0U; it && consecutive_quotes != 3; next())
{
if (skip_whitespaces && std::isspace(it))
{
continue;
}
skip_whitespaces = false;
result += static_cast<char>(it);
if (it == '"')
{
++consecutive_quotes;
continue;
}
consecutive_quotes = 0;
if (it == '\\')
{
next();
if (it != '\n')
{
result.back() = static_cast<char>(unescape(it));
}
else
{
result.pop_back();
skip_whitespaces = true;
}
}
}
if (it)
{
result.erase(result.size() - 3);
}
else
{
throw_unexpected("end of input");
}
return result;
}
std::string config_reader_t::impl_t::extract_literal_multiline_string ()
{
std::string result;
if (it == '\n')
{
next();
}
for (auto consecutive_quotes = 0U; it && consecutive_quotes != 3; next())
{
result += static_cast<char>(it);
if (it != '\'')
{
consecutive_quotes = 0;
}
else
{
++consecutive_quotes;
}
}
if (it)
{
result.erase(result.size() - 3);
}
else
{
throw_unexpected("end of input");
}
return result;
}
std::string config_reader_t::impl_t::next_line ()
{
std::string result;
if (std::getline(input, result))
{
while (result.size()
&& std::isspace(static_cast<int>(result.back())))
{
result.pop_back();
}
result.push_back('\n');
line++;
}
return result;
}
bool config_reader_t::impl_t::next ()
{
if (cache_it == cache.end())
{
cache = next_line();
cache_it = cache.begin();
}
if (cache_it != cache.end())
{
it = *cache_it++;
}
else
{
it = 0;
}
return it != 0;
}
bool config_reader_t::impl_t::skip_spaces_and_comments ()
{
auto comment_recursion_depth = 0U;
do
{
if (!it)
{
break;
}
else if (it == '/' && peek() == '*')
{
comment_recursion_depth++;
next();
}
else if (it == '*' && peek() == '/')
{
comment_recursion_depth--;
next();
}
else if (!comment_recursion_depth)
{
if (it == '/' && peek() == '/')
{
cache_it = cache.end();
}
else if (!std::isspace(it))
{
return true;
}
}
} while (next());
if (comment_recursion_depth)
{
throw_unexpected("end of input");
}
return false;
}
} // namespace program_options
__sal_end
| 17.098361 | 82 | 0.564891 | [
"object"
] |
6b9a8706bed9c56ed3536d95618059c51bced742 | 8,663 | cpp | C++ | src/Mapper/mapper4.cpp | flavioribeiro/plainNES | 020e6fd042592de821d576fb8a02144322194b58 | [
"MIT"
] | 4 | 2019-11-21T19:33:42.000Z | 2021-11-17T19:44:32.000Z | src/Mapper/mapper4.cpp | flavioribeiro/plainNES | 020e6fd042592de821d576fb8a02144322194b58 | [
"MIT"
] | null | null | null | src/Mapper/mapper4.cpp | flavioribeiro/plainNES | 020e6fd042592de821d576fb8a02144322194b58 | [
"MIT"
] | 1 | 2020-04-05T03:01:24.000Z | 2020-04-05T03:01:24.000Z | #include "mapper4.h"
#include "ppu.h"
#include "cpu.h"
#include <iostream>
#include <algorithm>
//TODO: Add save ability for battery backed up PRG-RAM
Mapper4::Mapper4(GAMEPAK::ROMInfo romInfo, std::ifstream &file)
{
PRGRAM.resize(0x2000);
if(romInfo.fourScreenMode) {
VRAM.resize(0x1000);
fourScreenMode = true;
}
else VRAM.resize(0x800);
PRGROM.resize(romInfo.PRGROMsize / 0x2000, std::vector<uint8_t>(0x2000, 0));
CHRROM.resize(romInfo.CHRROMsize / 0x400, std::vector<uint8_t>(0x400, 0));
std::fill(PRGRAM.begin(), PRGRAM.end(), 0);
std::fill(VRAM.begin(), VRAM.end(), 0);
loadData(file);
}
uint8_t Mapper4::memGet(uint16_t addr, bool peek)
{
uint8_t returnedValue = CPU::busVal;
if(addr >= 0x6000 && addr < 0x8000) {
returnedValue = PRGRAM.at((addr - 0x6000) % 0x2000);
}
else if(addr >= 0x8000 && addr < 0xA000) {
if(PRGbankmode == 0) returnedValue = PRGROM.at(R6).at((addr - 0x8000) % 0x2000);
else returnedValue = PRGROM.end()[-2].at((addr - 0x8000) % 0x2000);
}
else if(addr >= 0xA000 && addr < 0xC000) {
returnedValue = PRGROM.at(R7).at((addr - 0xA000) % 0x2000);
}
else if(addr >= 0xC000 && addr < 0xE000) {
if(PRGbankmode == 0) returnedValue = PRGROM.end()[-2].at((addr - 0xC000) % 0x2000);
else returnedValue = PRGROM.at(R6).at((addr - 0xC000) % 0x2000);
}
else if(addr >= 0xE000) {
returnedValue = PRGROM.end()[-1].at((addr - 0xE000) % 0x2000);
}
if(peek) return returnedValue;
CPU::busVal = returnedValue;
return CPU::busVal;
}
void Mapper4::memSet(uint16_t addr, uint8_t val)
{
if(addr >= 0x6000 && addr < 0x8000) {
PRGRAM.at((addr - 0x6000) % 0x2000) = val;
}
if(addr >= 0x8000 && addr < 0xA000) {
if(addr % 2 == 0) { //Even
regWriteSel = val & 7;
PRGbankmode = ((val & 0x40) > 0) ? 1 : 0;
CHRbankmode = ((val & 0x80) > 0) ? 1 : 0;
}
else { //Odd
switch(regWriteSel) {
case 0: R0 = (val & 0xFE); break;
case 1: R1 = (val & 0xFE); break;
case 2: R2 = val; break;
case 3: R3 = val; break;
case 4: R4 = val; break;
case 5: R5 = val; break;
case 6: R6 = (val & 0x3F); break;
case 7: R7 = (val & 0x3F); break;
}
}
}
else if(addr >= 0xA000 && addr < 0xC000) {
if(addr % 2 == 0) { //Even
horzMirroring = (val & 1) > 0;
}
//Ignore odd writes
//PRG RAM protection doesn't need to be emulated
}
else if(addr >= 0xC000 && addr < 0xE000) {
if(addr % 2 == 0) { //Even
IRQlatch = val;
}
else { //Odd
IRQreload = true;
}
}
else if(addr >= 0xE000) {
if(addr % 2 == 0) { //Even
IRQenabled = false;
IRQrequested = false;
CPU::setIRQfromCart(IRQrequested);
}
else { //Odd
IRQenabled = true;
}
}
}
uint8_t Mapper4::PPUmemGet(uint16_t addr, bool peek)
{
PPUbusAddrChanged(addr % 0x3FFF);
try {
//Mirror addresses higher than 0x3FFF
addr %= 0x4000;
if(addr < 0x0400) {
if(CHRbankmode) return CHRROM.at(R2).at(addr % 0x400);
else return CHRROM.at(R0).at(addr % 0x400);
}
else if(addr < 0x0800) {
if(CHRbankmode) return CHRROM.at(R3).at(addr % 0x400);
else return CHRROM.at(R0+1).at(addr % 0x400);
}
else if(addr < 0x0C00) {
if(CHRbankmode) return CHRROM.at(R4).at(addr % 0x400);
else return CHRROM.at(R1).at(addr % 0x400);
}
else if(addr < 0x1000) {
if(CHRbankmode) return CHRROM.at(R5).at(addr % 0x400);
else return CHRROM.at(R1+1).at(addr % 0x400);
}
else if(addr < 0x1400) {
if(CHRbankmode) return CHRROM.at(R0).at(addr % 0x400);
else return CHRROM.at(R2).at(addr % 0x400);
}
else if(addr < 0x1800) {
if(CHRbankmode) return CHRROM.at(R0+1).at(addr % 0x400);
else return CHRROM.at(R3).at(addr % 0x400);
}
else if(addr < 0x1C00) {
if(CHRbankmode) return CHRROM.at(R1).at(addr % 0x400);
else return CHRROM.at(R4).at(addr % 0x400);
}
else if(addr < 0x2000) {
if(CHRbankmode) return CHRROM.at(R1+1).at(addr % 0x400);
else return CHRROM.at(R5).at(addr % 0x400);
}
else if(addr < 0x3F00) {
if(addr > 0x2FFF) addr -= 0x1000;
if(fourScreenMode) return VRAM.at(addr - 0x2000);
if(horzMirroring == false) {
if(addr < 0x2800)
return VRAM.at(addr - 0x2000);
else
return VRAM.at(addr - 0x2800);
}
else {
if(addr < 0x2800)
return VRAM.at(addr % 0x0400);
else
return VRAM.at(0x0400 + addr % 0x0400);
}
}
else if(addr < 0x4000) {
//Internal to PPU. Never mapped.
return PPU::getPalette((uint8_t)(addr % 0x20));
}
}
catch(const std::out_of_range err)
{
std::cerr << "Out of range error when trying to get addr: " << addr << std::endl;
}
return 0;
}
void Mapper4::PPUmemSet(uint16_t addr, uint8_t val)
{
PPUbusAddrChanged(addr % 0x3FFF);
try {
//Mirror addresses higher than 0x3FFF
addr %= 0x4000;
//Can't write to CHRROM
/*if(addr < 0x0400) {
if(CHRbankmode) CHRROM.at(R2).at(addr % 0x400) = val;
else CHRROM.at(R0).at(addr % 0x400) = val;
}
else if(addr < 0x0800) {
if(CHRbankmode) CHRROM.at(R3).at(addr % 0x400) = val;
else CHRROM.at(R0+1).at(addr % 0x400) = val;
}
else if(addr < 0x0C00) {
if(CHRbankmode) CHRROM.at(R4).at(addr % 0x400) = val;
else CHRROM.at(R1).at(addr % 0x400) = val;
}
else if(addr < 0x1000) {
if(CHRbankmode) CHRROM.at(R5).at(addr % 0x400) = val;
else CHRROM.at(R1+1).at(addr % 0x400) = val;
}
else if(addr < 0x1400) {
if(CHRbankmode) CHRROM.at(R0).at(addr % 0x400) = val;
else CHRROM.at(R2).at(addr % 0x400) = val;
}
else if(addr < 0x1800) {
if(CHRbankmode) CHRROM.at(R0+1).at(addr % 0x400) = val;
else CHRROM.at(R3).at(addr % 0x400) = val;
}
else if(addr < 0x1C00) {
if(CHRbankmode) CHRROM.at(R1).at(addr % 0x400) = val;
else CHRROM.at(R4).at(addr % 0x400) = val;
}
else if(addr < 0x2000) {
if(CHRbankmode) CHRROM.at(R1+1).at(addr % 0x400) = val;
else CHRROM.at(R5).at(addr % 0x400) = val;
}*/
if(addr >= 0x2000 && addr < 0x3F00) {
if(addr > 0x2FFF) addr -= 0x1000;
if(fourScreenMode) VRAM.at(addr - 0x2000) = val;
if(horzMirroring == false) {
if(addr < 0x2800)
VRAM.at(addr - 0x2000) = val;
else
VRAM.at(addr - 0x2800) = val;
}
else {
if(addr < 0x2800)
VRAM.at(addr % 0x0400) = val;
else
VRAM.at(0x0400 + addr % 0x0400) = val;
}
}
else if(addr >= 0x3F00 && addr < 0x4000) {
//Internal to PPU. Never mapped.
return PPU::setPalette((uint8_t)(addr % 0x20), val);
}
}
catch(const std::out_of_range err)
{
std::cerr << "Out of range error when trying to set addr: " << addr << std::endl;
}
}
void Mapper4::loadData(std::ifstream &file)
{
for(unsigned int bank=0; bank < PRGROM.size(); ++bank) {
for(unsigned int idx=0; idx < PRGROM[bank].size(); ++idx) {
if(file.eof())
throw std::out_of_range("Reached EOF unexpectantly while loading ROM");
file.read((char*)&PRGROM[bank][idx],1);
}
}
for(unsigned int bank=0; bank < CHRROM.size(); ++bank) {
for(unsigned int idx=0; idx < CHRROM[bank].size(); ++idx) {
if(file.eof())
throw std::out_of_range("Reached EOF unexpectantly while loading ROM");
file.read((char*)&CHRROM[bank][idx],1);
}
}
}
void Mapper4::powerOn()
{
//Assumed power on states
fourScreenMode = false;
horzMirroring = false;
IRQreload = false;
IRQenabled = false;
IRQrequested = false;
R0 = R1 = R2 = R3 = R4 = R5 = R6 = R7 = 0;
regWriteSel = 0;
PRGbankmode = 0;
CHRbankmode = 0;
IRQlatch = 0;
}
void Mapper4::PPUstep()
{
CPU::setIRQfromCart(IRQrequested);
}
void Mapper4::PPUbusAddrChanged(uint16_t newAddr)
{
if((lastVRAMaddr & 0x1000) == 0 && (newAddr & 0x1000) > 0) {
//std::cout << PPU::scanline << ":" << PPU::dot << " Clocking" << std::endl;
if(IRQcntr == 0 || IRQreload) {
IRQcntr = IRQlatch;
IRQreload = false;
}
else {
--IRQcntr;
}
if(IRQcntr == 0 && IRQenabled) {
IRQrequested = true;
CPU::setIRQfromCart(IRQrequested);
}
}
lastVRAMaddr = newAddr;
} | 29.566553 | 91 | 0.55916 | [
"vector"
] |
6ba33f9f4730e11888e11a2b0b40c06c61760e2a | 2,609 | cpp | C++ | src/2021/day20.cpp | dholmes215/adventofcode-cpp | 2a0ce43c51ec3beccc56fb48bf91de070e6ca136 | [
"BSL-1.0"
] | null | null | null | src/2021/day20.cpp | dholmes215/adventofcode-cpp | 2a0ce43c51ec3beccc56fb48bf91de070e6ca136 | [
"BSL-1.0"
] | null | null | null | src/2021/day20.cpp | dholmes215/adventofcode-cpp | 2a0ce43c51ec3beccc56fb48bf91de070e6ca136 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2020-2021 David Holmes (dholmes at dholmes dot us)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <aoc.hpp>
#include <aoc_grid.hpp>
#include <aoc_range.hpp>
#include <aoc_vec.hpp>
#include <bitset>
#include <string>
#include <string_view>
#include <vector>
namespace aoc::year2021 {
namespace {
using enhance_alg_t = std::bitset<512>;
using grid_t = dynamic_grid<bool>;
enhance_alg_t parse_enhance_alg(std::string_view s)
{
std::string reversed{s | rv::reverse | r::to<std::string>};
return std::bitset<512>(reversed.data(), reversed.size(), '.', '#');
}
struct parse_result {
enhance_alg_t enhance_alg;
grid_t grid;
};
parse_result parse(std::string_view input)
{
auto lines{sv_lines(input)};
auto rest{lines | rv::drop(2)};
const int grid_width{static_cast<int>(rest.front().size())};
const int grid_height{static_cast<int>(r::distance(rest))};
parse_result out{parse_enhance_alg(lines.front()),
grid_t{grid_width, grid_height}};
auto bools{rest | rv::join |
rv::transform([](char c) { return c == '#'; })};
r::copy(bools, out.grid.data().begin());
return out;
}
grid_t widen(grid_t& grid, int padding, bool new_value)
{
grid_t widened{grid.width() + padding * 2, grid.height() + padding * 2};
if (new_value) {
r::fill(widened.data(), true);
}
r::copy(grid.data(),
widened.subgrid({{padding, padding}, {grid.width(), grid.height()}})
.data()
.begin());
return widened;
}
grid_t enhance(grid_t& grid, const enhance_alg_t& enhance_alg)
{
grid_t widened{widen(grid, 2, grid[{0, 0}])};
grid_t out{grid.width() + 2, grid.height() + 2};
for (const auto p : out.area().all_points()) {
auto nine_pixel_subgrid{widened.subgrid({p, {3, 3}})};
auto index{static_cast<std::size_t>(
bool_range_to_int(nine_pixel_subgrid.data()))};
out[p] = enhance_alg[index];
}
return out;
}
} // namespace
aoc::solution_result day20(std::string_view input)
{
auto [enhance_alg, grid]{parse(input)};
std::vector<grid_t> enhancements;
enhancements.emplace_back(widen(grid, 10, false));
for (std::size_t i = 1; i <= 50; i++) {
enhancements.emplace_back(enhance(enhancements[i - 1], enhance_alg));
}
return {r::count(enhancements[2].data(), true),
r::count(enhancements[50].data(), true)};
}
} // namespace aoc::year2021
| 26.896907 | 80 | 0.634343 | [
"vector",
"transform"
] |
6ba9b17e4668525fc0f01cc3e4de6abebbf91038 | 11,672 | cpp | C++ | Polygon_mesh_processing/test/Polygon_mesh_processing/test_pmp_manifoldness.cpp | antoniospg/cgal | 2891c22fc7f64f680ac7e144407afe49f6425cb9 | [
"CC0-1.0"
] | 2 | 2020-12-12T09:30:07.000Z | 2021-01-04T05:00:23.000Z | Polygon_mesh_processing/test/Polygon_mesh_processing/test_pmp_manifoldness.cpp | antoniospg/cgal | 2891c22fc7f64f680ac7e144407afe49f6425cb9 | [
"CC0-1.0"
] | 17 | 2018-01-10T13:32:24.000Z | 2021-07-30T12:23:20.000Z | Polygon_mesh_processing/test/Polygon_mesh_processing/test_pmp_manifoldness.cpp | antoniospg/cgal | 2891c22fc7f64f680ac7e144407afe49f6425cb9 | [
"CC0-1.0"
] | 1 | 2019-02-21T15:26:25.000Z | 2019-02-21T15:26:25.000Z | #include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/Surface_mesh.h>
#include <CGAL/boost/graph/named_params_helper.h>
#include <CGAL/Polygon_mesh_processing/repair.h>
#include <cassert>
#include <fstream>
#include <map>
#include <vector>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Surface_mesh<K::Point_3> Surface_mesh;
typedef CGAL::Polyhedron_3<K> Polyhedron;
typedef std::vector<std::vector<std::size_t> > Vertices_to_merge_container;
template <typename PolygonMesh>
void read_mesh(const char* fname,
PolygonMesh& mesh)
{
std::ifstream input(fname);
if (!input || !(input >> mesh) || mesh.is_empty())
{
std::cerr << fname << " is not a valid off file." << std::endl;
std::exit(1);
}
}
// tests merge_and_duplication
template <typename PolygonMesh>
void merge_vertices(typename boost::graph_traits<PolygonMesh>::vertex_descriptor v_keep,
typename boost::graph_traits<PolygonMesh>::vertex_descriptor v_rm,
PolygonMesh& mesh)
{
typedef typename boost::graph_traits<PolygonMesh>::halfedge_descriptor halfedge_descriptor;
assert(v_keep != v_rm);
std::size_t ini_nv = static_cast<std::size_t>(vertices(mesh).size());
halfedge_descriptor h = halfedge(v_rm, mesh);
halfedge_descriptor start = h;
do
{
set_target(h, v_keep, mesh);
h = opposite(next(h, mesh), mesh);
}
while(h != start);
remove_vertex(v_rm, mesh);
assert(vertices(mesh).size() == ini_nv - 1);
}
template <typename PolygonMesh>
void merge_vertices(const Vertices_to_merge_container& all_vertices_to_merge,
std::map<typename boost::graph_traits<PolygonMesh>::vertex_descriptor, std::size_t>& merged_onto,
PolygonMesh& mesh)
{
typedef typename boost::graph_traits<PolygonMesh>::vertex_descriptor vertex_descriptor;
// int to vd
std::vector<vertex_descriptor> vds(vertices(mesh).begin(), vertices(mesh).end());
for(std::size_t i=0, avtmn=all_vertices_to_merge.size(); i<avtmn; ++i)
{
const std::vector<std::size_t>& vertices_to_merge = all_vertices_to_merge[i];
if(vertices_to_merge.size() <= 1)
continue;
vertex_descriptor vd_to_merge_onto = vds[vertices_to_merge[0]];
for(std::size_t j=1, vtmn=vertices_to_merge.size(); j<vtmn; ++j)
merge_vertices(vd_to_merge_onto, vds[vertices_to_merge[j]], mesh);
std::pair<typename std::map<vertex_descriptor, std::size_t>::iterator, bool > is_insert_successful =
merged_onto.insert(std::make_pair(vd_to_merge_onto, vertices_to_merge.size() - 1));
if(!is_insert_successful.second)
is_insert_successful.first->second += vertices_to_merge.size() - 1;
assert(CGAL::Polygon_mesh_processing::is_non_manifold_vertex(vd_to_merge_onto, mesh));
}
}
template <typename PolygonMesh>
std::size_t test_nm_vertices_duplication(const Vertices_to_merge_container& all_merges,
std::map<typename boost::graph_traits<PolygonMesh>::vertex_descriptor, std::size_t>& merged_onto,
std::vector<std::vector<
typename boost::graph_traits<PolygonMesh>::vertex_descriptor> >& duplicated_vertices,
PolygonMesh& mesh)
{
typedef typename boost::graph_traits<PolygonMesh>::halfedge_descriptor halfedge_descriptor;
merge_vertices(all_merges, merged_onto, mesh);
std::size_t new_vertices_nb =
CGAL::Polygon_mesh_processing::duplicate_non_manifold_vertices(mesh,
CGAL::parameters::output_iterator(std::back_inserter(duplicated_vertices)));
std::vector<halfedge_descriptor> non_manifold_cones;
CGAL::Polygon_mesh_processing::non_manifold_vertices(mesh, std::back_inserter(non_manifold_cones));
assert(non_manifold_cones.empty());
assert(CGAL::is_valid_polygon_mesh(mesh));
return new_vertices_nb;
}
template <typename PolygonMesh>
std::size_t test_nm_vertices_duplication(const Vertices_to_merge_container& all_merges,
std::vector<std::vector<
typename boost::graph_traits<PolygonMesh>::vertex_descriptor> >& duplicated_vertices,
PolygonMesh& mesh)
{
std::map<typename boost::graph_traits<PolygonMesh>::vertex_descriptor, std::size_t> useless_map;
return test_nm_vertices_duplication(all_merges, useless_map, duplicated_vertices, mesh);
}
template <typename PolygonMesh>
std::size_t test_nm_vertices_duplication(std::vector<std::vector<
typename boost::graph_traits<PolygonMesh>::vertex_descriptor> >& duplicated_vertices,
PolygonMesh& mesh)
{
Vertices_to_merge_container all_merges;
std::map<typename boost::graph_traits<PolygonMesh>::vertex_descriptor, std::size_t> useless_map;
return test_nm_vertices_duplication(all_merges, useless_map, duplicated_vertices, mesh);
}
template <typename PolygonMesh>
void test_unpinched_mesh(const Vertices_to_merge_container& all_merges,
PolygonMesh& mesh)
{
typedef typename boost::graph_traits<PolygonMesh>::vertex_descriptor vertex_descriptor;
const std::size_t ini_vertices_size = num_vertices(mesh);
// this is a nice, smooth, surface initially
for(vertex_descriptor vd : vertices(mesh)) {
assert(!CGAL::Polygon_mesh_processing::is_non_manifold_vertex(vd, mesh));
}
std::vector<std::vector<vertex_descriptor> > duplicated_vertices;
std::map<vertex_descriptor, std::size_t> number_of_vertices_merged_onto;
std::size_t nb = test_nm_vertices_duplication(all_merges,
number_of_vertices_merged_onto,
duplicated_vertices,
mesh);
const std::size_t final_vertices_size = vertices(mesh).size();
std::cout << " ini: " << ini_vertices_size << " final: " << final_vertices_size << std::endl;
assert(final_vertices_size == ini_vertices_size);
std::size_t expected_nb = 0;
for(std::size_t i=0, n=all_merges.size(); i<n; ++i)
expected_nb += all_merges[i].size() - 1;
assert(nb == expected_nb);
assert(duplicated_vertices.size() == all_merges.size());
for(std::size_t i=0, n=duplicated_vertices.size(); i<n; ++i)
assert(duplicated_vertices[i].size() - 1 == number_of_vertices_merged_onto[duplicated_vertices[i][0]]);
}
template <typename PolygonMesh>
void test_blobby()
{
std::cout << " test: data/blobby.off" << std::endl;
PolygonMesh mesh;
read_mesh("data/blobby.off", mesh);
// non-manifold vertices
Vertices_to_merge_container all_merges;
std::vector<std::size_t> single_merge;
single_merge.push_back(1); single_merge.push_back(7); single_merge.push_back(14); single_merge.push_back(21);
all_merges.push_back(single_merge);
single_merge.clear();
single_merge.push_back(2); single_merge.push_back(8);
all_merges.push_back(single_merge);
test_unpinched_mesh(all_merges, mesh);
}
template <typename PolygonMesh>
void test_nm_cubes()
{
std::cout << " test: data_repair/nm_closed_cubes.off" << std::endl;
PolygonMesh mesh;
read_mesh("data_repair/nm_closed_cubes.off", mesh);
// non-manifold vertices
Vertices_to_merge_container all_merges;
std::vector<std::size_t> single_merge;
single_merge.push_back(5); single_merge.push_back(14);
all_merges.push_back(single_merge);
single_merge.clear();
single_merge.push_back(6); single_merge.push_back(15);
all_merges.push_back(single_merge);
test_unpinched_mesh(all_merges, mesh);
}
template <typename PolygonMesh>
void test_pinched_triangles(const char* filename,
const std::size_t expected_nb)
{
typedef typename boost::graph_traits<PolygonMesh>::vertex_descriptor vertex_descriptor;
std::cout << " test: " << filename << " expected: " << expected_nb << std::endl;
PolygonMesh mesh;
read_mesh(filename, mesh);
// in the triangles, the second (id==1) vertex is non-manifold because it is pinched
int id = 0;
for(vertex_descriptor vd : vertices(mesh)) {
if(id++ == 1) {
assert(CGAL::Polygon_mesh_processing::is_non_manifold_vertex(vd, mesh));
} else {
assert(!CGAL::Polygon_mesh_processing::is_non_manifold_vertex(vd, mesh));
}
}
std::vector<std::vector<vertex_descriptor> > duplicated_vertices;
std::size_t new_vertices_nb =
CGAL::Polygon_mesh_processing::duplicate_non_manifold_vertices(mesh,
CGAL::parameters::output_iterator(std::back_inserter(duplicated_vertices)));
std::cout << " new_vertices_nb: " << new_vertices_nb << " vs expected: " << expected_nb << std::endl;
assert(new_vertices_nb == expected_nb);
assert(duplicated_vertices.size() == 1);
assert(duplicated_vertices[0].size() == 1 + expected_nb);
}
template <typename PolygonMesh>
void test_many_umbrellas()
{
typedef typename boost::graph_traits<PolygonMesh>::vertex_descriptor vertex_descriptor;
std::cout << " test: data_repair/many_umbrellas.off" << std::endl;
PolygonMesh mesh;
read_mesh("data_repair/many_umbrellas.off", mesh);
// non-manifold vertices
Vertices_to_merge_container all_merges;
std::vector<std::size_t> single_merge;
single_merge.push_back(1); single_merge.push_back(9); single_merge.push_back(15);
all_merges.push_back(single_merge);
std::vector<std::vector<vertex_descriptor> > duplicated_vertices;
std::size_t nb = test_nm_vertices_duplication(all_merges, duplicated_vertices, mesh);
assert(nb == 5);
const std::size_t final_vertices_size = vertices(mesh).size();
assert(duplicated_vertices.size() == 1);
assert(duplicated_vertices[0].size() == 6);
assert(final_vertices_size == 19); // 5 new ones, but we merged 2 before, so +3 from '16' at the start
}
template <typename PolygonMesh>
void test_torso()
{
typedef typename boost::graph_traits<PolygonMesh>::vertex_descriptor vertex_descriptor;
std::cout << " test: data_repair/torso.off" << std::endl;
PolygonMesh mesh;
read_mesh("data_repair/torso.off", mesh);
CGAL::Polygon_mesh_processing::remove_isolated_vertices(mesh);
std::vector<std::vector<vertex_descriptor> > duplicated_vertices;
std::size_t nb = test_nm_vertices_duplication(duplicated_vertices, mesh);
std::cout << " new vertices: " << nb << std::endl;
}
int main(int /*argc*/, char** /*argv*/)
{
std::cout << "Test Vertex Manifoldness Functions (SM)" << std::endl;
test_blobby<Surface_mesh>(); // data/blobby.off
test_nm_cubes<Surface_mesh>(); // data_repair/nm_closed_cubes.off
test_pinched_triangles<Surface_mesh>("data_repair/two_triangles_sharing_a_vertex.off", 1);
test_pinched_triangles<Surface_mesh>("data_repair/three_triangles_sharing_a_vertex.off", 2);
test_many_umbrellas<Surface_mesh>(); // data_repair/many_umbrellas.off
test_torso<Surface_mesh>(); // data_repair/torso.off (only for SM because Polyhedron cannot even read it)
std::cout << "Test Vertex Manifoldness Functions (Polyhedron)" << std::endl;
test_blobby<Polyhedron>(); // data/blobby.off
test_nm_cubes<Polyhedron>(); // data_repair/nm_closed_cubes.off
test_pinched_triangles<Polyhedron>("data_repair/two_triangles_sharing_a_vertex.off", 1);
test_pinched_triangles<Polyhedron>("data_repair/three_triangles_sharing_a_vertex.off", 2);
test_many_umbrellas<Polyhedron>(); // data_repair/many_umbrellas.off
return EXIT_SUCCESS;
}
| 37.896104 | 138 | 0.707248 | [
"mesh",
"vector"
] |
6baa72018e5857463127a0f4acd878d7ca95318b | 10,217 | cpp | C++ | cvs/objects/consumers/source/invest_consumer.cpp | zcranmer/OWEProject | 67d2367d6bdb5dd2a0aa0285be7e33ce64348677 | [
"ECL-2.0"
] | null | null | null | cvs/objects/consumers/source/invest_consumer.cpp | zcranmer/OWEProject | 67d2367d6bdb5dd2a0aa0285be7e33ce64348677 | [
"ECL-2.0"
] | null | null | null | cvs/objects/consumers/source/invest_consumer.cpp | zcranmer/OWEProject | 67d2367d6bdb5dd2a0aa0285be7e33ce64348677 | [
"ECL-2.0"
] | null | null | null | /*
* LEGAL NOTICE
* This computer software was prepared by Battelle Memorial Institute,
* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830
* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE
* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY
* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this
* sentence must appear on any copies of this computer software.
*
* EXPORT CONTROL
* User agrees that the Software will not be shipped, transferred or
* exported into any country or used in any manner prohibited by the
* United States Export Administration Act or any other applicable
* export laws, restrictions or regulations (collectively the "Export Laws").
* Export of the Software may require some form of license or other
* authority from the U.S. Government, and failure to obtain such
* export control license may result in criminal liability under
* U.S. laws. In addition, if the Software is identified as export controlled
* items under the Export Laws, User represents and warrants that User
* is not a citizen, or otherwise located within, an embargoed nation
* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)
* and that User is not otherwise prohibited
* under the Export Laws from receiving the Software.
*
* Copyright 2011 Battelle Memorial Institute. All Rights Reserved.
* Distributed as open-source under the terms of the Educational Community
* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php
*
* For further details, see: http://www.globalchange.umd.edu/models/gcam/
*
*/
/*!
* \file invest_consumer.cpp
* \ingroup Objects
* \brief The InvestConsumer class source file.
*
* \author Sonny Kim
* \author Pralit Patel
*/
#include "util/base/include/definitions.h"
#include <xercesc/dom/DOMNode.hpp>
#include "consumers/include/invest_consumer.h"
#include "util/base/include/xml_helper.h"
#include "containers/include/national_account.h"
#include "functions/include/iinput.h"
#include "functions/include/ifunction.h"
#include "containers/include/scenario.h"
#include "util/base/include/ivisitor.h"
#include "marketplace/include/marketplace.h"
#include "technologies/include/ioutput.h"
#include "functions/include/node_input.h"
#include "functions/include/function_utils.h"
using namespace std;
using namespace xercesc;
extern Scenario* scenario;
InvestConsumer::InvestConsumer(){
}
void InvestConsumer::copyParam( const BaseTechnology* aInvestConsumer,
const int aPeriod ) {
BaseTechnology::copyParam( aInvestConsumer, aPeriod );
aInvestConsumer->copyParamsInto( *this, aPeriod );
}
void InvestConsumer::copyParamsInto( InvestConsumer& aInvestConsumer,
const int aPeriod ) const {
}
InvestConsumer* InvestConsumer::clone() const {
return new InvestConsumer( *this );
}
//! parses rest of InvestConsumer xml object
bool InvestConsumer::XMLDerivedClassParse( const string& aNodeName, const DOMNode* aCurr ) {
return false;
}
//! Write out additional data members to XML output stream.
void InvestConsumer::toInputXMLDerived( ostream& aOut, Tabs* aTabs ) const {
}
//! Output debug info for derived class
void InvestConsumer::toDebugXMLDerived( const int aPeriod, ostream& aOut, Tabs* aTabs ) const {
}
//! Complete the initialization.
void InvestConsumer::completeInit( const string& aRegionName,
const string& aSectorName,
const string& aSubsectorName )
{
BaseTechnology::completeInit( aRegionName, aSectorName, aSubsectorName );
}
//! initialize anything that won't change during the calculation
void InvestConsumer::initCalc( const MoreSectorInfo* aMoreSectorInfo, const string& aRegionName,
const string& aSectorName, NationalAccount& aNationalAccount,
const Demographic* aDemographics, const double aCapitalStock, const int aPeriod )
{
Consumer::initCalc( aMoreSectorInfo, aRegionName, aSectorName,
aNationalAccount, aDemographics, aCapitalStock,
aPeriod );
const Modeltime* modelTime = scenario->getModeltime();
if ( aPeriod == 0 && year == modelTime->getper_to_yr( aPeriod ) ) {
Marketplace* marketplace = scenario->getMarketplace();
// calculate Price Paid
BaseTechnology::calcPricePaid(aMoreSectorInfo, aRegionName, aSectorName, aPeriod,
modelTime->gettimestep( aPeriod ) );
// the initial capital good price should have been set by now
mNestedInputRoot->setPricePaid( FunctionUtils::getCapitalGoodPrice( aRegionName, aPeriod ),
aPeriod );
mNestedInputRoot->calcCoefficient( aRegionName, aSectorName, 0 );
}
else if ( year == modelTime->getper_to_yr( aPeriod ) ) {
mNestedInputRoot->changeSigma( aRegionName, aPeriod,
mNestedInputRoot->getCoefficient( aPeriod ) );
}
// tech change?
}
//! calculate income
void InvestConsumer::calcIncome( NationalAccount& aNationalAccount, const Demographic* aDemographics,
const string& aRegionName, int aPeriod )
{
// Whats up with these?-JPL
//allocateTransportationDemand( nationalAccount, regionName, period );
//allocateDistributionCost( nationalAccount, regionName, period );
double investment = aNationalAccount.getAccountValue( NationalAccount::ANNUAL_INVESTMENT );
expenditures[ aPeriod ].setType( Expenditure::INVESTMENT, investment );
//scenario->getMarketplace()->addToDemand( "Capital", aRegionName, investment, aPeriod );
// set National Accounts Consumption for GNP calculation
aNationalAccount.addToAccount( NationalAccount::GNP_NOMINAL, investment );
aNationalAccount.addToAccount( NationalAccount::INVESTMENT_NOMINAL, investment );
}
//! calculate demand
void InvestConsumer::operate( NationalAccount& aNationalAccount, const Demographic* aDemographics,
const MoreSectorInfo* aMoreSectorInfo, const string& aRegionName,
const string& aSectorName, const bool aIsNewVintageMode, int aPeriod )
{
const Modeltime* modelTime = scenario->getModeltime();
if( year == modelTime->getper_to_yr( aPeriod ) ) {
expenditures[ aPeriod ].reset();
// calculate prices paid for consumer inputs
BaseTechnology::calcPricePaid(aMoreSectorInfo, aRegionName, aSectorName, aPeriod,
modelTime->gettimestep( aPeriod ) );
mNestedInputRoot->calcLevelizedCost( aRegionName, aSectorName, aPeriod,
mNestedInputRoot->getCoefficient( aPeriod ) ); // alpha zero is the root's alpha
// store the price for reporting
mCapitalGoodPrice.set( mNestedInputRoot->getPricePaid( aRegionName, aPeriod ) );
// we need to convert the annual investment from a value to a quantity by dividing
// by the price of the capital good and use that to drive demands
const double capitalQuantity = aNationalAccount.getAccountValue( NationalAccount::ANNUAL_INVESTMENT )
/ mCapitalGoodPrice;
// calculate consumption demands for each final good or service
calcInputDemand( capitalQuantity, aRegionName, aSectorName, aPeriod );
calcIncome( aNationalAccount, aDemographics, aRegionName, aPeriod );
calcEmissions( aSectorName, aRegionName, aPeriod );
Expenditure& currExpenditure = expenditures[ aPeriod ];
for( vector<IInput*>::const_iterator inputIt = mLeafInputs.begin(); inputIt != mLeafInputs.end(); ++inputIt ) {
(*inputIt)->calcTaxes( aRegionName, &aNationalAccount, &currExpenditure, aPeriod );
}
// TODO: what about emissions taxes?
double investmentTaxes = expenditures[ aPeriod ].getValue( Expenditure::INDIRECT_TAXES );
//scenario->getMarketplace()->addToDemand( "government-taxes", aRegionName, investmentTaxes, aPeriod );
// calculate the real amount consumed
// TODO: this could currently just go in post calc
aNationalAccount.addToAccount( NationalAccount::INVESTMENT_REAL,
calcRealGNP( aNationalAccount, aRegionName, aPeriod ) );
mPricePaidCached = false;
mNestedInputRoot->resetCalcLevelizedCostFlag();
}
}
/*! \brief Get the XML node name for output to XML.
*
* This public function accesses the private constant string, XML_NAME.
* This way the tag is always consistent for both read-in and output and can be easily changed.
* This function may be virtual to be overriden by derived class pointers.
* \author Josh Lurz, James Blackwood
* \return The constant XML_NAME.
*/
const string& InvestConsumer::getXMLName() const {
return getXMLNameStatic();
}
/*! \brief Get the XML node name in static form for comparison when parsing XML.
*
* This public function accesses the private constant string, XML_NAME.
* This way the tag is always consistent for both read-in and output and can be easily changed.
* The "==" operator that is used when parsing, required this second function to return static.
* \note A function cannot be static and virtual.
* \author Josh Lurz, James Blackwood
* \return The constant XML_NAME as a static.
*/
const string& InvestConsumer::getXMLNameStatic() {
const static string XML_NAME = "investConsumer";
return XML_NAME;
}
//! SGM version of outputing data members to a csv file
void InvestConsumer::csvSGMOutputFile( ostream& aFile, const int aPeriod ) const {
if ( year == scenario->getModeltime()->getper_to_yr( aPeriod ) ) {
aFile << "***** Investment Sector Results *****" << endl << endl;
aFile << "Capital good price," << mCapitalGoodPrice << endl;
expenditures[ aPeriod ].csvSGMOutputFile( aFile, aPeriod );
aFile << endl;
aFile << "Investment Consumer Expenditure" << endl << endl;
BaseTechnology::csvSGMOutputFile( aFile, aPeriod );
}
}
void InvestConsumer::accept( IVisitor* aVisitor, const int aPeriod ) const {
aVisitor->startVisitInvestConsumer( this, aPeriod );
Consumer::accept( aVisitor, aPeriod );
aVisitor->endVisitInvestConsumer( this, aPeriod );
}
| 43.849785 | 119 | 0.718019 | [
"object",
"vector"
] |
6bae470588fb05277ff54633ca5f571ad05bc3fa | 134,013 | cpp | C++ | basics.cpp | WarwickDumas/FocusFusion2D | 445903f3e9e447985cdfa40444787c108d834e48 | [
"MIT"
] | 1 | 2021-06-21T22:21:57.000Z | 2021-06-21T22:21:57.000Z | basics.cpp | WarwickDumas/FocusFusion2D | 445903f3e9e447985cdfa40444787c108d834e48 | [
"MIT"
] | 2 | 2017-07-16T01:41:11.000Z | 2021-07-05T08:40:01.000Z | basics.cpp | WarwickDumas/FocusFusion2D | 445903f3e9e447985cdfa40444787c108d834e48 | [
"MIT"
] | 1 | 2017-07-16T01:26:51.000Z | 2017-07-16T01:26:51.000Z | #ifndef BASICSCPP
#define BASICSCPP
#include "mesh.h"
#include "globals.h"
#include "vector_tensor.cu"
//#include "vector_tensor.cpp"
// For manipulations of triangles and vertices.
smartlong GlobalVertexScratchList;
//real const minimum_pressure_SD_at_1e18_sq = minimum_pressure_SD_at_1e18*minimum_pressure_SD_at_1e18;
//real const min_variance_heat = min_SD_heat*min_SD_heat;
Tensor2 const Anticlockwise(cos(FULLANGLE),-sin(FULLANGLE),sin(FULLANGLE),cos(FULLANGLE));
Tensor2 const Clockwise(cos(FULLANGLE),sin(FULLANGLE),-sin(FULLANGLE),cos(FULLANGLE));
Tensor3 const Anticlockwise3 (cos(FULLANGLE),-sin(FULLANGLE), 0.0,
sin(FULLANGLE),cos(FULLANGLE), 0.0,
0.0, 0.0, 1.0);
Tensor3 const Clockwise3 (cos(FULLANGLE),sin(FULLANGLE), 0.0,
-sin(FULLANGLE),cos(FULLANGLE), 0.0,
0.0, 0.0, 1.0);
Tensor2 const HalfAnticlockwise (cos(HALFANGLE),-sin(HALFANGLE),sin(HALFANGLE),cos(HALFANGLE));
Tensor2 const HalfClockwise(cos(HALFANGLE),sin(HALFANGLE),-sin(HALFANGLE),cos(HALFANGLE));
real modelled_n;
void ConvexPolygon::CreateClockwiseImage(const ConvexPolygon & cpSrc)
{
numCoords = cpSrc.numCoords;
for (int i = 0; i < numCoords; i++)
coord[i] = Clockwise*cpSrc.coord[i];
}
void ConvexPolygon::CreateAnticlockwiseImage(const ConvexPolygon & cpSrc)
{
numCoords = cpSrc.numCoords;
for (int i = 0; i < numCoords; i++)
coord[i] = Anticlockwise*cpSrc.coord[i];
}
fluid_nvT fluid_nvT::Clockwise() const
{
fluid_nvT result;
memcpy(&(result.n),&(n),sizeof(real)*3);
memcpy(&(result.nT),&(nT),sizeof(real)*3);
result.nv[0] = Clockwise3*nv[0];
result.nv[1] = Clockwise3*nv[1];
result.nv[2] = Clockwise3*nv[2];
return result;
}
fluid_nvT fluid_nvT::Anticlockwise() const
{
fluid_nvT result;
memcpy(&(result.n),&(n),sizeof(real)*3);
memcpy(&(result.nT),&(nT),sizeof(real)*3);
result.nv[0] = Anticlockwise3*nv[0];
result.nv[1] = Anticlockwise3*nv[1];
result.nv[2] = Anticlockwise3*nv[2];
return result;
}
void fluidnvT::Interpolate ( fluidnvT* pvv1, fluidnvT * pvv2,
Vector2 & pos1, Vector2 & pos2, Vector2 & ourpos)
{
// want to take dist1/(dist1 + dist2)
// (dist1/(dist1+dist2)) = dist1/dist2 / (1 + dist1/dist2)
// real ratio = sqrt(
// ((pos1.x-ourpos.x)*(pos1.x-ourpos.x)+(pos1.y-ourpos.y)*(pos1.y-ourpos.y))/
// ((pos2.x-ourpos.x)*(pos2.x-ourpos.x)+(pos2.y-ourpos.y)*(pos2.y-ourpos.y)));
// this is too dangerous - maybe ourpos == pos2
real dist1 = sqrt((pos1.x-ourpos.x)*(pos1.x-ourpos.x)+(pos1.y-ourpos.y)*(pos1.y-ourpos.y));
real dist2 = sqrt((pos2.x-ourpos.x)*(pos2.x-ourpos.x)+(pos2.y-ourpos.y)*(pos2.y-ourpos.y));
real ppn = dist1/(dist1+dist2);
real minus = 1.0-ppn;
n = ppn*pvv2->n + minus*pvv1->n;
T = ppn*pvv2->T + minus*pvv1->T;
v = ppn*pvv2->v + minus*pvv1->v;
}
void GetInterpolationCoefficients( real beta[3],
real x, real y,
Vector2 pos0, Vector2 pos1, Vector2 pos2)
{
// idea is to form a plane that passes through z0,z1,z2.
// so firstly if we lie on a line between 0 and 1, we know what that is;
// then we have some gradient in the direction normal to that which is determined by y2
//relative = pos-pos0;
//along01 = relative.dot(pos1-pos0)/(pos1-pos0).modulus();
//// by being clever we should be able to avoid the square root since have z0 + (z1-z0)/(pos1-pos0).modulus()
//perp.x = pos0.y-pos1.y;
//perp.y = pos1.x-pos0.x;
//away = relative.dot(perp)/perp.modulus();
//pos2along01 = (pos2 - pos0).dot(pos1-pos0)/(pos1-pos0).modulus();
//pos2away = (pos2-pos0).dot(perp)/perp.modulus();
//real z_ = z0 + pos2along01*(z1-z0)/(pos1-pos0).modulus();
//gradient_away = (z2-z_)/pos2away;
//real z = z0 + along01*((z1-z0)/(pos1-pos0).modulus()) + away*gradient_away;
//*pResult = z;
// fast version:
Vector2 pos(x,y);
Vector2 perp;
real ratio;//, coeff_on_z0, coeff_on_z1, coeff_on_z2;
Vector2 relative = pos-pos0;
Vector2 rel1 = pos1-pos0;
Vector2 rel2 = pos2-pos0;
real mod01sq = rel1.dot(rel1);
real along01_over_mod01 = relative.dot(rel1)/mod01sq;
real pos2along01_over_mod01 = rel2.dot(rel1)/mod01sq;
//real z_expect = z0 + pos2along01_over_mod01*(z1-z0);
//gradient_away = (z2-z_expect)*(perp.modulus()/((pos2-pos0).dot(perp)));
//away_times_gradient_away = (z2-z_expect)*relative.dot(perp)/((pos2-pos0).dot(perp));
//real z = z0 + along01_over_mod01*((z1-z0)) + away_times_gradient_away;
// can we work out coefficients actually on z0,z1,z2 because then can do faster in 2D,3D. :
perp.x = -rel1.y;
perp.y = rel1.x;
ratio = relative.dot(perp)/(rel2.dot(perp));
//beta[0] = 1.0 - along01_over_mod01 - ratio + ratio*pos2along01_over_mod01;
beta[1] = along01_over_mod01 - ratio*pos2along01_over_mod01;
beta[2] = ratio;
beta[0] = 1.0 - beta[1] - beta[2];
//*pResult = coeff_on_z0*z0 + coeff_on_z1*z1 + coeff_on_z2*z2;
}
void TriMesh::RecalculateCentroid(Vertex * pVertex)
{
// ASSUMES TRI CENTROIDS SET.
long tri_len, i;
Triangle * pTri;
ConvexPolygon cp;
long izTri[128];
Vector2 tri_cent;
if ((pVertex->flags != INNERMOST) && (pVertex->flags != CONVEX_EDGE_VERTEX))
{
cp.Clear();
tri_len = pVertex->GetTriIndexArray(izTri);
for (i = 0; i < tri_len; i++)
{
pTri = T + izTri[i];
tri_cent = pTri->GetContiguousCent_AssumingCentroidsSet(pVertex);
cp.add(tri_cent);
}
pVertex->centroid = cp.CalculateBarycenter();
} else {
pVertex->centroid = pVertex->pos; // at edge of memory
};
}
Vector3 Triangle::GetAAvg() const
{
Vector3 A;
if (u8domain_flag != CROSSING_INS)
{
if (periodic == 0)
{ A = (cornerptr[0]->A + cornerptr[1]->A + cornerptr[2]->A)/3.0;
return A;
};
int par[3];
GetParity(par);
A.x = 0.0; A.y = 0.0; A.z = 0.0;
if (par[0] == 0){
A += cornerptr[0]->A;
} else {
A += Anticlockwise3*cornerptr[0]->A;
};
if (par[1] == 0) {
A += cornerptr[1]->A;
} else {
A += Anticlockwise3*cornerptr[1]->A;
};
if (par[2] == 0) {
A += cornerptr[2]->A;
} else {
A += Anticlockwise3*cornerptr[2]->A;
};
A /= 3.0;
return A;
}
// In the insulator crossing case the used position is shifted from
// the centroid down to the insulator.
real beta[3];
GetInterpolationCoefficients(beta, cent.x, cent.y,
cornerptr[0]->pos,
cornerptr[1]->pos,
cornerptr[2]->pos);
if (periodic == 0) {
A = beta[0]*cornerptr[0]->A + beta[1]*cornerptr[1]->A + beta[2]*cornerptr[2]->A;
return A;
};
int par[3];
GetParity(par);
A.x = 0.0; A.y = 0.0; A.z = 0.0;
if (par[0] == 0){
A += beta[0]*cornerptr[0]->A;
} else {
A += beta[0]*(Anticlockwise3*cornerptr[0]->A);
};
if (par[1] == 0) {
A += beta[1]*cornerptr[1]->A;
} else {
A += beta[1]*(Anticlockwise3*cornerptr[1]->A);
};
if (par[2] == 0) {
A += beta[2]*cornerptr[2]->A;
} else {
A += beta[2]*(Anticlockwise3*cornerptr[2]->A);
};
return A;
}
/*macroscopic macroscopic::operator* (const real hh,const macroscopic &vars)
{
macroscopic cv;
cv.mass = hh*vars.mass;
cv.heat = hh*vars.heat;
cv.mom = hh*vars.mom;
return cv;
}
*/
/*
bool inline AuxTriangle::has_vertex(AuxVertex * pVertex)
{
return ((cornerptr[0] == pVertex) || (cornerptr[1] == pVertex) || (cornerptr[2] == pVertex));
};
AuxVertex::AuxVertex() {
flags = 0;
tri_len = 0;
neigh_len = 0;
};
void AuxVertex::addtri(long iTri)
{
iTriangles[tri_len] = iTri;
tri_len++;
if (tri_len > MAXNEIGH) {
printf("\n\ntri_len > MAXNEIGH. stop.\n\n");
getch();
tri_len = tri_len;
};
if (tri_len > 8)
{
tri_len = tri_len;
}
};
void AuxVertex::remove_tri(long iTri)
{
long iWhich = 0;
while ((iWhich < tri_len)
&& (iTriangles[iWhich] != iTri)) iWhich++;
if (iWhich == tri_len)
{
iWhich = iWhich;
}
memmove(iTriangles+iWhich,iTriangles+iWhich+1,sizeof(long)*(tri_len-iWhich-1));
tri_len--;
};
void AuxVertex::add_neigh(long iNeigh)
{
if (neigh_len == MAXNEIGH){
printf("Had to stop: too many neighs in Aux mesh.\n");
getch();
return;
}
iNeighbours[neigh_len] = iNeigh;
neigh_len++;
};
int AuxVertex::add_neigh_unique(long iNeigh)
{
int i;
for (i = 0; i < neigh_len; i++)
if (iNeighbours[i] == iNeigh) return 0;
if (neigh_len == MAXNEIGH){
printf("Had to stop: too many neighs in Aux mesh.\n");
getch();
return 2;
}
iNeighbours[neigh_len] = iNeigh;
neigh_len++;
return 1;
};
//void coeff_add(long iVertex, real beta)
//{
// coeff_extra.add(beta);
// coeff_self -= beta;
// index_extra.add(iVertex);
//};
void AuxVertex::PopulatePosition(Vector2 & result)
{
result.x = x; result.y = y;
}
AuxTriangle::AuxTriangle() {
flags = DOMAIN_TRIANGLE;
periodic = 0;
}
AuxTriangle::~AuxTriangle() {}
void AuxTriangle::PopulatePositions(Vector2 & u0, Vector2 & u1, Vector2 & u2)
{
cornerptr[0]->PopulatePosition(u0);
cornerptr[1]->PopulatePosition(u1);
cornerptr[2]->PopulatePosition(u2);
};
int AuxTriangle::GetLeftmostIndex()
{
// Note: we could put an argument for returning the one with leftmost gradient x/y
int c1 = 1;
if (cornerptr[2]->pos.x/cornerptr[2]->pos.y < cornerptr[1]->pos.x/cornerptr[1]->pos.y)
c1 = 2;
if (cornerptr[0]->pos.y != 0.0) {
if (cornerptr[0]->pos.x/cornerptr[0]->pos.y < cornerptr[c1]->x/cornerptr[c1]->y)
c1 = 0;
};
return c1;
}
int AuxTriangle::GetRightmostIndex()
{
int c1 = 1;
if (cornerptr[2]->pos.x/cornerptr[2]->pos.y > cornerptr[1]->pos.x/cornerptr[1]->pos.y)
c1 = 2;
if (cornerptr[0]->pos.y != 0.0) {
if (cornerptr[0]->pos.x/cornerptr[0]->pos.y > cornerptr[c1]->x/cornerptr[c1]->y)
c1 = 0;
};
return c1;
}
*/
smartlong::smartlong()
{
ptr = NULL;
len = 0;
alloclen = 0;
};
void smartlong::clear()
{
if (ptr != NULL) free(ptr);
ptr = NULL;
len = 0;
alloclen = 0;
};
void smartlong::remove_if_exists(long what)
{
if (len == 0) return;
long * look = ptr;
long * ptrlast = ptr+len-1;
for (look = ptr; look <= ptrlast; ++look)
{
if (*look == what) {
for (; look < ptrlast; ++look)
*look = look[1];
len--;
return;
}
};
}
void smartlong::remove(long what)
{
// DEBUG VERSION:
//
if (len == 0) return;
//long * look = ptr;
//while (*look != what) ++look;
//long * ptrlast = ptr+len-1;
//for (; look < ptrlast; ++look)
// *look = look[1];
//len--;
long * look = ptr;
long * ptrlast = ptr+len-1;
while ((look <= ptrlast) && (*look != what)) ++look;
if (look > ptrlast)
{
printf("!!!");
getch();
};
for (; look < ptrlast; ++look)
*look = look[1];
len--;
}
void smartlong::IncreaseDim()
{
ptr = (long *)realloc(ptr,sizeof(long)*(alloclen+ALLOC));
if (ptr == 0)
{
printf("smartlong memory alloc failed!!!\n"); getch();
len = len;
};
alloclen = alloclen+ALLOC;
}
void smartlong::add(long what)
{
// make another function to only add unique....
len++;
if (len >= alloclen) IncreaseDim();
ptr[len-1] = what;
};
void smartlong::add_at_element(long what,long iInsert)
{
len++;
if (len >= alloclen) IncreaseDim();
memmove(ptr+iInsert+1,ptr+iInsert,sizeof(long)*(len-iInsert-1)); // new len ...
ptr[iInsert] = what;
}
void smartlong::copyfrom(smartlong & src)
{
clear();
for (int i = 0; i < src.len; i++)
add(src.ptr[i]);
}
bool smartlong::contains(long what)
{
if (len == 0) return false;
long * look = ptr;
long * ptrlast = ptr+len-1;
for (; look <= ptrlast; ++look)
if (*look == what) return true;
return false;
};
long smartlong::FindIndex(long what)
{
long * look = ptr;
long * ptrafter = ptr+len;
while ( look < ptrafter )
{
if (*look == what) return look-ptr;
++look;
};
return -1;
}
void smartlong::add_unique(long what)
{
long * look = ptr;
for (long k = 0; k < len; k++)
{
if (*look == what) return;
++look;
};
// Still here => it was not already in the array.
add(what);
}
void smartlong::remove_element( long iWhich )
{
if (iWhich >= len) {
iWhich = iWhich;
}
long * look = ptr+iWhich;
memmove(look, look+1,sizeof(long)*(len-iWhich-1));
// if len == 4: 0 1 2 3, delete element 2 -> copy 1 element.
len--;
if (len <= 0) {
printf("Pls don't use remove_element to delte all elemetns. \n");
getch();
};
}
int smartlong::remove_elements( long iStart, long iHowmany)
{
int iReturn;
if (iStart+iHowmany > len) {
memmove(ptr,ptr+(iHowmany+iStart-len),sizeof(long)*(len-iHowmany));
len-= iHowmany;
iReturn = 0;
} else {
long * look = ptr+iStart;
memmove(look,look+iHowmany,sizeof(long)*(len-iStart-iHowmany));
len -= iHowmany;
iReturn = iStart;
};
if (len <= 0) {
printf("Pls don't use remove_elements to delte all elemetns. \n");
getch();
};
return iReturn;
// check this over again.
}
smartlong::~smartlong()
{
if (ptr != NULL) free(ptr);
}
Triangle::Triangle()
{
indicator = 0;
}
int Triangle::FindNeighbour(Triangle * pTri)
{
if (pTri == neighbours[0]) return 0;
if (pTri == neighbours[1]) return 1;
if (pTri == neighbours[2]) return 2;
return -1;
}
void Triangle::IncrementPeriodic(void)
{
++periodic;
if (periodic == 3) periodic = 0;
}
void Triangle::DecrementPeriodic(void)
{
--periodic;
if (periodic < 0) periodic = 2;
}
void TriMesh::SetTriangleVertex(int iWhichCorner, Triangle * pTri, Vertex * pVertex)
{
pTri->cornerptr[iWhichCorner] = pVertex;
pVertex->AddTriIndex(pTri-T);
}
bool Triangle::ContainsPointInterior (Vertex * pVert)
{
if (cornerptr[0] == pVert) return false;
if (cornerptr[1] == pVert) return false;
if (cornerptr[2] == pVert) return false;
return ContainsPoint(pVert->pos.x,pVert->pos.y);
}
// Helper function:
void GetIntercept(const Vector2 & a1,const Vector2 & b1, const Vector2 & a2, const Vector2 & b2,
Vector2 * pIntercept)
{
// where does (a1 -> b1) cross (a2 -> b2) ?
real t1 = ((a1.x-a2.x)*(b2.y-a2.y)-(b2.x-a2.x)*(a1.y-a2.y))/
((a1.x-b1.x)*(b2.y-a2.y)-(b2.x-a2.x)*(a1.y-b1.y));
pIntercept->x = a1.x + t1*(b1.x-a1.x);
pIntercept->y = a1.y + t1*(b1.y-a1.y);
}
/*real GetPossiblyPeriodicDist(Vertex * pVert1, Vertex * pVert2)
{
real dist1sq,dist2sq,dist3sq,mindistsq;
Vector2 uL,uR;
uL = Anticlockwise*pVert1->pos;
uR = Clockwise*pVert1->pos;
dist1sq = (pVert2->pos.x-uL.x)*(pVert2->pos.x-uL.x)+(pVert2->pos.y-uL.y)*(pVert2->pos.y-uL.y);
dist2sq = (pVert2->pos.x-pVert1->pos.x)*(pVert2->pos.x-pVert1->pos.x)+(pVert2->pos.y-pVert1->pos.y)*(pVert2->pos.y-pVert1->pos.y);
dist3sq = (pVert2->pos.x-uR.x)*(pVert2->pos.x-uR.x)+(pVert2->pos.y-uR.y)*(pVert2->pos.y-uR.y);
mindistsq = min(dist1sq,min(dist2sq,dist3sq));
return sqrt(mindistsq);
}*/ // use GetPossiblyPeriodicDist(pVert1->pos,pVert2->pos);
real CalculateAngle(real x, real y)
{
static const real TWOPI = 2.0*PI;
real angle = atan2(y,x);
if (angle < 0.0) angle += TWOPI;
#ifdef DEBUG
if (((x > 0.0) && (y > 0.0)) && ((angle > PI*0.5) || (angle < 0.0)))
{
x = x;
};
if (((x < 0.0) && (y > 0.0)) && ((angle > PI) || (angle < PI*0.5)))
{
x = x;
};
if (((x < 0.0) && (y < 0.0)) && ((angle > PI*1.5) || (angle < PI)))
{
x= x;
};
if (((x > 0.0) && (y < 0.0)) && ((angle > PI*2.0) || (angle < PI*1.5)))
{
x= x;
};
#endif
return angle;
}
real GetPossiblyPeriodicDist(Vector2 & vec1, Vector2 & vec2)
{
real dist1sq,dist2sq,dist3sq,mindistsq;
Vector2 uL,uR;
uL = Anticlockwise*vec1;
uR = Clockwise*vec1;
dist1sq = (vec2.x-uL.x)*(vec2.x-uL.x)+(vec2.y-uL.y)*(vec2.y-uL.y);
dist2sq = (vec2.x-vec1.x)*(vec2.x-vec1.x)+(vec2.y-vec1.y)*(vec2.y-vec1.y);
dist3sq = (vec2.x-uR.x)*(vec2.x-uR.x)+(vec2.y-uR.y)*(vec2.y-uR.y);
mindistsq = min(dist1sq,min(dist2sq,dist3sq));
return sqrt(mindistsq);
}
real GetPossiblyPeriodicDistSq(Vector2 & vec1, Vector2 & vec2)
{
real dist1sq,dist2sq,dist3sq,mindistsq;
Vector2 uL,uR;
uL = Anticlockwise*vec1;
uR = Clockwise*vec1;
dist1sq = (vec2.x-uL.x)*(vec2.x-uL.x)+(vec2.y-uL.y)*(vec2.y-uL.y);
dist2sq = (vec2.x-vec1.x)*(vec2.x-vec1.x)+(vec2.y-vec1.y)*(vec2.y-vec1.y);
dist3sq = (vec2.x-uR.x)*(vec2.x-uR.x)+(vec2.y-uR.y)*(vec2.y-uR.y);
mindistsq = min(dist1sq,min(dist2sq,dist3sq));
return (mindistsq);
}
/*real GetPossiblyPeriodicDistSq(Vertex * pVert1, Vector2 & u)
{
real dist1sq,dist2sq,dist3sq,mindistsq;
Vector2 uL,uR;
pVert1->periodic_image(uL,0,1);
pVert1->periodic_image(uR,1,1);
dist1sq = (u.x-uL.x)*(u.x-uL.x)+(u.y-uL.y)*(u.y-uL.y);
dist2sq = (u.x-pVert1->pos.x)*(u.x-pVert1->pos.x)+(u.y-pVert1->pos.y)*(u.y-pVert1->pos.y);
dist3sq = (u.x-uR.x)*(u.x-uR.x)+(u.y-uR.y)*(u.y-uR.y);
mindistsq = min(dist1sq,min(dist2sq,dist3sq));
return mindistsq;
}
real GetPossiblyPeriodicDistSq(real x1, real y1, real x2, real y2)
{
real dist1sq,dist2sq,dist3sq,mindistsq;
Vector2 uL,uR;
Vector2 u1(x1,y1), u2(x2,y2);
uL = Anticlockwise*u1;
uR = Clockwise*u1;
dist1sq = (uL.x-u2.x)*(uL.x-u2.x)+(u2.y-uL.y)*(u2.y-uL.y);
dist2sq = (u1.x-u2.x)*(u1.x-u2.x)+(u1.y-u2.y)*(u1.y-u2.y);
dist3sq = (u2.x-uR.x)*(u2.x-uR.x)+(u2.y-uR.y)*(u2.y-uR.y);
mindistsq = min(dist1sq,min(dist2sq,dist3sq));
return mindistsq;
}
real GetPossiblyPeriodicDistAcrossTriangle(Triangle * pTri,int which)
{
int i1,i2;
real linex,liney,modulus,dist1x,dist1y;
// to avoid periodic woes, if it's periodic then we map to left(?) and then
// call again for our temporary triangle
// (Make sure any pointers internal to Triangle are reset before it goes out of scope!)
if (pTri->periodic == 1)
{
// one point clockwise wrapped
// unwrap...
Triangle Tri2;
Vertex Tempvert;
Vector2 u;
i1 = pTri->GetLeftmostIndex();
for (int i = 0; i < 3; i++)
{
if (i == i1)
{
pTri->cornerptr[i1]->periodic_image(u,1,1);
Tempvert.x = u.x;
Tempvert.y = u.y;
Tri2.cornerptr[i] = &Tempvert;
} else {
Tri2.cornerptr[i] = pTri->cornerptr[i];
};
};
Tri2.periodic = 0;
return GetPossiblyPeriodicDistAcrossTriangle(&Tri2,which);
};
if (pTri->periodic == 2)
{
// one point not clockwise wrapped
Triangle Tri2;
Vertex Tempvert;
Vector2 u;
i1 = pTri->GetRightmostIndex();
for (int i = 0; i < 3; i++)
{
if (i == i1)
{
pTri->cornerptr[i1]->periodic_image(u,0,1);
Tempvert.x = u.x;
Tempvert.y = u.y;
Tri2.cornerptr[i] = &Tempvert;
} else {
Tri2.cornerptr[i] = pTri->cornerptr[i];
};
};
Tri2.periodic = 0;
return GetPossiblyPeriodicDistAcrossTriangle(&Tri2,which);
};
//// distance across from cornerptr[which]
//if ((pTri->flags == TRIFLAG_LOWWEDGE) || (pTri->flags == TRIFLAG_HIGHWEDGE))
//{
// // Assume which == 0 or which == 1
// i1 = 1-which;
//
// linex = pTri->cornerptr[i1]->x;
// liney = pTri->cornerptr[i1]->y;
//
// modulus = sqrt(linex*linex+liney*liney);
// linex /= modulus;
// liney /= modulus;
// dist1x = pTri->cornerptr[which]->x-pTri->cornerptr[i1]->x;
// dist1y = pTri->cornerptr[which]->y-pTri->cornerptr[i1]->y;
//
// // project on to (liney,-linex)
// return fabs(dist1x*liney - dist1y*linex);
//};
// Triangle...
i1 = which+1;
i2 = which+2;
if (i1 == 3) i1 = 0;
if (i2 > 2) i2 -= 3;
linex = pTri->cornerptr[i1]->x-pTri->cornerptr[i2]->x;
liney = pTri->cornerptr[i1]->y-pTri->cornerptr[i2]->y;
modulus = sqrt(linex*linex+liney*liney);
linex /= modulus;
liney /= modulus;
// we want the distance to that line...
dist1x = pTri->cornerptr[which]->x-pTri->cornerptr[i1]->x;
dist1y = pTri->cornerptr[which]->y-pTri->cornerptr[i1]->y;
// project on to (liney,-linex)
return fabs(dist1x*liney - dist1y*linex);
}
real GetSqDistance_SetGlobalFlagNeedPeriodicImage(Vertex * pVertSrc, Vertex * pVert2)
{
real distx = pVertSrc->x-pVert2->pos.x;
real disty = pVertSrc->y-pVert2->pos.y;
if (GlobalPeriodicSearch)
{
// in this case we check for Clockwise and anti-Clockwise rotations
Vector2 u_anti;
Vector2 u_clock;
pVertSrc->periodic_image(u_anti,0,1); // Anticlockwise
pVertSrc->periodic_image(u_clock,1,1);
real distx_anti,disty_anti,distx_clock,disty_clock;
distx_anti = u_anti.x-pVert2->pos.x;
disty_anti = u_anti.y-pVert2->pos.y;
distx_clock = u_clock.x-pVert2->pos.x;
disty_clock = u_clock.y-pVert2->pos.y;
real distsqanti = distx_anti*distx_anti+disty_anti*disty_anti;
real distsq0 = distx*distx+disty*disty;
real distsqclock = distx_clock*distx_clock+disty_clock*disty_clock;
// If we find that Clockwise is nearest, set a flag on VertSrc
// If we find that Anticlockwise is nearest, set a flag on VertSrc
if (distsq0 < distsqanti)
{
if (distsq0 < distsqclock) {
return distsq0;
} else {
//pVertSrc->flags |= VERTFLAGS_INFLUENCE_Anticlockwise;
GlobalFlagNeedPeriodicImage = true;
return distsqclock;
};
} else {
if (distsqanti < distsqclock) {
//pVertSrc->flags |= VERTFLAGS_INFLUENCE_CLOCKWISE;
GlobalFlagNeedPeriodicImage = true;
return distsqanti;
} else {
//pVertSrc->flags |= VERTFLAGS_INFLUENCE_Anticlockwise; // this vertex was Clockwise rotated.
GlobalFlagNeedPeriodicImage = true;
return distsqclock;
};
};
};
return distx*distx+disty*disty;
}
/*real GetSqDistance_SetPerInfluenceFlagOnVertex_Full(Vertex * pVertSrc, Vertex * pVert2, real * pRetDistx, real * pRetDisty)
{
real distx = pVertSrc->x-pVert2->pos.x;
real disty = pVertSrc->y-pVert2->pos.y;
if (GlobalPeriodicSearch)
{
// in this case we check for Clockwise and anti-Clockwise rotations
Vector2 u_anti;
Vector2 u_clock;
pVertSrc->periodic_image(u_anti,0,1); // Anticlockwise
pVertSrc->periodic_image(u_clock,1,1);
real distx_anti,disty_anti,distx_clock,disty_clock;
distx_anti = u_anti.x-pVert2->pos.x;
disty_anti = u_anti.y-pVert2->pos.y;
distx_clock = u_clock.x-pVert2->pos.x;
disty_clock = u_clock.y-pVert2->pos.y;
real distsqanti = distx_anti*distx_anti+disty_anti*disty_anti;
real distsq0 = distx*distx+disty*disty;
real distsqclock = distx_clock*distx_clock+disty_clock*disty_clock;
// If we find that Clockwise is nearest, set a flag on VertSrc
// If we find that Anticlockwise is nearest, set a flag on VertSrc
if (distsq0 < distsqanti)
{
if (distsq0 < distsqclock) {
*pRetDistx = distx;
*pRetDisty = disty;
return distsq0;
} else {
pVertSrc->flags |= VERTFLAGS_INFLUENCE_Anticlockwise;
*pRetDistx = distx_clock;
*pRetDisty = disty_clock;
return distsqclock;
};
} else {
if (distsqanti < distsqclock) {
pVertSrc->flags |= VERTFLAGS_INFLUENCE_CLOCKWISE;
*pRetDistx = distx_anti;
*pRetDisty = disty_anti;
return distsqanti;
} else {
pVertSrc->flags |= VERTFLAGS_INFLUENCE_Anticlockwise; // this vertex was Clockwise rotated.
*pRetDistx = distx_clock;
*pRetDisty = disty_clock;
return distsqclock;
};
};
};
*pRetDistx = distx;
*pRetDisty = disty;
return distx*distx+disty*disty;
}
*/
int sgn(real x)
{
if (x > 0.0) return 1;
return -1;
};
int GetNumberSharedVertices(Triangle & tri1, Triangle & tri2)
{
int match;
int matches = 0;
for (int i = 0; i < 3; i++)
{
match = 0;
for (int j = 0; j < 3; j++)
if (tri1.cornerptr[i] == tri2.cornerptr[j])
match = 1;
if (match == 1) matches++;
};
return matches;
}
real Triangle::ReturnAngle(Vertex * pVertex)
{
Vector2 v1,v2,u[3];
real dotproduct_over_moduli,weight;
static const real TWOPI = 2.0*PI;
MapLeftIfNecessary(u[0],u[1],u[2]);
if (pVertex == cornerptr[0]) {
v1 = u[1]-u[0];
v2 = u[2]-u[0];
} else {
if (pVertex == cornerptr[1]) {
v1 = u[0]-u[1];
v2 = u[2]-u[1];
} else {
v1 = u[0]-u[2];
v2 = u[1]-u[2];
};
};
dotproduct_over_moduli = (v1.x*v2.x+v1.y*v2.y)/
sqrt((v1.x*v1.x+v1.y*v1.y)*(v2.x*v2.x+v2.y*v2.y));
weight = acos(dotproduct_over_moduli)/TWOPI;
return weight;
}
Vector2 Triangle::RecalculateCentroid(real InnermostFrillCentroidRadius,real OutermostFrillCentroidRadius)
{
Vector2 u[3];
MapLeftIfNecessary(u[0],u[1],u[2]);
cent = (u[0]+u[1]+u[2])/3.0;
if (u8domain_flag == CROSSING_INS)
{
// Modify the centre to be the centre of the intersection of insulator
GetCentreOfIntersectionWithInsulator(cent);
}
if (u8domain_flag == OUTER_FRILL) {
Vector2 temp = 0.5*(u[0]+u[1]); // ? compare to GPU
temp.project_to_radius(cent, OutermostFrillCentroidRadius);
};
if (u8domain_flag == INNER_FRILL) {
Vector2 temp = 0.5*(u[0]+u[1]); // ? compare to GPU
temp.project_to_radius(cent, InnermostFrillCentroidRadius);
};
return cent;
}
Vector2 Triangle::GetContiguousCent_AssumingCentroidsSet(Vertex * pVertex)
{
if (periodic == 0) return cent;
// It is assumed that pVertex is one of the corners.
if (pVertex->pos.x < 0.0) return cent;
return Clockwise*cent;
}
void TriMesh::Recalculate_TriCentroids_VertexCellAreas_And_Centroids()
{
ConvexPolygon cp;
Triangle * pTri;
Vertex * pVertex;
long iVertex, iTri;
Vector2 u;
int i;
// 1. Reset triangle centroids.
pTri = T;
for (iTri = 0; iTri < numTriangles; iTri++)
{
pTri->RecalculateCentroid(this->InnermostFrillCentroidRadius,
this->OutermostFrillCentroidRadius);
++pTri; // this seems like it should still work if we have not wrapped any vertex that moved, even if tri no longer periodic in truth but some pts outside tranche
};
// 2. Reset vertex cell areas.
long izTri[128];
long tri_len;
pVertex = X;
for (iVertex = 0; iVertex < numVertices; iVertex++)
{
tri_len = pVertex->GetTriIndexArray(izTri);
cp.Clear();
if ((pVertex->flags == CONCAVE_EDGE_VERTEX) ||
(pVertex->flags == CONVEX_EDGE_VERTEX) )
{
for (i = 0; i < tri_len; i++)
{
pTri = T + izTri[i];
u = pTri->GetContiguousCent_AssumingCentroidsSet(pVertex);
if (u.x*u.x+u.y*u.y < INNER_A_BOUNDARY*INNER_A_BOUNDARY)
u.project_to_radius(u,INNER_A_BOUNDARY);
if (u.x*u.x+u.y*u.y > DOMAIN_OUTER_RADIUS*DOMAIN_OUTER_RADIUS)
u.project_to_radius(u,DOMAIN_OUTER_RADIUS);
cp.add(u);
};
/*
// Project to a radius ...
pTri = T + izTri[0];
u = pTri->GetContiguousCent_AssumingCentroidsSet(pVertex);
if (pVertex->flags == INNERMOST) {
u.project_to_radius(u,INNER_A_BOUNDARY);
} else {
u.project_to_radius(u,DOMAIN_OUTER_RADIUS);
};
cp.add(u);
// Outermost should project to DOMAIN_OUTER_RADIUS.
// what if innermost should project also?
// Innermost is on INNERMOST_A_BOUNDARY.
for (i = 0; i < tri_len; i++)
{
pTri = T + izTri[i];
cp.add(pTri->GetContiguousCent_AssumingCentroidsSet(pVertex));
};
u = pTri->GetContiguousCent_AssumingCentroidsSet(pVertex);
if (pVertex->flags == INNERMOST) {
u.project_to_radius(u,INNER_A_BOUNDARY);
} else {
u.project_to_radius(u,DOMAIN_OUTER_RADIUS);
};
cp.add(u);
*/
} else {
for (i = 0; i < tri_len; i++)
{
pTri = T + izTri[i];
cp.add(pTri->GetContiguousCent_AssumingCentroidsSet(pVertex));
};
};
pVertex->AreaCell = cp.GetArea();
pVertex->centroid = cp.CalculateBarycenter();
//if (iVertex == 36685) {
// printf("vertex %d flag %d \n",iVertex,pVertex->flags);
// for (i = 0; i < cp.numCoords; i++)
// printf("%1.5E %1.5E ... %1.5E \n",cp.coord[i].x,cp.coord[i].y,
// cp.coord[i].modulus());
// printf("\n\n");
//
// for (i = 0; i < tri_len; i++)
// {
// pTri = T + izTri[i];
// u = pTri->GetContiguousCent_AssumingCentroidsSet(pVertex);
// printf("%1.5E %1.5E ... %1.5E \n",u.x,u.y,u.modulus());
// };
// getch();
//}
//
++pVertex;
};
}
void Triangle::MapLeftIfNecessary(Vector2 & u0, Vector2 & u1, Vector2 & u2) const
{
PopulatePositions(u0,u1,u2);
if (periodic == 1)
{
int o1 = GetLeftmostIndex();
if (o1 != 0) u0 = Anticlockwise*u0;
if (o1 != 1) u1 = Anticlockwise*u1;
if (o1 != 2) u2 = Anticlockwise*u2;
return;
};
if (periodic == 2)
{
int o1 = GetRightmostIndex();
if (o1 == 0) u0 = Anticlockwise*u0;
if (o1 == 1) u1 = Anticlockwise*u1;
if (o1 == 2) u2 = Anticlockwise*u2;
return;
};
}
real Triangle::GetDomainIntersectionAreaROC(Vector2 u[3],int iWhichMove,Vector2 ROC)
{
// Call once for each moving corner to get total ROC area.
// ROC is the rate of change of position u[iWhichMove] which is in the domain.
bool bDomain[3];
int iDomain, iWhich, iWhich1, iWhich2;
Vector2 intercept1, intercept2, ROCintercept1, ROCintercept2,
dArea_by_d_top, dArea_by_d1,dArea_by_d2;
real shoelace;
bDomain[0] = (cornerptr[0]->flags == DOMAIN_VERTEX)?1:0;
bDomain[1] = (cornerptr[1]->flags == DOMAIN_VERTEX)?1:0;
bDomain[2] = (cornerptr[2]->flags == DOMAIN_VERTEX)?1:0;
iDomain = bDomain[0]+bDomain[1]+bDomain[2];
if (iDomain == 1) {
if (bDomain[iWhichMove] != 1) {
printf("dodginesse\n");
getch();
}
iWhich = 0; while (bDomain[iWhich] == 0) iWhich++;
iWhich1 = iWhich-1; if (iWhich1 == -1) iWhich1 = 2;
iWhich2 = iWhich+1; if (iWhich2 == 3) iWhich2 = 0;
GetInsulatorIntercept(&intercept1,u[iWhich1],u[iWhich]);
GetInsulatorIntercept(&intercept2,u[iWhich2],u[iWhich]);
Get_ROC_InsulatorIntercept(&ROCintercept1,u[iWhich1],u[iWhich],ROC);
Get_ROC_InsulatorIntercept(&ROCintercept2,u[iWhich2],u[iWhich],ROC);
// cp.GetArea contents:
// for (i = 0; i < numCoords-1; i++)
// area += coord[i].x*coord[i+1].y - coord[i+1].x*coord[i].y;
// area += coord[i].x*coord[0].y - coord[0].x*coord[i].y;
// return fabs(area*0.5);
// ROCArea = sum_i[top & intercepts] dArea/dx_i . dx_i/dt
// establish which way round shoelace is positive:
shoelace = u[iWhich].x*u[iWhich2].y - u[iWhich2].x*u[iWhich].y
+ u[iWhich2].x*u[iWhich1].y - u[iWhich1].x*u[iWhich2].y
+ u[iWhich1].x*u[iWhich].y - u[iWhich].x*u[iWhich1].y;
real sign = 1.0;
if (shoelace < 0.0) sign = -1.0;
// area = 0.5*sign* that shoelace.
dArea_by_d_top.x = 0.5*sign*(u[iWhich2].y - u[iWhich1].y);
dArea_by_d_top.y = 0.5*sign*(u[iWhich1].x - u[iWhich2].x);
dArea_by_d1.x = 0.5*sign*(u[iWhich].y-u[iWhich2].y);
dArea_by_d1.y = 0.5*sign*(u[iWhich2].x-u[iWhich].x);
dArea_by_d2.x = 0.5*sign*(u[iWhich1].y-u[iWhich].y);
dArea_by_d2.y = 0.5*sign*(u[iWhich].x-u[iWhich1].x);
real answer = dArea_by_d1.dot(ROCintercept1) + dArea_by_d2.dot(ROCintercept2)
+ dArea_by_d_top.dot(ROC);
return answer;
};
// We consider one corner moving at a time.
iWhich = 0; while (bDomain[iWhich] == 1) iWhich++;
iWhich1 = 0; while (bDomain[iWhich1] == 0) iWhich1++;
iWhich2 = iWhich1+1; while (bDomain[iWhich2] == 0) iWhich2++;
GetInsulatorIntercept(&intercept1,u[iWhich1],u[iWhich]);
GetInsulatorIntercept(&intercept2,u[iWhich2],u[iWhich]);
if (iWhichMove == iWhich1) {
Get_ROC_InsulatorIntercept(&ROCintercept1,u[iWhich],u[iWhich1],ROC);
shoelace = u[iWhich1].x*intercept1.y - intercept1.x*u[iWhich1].y
+ intercept1.x*intercept2.y - intercept2.x*intercept1.y
+ intercept2.x*u[iWhich2].y - u[iWhich2].x*intercept2.y
+ u[iWhich2].x*u[iWhich1].y - u[iWhich1].x*u[iWhich2].y;
real sign = 1.0;
if (shoelace < 0.0) sign = -1.0;
dArea_by_d_top.x = 0.5*sign*(intercept1.y - u[iWhich2].y);
dArea_by_d_top.y = 0.5*sign*(u[iWhich2].x - intercept1.x);
dArea_by_d1.x = 0.5*sign*(intercept2.y - u[iWhich1].x);
dArea_by_d1.y = 0.5*sign*(u[iWhich1].y - intercept2.y);
real answer = dArea_by_d_top.dot(ROC) + dArea_by_d1.dot(ROCintercept1);
return answer;
} else {
Get_ROC_InsulatorIntercept(&ROCintercept2,u[iWhich],u[iWhich2],ROC);
shoelace = u[iWhich1].x*intercept1.y - intercept1.x*u[iWhich1].y
+ intercept1.x*intercept2.y - intercept2.x*intercept1.y
+ intercept2.x*u[iWhich2].y - u[iWhich2].x*intercept2.y
+ u[iWhich2].x*u[iWhich1].y - u[iWhich1].x*u[iWhich2].y;
real sign = 1.0;
if (shoelace < 0.0) sign = -1.0;
dArea_by_d_top.x = 0.5*sign*(u[iWhich1].y - intercept2.y);
dArea_by_d_top.y = 0.5*sign*(intercept2.x - u[iWhich2].x);
dArea_by_d2.x = 0.5*sign*(u[iWhich2].y - intercept1.y);
dArea_by_d2.y = 0.5*sign*(intercept1.x - u[iWhich2].x);
real answer = dArea_by_d_top.dot(ROC) + dArea_by_d2.dot(ROCintercept2);
return answer;
};
}
real Triangle::GetDomainIntersectionArea(bool bUseOwnCoords, Vector2 u[3]) const
{
ConvexPolygon cp;
int iDomain, iWhich, iWhich1, iWhich2;
int bDomain[3];
Vector2 intercept1, intercept2;
if (u8domain_flag == OUT_OF_DOMAIN) return 0.0;
if (u8domain_flag == DOMAIN_TRIANGLE) return this->GetArea();
if (bUseOwnCoords) MapLeftIfNecessary(u[0],u[1],u[2]); // This gives for the original triangle.
bDomain[0] = (cornerptr[0]->flags == DOMAIN_VERTEX)?1:0;
bDomain[1] = (cornerptr[1]->flags == DOMAIN_VERTEX)?1:0;
bDomain[2] = (cornerptr[2]->flags == DOMAIN_VERTEX)?1:0;
iDomain = bDomain[0]+bDomain[1]+bDomain[2];
if (iDomain == 1) {
iWhich = 0; while (bDomain[iWhich] == 0) iWhich++;
iWhich1 = 0; while (bDomain[iWhich1] == 1) iWhich1++;
iWhich2 = iWhich1+1; while (bDomain[iWhich2] == 1) iWhich2++;
GetInsulatorIntercept(&intercept1,u[iWhich1],u[iWhich]);
GetInsulatorIntercept(&intercept2,u[iWhich2],u[iWhich]);
cp.Clear();
cp.add(intercept1);
cp.add(u[iWhich]);
cp.add(intercept2);
return cp.GetArea();
};
if (iDomain != 2) {
printf("Error in GetDomainIntersectionArea.\n");
return 0.0;
};
iWhich = 0; while (bDomain[iWhich] == 1) iWhich++;
iWhich1 = 0; while (bDomain[iWhich1] == 0) iWhich1++;
iWhich2 = iWhich1+1; while (bDomain[iWhich2] == 0) iWhich2++;
// iWhich1 shall go next to intercept1 in the sequence.
GetInsulatorIntercept(&intercept1,u[iWhich1],u[iWhich]);
GetInsulatorIntercept(&intercept2,u[iWhich2],u[iWhich]);
cp.Clear();
cp.add(intercept1);
cp.add(u[iWhich1]);
cp.add(u[iWhich2]);
cp.add(intercept2);
return cp.GetArea();
}
void Triangle::GuessPeriodic(void)
{
real ratio0,ratio1,ratio2,gradient;
ratio0 = cornerptr[0]->pos.x/cornerptr[0]->pos.y;
ratio1 = cornerptr[1]->pos.x/cornerptr[1]->pos.y;
ratio2 = cornerptr[2]->pos.x/cornerptr[2]->pos.y;
gradient = GRADIENT_X_PER_Y/2.0;
periodic = 0;
if (ratio0 > gradient)
{
// number periodic is the number of others that are < -GRADIENT_X_PER_Y/3.0
if (ratio1 < -gradient)
++periodic;
if (ratio2 < -gradient)
++periodic;
} else {
if (ratio1 > gradient)
{
if (ratio0 < -gradient)
++periodic;
if (ratio2 < -gradient)
++periodic;
} else {
if (ratio2 > gradient)
{
if (ratio0 < -gradient)
++periodic;
if (ratio1 < -gradient)
++periodic;
};
};
};
}
void Triangle::RecalculateEdgeNormalVectors(bool normalise)
{
int iPrev,iNext;
Vector2 u[3];
MapLeftIfNecessary(u[0],u[1],u[2]);
for (int i = 0; i < 3; i++)
{
iPrev = i-1; if (iPrev < 0) iPrev = 2;
iNext = i+1; if (iNext > 2) iNext = 0;
edge_normal[i].x = u[iNext].y-u[iPrev].y;
edge_normal[i].y = u[iPrev].x-u[iNext].x;
if (edge_normal[i].dot(u[i]-u[iPrev]) > 0.0)
{
// facing the wrong way - should face away from u[i]
edge_normal[i].x = -edge_normal[i].x;
edge_normal[i].y = -edge_normal[i].y;
};
if (normalise) edge_normal[i].Normalise();
// NOTE: if normalise == false then the length of edge_normal is the side length -- quite convenient
};
// Same code will work even if looking out of the domain.
}
// Better if we make this part of some prototypical base class.
// OR, AuxTriangles just are Triangles. Why not?
/*void AuxTriangle::GuessPeriodic(void)
{
real ratio0,ratio1,ratio2,gradient;
ratio0 = cornerptr[0]->pos.x/cornerptr[0]->pos.y;
ratio1 = cornerptr[1]->pos.x/cornerptr[1]->pos.y;
ratio2 = cornerptr[2]->pos.x/cornerptr[2]->pos.y;
gradient = GRADIENT_X_PER_Y/2.0;
periodic = 0;
if (ratio0 > gradient)
{
// number periodic is the number of others that are < -GRADIENT_X_PER_Y/3.0
if (ratio1 < -gradient)
++periodic;
if (ratio2 < -gradient)
++periodic;
} else {
if (ratio1 > gradient)
{
if (ratio0 < -gradient)
++periodic;
if (ratio2 < -gradient)
++periodic;
} else {
if (ratio2 > gradient)
{
if (ratio0 < -gradient)
++periodic;
if (ratio1 < -gradient)
++periodic;
};
};
};
}
void AuxTriangle::RecalculateEdgeNormalVectors(bool normalise)
{
// copy of function below
// !
int iPrev,iNext;
Vector2 u[3];
if (periodic == 0)
{
this->PopulatePositions(u[0],u[1],u[2]);
} else {
this->MapLeft(u[0],u[1],u[2]);
};
for (int i = 0; i < 3; i++)
{
iPrev = i-1; if (iPrev < 0) iPrev = 2;
iNext = i+1; if (iNext > 2) iNext = 0;
edge_normal[i].x = u[iNext].y-u[iPrev].y;
edge_normal[i].y = u[iPrev].x-u[iNext].x;
if (edge_normal[i].dot(u[i]-u[iPrev]) > 0.0)
{
// facing the wrong way - should face away from u[i]
edge_normal[i].x = -edge_normal[i].x;
edge_normal[i].y = -edge_normal[i].y;
};
if (normalise) edge_normal[i].Normalise();
// NOTE: if normalise == false then the length of edge_normal is the side length -- quite convenient
};
// Same code will work even if looking out of the domain.
}
*/
// unnecessary as far as I know:
/*void AuxTriangle::RecalculateEdgeNormalVectors(bool normalise)
{
// in CUDA version we will only use edge_normal and get rid of transvec stuff
int iPrev,iNext;
Vector2 u[3];
if (periodic == 0)
{
this->PopulatePositions(u[0],u[1],u[2]);
} else {
this->MapLeft(u[0],u[1],u[2]);
};
for (int i = 0; i < 3; i++)
{
iPrev = i-1; if (iPrev < 0) iPrev = 2;
iNext = i+1; if (iNext > 2) iNext = 0;
edge_normal[i].x = u[iNext].y-u[iPrev].y;
edge_normal[i].y = u[iPrev].x-u[iNext].x;
if (edge_normal[i].dot(u[i]-u[iPrev]) > 0.0)
{
// facing the wrong way - should face away from u[i]
edge_normal[i].x = -edge_normal[i].x;
edge_normal[i].y = -edge_normal[i].y;
};
if (normalise) edge_normal[i].Normalise();
// NOTE: if normalise == false then the length of edge_normal is the side length -- quite convenient
};
// Same code will work even if looking out of the domain.
}
*/
/*real Triangle::GetShortArea()
{
Vector2 u0,u1,u2;
Vector2 u0dash, u1dash;
real u0mod, u1mod;
if (flags != 2)
{
printf("bad call.\n");
getch();
};
// place u0dash, u1dash at projected coordinates NOTIONAL_DISTANCE further out.
if (periodic == 0) {
PopulatePositions(u0,u1,u2);
} else {
MapLeft(u0,u1,u2);
};
u0mod = u0.modulus();
u1mod = u1.modulus();
u0dash = ((u0mod+NOTIONAL_DISTANCE)/u0mod)*u0;
u1dash = ((u0mod+NOTIONAL_DISTANCE)/u1mod)*u1;
// shoelace:
//return 0.5*fabs( u0.x*u1.y - u1.x*u0.y
// + u1.x*u2.y - u2.x*u1.y
// + u2.x*u0.y - u0.x*u2.y);
return 0.5*fabs( u0.x*u0dash.y - u0dash.x*u0.y
+ u0dash.x*u1dash.y - u1dash.x*u0dash.y
+ u1dash.x*u1.y - u1.x*u1dash.y
+ u1.x*u0.y - u0.x*u1.y);
};*/
/*real Triangle::GetNormalDistance(int opp)
{
/* // Requires that transvec be already set correctly.
real diffx,diffy;
// This is only for the non-periodic case -- we need to allow for periodic
real transmod = sqrt(transvecx[opp]*transvecx[opp]+transvecy[opp]*transvecy[opp]);
real transhatx = transvecx[opp]/transmod;
real transhaty = transvecy[opp]/transmod;
// But how to know if transhat faces in or out??
// we're not guaranteed this is same as transhat start.
int which = opp-1;
if (which < 0) which = 2;
if (periodic == 0)
{
// difference dot with trans hat vector = normal distance
diffx = cornerptr[opp]->x-cornerptr[which]->x;
diffy = cornerptr[opp]->y-cornerptr[which]->y;
} else {
// note that transvec is calculated by moving all to the left.
// difference dot with trans hat vector = normal distance
Vector2 v_opp, v_which;
cornerptr[opp]->periodic_image(v_opp,0);
cornerptr[which]->periodic_image(v_which,0);
diffx = v_opp.x-v_which.x;
diffy = v_opp.y-v_which.y;
};
return diffx*transhatx + diffy*transhaty;*/
// Better to do differently:
// Pythagoras:
// side1^2 = x^2 + y^2
// side2^2 = (a-x)^2 + y^2
// we want y, we do not know x, we know a & side1,side2.
// side2^2 - side1^2 = a^2 - 2ax
// x = (s2^2 - s1^2 - a^2)/(-2a)
// y = sqrt(s1^2 - x^2)
// PERIODIC CASE?
// Normal distance may need to be given correctly!!!
// ->proceed to populate 3 Vector2's based on flags, periodic and
// then do the Pythagoras normal distance calculation.
/*
Vector2 u1,u2,uO;
if (flags == 0)
{
int c1 = opp-1;
if (c1 < 0) c1 = 2;
int c2 = opp+1;
if (c2 > 2) c2 = 0;
if (periodic == 0)
{
cornerptr[c1]->PopulatePosition(u1);
cornerptr[c2]->PopulatePosition(u2);
cornerptr[opp]->PopulatePosition(uO);
} else {
cornerptr[c1]->periodic_image(u1,0);
cornerptr[c2]->periodic_image(u2,0);
cornerptr[opp]->periodic_image(uO,0);
};
} else {
if (flags == 1)
{
// low wedge
// in this case, normal distance is construed relative to
// the sides and top
// X Don't do -->>> just assume periodic to make code shorter.
if (periodic > 0)
{
if (opp == 0)
{
// side goes from 1 to ins
cornerptr[1]->periodic_image(u1,0);
cornerptr[1]->project_to_ins_periodic(u2,0);
cornerptr[0]->periodic_image(uO,0);
} else {
if (opp == 1)
{
// side goes from 0 to ins
cornerptr[0]->periodic_image(u1,0);
cornerptr[0]->project_to_ins_periodic(u2,0);
cornerptr[1]->periodic_image(uO,0);
} else {
// side goes from 0 to 1
cornerptr[0]->periodic_image(u1,0);
cornerptr[1]->periodic_image(u2,0);
cornerptr[0]->project_to_ins_periodic(uO,0);
};
};
} else {
if (opp == 0)
{
// side goes from 1 to ins
cornerptr[1]->PopulatePosition(u1);
cornerptr[1]->project_to_ins(u2);
cornerptr[0]->PopulatePosition(uO);
} else {
if (opp == 1)
{
// side goes from 0 to ins
cornerptr[0]->PopulatePosition(u1);
cornerptr[0]->project_to_ins(u2);
cornerptr[1]->PopulatePosition(uO);
} else {
// side goes from 0 to 1
cornerptr[0]->PopulatePosition(u1);
cornerptr[1]->PopulatePosition(u2);
cornerptr[0]->project_to_ins(uO);
};
};
};
} else {
if (periodic > 0)
{
// high wedge
if (opp == 0)
{
// side goes from 1 to ins
cornerptr[1]->periodic_image(u1,0);
cornerptr[1]->project_to_100cm_periodic(u2,0);
cornerptr[0]->periodic_image(uO,0);
} else {
if (opp == 1)
{
// side goes from 0 to ins
cornerptr[0]->periodic_image(u1,0);
cornerptr[0]->project_to_100cm_periodic(u2,0);
cornerptr[1]->periodic_image(uO,0);
} else {
// side goes from 0 to 1
cornerptr[0]->periodic_image(u1,0);
cornerptr[1]->periodic_image(u2,0);
cornerptr[0]->project_to_100cm_periodic(uO,0);
};
};
} else {
// high wedge
if (opp == 0)
{
// side goes from 1 to ins
cornerptr[1]->PopulatePosition(u1);
cornerptr[1]->project_to_100cm(u2);
cornerptr[0]->PopulatePosition(uO);
} else {
if (opp == 1)
{
// side goes from 0 to ins
cornerptr[0]->PopulatePosition(u1);
cornerptr[0]->project_to_100cm(u2);
cornerptr[1]->PopulatePosition(uO);
} else {
// side goes from 0 to 1
cornerptr[0]->PopulatePosition(u1);
cornerptr[1]->PopulatePosition(u2);
cornerptr[0]->project_to_100cm(uO);
};
};
};
};
};
real dist1sq = (u1.x-uO.x)*(u1.x-uO.x)+(u1.y-uO.y)*(u1.y-uO.y);
real dist2sq = (u2.x-uO.x)*(u2.x-uO.x)+(u2.y-uO.y)*(u2.y-uO.y);
real distasq = (u1.x-u2.x)*(u1.x-u2.x)+(u1.y-u2.y)*(u1.y-u2.y);;
real x = (dist2sq - dist1sq - distasq)/(-2.0*sqrt(distasq));
real y = sqrt(dist1sq - x*x);
return y;
}*/
/*real Vertex::CalculateVoronoiArea()
{
// Voronoi area is found assuming that ... circumcenters were already calculated.
// (!)
// and stored as pTri->numerator_x,y
Triangle * pTri;
ConvexPolygon cp;
Vector2 circumcenter, cc;
real theta;
int i,j,k;
real angle[100];
int index[100];
Proto * tempptr[100];
if (triangles.len >= 100)
{
printf("\ncannot do it - static array not big enough\n");
getch();
};
// First got to sort the triangles:
for (i = 0; i < triangles.len; i++)
{
pTri = (Triangle *)(triangles.ptr[i]);
pTri->ReturnCentre(&cc,this);
// For now do this lazy and inefficient trig way:
theta = CalculateAngle(cc.x-x,cc.y-y);
j = 0;
while ((j < i) && (theta > angle[j])) j++; // if i == 1 then we can only move up to place 1, since we have 1 element already
if (j < i) {
// move the rest of them forward in the list:
for (k = i; k > j ; k--)
{
index[k] = index[k-1];
angle[k] = angle[k-1];
};
}
angle[j] = theta;
index[j] = i;
};
for (i = 0; i < triangles.len; i++)
tempptr[i] = triangles.ptr[index[i]];
for (i = 0; i < triangles.len; i++)
triangles.ptr[i] = tempptr[i];
for (i = 0; i < triangles.len; i++)
{
pTri = (Triangle *)(triangles.ptr[i]);
circumcenter.x = pTri->numerator_x;
circumcenter.y = pTri->numerator_y;
if ((pTri->periodic > 0) && (x > 0.0))
{
// for a per tri, the circumcenter is found for left image.
// if our point on the right, circumcenter will need to be mapped over.
circumcenter = Clockwise*circumcenter;
};
cp.add(circumcenter);
};
return cp.GetArea();
}
*/
void Triangle::ReturnPositionOtherSharedVertex_conts_tranche(Triangle * pTri, Vertex * pVert, Vector2 * pResult)
{
// First find the common vertex that is not pVert :
int iShared;
if (pVert == cornerptr[0])
{
if ( (pTri->cornerptr[0] == cornerptr[1])
|| (pTri->cornerptr[1] == cornerptr[1])
|| (pTri->cornerptr[2] == cornerptr[1]) )
{
//cornerptr[1] is it
iShared = 1;
} else {
iShared = 2;
// DEBUG:
if ((pTri->cornerptr[0] != cornerptr[2])
&& (pTri->cornerptr[1] != cornerptr[2])
&& (pTri->cornerptr[2] != cornerptr[2]) )
{
printf("!JDdewjiw!\n"); getch();
};
};
} else {
if (pVert == cornerptr[1])
{
if ((pTri->cornerptr[0] == cornerptr[0])
|| (pTri->cornerptr[1] == cornerptr[0])
|| (pTri->cornerptr[2] == cornerptr[0]) )
{
iShared = 0;
} else {
iShared = 2;
// DEBUG:
if ( (pTri->cornerptr[0] != cornerptr[2])
&& (pTri->cornerptr[1] != cornerptr[2])
&& (pTri->cornerptr[2] != cornerptr[2]) )
{
printf("!JDdewjiw!\n"); getch();
};
};
} else {
// pVert == cornerptr[2]
if ( (pTri->cornerptr[0] == cornerptr[0])
|| (pTri->cornerptr[1] == cornerptr[0])
|| (pTri->cornerptr[2] == cornerptr[0]) )
{
iShared = 0;
} else {
iShared = 1;
// DEBUG:
if ( (pTri->cornerptr[0] != cornerptr[1])
&& (pTri->cornerptr[1] != cornerptr[1])
&& (pTri->cornerptr[2] != cornerptr[1]) )
{
printf("!JDdewjiw!\n"); getch();
};
};
};
};
// Populate position with same wrapping as pVert .
// If the vertex is INS_VERT or HIGH_VERT -- as it may be -- then populate by projection.
//if (cornerptr[iShared] == INS_VERT)
//{
// pVert->project_to_ins(*pResult);
//} else {
// if (cornerptr[iShared] == HIGH_VERT)
// {
// pVert->project_to_radius(*pResult, HIGH_WEDGE_OUTER_RADIUS);
// } else {
if (periodic == 0)
{
// usual case:
*pResult = cornerptr[iShared]->pos;
} else {
// periodic; not at inner or outer boundary
*pResult = cornerptr[iShared]->pos;
int iVert = 0;
while (pVert != cornerptr[iVert]) iVert++;
if (periodic == 1)
{
int o = GetLeftmostIndex();
// o is the wrapped point
if (o == iVert)
{
// want to wrap the other point anticlockwise:
*pResult = Anticlockwise*(*pResult);
} else {
if (o == iShared) {
// unwrap the other point to clockwise:
*pResult = Clockwise*(*pResult);
};
};
} else {
int o = GetRightmostIndex();
if (o == iVert)
{
// unwrap the other point clockwise:
*pResult = Clockwise*(*pResult);
} else {
if (o == iShared)
{
// wrap it anticlockwise:
*pResult = Anticlockwise*(*pResult);
};
};
};
};
// };
//};
//
}
Vertex * Triangle::ReturnOtherSharedVertex(Triangle * pTri,Vertex * pVertex)
{
if ((cornerptr[0] != pVertex) && (pTri->has_vertex(cornerptr[0]))) return cornerptr[0];
if ((cornerptr[1] != pVertex) && (pTri->has_vertex(cornerptr[1]))) return cornerptr[1];
return cornerptr[2];
}
/*
AuxVertex * AuxTriangle::ReturnUnsharedVertex(AuxTriangle * pTri2, int * pwhich)
{
if ( (pTri2->cornerptr[0] == cornerptr[0])
|| (pTri2->cornerptr[1] == cornerptr[0])
|| (pTri2->cornerptr[2] == cornerptr[0]) )
{
// it's not vertices[0]
if ( (pTri2->cornerptr[0] == cornerptr[1])
|| (pTri2->cornerptr[1] == cornerptr[1])
|| (pTri2->cornerptr[2] == cornerptr[1]) )
{
if (pwhich != 0) *pwhich = 2;
return cornerptr[2]; // which might well be 0
} else {
if (pwhich != 0) *pwhich = 1;
return cornerptr[1];
};
} else {
if (pwhich != 0) *pwhich = 0;
return cornerptr[0];
};
}
*/
Vertex * Triangle::ReturnUnsharedVertex(Triangle * pTri2, int * pwhich) // pwhich = 0
{
// test each one in turn.
//if (flags == 0)
//{
// in case of wedge, we do want to return 0 if it is not sharing either of the top ones.
if ( (pTri2->cornerptr[0] == cornerptr[0])
|| (pTri2->cornerptr[1] == cornerptr[0])
|| (pTri2->cornerptr[2] == cornerptr[0]) )
{
// it's not vertices[0]
if ( (pTri2->cornerptr[0] == cornerptr[1])
|| (pTri2->cornerptr[1] == cornerptr[1])
|| (pTri2->cornerptr[2] == cornerptr[1]) )
{
if (pwhich != 0) *pwhich = 2;
return cornerptr[2]; // which might well be 0
} else {
if (pwhich != 0) *pwhich = 1;
return cornerptr[1];
};
} else {
if (pwhich != 0) *pwhich = 0;
return cornerptr[0];
};
//} else {
// // Only test vertex 0 and 1.
// if ( (pTri2->cornerptr[0] == cornerptr[0])
// || (pTri2->cornerptr[1] == cornerptr[0])
// || (pTri2->cornerptr[2] == cornerptr[0]) )
// {
// // it's not vertices[0]
// if (pwhich != 0) *pwhich = 1;
// return cornerptr[1];
//
// } else {
//
// if (pwhich != 0) *pwhich = 0;
// return cornerptr[0];
// };
//};
}
//int Triangle::DecodeSign(int other)
//{
// switch(other)
// {
// case 0:
// return ((sign_other_dot_transvec & TRIFLAG_SIGN0) > 0)?1:-1;
// case 1:
// return ((sign_other_dot_transvec & TRIFLAG_SIGN1) > 0)?1:-1;
// case 2:
// return ((sign_other_dot_transvec & TRIFLAG_SIGN2) > 0)?1:-1;
// }
// return 0; // just to suppress warning
//}
// double-precision overload:
// NEW TESTAGAINSTEDGE FUNCTIONS:
/*
int Triangle::TestAgainstEdge(float x,float y,
int c1, // the "start" of the relevant edge
int other, // the point opposite the relevant edge
Triangle ** ppNeigh)
{
// returns 1 in the event that (x,y) is outside the triangle.
Vector2 u1;//, u2, uO;
bool outside;
// Vector2 edge;
Vector2 transverse;
//long Tindex;
real x_dot_transverse;//,other_dot_transverse;
if (periodic == 0)
{
cornerptr[c1]->PopulatePosition(u1);
} else {
// ensure c1 is mapped to left if need be:
if (periodic == 1)
{
int iMapped = GetLeftmostIndex();
if (iMapped == c1)
{
cornerptr[c1]->PopulatePosition(u1);
} else {
cornerptr[c1]->periodic_image(u1,0,1);
};
} else {
int iUnmapped = GetRightmostIndex();
if (iUnmapped == c1)
{
cornerptr[c1]->periodic_image(u1,0,1);
} else {
cornerptr[c1]->PopulatePosition(u1);
};
};
};
x_dot_transverse = (x-u1.x)*transvecx[other] + (y-u1.y)*transvecy[other];
outside = (sgn(x_dot_transverse) == DecodeSign(other))?0:1;
if (outside)
{
*ppNeigh = neighbours[other]; // neighbours is now always a valid value.
return 1;
};
return 0;
}
*/
int Triangle::TestAgainstEdge(real x,real y,
int c1, // the "start" of the relevant edge
int other, // the point opposite the relevant edge
Triangle ** ppNeigh)
{
// returns 1 in the event that (x,y) is outside the triangle.
Vector2 u1;//, u2, uO;
bool outside;
Vector2 transverse;
real x_dot_transverse;
u1 = cornerptr[c1]->pos;
if (periodic == 0)
{
} else {
// ensure c1 is mapped to left if need be:
if (periodic == 1)
{
int iMapped = GetLeftmostIndex();
if (iMapped != c1)
u1 = Anticlockwise*u1;
} else {
int iUnmapped = GetRightmostIndex();
if (iUnmapped == c1)
u1 = Anticlockwise*u1;
};
};
// Seems this routine assumes that we can test against a left-mapped periodic triangle.
x_dot_transverse = (x-u1.x)*edge_normal[other].x + (y-u1.y)*edge_normal[other].y;
outside = (x_dot_transverse > 0.0)?1:0; // edge_normal points outside
if (outside)
{
*ppNeigh = neighbours[other]; // neighbours is now always a valid value.
if ((neighbours[other]->u8domain_flag == OUTER_FRILL) ||
(neighbours[other]->u8domain_flag == INNER_FRILL))
*ppNeigh = this;
return 1;
};
return 0;
}
/*
int Triangle::TestAgainstEdge(real x,real y,
int c1, // the "start" of the relevant edge
int other, // the point opposite the relevant edge
Triangle ** ppNeigh)
{
// returns 1 in the event that (x,y) is outside the triangle.
Vector2 u1;//, u2, uO;
bool outside;
// Vector2 edge;
Vector2 transverse;
// long Tindex;
real x_dot_transverse;//,other_dot_transverse;
if (periodic == 0)
{
cornerptr[c1]->PopulatePosition(u1);
} else {
// ensure c1 is mapped to left if need be:
if (periodic == 1)
{
int iMapped = GetLeftmostIndex();
if (iMapped == c1)
{
cornerptr[c1]->PopulatePosition(u1);
} else {
cornerptr[c1]->periodic_image(u1,0,1);
};
} else {
int iUnmapped = GetRightmostIndex();
if (iUnmapped == c1)
{
cornerptr[c1]->periodic_image(u1,0,1);
} else {
cornerptr[c1]->PopulatePosition(u1);
};
};
};
x_dot_transverse = (x-u1.x)*transvecx[other] + (y-u1.y)*transvecy[other];
outside = (sgn(x_dot_transverse) == DecodeSign(other))?0:1;
if (outside)
{
*ppNeigh = neighbours[other]; // neighbours is now always a valid value.
return 1;
};
return 0;
}
*/
/*
int Triangle::TestAgainstEdge(float x,float y,
int c1, // the "start" of the relevant edge
int other, // the point opposite the relevant edge
Triangle ** ppNeigh)
{
// returns 1 in the event that (x,y) is outside the triangle.
Vector2 u1;//, u2, uO;
bool outside;
// Vector2 edge;
Vector2 transverse;
long Tindex;
real x_dot_transverse,other_dot_transverse;
if (periodic == 0)
{
cornerptr[c1]->PopulatePosition(u1);
//pTri->cornerptr[c2]->PopulatePosition(u2);
//pTri->cornerptr[other]->PopulatePosition(uO);
// test whether we are on the inside side of edge [0]<->[1]:
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// transverse:
// transverse.x = (u1.y-u2.y);//-edge.y;
// transverse.y = (u2.x-u1.x);//edge.x;
// x_dot_transverse = (x-u1.x)*transverse.x + (y-u1.y)*transverse.y;
x_dot_transverse = (x-u1.x)*transvecx[other] + (y-u1.y)*transvecy[other];
// now take the vector headed to the other point, to compare:
//edge.x = uO.x-u1.x;
//edge.y = uO.y-u1.y;
// other_dot_transverse = //edge.x*transverse.x + edge.y*transverse.y;
// (uO.x-u1.x)*transverse.x + (uO.y-u1.y)*transverse.y;
// we're outside the triangle in the case that these are not the same sign.
outside = (sgn(x_dot_transverse) == DecodeSign(other))?0:1;
if (outside)
{
// This should work OK for wedges, I think. [2] should send us north.
*ppNeigh = neighbours[other]; // neighbours is now always a valid value.
// Tindex = neighbours[other];
// if (Tindex >= 0)
// {
// *piNeigh = Tindex;
// return 1;
// } else {
// if that is the only boundary it's outside then stick with this triangle...
// *piNeigh = -2; // this triangle not known
// -1 indicates outside hopefully the upper boundary
// return 0;
// };
return 1;
};
return 0;
} else {
int side = (x > 0.0f)?1:0;
Vector2 u2,uO;
int c2 = other-1; if (c2 == -1) c2 = 2;
cornerptr[c1]->periodic_image(u1,side);
cornerptr[c2]->periodic_image(u2,side);
cornerptr[other]->periodic_image(uO,side);
// test whether we are on the inside side of edge [0]<->[1]:
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// the vector that runs along this edge:
// this is why Vertex should have contained a Float2
// transverse:
transverse.x = (u1.y-u2.y);//-edge.y;
transverse.y = (u2.x-u1.x);//edge.x;
x_dot_transverse = (x-u1.x)*transverse.x + (y-u1.y)*transverse.y;
// now take the vector headed to the other point, to compare:
//edge.x = uO.x-u1.x;
//edge.y = uO.y-u1.y;
other_dot_transverse = //edge.x*transverse.x + edge.y*transverse.y;
(uO.x-u1.x)*transverse.x + (uO.y-u1.y)*transverse.y;
// we're outside the triangle in the case that these are not the same sign.
outside = (sgn(x_dot_transverse) == sgn(other_dot_transverse))?0:1;
if (outside)
{
*ppNeigh = neighbours[other];
return 1;
////Tindex = pTri->neighbours[other];
////if (Tindex >= 0)
////{
//// *piNeigh = Tindex;
//// return 1;
////} else {
//// // if that is the only boundary it's outside then stick with this triangle...
//// *piNeigh = -2; // this triangle not known
//// // -1 indicates outside hopefully the upper boundary
//// // Thing is, that means we're allowing this triangle's domain to be a spray
//// // Oh well to that.
//// return 0;
////};
};
return 0;
};
}
int Triangle::TestAgainstEdge(real x,real y,
int c1, // the "start" of the relevant edge
int other, // the point opposite the relevant edge
Triangle ** ppNeigh)
{
// returns 1 in the event that (x,y) is outside the triangle.
Vector2 u1;//, u2, uO;
bool outside;
// Vector2 edge;
Vector2 transverse;
long Tindex;
real x_dot_transverse,other_dot_transverse;
if (periodic == 0)
{
cornerptr[c1]->PopulatePosition(u1);
x_dot_transverse = (x-u1.x)*transvecx[other] + (y-u1.y)*transvecy[other];
//outside = (sgn(x_dot_transverse) == DecodeSign(other))?false:true;
} else {
// But should we even be doing this?
// Note that the recorded transverse sign is set up by using everything mapped to left side.
// That should be fine?
// int side = (x > 0.0)?1:0;
Vector2 u2,uO;
// In periodic case, we have set up transvec etc for the left-mapped cell.
// Therefore we are willing to compare multiple periodic images of (x,y) to this cell.
// If x > 0 however then we might as well just compare the rotated (x,y); if x < 0 just compare (x,y)
cornerptr[c1]->periodic_image(u1,0);
Vector2 u;
if (x > 0)
{
Vertex temp;
temp.x = x;
temp.y = y;
temp.periodic_image(u,0);
} else {
u.x = x;
u.y = y;
};
x_dot_transverse = (u.x-u1.x)*transvecx[other] + (u.y-u1.y)*transvecy[other];
// int c2 = 0; while ((c2 == other) || (c2 == c1)) c2++;
// cornerptr[c1]->periodic_image(u1,side);
// cornerptr[c2]->periodic_image(u2,side);
// Nothing to stop c2 from being 0 here .
// The following brazen function call gives an error because cornerptr[2] might be ==0.
//cornerptr[other]->periodic_image(uO,side);
// test whether we are on the inside side of edge [0]<->[1]:
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// transverse:
// transverse.x = (u1.y-u2.y);//-edge.y;
// transverse.y = (u2.x-u1.x);//edge.x;
// x_dot_transverse = (x-u1.x)*transverse.x + (y-u1.y)*transverse.y;
// other_dot_transverse = //edge.x*transverse.x + edge.y*transverse.y;
// (uO.x-u1.x)*transverse.x + (uO.y-u1.y)*transverse.y;
// outside = (sgn(x_dot_transverse) == sgn(other_dot_transverse))?0:1;
};
outside = (sgn(x_dot_transverse) == DecodeSign(other))?false:true;
if (outside)
{
*ppNeigh = neighbours[other]; // neighbours is now always a valid value.
return 1;
};
return 0;
}
*/
Triangle * TriMesh::ReturnPointerToOtherSharedTriangle(
Vertex * pVert,
Vertex * pOther,
Triangle * p_not_this_one, int iLevel)
{
// Ask what tri contains pVert and pOther that is not p_not_this_one
// Usually used for setting neighbours.
long tri_len, izTri[128];
Triangle *pTri,*Tarray;
long iNot;
if (iLevel == -1) {
Tarray = T;
} else {
Tarray = AuxT[iLevel];
};
iNot = p_not_this_one-Tarray;
tri_len = pVert->GetTriIndexArray(izTri);
for (int i = 0; i < tri_len; i++)
{
if (izTri[i] != iNot)
{
pTri = Tarray + izTri[i];
// does this triangle also contain otherpoint?
if ( (pTri->cornerptr[0] == pOther)
|| (pTri->cornerptr[1] == pOther)
|| (pTri->cornerptr[2] == pOther) ) // note that since cornerptr[2] == 0 for wedge, this should not cause a problem.
return pTri;
};
};
// got here -> no triangle found
return p_not_this_one;
// Return itself instead.
}
/*
AuxTriangle * TriMesh::ReturnPointerToOtherSharedTriangle(
AuxVertex * pVert,
AuxVertex * pOther,
AuxTriangle * p_not_this_one)
{
// Ask what tri contains pVert and pOther that is not p_not_this_one
// Usually used for setting neighbours.
// Note that if pOther == 0 then the question is just,
// what tri contains pVert and is a wedge -
// in this case p_not_this_one should also be a wedge so that
// the answer can be unique.
// If pOther == 0 then of course, cornerptr[2] == 0 will test for wedgeness anyway.
// AuxTriangle ** ptr = (Triangle **)pVert->triangles.ptr;
AuxTriangle * ptr;
for (int i = 0; i < pVert->tri_len; i++)
{
ptr = InnerT + pVert->iTriangles[i];
if (ptr != p_not_this_one)
{
// does this triangle also contain otherpoint?
if ( (ptr->cornerptr[0] == pOther)
|| (ptr->cornerptr[1] == pOther)
|| (ptr->cornerptr[2] == pOther) ) // note that since cornerptr[2] == 0 for wedge, this should not cause a problem.
return ptr;
};
};
return 0;
}*/
/*
AuxTriangle * TriMesh::ReturnPointerToOtherSharedTriangleAux(
AuxVertex * pVert,
AuxVertex * pOther,
AuxTriangle * p_not_this_one,
int iLevel)
{
// Ask what tri contains pVert and pOther that is not p_not_this_one
// Usually used for setting neighbours.
AuxTriangle * ptr;
for (int i = 0; i < pVert->tri_len; i++)
{
ptr = AuxT[iLevel] + pVert->iTriangles[i];
if (ptr != p_not_this_one)
{
// does this triangle also contain otherpoint?
if ( (ptr->cornerptr[0] == pOther)
|| (ptr->cornerptr[1] == pOther)
|| (ptr->cornerptr[2] == pOther) ) // note that since cornerptr[2] == 0 for wedge, this should not cause a problem.
return ptr;
};
};
return p_not_this_one; // default if another neighbour sharing the edge not found.
}
*/
/*Triangle * TriMesh::SearchCornerptr(long index0, long index1, long index2, Triangle * pTriSeed)
{
// Is pTriSeed, it?
int test[3];
Triangle * pTri = pTriSeed;
test[0] = pTri->cornerptr[0]-X;
test[1] = pTri->cornerptr[1]-X;
test[2] = pTri->cornerptr[2]-X;
if (((test[0] == index0) || (test[1] == index0) || (test[2] == index0))
&&
((test[0] == index1) || (test[1] == index1) || (test[2] == index1))
&&
((test[0] == index2) || (test[1] == index2) || (test[2] == index2)))
return pTri;
// No? Then search all tris of X+index0
Vertex * pVertex = X + index0;
int i;
for (i = 0; i < pVertex->triangles.len; i++)
{
pTri = (Triangle *)(pVertex->triangles.ptr[i]);
test[0] = pTri->cornerptr[0]-X;
test[1] = pTri->cornerptr[1]-X;
test[2] = pTri->cornerptr[2]-X;
if (((test[0] == index0) || (test[1] == index0) || (test[2] == index0))
&&
((test[0] == index1) || (test[1] == index1) || (test[2] == index1))
&&
((test[0] == index2) || (test[1] == index2) || (test[2] == index2)))
return pTri;
}
return 0; // triangle with these 3 did not exist!
}
int AuxTriangle::TestAgainstEdge(real x,real y,
int c1, // the "start" of the relevant edge
int other, // the point opposite the relevant edge
AuxTriangle ** ppNeigh)
{
// returns 1 in the event that (x,y) is outside the triangle.
Vector2 u1;//, u2, uO;
bool outside;
Vector2 transverse;
real x_dot_transverse;
if (periodic == 0)
{
cornerptr[c1]->PopulatePosition(u1);
} else {
// ensure c1 is mapped to left if need be:
if (periodic == 1)
{
int iMapped = GetLeftmostIndex();
if (iMapped == c1)
{
cornerptr[c1]->PopulatePosition(u1);
} else {
cornerptr[c1]->periodic_image(u1,0,1);
};
} else {
int iUnmapped = GetRightmostIndex();
if (iUnmapped == c1)
{
cornerptr[c1]->periodic_image(u1,0,1);
} else {
cornerptr[c1]->PopulatePosition(u1);
};
};
};
x_dot_transverse = (x-u1.x)*edge_normal[other] .x+ (y-u1.y)*edge_normal[other].y;
outside = (x_dot_transverse > 0.0)?1:0; // edge_normal points outside
//(sgn(x_dot_transverse) == DecodeSign(other))?0:1;
if (outside)
{
*ppNeigh = neighbours[other]; // neighbours is now always a valid value.
return 1;
};
return 0;
}
bool AuxTriangle::ContainsPoint(real x, real y)
{
// Note that this is returning true in the case that it is
// only outside on the side where neighbours[i] == this.
// That is a very liberal test for being inside.
// We ought to probably put a limit on what can be considered azimuthally to belong to this one.
AuxTriangle * pNeigh;
// always test for our triangle unmapped:
int out = 0;
if (TestAgainstEdge(x,y,
0, // edge corner
2, // the opposite point
&pNeigh // neighbour in this direction, if it's outside this way
) && (neighbours[2] != this))
{
out = 1;
} else {
if (TestAgainstEdge(x,y, 1, 0, &pNeigh) && (neighbours[0] != this))
{
out = 1;
} else {
if (TestAgainstEdge(x,y, 0, 1, &pNeigh) && (neighbours[1] != this))
out = 1;
};
};
if (periodic == 0) return (1-out);
if (out == 0) return (1-out); // found point already in left interpreted tri
// if periodic > 0, we want to also test RH
int out2 = 0;
real destx,desty;
// map point Anticlockwise to represent mapping triangle Clockwise:
destx = Anticlockwise.xx*x + Anticlockwise.xy*y;
desty = Anticlockwise.yx*x + Anticlockwise.yy*y;
if ((TestAgainstEdge(destx,desty,0,2,&pNeigh)) && (neighbours[2] != this))
return false;
if ((TestAgainstEdge(destx,desty, 1, 0, &pNeigh)) && (neighbours[0] != this))
return false;
if ((TestAgainstEdge(destx,desty, 0, 1, &pNeigh)) && (neighbours[1] != this))
return false;
return true;
// Note that this is returning true in the case that it is
// only outside on the side where neighbours[i] == this.
// That is a very liberal test for being inside.
// We ought to probably put a limit on what can be considered azimuthally to belong to this one.
}
*/
bool Triangle::ContainsPoint(real x, real y)
{
Triangle * pNeigh;
// always test for our triangle unmapped:
int out = 0;
if(TestAgainstEdge(x,y,
0, // edge corner
2, // the opposite point
&pNeigh // neighbour in this direction, if it's outside this way
))
{
out = 1;
} else {
if(TestAgainstEdge(x,y, 1, 0, &pNeigh))
{
out = 1;
} else {
if(TestAgainstEdge(x,y, 0, 1, &pNeigh))
out = 1;
};
};
if (periodic == 0) return (1-out);
if (out == 0) return (1-out); // found point already in left interpreted tri
// if periodic > 0, we want to also test RH
int out2 = 0;
real destx,desty;
// map point Anticlockwise to represent mapping triangle Clockwise:
destx = Anticlockwise.xx*x + Anticlockwise.xy*y;
desty = Anticlockwise.yx*x + Anticlockwise.yy*y;
if(TestAgainstEdge(destx,desty,0,2,&pNeigh))
{
out2 = 1;
} else {
if(TestAgainstEdge(destx,desty, 1, 0, &pNeigh))
{
out2 = 1;
} else {
if(TestAgainstEdge(destx,desty, 0, 1, &pNeigh)) // do not send vertex 2 here in case it does not exist.
out2 = 1;
};
};
return (1-out2);
}
// same as above function basically but now periodic lives only on left
bool Triangle::TestAgainstEdges(real x,real y, Triangle ** ppNeigh)
{
// If an edge triangle, we require it give preference to a neighbour other than itself.
// static real const FP_FUZZY_THRESH_LARGE = 1.0e-8;
// ^^ more sophistication called for. !
// Two things to concern with it seems:
// If point is outside edge of memory, it should test positive that it is
// NOT in this triangle... there are no holes in the domain though.
// Return self in this case. ??
// Then look at calls to this function to see how to handle that.
// Maybe change function return type to int, return a flag for Out Of Memory Domain.
// However we must FIRST test against the other edges. This rules out that
// the point in question belongs to the memory domain at all.
if ((periodic != 0) && (x > 0.0)) // in this case test anticlock image of x, which had to be within domain tranche to begin with.
{
real newx = Anticlockwise.xx*x+Anticlockwise.xy*y;
real newy = Anticlockwise.yx*x+Anticlockwise.yy*y;
x = newx; y = newy;
// Prioritize looking left.
if ((cornerptr[2]->pos.x > 0.0) && (cornerptr[1]->pos.x > 0.0))
if (TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
if ((cornerptr[0]->pos.x > 0.0) && (cornerptr[2]->pos.x > 0.0))
if (TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
if ((cornerptr[1]->pos.x > 0.0) && (cornerptr[0]->pos.x > 0.0))
if (TestAgainstEdge(x,y, 0, 2, ppNeigh)) return 1;
// Second favourite: stay within periodic.
if ((cornerptr[2]->pos.x > 0.0) || (cornerptr[1]->pos.x > 0.0))
if (TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
if ((cornerptr[0]->pos.x > 0.0) || (cornerptr[2]->pos.x > 0.0))
if (TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
if ((cornerptr[1]->pos.x > 0.0) || (cornerptr[0]->pos.x > 0.0))
if (TestAgainstEdge(x,y, 0, 2, ppNeigh)) return 1;
// Got here: we'll have to exit to the left side of domain then.
if (TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 0, 2, ppNeigh)) return 1;
};
// Idea: We need to prioritize NOT CROSSING to the x < 0 side if the target x > 0.
// New attempt:
if ((neighbours[0]->u8domain_flag == OUTER_FRILL) || (neighbours[0]->u8domain_flag == INNER_FRILL)
|| (neighbours[0] == this))
{
// In this case:
// prioritize neighbours[1] and [2].
if(TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
if(TestAgainstEdge(x,y, 0, // edge corner
2, // the opposite point - ie which edge
ppNeigh)) // neighbour in this direction, if it's outside this way
return 1;
if(TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
return 0; // inside *this
}
if ((neighbours[1]->u8domain_flag == OUTER_FRILL) || (neighbours[1]->u8domain_flag == INNER_FRILL)
|| (neighbours[1] == this))
{
if (TestAgainstEdge(x,y, 0, 2, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
return 0;
}
// Just changed the order of tests.
/*
if (neighbours[0] == this) {
if(TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
if(TestAgainstEdge(x,y, 0, // edge corner
2, // the opposite point - ie which edge
ppNeigh)) // neighbour in this direction, if it's outside this way
return 1;
if(TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
return 0; // inside *this
}
if (neighbours[1] == this) {
if (TestAgainstEdge(x,y, 0, 2, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
return 0;
}
*/
if ((periodic != 0) && (x > 0.0))
if (TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
if (TestAgainstEdge(x,y, 0, 2, ppNeigh)) return 1;
return 0;
// .
// .
// If point is within insulator, we should return the correct triangle.
// But how that is handled, in the case of placement?
//if (u8EdgeFlag > 0)
//{
// int c1,c2;
// // Find not base corner:
// int iBase = 0; while (cornerptr[iBase]->flags > 3) iBase++;
// c1 = iBase+1; if (c1 == 3) c1 = 0;
// c2 = c1+1; if (c2 == 3) c2 = 0;
// if(TestAgainstEdge(x,y,c1,c2, // the opposite point
// ppNeigh )) // neighbour in this direction, if it's outside this way
// return 1;
// if (TestAgainstEdge(x,y,c2,c1, // the opposite point
// ppNeigh )) // neighbour in this direction, if it's outside this way
// return 1;
// // finally test against inner edge .... but maybe wish to return 0
// if (TestAgainstEdge(x,y,c1,iBase, // the opposite point
// ppNeigh )) // neighbour in this direction, if it's outside this way
// {
// // ask if it is azimuthally compatible. If it is, we can return 0.
// Vector2 u[3];
// PopulatePositions(u[0],u[1],u[2]);
// if (periodic) {
// if (x > 0.0) { MapRight(u[0],u[1],u[2]); } else {MapLeft(u[0],u[1],u[2]); };
// };
// real grad1 = u[c1].x/u[c1].y; real grad2 = u[c2].x/u[c2].y;
// real grad = x/y;
// // realise we can afford to be quite liberal here
// // It failed to test as outside either of the other two sides
// // The only options: we are nowhere near, or this really is it.
// // If we are nowhere near , the following comparator will be quite large, so:
// if ((grad-grad1)*(grad-grad2) <= FP_FUZZY_THRESH_LARGE) return 0;
// return 1;
// // outside azimuthally and on edge of domain therefore returning 1 with *ppNeigh as itself.
// }
// return 0;
//} else {
// if(TestAgainstEdge(x,y,
// 0, // edge corner
// 2, // the opposite point
// ppNeigh // neighbour in this direction, if it's outside this way
// ))
// return 1;
// if(TestAgainstEdge(x,y, 1, 0, ppNeigh)) return 1;
// if(TestAgainstEdge(x,y, 0, 1, ppNeigh)) return 1;
// return 0;
//};
}
// same as above function basically
/*bool Triangle::TestAgainstEdges(float x,float y, Triangle ** ppNeigh)
{
int out = 0;
if(TestAgainstEdge(x,y,
0, // edge corner
2, // the opposite point
ppNeigh // neighbour in this direction, if it's outside this way
))
{
out = 1;
} else {
if(TestAgainstEdge(x,y, 1, 0, ppNeigh))
{
out = 1;
} else {
if(TestAgainstEdge(x,y, 0, 1, ppNeigh)) // do not send vertex 2 here in case it does not exist.
out = 1;
};
};
return out;
}
*/
// Now here we implement routines to calculate triangle intersections:
#define DYDX 0
#define DXDY 1
void GetIntersection(Vector2 * result,const Vector2 & x0,real gradient,int flagdydx, Vector2 & a, Vector2 & b)
{
real x,y;
// where is line a->b cut by the line that starts at start and has gradient gradient,
// DEBUG:
if (!(_finite(a.x) && _finite(a.y) && _finite(b.x) && _finite(b.y)))
{
a.x = a.x;
}
if (flagdydx == DYDX)
{
// on first line,
// x = x0.x + t
// y = x0.y + t dy/dx
// x - y/ dy/dx = x0.x - x0.y / dy/dx
// y = dy/dx(x - x0.x) + x0.y
// on second line
// x = a.x + t(b.x-a.x)
// y = a.y + t(b.y-a.y)
// (b.x-a.x)y - x(b.y-a.y) = (b.x-a.x)a.y - (b.y-a.y)a.x
// For both to be true simultaneously?
// (b.x-a.x)(dy/dx(x - x0.x) + x0.y ) - x(b.y-a.y) = (b.x-a.x)a.y - (b.y-a.y)a.x
// ((b.x - a.x)dy/dx - (b.y-a.y) ) x = (b.x-a.x)a.y - (b.y-a.y)a.x + (b.x-a.x)dy/dx x0.x - (b.x-a.x)x0.y
// looks too complicated?
x = ((b.x-a.x)*(a.y + gradient*x0.x - x0.y) - (b.y-a.y)*a.x)/
((b.x - a.x)*gradient - (b.y-a.y));
y = x0.y + gradient*(x - x0.x);
// DEBUG:
// Test that (x,y) is actually a solution:
} else {
// x = dx/dy (y- x0.y) + x0.x
// (b.x-a.x)y - x(b.y-a.y) = (b.x-a.x)a.y - (b.y-a.y)a.x
// (b.x-a.x)y - (dx/dy (y- x0.y) + x0.x)(b.y-a.y) = (b.x-a.x)a.y - (b.y-a.y)a.x
// (b.x-a.x - dx/dy (b.y-a.y)) y = (b.x-a.x)a.y - (b.y-a.y)a.x + (x0.x - dx/dy x0.y) (b.y-a.y)
y = ((b.x-a.x)*a.y + (x0.x - gradient*x0.y - a.x)*(b.y-a.y))/
(b.x-a.x - gradient * (b.y-a.y));
x = gradient*(y-x0.y) + x0.x;
};
result->x = x;
result->y = y;
}
void Triangle::CalculateCircumcenter(Vector2 & cc, real * pdistsq)
{
Vector2 Bb,C,b,c,a;
MapLeftIfNecessary(a,b,c);
Bb = b-a;
C = c-a;
real D = 2.0*(Bb.x*C.y-Bb.y*C.x);
real modB = Bb.x*Bb.x+Bb.y*Bb.y;
real modC = C.x*C.x+C.y*C.y;
cc.x = (C.y*modB-Bb.y*modC)/D + a.x;
cc.y = (Bb.x*modC-C.x*modB)/D + a.y;
*pdistsq = (a.x-cc.x)*(a.x-cc.x)+(a.y-cc.y)*(a.y-cc.y); // why?
}
void GetInsulatorIntercept(Vector2 *result, const Vector2 & x1, const Vector2 & x2)
{
// find where line x1->x2 crosses r = DEVICE_RADIUS_INSULATOR_OUTER
// x = x1.x + t(x2.x-x1.x)
// y = x1.y + t(x2.y-x1.y)
// x^2+y^2 = c^2
// (x1.x + t(x2.x-x1.x))^2 + (x1.y + t(x2.y-x1.y))^2 = c^2
// or, y = x1.y + dy/dx (x-x1.x)
// x^2 + (x1.y - dy/dx x1.x + dy/dx x)^2 = c^2
// (x1.x + t(x2.x-x1.x))^2 + (x1.y + t(x2.y-x1.y))^2 = c^2
// t^2 ( (x2.x-x1.x)^2 + (x2.y - x1.y)^2 ) + 2t (x1.x (x2.x-x1.x) + x1.y (x2.y-x1.y) )
// + x1.x^2 + x1.y^2 = c^2
// t^2 + 2t ( -- ) / (-- ) = (c^2 - x1.x^2 - x1.y^2)/ (-- )
real den = (x2.x-x1.x)*(x2.x-x1.x) + (x2.y - x1.y)*(x2.y - x1.y) ;
real a = (x1.x * (x2.x-x1.x) + x1.y * (x2.y-x1.y) ) / den;
// (t + a)^2 - a^2 = ( c^2 - x1.x^2 - x1.y^2 )/den
real root = sqrt( (DEVICE_RADIUS_INSULATOR_OUTER*DEVICE_RADIUS_INSULATOR_OUTER
- x1.x*x1.x - x1.y*x1.y)/den + a*a ) ;
real t1 = root - a;
real t2 = -root - a;
// since this is a sufficient condition to satisfy the circle, this probably means that
// the other solution is on the other side of the circle.
// Which root is within x1, x2 ? Remember x2 would be t = 1.
if (t1 > 1.0)
{
if ((t2 < 0.0) || (t2 > 1.0))
{
// This usually means one of the points actually is on the curve.
real dist1 = min(fabs(t1-1.0),fabs(t1));
real dist2 = min(fabs(t2-1.0),fabs(t2));
if (dist1 < dist2)
{
// use t1
if (dist1 > 0.00000001)
{
printf("\n\nError.\n");
getch();
};
result->x = x1.x + t1*(x2.x-x1.x);
result->y = x1.y + t1*(x2.y-x1.y);
} else {
// use t2
if (dist2 > 0.00000001)
{
printf("\n\nError.\n");
printf("t1 = %1.10E , \nt2 = %1.10E , \nx1.x= %1.10E ,\nx1.y = %1.10E ,\nx2.x = %1.10E ,\nx2.y = %1.10E\n",
t1,t2,x1.x,x1.y,x2.x,x2.y);
getch();
};
result->x = x1.x + t2*(x2.x-x1.x);
result->y = x1.y + t2*(x2.y-x1.y);
};
} else {
// use t2:
result->x = x1.x + t2*(x2.x-x1.x);
result->y = x1.y + t2*(x2.y-x1.y);
};
} else {
if (t1 < -1.0e-13)
{
printf("\n\nError.KL\n");
printf("t1 = %1.10E , \nt2 = %1.10E , \nx1.x= %1.10E ,\nx1.y = %1.10E ,\nx2.x = %1.10E ,\nx2.y = %1.10E\n",
t1,t2,x1.x,x1.y,x2.x,x2.y);
getch();
};
result->x = x1.x + t1*(x2.x-x1.x);
result->y = x1.y + t1*(x2.y-x1.y);
};
#ifdef DEBUG
if (result->x*result->x + result->y*result->y > 1.000001*DEVICE_RADIUS_INSULATOR_OUTER*DEVICE_RADIUS_INSULATOR_OUTER)
{
result = result;
};
if (result->y < 0.0)
{
result = result;
};
#endif
}
void Get_ROC_InsulatorIntercept(Vector2 * pROCintercept1,
Vector2 lower , Vector2 moving,Vector2 ROC)
{
// A rough estimate might do.
// Moving away directly from lower does not change the intercept;
// moving perpendicularly does.
// Do empirically:
Vector2 interceptplus, interceptminus;
real length = (moving-lower).modulus();
real ROClength = ROC.modulus();
real ROCfactor = length*0.0001/ROClength;
Vector2 ROCmove = ROC*ROCfactor;
Vector2 plus = moving + ROCmove;
Vector2 minus = moving - ROCmove;
GetInsulatorIntercept(&interceptplus, lower, plus);
GetInsulatorIntercept(&interceptminus, lower, minus);
Vector2 derivative = (interceptplus-interceptminus)/(2.0*ROCfactor);
*pROCintercept1 = derivative;
}
int Triangle::GetCentreOfIntersectionWithInsulator(Vector2 & cc)
{
// where this triangle crosses r=3.44,
// we want to return the middle of that arc.
// 3 lines; should give 2 intercepts of 3.44
// If not, failed.
real azimuth01,azimuth12,azimuth02;
real r0sq, r1sq, r2sq, Rsq;
int number_of_intercepts;
real angle;
Vector2 u[3];
Vector2 intercept;
MapLeftIfNecessary(u[0],u[1],u[2]);
r0sq = u[0].dot(u[0]);
r1sq = u[1].dot(u[1]);
r2sq = u[2].dot(u[2]);
Rsq = DEVICE_RADIUS_INSULATOR_OUTER*DEVICE_RADIUS_INSULATOR_OUTER;
number_of_intercepts = 0;
azimuth01 = 0.0;
azimuth12 = 0.0;
azimuth02 = 0.0;
// 0-1:
if ((r0sq-Rsq)*(r1sq-Rsq) < 0.0)
{
number_of_intercepts++;
GetInsulatorIntercept(&intercept,u[0],u[1]);
azimuth01 = atan2(intercept.y,intercept.x);
};
// 1-2:
if ((r2sq-Rsq)*(r1sq-Rsq) < 0.0)
{
number_of_intercepts++;
GetInsulatorIntercept(&intercept,u[1],u[2]);
azimuth12 = atan2(intercept.y,intercept.x);
};
// 0-2:
if ((r2sq-Rsq)*(r0sq-Rsq) < 0.0)
{
number_of_intercepts++;
GetInsulatorIntercept(&intercept,u[0],u[2]);
azimuth02 = atan2(intercept.y,intercept.x);
};
if (number_of_intercepts != 2)
{
printf("intercept fail\n"); getch();
return 1;
};
angle = 0.5*(azimuth01+azimuth12+azimuth02);
//if (angle < -HALFANGLE+PI*0.5) angle += FULLANGLE;
//if (angle > HALFANGLE+PI*0.5) angle -= FULLANGLE; // not wanted
// If this is periodic triangle then allow that angle is contiguous with tri, not part of canonical tranche
cc.x = cos(angle)*DEVICE_RADIUS_INSULATOR_OUTER;
cc.y = sin(angle)*DEVICE_RADIUS_INSULATOR_OUTER;
// defend against errors:
// Is cc within triangle?
// This is a fairly unnecessary way of doing it.
// Here's a better one:
// take linear average then project. That requires sqrt not atan.
return 0;
}
/*void AuxTriangle::CalculateCircumcenter(Vector2 & cc, real * pdistsq)
{
Vector2 Bb,C,b,c,a;
Vector2 basea,baseb;
if (periodic > 0)
{
// map everything to left hand side.
MapLeft(a,b,c);
} else {
PopulatePositions(a,b,c);
};
Bb = b-a;
C = c-a;
real D = 2.0*(Bb.x*C.y-Bb.y*C.x);
real modB = Bb.x*Bb.x+Bb.y*Bb.y;
real modC = C.x*C.x+C.y*C.y;
cc.x = (C.y*modB-Bb.y*modC)/D + a.x;
cc.y = (Bb.x*modC-C.x*modB)/D + a.y;
if (pdistsq != 0)
*pdistsq = (a.x-cc.x)*(a.x-cc.x)+(a.y-cc.y)*(a.y-cc.y);
}
*/
void ConvexPolygon::SetTri(const Vector2 & x1,const Vector2 & x2, const Vector2 & x3)
{
numCoords = 3;
coord[0] = x1;
coord[1] = x2;
coord[2] = x3;
}
ConvexPolygon::ConvexPolygon(const Vector2 & x1,const Vector2 & x2,const Vector2 & x3)
{
SetTri(x1, x2, x3);
}
ConvexPolygon::ConvexPolygon()
{
numCoords = 0;
}
void ConvexPolygon::Get_Bxy_From_Az(real Az_array[], real * pBx,real * pBy)
{
// Assume we have coords that are sorted anticlockwise
int i, inext;
real Bx = 0, By = 0;
real Integral_x, Integral_y;
for (i = 0; i < numCoords; i++)
{
inext = i+1; if (inext == numCoords) inext = 0;
Integral_x = (Az_array[i] + Az_array[inext])
*(coord[inext].x-coord[i].x);
Integral_y = (Az_array[i] + Az_array[inext])
*(coord[inext].y-coord[i].y);
Bx += Integral_x;
By += Integral_y;
}
real area = this->GetArea();
*pBx = 0.5*Bx/area;
*pBy = 0.5*By/area;
}
Vector3 ConvexPolygon::Get_curl2D_from_anticlockwise_array(Vector3 A[])
{
// Assuming we have coords that are sorted anticlockwise
int i, inext;
Vector3 B;
memset(&B,0,sizeof(Vector3));
real Integral_x, Integral_y, Integral_z;
for (i = 0; i < numCoords; i++)
{
inext = i+1; if (inext == numCoords) inext = 0;
Integral_x = (A[i].z + A[inext].z)
*(coord[inext].x-coord[i].x); // [anticlockwise]--> -dAz/dy
Integral_y = (A[i].z + A[inext].z)
*(coord[inext].y-coord[i].y); // [anticlockwise]--> dAz/dx
Integral_z = (A[i].y+A[inext].y)
*(coord[inext].y-coord[i].y) // [anticlockwise] --> dAy/dx
+ (A[i].x+A[inext].x)
*(coord[inext].x-coord[i].x); // --> -dAx/dy
B.x += Integral_x;
B.y += Integral_y;
B.z += Integral_z;
}
real area = this->GetArea();
B *= 0.5/area;
B.z += BZ_CONSTANT;
return B;
}
Vector2 ConvexPolygon::Get_Integral_grad_from_anticlockwise_array(real Te[])
{
Vector2 grad;
int i, inext;
memset(&grad,0,sizeof(Vector2));
real Integral_x, Integral_y;
for (i = 0; i < numCoords; i++)
{
inext = i+1; if (inext == numCoords) inext = 0;
Integral_x = 0.5*(Te[i] + Te[inext])
*(coord[inext].y-coord[i].y); // [anticlockwise]--> dTe/dx
Integral_y = 0.5*(Te[i] + Te[inext])
*(coord[i].x-coord[inext].x); // [anticlockwise]--> dTe/dy
grad.x += Integral_x;
grad.y += Integral_y;
}
// ---> Compare to GradTe formula on tris.
return grad;
}
Vector2 ConvexPolygon::Get_grad_from_anticlockwise_array(real Te[])
{
Vector2 grad;
grad = Get_Integral_grad_from_anticlockwise_array(Te);
real area = this->GetArea();
grad /= area;
return grad;
}
Vector2 ConvexPolygon::CalculateBarycenter()
{
// Assume we have coords that are sorted anticlockwise or clockwise
Vector2 u;
int i, inext;
real Integral_x, Integral_y, shoelace;
Integral_x = 0.0;
Integral_y = 0.0;
shoelace = 0.0;
real lace;
for (i = 0; i < numCoords; i++)
{
inext = i+1; if (inext == numCoords) inext = 0;
lace = (coord[i].x * coord[inext].y - coord[inext].x*coord[i].y);
Integral_x += (coord[i].x + coord[inext].x)*lace;
Integral_y += (coord[i].y + coord[inext].y)*lace;
shoelace += lace;
};
u.x = THIRD*Integral_x/shoelace;
u.y = THIRD*Integral_y/shoelace;
return u;
}
// Now, we will make sure that we enter the points in anticlockwise
// order.
// Make polygon method: return_Bxy_from_Az( set of anticlockwise values)
// Note: cases that apply:
// when we introduce the first corner, it may cut the LH and bottom sides of the "house".
// It cannot cut off the bottom entirely, I don't think.
// The second one may cut the RH edge and either the bottom or the LH diagonal.
// ^^^ 1. Get some confidence that this is true.
// %%% then we can proceed to say? First look at LH then at RH. We want to end up with
// 1. Edge length in each of 5 directions: maintain this as we go?
// 2. Voronoi ConvexPolygon so that we can take intersections with wedges.
/*
bool VoronoiPolygon::ClipAgainstHalfplane_Update_SideIndexList(const Vector2 & r1, const Vector2 & r2, const Vector2 & r3, int flag_new)
{
// Similar to the standard function except here, we will maintain for each vertex a number that indicates, for the side to anticlockwise
// what flag that side corresponded to.
// When we clip a vertex, the new vertex on the right takes up the rightmost clipped vertex's index
// The new vertex on the left takes up the flag that was passed.
// We can then look back (in the caller) and see which sides still exist and how long they are.
// Less clear what we can do about overlaps with other wedges ... maybe ignore carefully.
// first le's cut n paste:
bool intersect;
bool above_is_inside;
real compare;
int first, last;
bool setfirst;
real gradient ;
int flag, pullback, i, post_last, pre_first;
Vector2 cross1, cross2;
static const real EPS = 5.0e-14;
// Now we have to be able to deal with degenerate cases.
// =====================================
// We assign each point a status: INSIDE the clip region, NEAR the clip boundary, or OUTSIDE the clip region.
// When some consecutive points are found to be OUTSIDE the clip region, we also
// remove any consecutive points that are NEAR the clip boundary.
// This ensures hopefully that intersections are only taken towards points that are away from the clip boundary.
// If no points figure as actually OUTSIDE (further outside than EPS) then clipping is skipped.
// If no points figure as actually INSIDE (further inside than EPS) then we return no intersection.
#define INSIDE 0
#define OUTSIDE 1
#define NEARBY 2
// There is no point distinguishing near inside and near outside as this will be unreliable due to rounding anyway.
Vector2 direction = r2-r1;
// r1 + alpha.direction is the line
if (direction.x*direction.x > direction.y*direction.y)
// defend against case that it's basically vertical
{
flag = DYDX;
// determine whether r3 is above line:
gradient = direction.y/direction.x;
above_is_inside = (r3.y > r1.y + (r3.x-r1.x)*gradient) ;
// Hope we didn't get passed r3 that is on the line r1-r2 . If so it's an unfair call and we have to change the caller.
// Now ask which of our existing coordinates is in/near/out:
intersect = false;
setfirst = false;
for (int i = 0; i < numCoords; i++)
{
compare = r1.y + (coord[i].x-r1.x)*gradient;
//if (above)
//{
// is_above[i] = (coord[i].y > r1.y + (coord[i].x-r1.x)*gradient - EPS);
//} else {
// is_above[i] = (coord[i].y > r1.y + (coord[i].x-r1.x)*gradient + EPS);
//};
if (above_is_inside)
{
if (coord[i].y > compare + EPS) {
status[i] = INSIDE;
intersect = true;
} else {
if (coord[i].y < compare - EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
status[i] = NEARBY;
};
};
} else {
if (coord[i].y > compare + EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
if (coord[i].y < compare - EPS) {
status[i] = INSIDE;
intersect = true;
} else {
status[i] = NEARBY;
};
};
};
// last = i; // ordinarily this means we stored the first and last scrappable vertex
// but beware that it won't work if the scrapped section crossed 0
};
} else {
// line was more vertical than horizontal so take gradient x per y
flag = DXDY;
gradient = direction.x/direction.y;
above_is_inside = (r3.x > r1.x + (r3.y-r1.y)*gradient); // true if r3 is to right
// Now ask which of our existing coordinates is above
intersect = false;
setfirst = false;
for (int i = 0; i < numCoords; i++)
{
compare = r1.x + (coord[i].y-r1.y)*gradient;
if (above_is_inside)
{
if (coord[i].x > compare + EPS) {
status[i] = INSIDE;
intersect = true;
} else {
if (coord[i].x < compare - EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
status[i] = NEARBY;
};
};
} else {
if (coord[i].x > compare + EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
if (coord[i].x < compare - EPS) {
status[i] = INSIDE;
intersect = true;
} else {
status[i] = NEARBY;
};
};
};
};
};
if (intersect == false)
{
printf("error - Voronoi cell eclipsed.\n");
// no intersection of halfplane and existing polygon
return false;
};
if (setfirst == false)
{
// no clipping applies
return true;
};
// If we get here, some polygon vertices were (properly) clipped and some were (properly) not.
// OK now scrap those that did not intersect, if any, and replace them with the points where the lines are intersected
// Let's get the first point before our OUTSIDE subset that is not INSIDE.
while (status[first] != INSIDE)
{
first--;
if (first < 0) first = numCoords-1;
};
pre_first = first;
first++;
if (first == numCoords) first = 0; // the first clipped vertex
GetIntersection(&cross1,r1,gradient,flag,coord[pre_first],coord[first]);
// Now move forward to last scrappable.
last = first;
while (status[last] != INSIDE)
{
last++;
if (last == numCoords) last = 0;
};
post_last = last;
last--;
if (last < 0) last = numCoords-1; // the last clipped vertex
GetIntersection(&cross2,r1,gradient,flag,coord[last],coord[post_last]);
// now repopulate the array:
// cases:
if (last >= first)
{
// easy cases:
if (last == first)
{
// exactly one vertex is clipped.
// debug check: Never scrap a circumcenter:
if (last <= max_index_no_scrap) {
printf("circumcenter scrapped - not cool\n");
last = last;
};
// * // When we clip a vertex, the new vertex on the right takes up the rightmost clipped vertex's index
// * // The new vertex on the left takes up the flag that was passed.
// array gets longer - need to move elements outwards first
for (i = numCoords-1; i >= last+1; i--)
{
coord[i+1] = coord[i];
edge_flag[i+1] = edge_flag[i];
}
numCoords++;
coord[first] = cross1;
coord[first+1] = cross2;
// The anticlockwise added point now indexes the rest of the existing anticlock side:
edge_flag[first+1] = edge_flag[first];
// The clockwise added point indexes our new side:
edge_flag[first] = flag_new;
} else {
if (first <= max_index_no_scrap) {
printf("circumcenter scrapped - not cool - first %d max_index_no_scrap %d \n",first,max_index_no_scrap);
first = first;
getch();
};
edge_flag[first+1] = edge_flag[last];
edge_flag[first] = flag_new;
// last > first so we may need to pull some elements backwards
pullback = last-first-1; // last == first +1 => pullback == 0
for (i = last+1; i < numCoords; i++)
{
coord[i-pullback] = coord[i];
edge_flag[i-pullback] = edge_flag[i];
};
numCoords -= pullback;
coord[first] = cross1;
coord[first+1] = cross2;
};
} else {
// scrappable subset crosses 0
// post_last is the first element that is INSIDE
// debug check: Never scrap a circumcenter:
if (this->max_index_no_scrap >= 0)
{
printf("circumcenter scrapped - not cool - first %d last %d post_last %d \n", first, last, post_last);
numCoords = numCoords;
getch();
};
// Move elements back to 0; if post_last = 4, first = 6 then there are 2 such elements + 2 new ones
i = first-post_last;
edge_flag[i+1] = edge_flag[last]; // last should be last scrapped vertex, > 0
for (i =0; i < first-post_last; i++)
{
coord[i] = coord[i+post_last];
edge_flag[i] = edge_flag[i+post_last];
};
coord[i] = cross1;
coord[i+1] = cross2;
edge_flag[i] = flag_new;
numCoords = i+2;
};
return true;
}
*/
real ConvexPolygon::GetSucceedingSideLength(int side)
{
int next = side+1;
if (next == numCoords) next = 0;
return sqrt(
(coord[next].x-coord[side].x)*(coord[next].x-coord[side].x)+
(coord[next].y-coord[side].y)*(coord[next].y-coord[side].y));
}
real ConvexPolygon::GetPrecedingSideLength(int side)
{
int prev = side-1;
if (prev == -1) prev = numCoords-1;
return sqrt(
(coord[prev].x-coord[side].x)*(coord[prev].x-coord[side].x)+
(coord[prev].y-coord[side].y)*(coord[prev].y-coord[side].y));
}
bool ConvexPolygon::ClipAgainstHalfplane(const Vector2 & r1, const Vector2 & r2, const Vector2 & r3)
{
// The reason this way is not succeeding: basically we can create two equal points due to
// clipping a vertex that is on the boundary and replacing with 2
bool intersect;
bool above_is_inside;
real compare;
int first, last;
bool setfirst;
real gradient ;
int flag, pullback, i, post_last, pre_first;
Vector2 cross1, cross2;
static const real EPS = 5.0e-14;
// Now we have to be able to deal with degenerate cases.
// =====================================
// We assign each point a status: INSIDE the clip region, NEAR the clip boundary, or OUTSIDE the clip region.
// When some consecutive points are found to be OUTSIDE the clip region, we also
// remove any consecutive points that are NEAR the clip boundary.
// This ensures hopefully that intersections are only taken towards points that are away from the clip boundary.
// If no points figure as actually OUTSIDE (further outside than EPS) then clipping is skipped.
// If no points figure as actually INSIDE (further inside than EPS) then we return no intersection.
#define INSIDE 0
#define OUTSIDE 1
#define NEARBY 2
// There is no point distinguishing near inside and near outside as this will be unreliable due to rounding anyway.
Vector2 direction = r2-r1;
// r1 + alpha.direction is the line
if (direction.x*direction.x > direction.y*direction.y)
// defend against case that it's basically vertical
{
flag = DYDX;
// determine whether r3 is above line:
gradient = direction.y/direction.x;
above_is_inside = (r3.y > r1.y + (r3.x-r1.x)*gradient) ;
// Hope we didn't get passed r3 that is on the line r1-r2 . If so it's an unfair call and we have to change the caller.
// Now ask which of our existing coordinates is in/near/out:
intersect = false;
setfirst = false;
for (int i = 0; i < numCoords; i++)
{
compare = r1.y + (coord[i].x-r1.x)*gradient;
//if (above)
//{
// is_above[i] = (coord[i].y > r1.y + (coord[i].x-r1.x)*gradient - EPS);
//} else {
// is_above[i] = (coord[i].y > r1.y + (coord[i].x-r1.x)*gradient + EPS);
//};
if (above_is_inside)
{
if (coord[i].y > compare + EPS) {
status[i] = INSIDE;
intersect = true;
} else {
if (coord[i].y < compare - EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
status[i] = NEARBY;
};
};
} else {
if (coord[i].y > compare + EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
if (coord[i].y < compare - EPS) {
status[i] = INSIDE;
intersect = true;
} else {
status[i] = NEARBY;
};
};
};
// last = i; // ordinarily this means we stored the first and last scrappable vertex
// but beware that it won't work if the scrapped section crossed 0
};
} else {
// line was more vertical than horizontal so take gradient x per y
flag = DXDY;
gradient = direction.x/direction.y;
above_is_inside = (r3.x > r1.x + (r3.y-r1.y)*gradient); // true if r3 is to right
// Now ask which of our existing coordinates is above
intersect = false;
setfirst = false;
for (int i = 0; i < numCoords; i++)
{
compare = r1.x + (coord[i].y-r1.y)*gradient;
if (above_is_inside)
{
if (coord[i].x > compare + EPS) {
status[i] = INSIDE;
intersect = true;
} else {
if (coord[i].x < compare - EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
status[i] = NEARBY;
};
};
} else {
if (coord[i].x > compare + EPS) {
status[i] = OUTSIDE;
first = i;
setfirst = true;
} else {
if (coord[i].x < compare - EPS) {
status[i] = INSIDE;
intersect = true;
} else {
status[i] = NEARBY;
};
};
};
};
};
if (intersect == false) return false; // nothing clipped
if (setfirst == false) return true; // all to be clipped - no change to ConvexPolygon object
// If we get here, some polygon vertices were (properly) clipped and some were (properly) not.
// OK now scrap those that did not intersect, if any, and replace them with the points where the lines are intersected
// Let's get the first point before our OUTSIDE subset that is not INSIDE.
while (status[first] != INSIDE)
{
first--;
if (first < 0) first = numCoords-1;
};
pre_first = first;
first++;
if (first == numCoords) first = 0;
GetIntersection(&cross1,r1,gradient,flag,coord[pre_first],coord[first]);
// Now move forward to last scrappable.
last = first;
while (status[last] != INSIDE)
{
last++;
if (last == numCoords) last = 0;
};
post_last = last;
last--;
if (last < 0) last = numCoords-1;
if (!_finite(coord[last].y)) {
printf("bad ness. %1.8E %1.8E %1.8E %1.8E %1.8E %1.8E \n",r1.x,r1.y,r2.x,r2.y,r3.x,r3.y);
getch();
};
GetIntersection(&cross2,r1,gradient,flag,coord[last],coord[post_last]); // this was passed a.y == #INF
// now repopulate the array:
// cases:
if (last >= first)
{
// easy cases:
if (last == first)
{
// array gets longer - need to move elements outwards first
for (i = numCoords-1; i >= last+1; i--)
coord[i+1] = coord[i];
numCoords++;
coord[first] = cross1;
coord[first+1] = cross2;
} else {
// last > first so we may need to pull some elements backwards
pullback = last-first-1; // last == first +1 => pullback == 0
for (i = last+1; i < numCoords; i++)
coord[i-pullback] = coord[i];
numCoords -= pullback;
coord[first] = cross1;
coord[first+1] = cross2;
};
} else {
// scrappable subset crosses 0
// post_last is the first element that is INSIDE
// Move elements back to 0; if post_last = 4, first = 6 then there are 2 such elements + 2 new ones
for (i =0; i < first-post_last; i++)
coord[i] = coord[i+post_last];
coord[i] = cross1;
coord[i+1] = cross2;
numCoords = i+2;
};
return true;
//// we know it goes from first to last
//// except in the case that first == 0 for which we have to go again
//if (first > 0)
//{
// // get the coordinates where it crosses
//
// GetIntersection(&cross1,r1,gradient,flag,coord[first-1],coord[first]);
// if (last < numCoords-1)
// {
// GetIntersection(&cross2,r1,gradient,flag,coord[last],coord[last+1]);
// } else {
// GetIntersection(&cross2,r1,gradient,flag,coord[last],coord[0]);
// };
// if (last == first)
// {
// // in this case we need to bop points forward, there are more coords in total
// for (i = numCoords-1; i >= last+1; i--)
// coord[i+1] = coord[i];
// numCoords++;
// coord[first] = cross1;
// coord[first+1] = cross2;
// } else {
// // in this case we may need to pull points backward in the array
// pullback = last-first-1; // last-first == 1 => 0
// if (pullback > 0)
// for (i = last+1; i < numCoords; i++)
// coord[i-pullback] = coord[i];
// coord[first] = cross1;
// coord[first+1] = cross2;
// numCoords -= pullback;
// };
//
//} else {
// // have to handle this special case that point 0 was not in: seek again to find the ends of the interval of scrappable vertices
// // work backwards from the end
// first = numCoords;
// while (is_above[first-1] != above) first--;
// if (first == numCoords) first = 0;
// last = 0;
// while (is_above[last+1] != above) last++;
// if (first == 0)
// {
// GetIntersection(&cross1,r1,gradient,flag,coord[numCoords-1],coord[0]);
// GetIntersection(&cross2,r1,gradient,flag,coord[last],coord[last+1]);
//
// // Now do exactly as above.
// // COPY-PASTE:
// if (last == first)
// {
// // in this case we need to bop points forward, there are more coords in total
// for (i = numCoords-1; i >= last+1; i--)
// coord[i+1] = coord[i];
// numCoords++;
// coord[first] = cross1;
// coord[first+1] = cross2;
// } else {
// // in this case we may need to pull points backward in the array
// pullback = last-first-1; // last-first = 1 -> 0
// if (pullback > 0)
// for (i = last+1; i < numCoords; i++)
// coord[i-pullback] = coord[i];
// coord[first] = cross1;
// coord[first+1] = cross2;
// numCoords -= pullback;
// };
// } else {
//
// // all those from first onwards are considered destroyed...
// GetIntersection(&cross1,r1,gradient,flag,coord[first-1],coord[first]);
// GetIntersection(&cross2,r1,gradient,flag,coord[last],coord[last+1]);
//
// coord[0] = cross2;
// // remove up until last
// pullback = last; // if last == 0 then we don't need to move anything
// // if last == 1 then we move element 2 to element 1
// for (i = last+1; i < numCoords; i++)
// coord[i-pullback] = coord[i];
// coord[first-pullback] = cross1;
// numCoords = first-pullback+1;
// };
//};
//
//return true;
}
void ConvexPolygon::CopyFrom(ConvexPolygon & cp)
{
numCoords = cp.numCoords;
for (int i = 0; i < numCoords; i++)
coord[i] = cp.coord[i];
}
void ConvexPolygon::GetCentre(Vector2 & centre)
{
centre.x = 0.0;
centre.y = 0.0;
for (int i = 0; i < numCoords; i++)
{
centre.x += coord[i].x;
centre.y += coord[i].y;
}
centre.x /= (real)numCoords;
centre.y /= (real)numCoords;
}
real ConvexPolygon::FindTriangleIntersectionArea(Vector2 & r1, Vector2 & r2, Vector2 & r3)
{
ConvexPolygon cp;
cp.CopyFrom(*this);
if (!cp.ClipAgainstHalfplane(r1,r2,r3)) return 0.0;
if (!cp.ClipAgainstHalfplane(r1,r3,r2)) return 0.0;
if (!cp.ClipAgainstHalfplane(r2,r3,r1)) return 0.0;
return cp.GetArea();
}
bool ConvexPolygon::GetIntersectionWithTriangle(ConvexPolygon * pPoly,Vector2 & r1, Vector2 & r2, Vector2 & r3)
{
pPoly->CopyFrom(*this);
if (!pPoly->ClipAgainstHalfplane(r1,r2,r3)) return false;
if (!pPoly->ClipAgainstHalfplane(r1,r3,r2)) return false;
if (!pPoly->ClipAgainstHalfplane(r2,r3,r1)) return false;
return true;
}
bool ConvexPolygon::GetIntersectionWithPolygon(ConvexPolygon * pPoly, // target
ConvexPolygon * pClip)// clip this against that.
{
int i, inext, inext2;
pPoly->CopyFrom(*this);
// convex polygon: if we take any edge then we should be fine to supply any other point as being on the "in" side of that edge..
for (i = 0; i < pClip->numCoords; i++)
{
inext = i+1; if (inext == pClip->numCoords) inext = 0;
inext2 = inext+1; if (inext2 == pClip->numCoords) inext2 = 0;
if (!pPoly->ClipAgainstHalfplane(pClip->coord[i],pClip->coord[inext],pClip->coord[inext2])) return false;
};
return true;
}
/*
real ConvexPolygon::IntegratePlane(Vector2 & r1, Vector2 & r2, Vector2 & r3,
real y1, real y2, real y3)
{
// Procedure:
// evaluate planar variable at all corners
// chop up this into triangles
// assume average attained by plane on each triangle
// take sum of multiplying average by area of triangle
real y[CP_MAX];
// make tri-aligned coordinates:
Vector2 x12 = r2 - r1;
real dist12 = x12.modulus();
x12.x /= dist12;
x12.y /= dist12;
Vector2 x12perp;
x12perp.x = x12.y;
x12perp.y = -x12.x;
dbyd12 = (y2-y1)/dist12;
Vector2 x13 = r3-r1;
real x13_12 = x13.x*x12.x + x13.y*x12.y;
real x13_perp = x13.x*x12perp.x + x13.y*x12perp.y;
//Vector2 position = r1 + x13_12*x12;
real ypos = y1 + dbyd12*x13_12;
real dbydperp = (y3-ypos)/x13_perp;
Vector2 relpos;
// Now plane is
// y1 + dbyd12*((x-r1) dot x12) + dbydperp*((x-r1) dot x12perp)
// evaluate planar variable at all corners
for (int i = 0; i < numCoords; i++)
{
relpos = coord[i] - r1;
y[i] = y1 + dbyd12*(relpos.x*x12.x + relpos.y*x12.y) + dbydperp*(relpos.x*x12perp.x+relpos.y*x12perp.y);
};
// chop up this into triangles
// assume average attained by plane on each triangle
// take sum of multiplying average by area of triangle
// pick point 0 and make tris
// we know the points should always be ordered
real average;
ConvexPolygon cpTri;
real sum = 0.0;
for (int i = 2; i < numCoords; i++)
{
average = (y[0] + y[i-1] + y[i])*THIRD;
cpTri.clear();
cpTri.add(coord[0]);
cpTri.add(coord[i-1]);
cpTri.add(coord[i]);
area = cpTri.GetArea();
sum += average*area;
};
// case of 3 coords: 0,1,2
// case of 4 coords: 0,1,2 0,2,3
return sum;
}*/
void ConvexPolygon::IntegrateMass(Vector2 & r1, Vector2 & r2, Vector2 & r3,
real yvals1, real yvals2, real yvals3, real * pResult)
{
real y[CP_MAX];
Vector2 relpos;
Vector2 x12perp,x12;
real dist12;
real ypos, dbyd12, dbydperp;
// make tri-aligned coordinates:
x12 = r2 - r1;
dist12 = x12.modulus();
x12.x /= dist12;
x12.y /= dist12;
x12perp.x = x12.y;
x12perp.y = -x12.x;
Vector2 x13 = r3-r1;
// dot products to give lengths:
real x13_12 = x13.x*x12.x + x13.y*x12.y;
real x13_perp = x13.x*x12perp.x + x13.y*x12perp.y;
dbyd12 = (yvals2-yvals1)/dist12;
ypos = yvals1 + dbyd12*x13_12;
dbydperp = (yvals3-ypos)/x13_perp;
for (int i = 0; i < numCoords; i++)
{
relpos = coord[i] - r1;
y[i] = yvals1 + dbyd12*(relpos.x*x12.x + relpos.y*x12.y) + dbydperp*(relpos.x*x12perp.x+relpos.y*x12perp.y);
};
*pResult = 0.0;
// pick point 0 and make tris
// we know the points should always be ordered
real average,area;
ConvexPolygon cpTri;
for (int i = 2; i < numCoords; i++)
{
cpTri.Clear();
cpTri.add(coord[0]);
cpTri.add(coord[i-1]);
cpTri.add(coord[i]);
area = cpTri.GetArea();
average = (y[0] + y[i-1] + y[i])*THIRD;
*pResult += average*area;
};
}
void ConvexPolygon::Integrate_Planes(Vector2 & r1, Vector2 & r2, Vector2 & r3,
real yvals1[],
real yvals2[],
real yvals3[],
real results[],
long N_planes)
{
// Procedure:
// evaluate planar variable at all corners
// chop up this into triangles
// assume average attained by plane on each triangle
// take sum of multiplying average by area of triangle
// So what are we assuming here? That the polygon to integrate over is
// a subset of the triangle??
real y[CP_MAX][15]; // max 15 planes
Vector2 relpos;
Vector2 x12perp,x12;
real dist12;
real ypos, dbyd12[15], dbydperp[15];
// make tri-aligned coordinates:
x12 = r2 - r1;
dist12 = x12.modulus();
x12.x /= dist12;
x12.y /= dist12;
x12perp.x = x12.y;
x12perp.y = -x12.x;
// So x12 is a unit vector
Vector2 x13 = r3-r1;
// dot products to give lengths:
real x13_12 = x13.x*x12.x + x13.y*x12.y;
real x13_perp = x13.x*x12perp.x + x13.y*x12perp.y;
// So x13_12 is projection of x13 in direction 12
for (int j = 0; j < N_planes; j++)
{
dbyd12[j] = (yvals2[j]-yvals1[j])/dist12;
ypos = yvals1[j] + dbyd12[j]*x13_12; // value at point along 12 as far as x13 projected
dbydperp[j] = (yvals3[j]-ypos)/x13_perp;
};
// Now plane is
// y1 + dbyd12*((x-r1) dot x12) + dbydperp*((x-r1) dot x12perp)
// evaluate planar variable at all corners
for (int i = 0; i < numCoords; i++)
{
relpos = coord[i] - r1;
for (int j = 0; j < N_planes; j++)
y[i][j] = yvals1[j] + dbyd12[j]*(relpos.x*x12.x + relpos.y*x12.y) + dbydperp[j]*(relpos.x*x12perp.x+relpos.y*x12perp.y);
};
// chop up this into triangles
// assume average attained by plane on each triangle
// take sum of multiplying average by area of triangle
for (int j = 0; j < N_planes; j++)
results[j] = 0.0;
// pick point 0 and make tris
// we know the points should always be ordered
real average,area;
ConvexPolygon cpTri;
for (int i = 2; i < numCoords; i++)
{
cpTri.Clear();
cpTri.add(coord[0]);
cpTri.add(coord[i-1]);
cpTri.add(coord[i]);
area = cpTri.GetArea();
for (int j = 0; j < N_planes; j++)
{
average = (y[0][j] + y[i-1][j] + y[i][j])*THIRD;
results[j] += average*area;
};
};
// case of 3 coords: 0,1,2
// case of 4 coords: 0,1,2 0,2,3
}
real ConvexPolygon::FindQuadrilateralIntersectionArea(Vector2 & r1, Vector2 & r2, Vector2 & r3, Vector2 & r4)
{
ConvexPolygon cp;
cp.CopyFrom(*this);
if (!cp.ClipAgainstHalfplane(r1,r2,r3)) return 0.0;
if (!cp.ClipAgainstHalfplane(r2,r3,r4)) return 0.0;
if (!cp.ClipAgainstHalfplane(r3,r4,r1)) return 0.0;
if (!cp.ClipAgainstHalfplane(r1,r4,r2)) return 0.0;
return cp.GetArea();
}
real ConvexPolygon::GetArea()
{
// shoelace formula as we should use elsewhere also.
if (numCoords == 0) return 0.0;
real area = 0.0;
int i;
for (i = 0; i < numCoords-1; i++)
{
area += coord[i].x*coord[i+1].y - coord[i+1].x*coord[i].y;
};
area += coord[i].x*coord[0].y - coord[0].x*coord[i].y;
if (area < 0.0)
return -area*0.5;
return area*0.5;
}
real CalculateTriangleIntersectionArea(Vector2 & x1, Vector2 & x2, Vector2 & x3,
Vector2 & r1, Vector2 & r2, Vector2 & r3)
{
// Get stack overflow and it appears here ?!!
// Sometimes this way fails.
// Spurious point gets added when we clip against a plane that meets the boundary.
// This invalidates the shoelace area formula which relies on convexity.
//bool boolIntersection_exists;
ConvexPolygon cp (x1,x2,x3);
// Clip against half plane created by r1 to r2 in the direction of r3
if (!cp.ClipAgainstHalfplane(r1,r2, r3)) // returns true if intersection existed
return 0.0;
if (!cp.ClipAgainstHalfplane(r2,r3,r1))
return 0.0;
if (!cp.ClipAgainstHalfplane(r1,r3,r2))
return 0.0;
return cp.GetArea(); // shoelace formula as we should use for triangle also.
// The way sketched out below may be faster so leave it in and try it after.
}
int Triangle::GetCornerIndex(Vertex * pVertex)
{
if (cornerptr[0] == pVertex) return 0;
if (cornerptr[1] == pVertex) return 1;
return 2;
}
real Triangle::ReturnNormalDist(Vertex * pOppVert)
{
Vector2 u[3];
real dist;
MapLeftIfNecessary(u[0],u[1],u[2]);
if (pOppVert == cornerptr[0])
{
dist = edge_normal[0].dot(u[1]-u[0]);
return dist;
};
if (pOppVert == cornerptr[1])
{
dist = edge_normal[1].dot(u[0]-u[1]);
return dist;
};
dist = edge_normal[2].dot(u[0]-u[2]);
return dist;
}
Vector2 CreateOutwardNormal(real x1, real y1,
real x2, real y2,
real x, real y)
{
// (x,y) is on the "inside"
Vector2 normal;
normal.x = y2-y1;
normal.y = x1-x2;
if (normal.x*(x-x1)+normal.y*(y-y1) > 0.0)
{
// case: normal points towards (x,y) from (x1,y1)
normal.x = -normal.x;
normal.y = -normal.y;
}
return normal;
}
Vertex * TriMesh::Search_for_iVolley_equals (Vertex * pSeed,int value)
{
if (pSeed->iVolley == value) return pSeed; // should not happen though
pSeed->iIndicator = 1; // searched
smartlong searched;
searched.add(pSeed-X);
Vertex * pNeigh,*pVertex,*pReturn;
int iNeigh, i;
// work outwards: look at neighbours
// set indicator for search? Need smth like this.
// Idea: Repeatedly take element from searched, scroll down it;
// if neighbours are not already searched, search them and add to
// bottom of the list.
long neigh_len;
long izNeighs[128];
long iSearchCaret = 0;
int not_found = true;
do
{
pVertex = X + searched.ptr[iSearchCaret];
neigh_len = pVertex->GetNeighIndexArray(izNeighs);
for (i = 0; i < neigh_len; i++)
{
pNeigh = X + izNeighs[i];
if (pNeigh->iIndicator == 0) {
if (pNeigh->iVolley == value)
{
not_found = false;
pReturn = pNeigh;
break; // where this takes us out to, not sure, but hopefully doesn't matter
}
pNeigh->iIndicator = 1;
searched.add(pNeigh-X);
}
}
iSearchCaret++;
} while (not_found);
// Need to restore iIndicator == 0 at the end of a search....
for (i = 0; i < searched.len; i++)
(X + searched.ptr[i])->iIndicator = 0;
return pReturn;
}
/*AuxVertex * TriMesh::Search_for_iVolley_equals (AuxVertex * pSeed,int value, int iLevel)
{
if (pSeed->iVolley == value) return pSeed; // should not happen though
pSeed->iIndicator = 1; // searched
smartlong searched;
searched.add(pSeed-AuxX[iLevel]);
AuxVertex * pNeigh,*pAux,*pReturn;
int iNeigh, i;
// work outwards: look at neighbours
// set indicator for search? Need smth like this.
// Idea: Repeatedly take element from searched, scroll down it;
// if neighbours are not already searched, search them and add to
// bottom of the list.
long iSearchCaret = 0;
int not_found = true;
do
{
pAux = AuxX[iLevel] + searched.ptr[iSearchCaret];
for (i = 0; i < pAux->neigh_len; i++)
{
pNeigh = AuxX[iLevel] + pAux->iNeighbours[i];
if (pNeigh->iIndicator == 0) {
if (pNeigh->iVolley == value)
{
not_found = false;
pReturn = pNeigh;
break; // where this takes us out to, not sure, but hopefully doesn't matter
}
pNeigh->iIndicator = 1;
searched.add(pNeigh-AuxX[iLevel]);
}
}
iSearchCaret++;
} while (not_found);
// Need to restore iIndicator == 0 at the end of a search....
for (i = 0; i < searched.len; i++)
(AuxX[iLevel] + searched.ptr[i])->iIndicator = 0;
return pReturn;
}*/
/*
void AuxTriangle::Set(AuxVertex * p1, AuxVertex * p2, AuxVertex * p3, long iTri)
{
cornerptr[0] = p1;
cornerptr[1] = p2;
cornerptr[2] = p3;
// Also calc circumcentre because we may be about to use it:
Vector2 Bb,C,b,c,a;
Vector2 basea,baseb;
if (periodic > 0)
{
// map everything to left hand side.
MapLeft(a,b,c);
} else {
PopulatePositions(a,b,c);
};
Bb = b-a;
C = c-a;
real D = 2.0*(Bb.x*C.y-Bb.y*C.x);
real modB = Bb.x*Bb.x+Bb.y*Bb.y;
real modC = C.x*C.x+C.y*C.y;
cc.x = (C.y*modB-Bb.y*modC)/D + a.x;
cc.y = (Bb.x*modC-C.x*modB)/D + a.y;
p1->addtri(iTri);
p2->addtri(iTri);
p3->addtri(iTri);
}
void AuxTriangle::Reset(AuxVertex * p1, AuxVertex * p2, AuxVertex * p3, long iTri)
{
// First delete from existing vertex lists
cornerptr[0]->remove_tri(iTri);
cornerptr[1]->remove_tri(iTri);
cornerptr[2]->remove_tri(iTri);
Set(p1,p2,p3,iTri);
}
AuxTriangle * TriMesh::GetAuxTriangleContaining(AuxVertex * pAux1,
AuxVertex * pAux2,
int iLevel)
{
int i;
AuxTriangle * pITri;
for (i = 0; i < pAux1->tri_len; i++)
{
pITri = AuxT[iLevel]+pAux1->iTriangles[i];
if ((pITri->cornerptr[0] == pAux2) ||
(pITri->cornerptr[1] == pAux2) ||
(pITri->cornerptr[2] == pAux2))
{
return pITri;
}
}
return 0;
}
bool AuxTriangle::TestDelaunay(AuxVertex * pAux)
{
real qdistsq = (pAux->x-cc.x)*(pAux->x-cc.x)+(pAux->y-cc.y)*(pAux->y-cc.y);
real pdistsq = (cornerptr[0]->pos.x-cc.x)*(cornerptr[0]->pos.x-cc.x)
+ (cornerptr[0]->pos.y-cc.y)*(cornerptr[0]->pos.y-cc.y);
return (qdistsq < pdistsq);
// return 1 if q is within circumcircle
}
/*
real Triangle::CalculateIntersectionArea(Vector2 & x1, Vector2 & x2, Vector2 & x3,
Vector2 & r1, Vector2 & r2, Vector2 & r3)
{
// Note that this routine works strictly on the actual given coordinates
// So make sure any periodic mapping is done beforehand.
// First let's establish a series of points that split up columns, starting with the leftmost point we have got.
// a. Put each triangle into left-to-right order
Vector2 temp,temp2;
if (x2.x > x1.x )
{
if (x3.x > x2.x)
{
// nothing to do
} else {
if (x3.x < x1.x)
{
// order is x3, x1, x2
temp.x = x1.x;
temp.y = x1.y;
x1.x = x3.x;
x1.y = x3.y;
x3.x = x2.x;
x3.y = x2.y;
x2.x = temp.x;
x2.y = temp.y;
} else {
// order is x1, x3, x2
temp.x = x2.x;
temp.y = x2.y;
x2.x = x3.x;
x2.y = x3.y;
x3.x = temp.x;
x3.y = temp.y;
};
};
} else {
if (x3.x > x1.x)
{
// order is x2 x1 x3
temp.x = x1.x;
temp.y = x1.y;
x1.x = x2.x;
x1.y = x2.y;
x2.x = temp.x;
x2.y = temp.y;
} else {
if (x3.x > x2.x)
{
// order is x2 x3 x1
temp.x = x1.x;
temp.y = x1.y;
x1.x = x2.x;
x1.y = x2.y;
x2.x = x3.x;
x2.y = x3.y;
x3.x = temp.x;
x3.y = temp.y;
} else {
// order is x3 x2 x1
temp.x = x1.x;
temp.y = x1.y;
x1.x = x3.x;
x1.y = x3.y;
x3.x = temp.x;
x3.y = temp.y;
};
};
};
// b. Where is the leftmost point?
// No point starting until both triangles are started.
// Write this out in a longwinded way unless and until we think of a clever way.
real area, gradient_r12, gradient_r23, gradient_x12, gradient_x23;
area = 0.0;
gradient_r12 = (r2.y-r1.y)/(r2.x-r1.x);
gradient_r13 = (r3.y-r1.y)/(r3.x-r1.x);
gradient_x12 = (x2.y-x1.y)/(x2.x-x1.x);
gradient_x13 = (x3.y-x1.y)/(x3.x-x1.x);
if (x1.x < r1.x)
{
// start at r1.x
if (x2.x < r2.x)
{
// x1 r1 x2
// going from r1.x to x2.x
area += ColumnIntersection(
// column x-values start and finish:
r1.x,x2.x,
// y-values:
r1.y, // left top for r
r1.y, // left bot for r
r1.y + gradient_r12*(x2.x-r1.x),//(r2.y-r1.y)*(x2.x-r1.x)/(r2.x-r1.x), // right top for r
r1.y + gradient_r13*(x2.x-r1.x),//(r3.y-r1.y)*(x2.x-r1.x)/(r3.x-r1.x), // right bot for r
x1.y + gradient_x12*(r1.x-x1.x),//(x2.y-x1.y)*(r1.x-x1.x)/(x2.x-x1.x), // left top for x
x1.y + gradient_x13*(r1.x-x1.x),//(x3.y-x1.y)*(r1.x-x1.x)/(x3.x-x1.x), // left bot for x
x2.y, // right top for x
x1.y + gradient_x13*(x2.x-x1.x)//(x3.y-x1.y)*(x2.x-x1.x)/(x3.x-x1.x) // right bot for x
);
if (r2.x < x3.x)
{
// going from x2.x to r2.x
area += ColumnIntersection(
// column x-values start and finish:
x2.x,r2.x,
// y-values:
r1.y+gradient_r12*(x2.x-r1.x),//(r2.y-r1.y)*(x2.x-r1.x)/(r2.x-r1.x), // left top for r
r1.y+gradient_r13*(x2.x-r1.x),//(r3.y-r1.y)*(x2.x-r1.x)/(r3.x-r1.x), // left bot for r
r2.y, // right top for r
r1.y + gradient_r13*(r2.x-r1.x),//(r3.y-r1.y)*(r2.x-r1.x)/(r3.x-r1.x), // right bot for r
x2.y, // left top for x
x1.y + gradient_x13*(x2.x-x1.x),//(x3.y-x1.y)*(x2.x-x1.x)/(x3.x-x1.x), // left bot for x
x2.y + gradient_x23*(r2.x-x2.x),//(x3.y-x2.y)*(r2.x-x2.x)/(x3.x-x2.x), // right top for x
x1.y + gradient_x13*(r2.x-x1.x)//(x3.y-x1.y)*(r2.x-x1.x)/(x3.x-x1.x) // right bot for x
);
if (x3.x < r3.x)
{
// the final one goes from r2.x to x3.x
area += ColumnIntersection(
r2.x,x3.x,
// y-values:
r2.y, // left via r2
r1.y+gradient_r13*(r2.x-r1.x),//(r3.y-r1.y)*(r2.x-r1.x)/(r3.x-r1.x), // left, r1->r3
r2.y + gradient_r23*(x3.x-r2.x),//(r3.y-r2.y)*(x3.x-r2.x)/(r3.x-r2.x), // right via r2,
r1.y + gradient_r13*(x3.x-r1.x),//(r3.y-r1.y)*(x3.x-r1.x)/(r3.x-r1.x), // right, r1->r3,
x2.y + gradient_x23*(r2.x-x2.x),//(x3.y-x2.y)*(r2.x-x2.x)/(x3.x-x2.x),
x1.y + gradient_x13*(r2.x-x1.x),//(x3.y-x1.y)*(r2.x-x1.x)/(x3.x-x1.x),
x3.y,
x3.y
);
} else {
// the final one goes from r2.x to r3.x
area += ColumnIntersection(
r2.x,r3.x,
// y-values:
r2.y,
r1.y+gradient_13*(r2.x-r1.x),//(r3.y-r1.y)*(r2.x-r1.x)/(r3.x-r1.x), // left, r1->r3
r3.y,
r3.y,
x2.y + gradient_x23*(r2.x-x2.x),//(x3.y-x2.y)*(r2.x-x2.x)/(x3.x-x2.x),
x1.y + gradient_x13*(r2.x-x1.x),//(x3.y-x1.y)*(r2.x-x1.x)/(x3.x-x1.x),
x2.y + gradient_x23*(r3.x-x2.x),//(x3.y-x2.y)*(r3.x-x2.x)/(x3.x-x2.x),
x1.y + gradient_x13*(r3.x-x1.x)//(x3.y-x1.y)*(r3.x-x1.x)/(x3.x-x1.x)
);
};
} else {
// the final one from x2.x to x3.x
// x1 r1 x2 x3
// some efficiency savings to be made if we calculate gradient_s before calling these functions.
area += ColumnIntersection(
x2.x,x3.x,
r1.y+gradient_r12*(x2.x-r1.x),
r1.y+gradient_r13*(x2.x-r1.x),
r1.y+gradient_r12*(x3.x-r1.x),
r1.y+gradient_r13*(x3.x-r1.x),
x2.y,
x1.y+gradient_x13*(x2.x-x1.x),
x3.y,
x3.y);
};
} else {
// x1 r1 r2
// going from r1.x to r2.x
area += ColumnIntersection(
// column x-values start and finish:
r1.x,r2.x,
// y-values:
r1.y, // left bot for r
r1.y, // left top for r
r2.y, // right top for r
r1.y + gradient_r13*(r2.x-r1.x), // right bot for r
x1.y + gradient_x12*(r1.x-x1.x), // left top for x
x1.y + gradient_x13*(r1.x-x1.x), // left bot for x
x1.y + gradient_x12*(r2.x-x1.x), // left top for x
x1.y + gradient_x13*(r2.x-x1.x), // left bot for x
);
if (x2.x < r3.x)
{
// x1 r1 r2 x2
// going from r2.x to x2.x
area += ColumnIntersection(
r2.x,x2.x,
// y-values:
r2.y,
r1.y+gradient_r13*(r2.x-r1.x),
r2.y+gradient_r23*(x2.x-r2.x),
r1.y+gradient_r13*(x2.x-r1.x),
x1.y+gradient_x12*(r2.x-x1.x),
x1.y+gradient_x13*(r2.x-x1.x),
x2.y,
x1.y+gradient_x13*(x2.x-x1.x)
);
if (r3.x < x3.x)
{
// the final one from x2.x to r3.x
// x1 r1 r2 x2 r3
area += ColumnIntersection(
x2.x,r3.x,
r2.y + gradient_r23*(x2.x-r2.x),
r1.y + gradient_r13*(x2.x-r1.x),
r3.y,
r3.y,
x2.y,
x1.y+gradient_x13*(x2.x-x1.x),
x2.y+gradient_x23*(r3.x-x2.x),
x1.y+gradient_x13*(r3.x-x1.x)
);
} else {
// the final one from x2.x to x3.x
// x1 r1 r2 x2 x3
area += ColumnIntersection(
x2.x,x3.x,
r2.y + gradient_r23*(x2.x-r2.x),
r1.y + gradient_r13*(x2.x-r1.x),
r2.y + gradient_r23*(x3.x-r2.x),
r1.y + gradient_r13*(x3.x-r1.x),
x2.y,
x1.y + gradient_x13*(x2.x-x1.x),
x3.y,
x3.y);
};
} else {
// the final one from r2.x to r3.x
// x1 r1 r2 r3
area += ColumnIntersection(
r2.x,r3.x,
r2.y,
r1.y + gradient_r13*(r2.x-r1.x),
r3.y,
r3.y,
x1.y + gradient_r12*(r2.x-x1.x),
x1.y + gradient_r13*(r2.x-x1.x),
x1.y + gradient_r12*(r3.x-x1.x),
x1.y + gradient_r13*(r3.x-x1.x)
);
};
};
} else {
// r1 x1
if (x2.x < r2.x)
{
// going from x1.x to x2.x
} else {
// r1 x1 r2
// going from x1.x to r2.x
}
};
return area;
}
real ColumnIntersection( real x1, real x2,
real y_a_1_left,
real y_a_2_left,
real y_a_1_right,
real y_a_2_right,
real y_b_1_left,
real y_b_2_left,
real y_b_1_right,
real y_b_2_right)
{
// Is it possible for x1->x2->x3 and x1->x3 to cross in this region?
// take average to determine which of 1,2 is higher for a
real b_bvg,a_avg, y_a_top_left,y_a_top_right,y_a_bot_left,y_a_bot_right,
y_b_top_left,y_b_top_right,y_b_bot_left,y_b_bot_right;
real width = x2-x1;
a_avg1 = y_a_1_left + y_a_1_right;
a_avg2 = y_a_2_left + y_a_2_right; // can avoid this by keeping global flag for whether gradient12 > gradient13 for first triangle
if (a_avg2 > a_avg1)
{
y_a_top_left = y_a_2_left; y_a_top_right = y_a_2_right;
y_a_bot_left = y_a_1_left; y_a_bot_right = y_a_1_right;
} else {
y_a_top_left = y_a_1_left; y_a_top_right = y_a_1_right;
y_a_bot_left = y_a_2_left; y_a_bot_right = y_a_2_right;
};
b_bvg1 = y_b_1_left + y_b_1_right;
b_bvg2 = y_b_2_left + y_b_2_right;
if (b_bvg2 > b_bvg1)
{
y_b_top_left = y_b_2_left; y_b_top_right = y_b_2_right;
y_b_bot_left = y_b_1_left; y_b_bot_right = y_b_1_right;
} else {
y_b_top_left = y_b_1_left; y_b_top_right = y_b_1_right;
y_b_bot_left = y_b_2_left; y_b_bot_right = y_b_2_right;
};
// Now consider some cases
// We are going to kind of clip a against the two half planes given by b
// Distinguish 3 possible locations for y_b_top_left rel to a, do cases for where y_b_top right is,
// then go from there with y_b_bot
// But do this in an order so that non-intersections can be detected quickly.
total = 0.0;
a_bot_gradient = (y_a_bot_right-y_a_bot_left)/width;
a_top_gradient = (y_a_top_right-y_a_top_left)/width;
b_bot_gradient = (y_b_bot_right-y_b_bot_left)/width;
b_top_gradient = (y_b_top_right-y_b_top_left)/width;
if (y_b_top_left < y_a_bot_left)
{
if (y_b_top_right < y_a_bot_right) return 0.0; // CASE I
if (y_b_top_right < y_a_top_right) {
// CASE II: b top cuts a bot upwards
total = triangle area()
x = (b
if (y_b_bot_right > y_a_bot_right)
{
// remove a triangle
total -= triangle area()
};
return total;
} else {
// CASE III: b top cuts both lines of a from below
if (
};
} else {
if (y_b_top_left > y_a_top_left)
{
// b top started above a
if (y_b_top_right > y_a_top_right)
{
// CASE IV: b top had no effect on a
} else {
if (y_b_top_right > y_a_bot_right)
{
// CASE V: b top cuts a top downwards
} else {
// CASE VI: b top cuts both lines of a, downwards
};
};
} else {
// b_top started in between
if (y_b_top_right > y_a_top_right)
{
// CASE VII: b top starts inside, goes up and outside
} else {
if (y_b_top_right > y_a_bot_right)
{
// CASE VIII: b top starts inside, stays inside;
} else {
// CASE XI: b top starts inside, goes below; only a triangle is then relevant
};
};
};
};
if (y_b_bot_left > y_a_top_left)
{
// First test for no intersection:
if (y_b_bot_right > y_a_top_right) return 0.0;
// therefore, at some point b_bot crosses a_top.
// until that point, we have no intersection.
// difference of gradients (b bot' - a top') * x + original difference (b bot - a top) = 0
// x = - original difference / difference of gradients
a_bot_gradient = (y_a_bot_right-y_a_bot_left)/width;
a_top_gradient = (y_a_top_right-y_a_top_left)/width;
b_bot_gradient = (y_b_bot_right-y_b_bot_left)/width;
b_top_gradient = (y_b_top_right-y_b_top_left)/width;
x = (y_a_top_left-y_b_bot_left)/(b_bot_gradient - a_top_gradient);
// Now from this point onwards what can happen?
x = (y_b_bot_left-y_a_top_left)/
} else {
if ((y_b_top_left < y_a_bot_left) && (y_b_top_right < y_a_bot_right)) return 0.0;
};
// OK so there is some intersection
}
*/
#endif
| 27.332857 | 165 | 0.58998 | [
"mesh",
"object",
"vector",
"3d"
] |
6bb2231a1bf720a4f9b6b2662a82ab23e88e38b3 | 41 | hpp | C++ | src/window/type.hpp | yydcnjjw/my-gui | 7d4c0836e861e991c42cecac4ddf6eda90ff36c8 | [
"Apache-2.0"
] | null | null | null | src/window/type.hpp | yydcnjjw/my-gui | 7d4c0836e861e991c42cecac4ddf6eda90ff36c8 | [
"Apache-2.0"
] | 1 | 2020-11-07T03:28:34.000Z | 2020-11-09T05:36:31.000Z | src/window/type.hpp | yydcnjjw/my-gui | 7d4c0836e861e991c42cecac4ddf6eda90ff36c8 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <render/type.hpp>
| 10.25 | 26 | 0.731707 | [
"render"
] |
6bb8eb29290fea68ff7acaabd728106261063222 | 5,821 | cpp | C++ | Sources/Display/Render/frame_buffer.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 248 | 2015-01-08T05:21:40.000Z | 2022-03-20T02:59:16.000Z | Sources/Display/Render/frame_buffer.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 39 | 2015-01-14T17:37:07.000Z | 2022-03-17T12:59:26.000Z | Sources/Display/Render/frame_buffer.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 82 | 2015-01-11T13:23:49.000Z | 2022-02-19T03:17:24.000Z | /*
** ClanLib SDK
** Copyright (c) 1997-2020 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
** Harry Storbacka
*/
#include "Display/precomp.h"
#include "API/Display/Render/frame_buffer.h"
#include "API/Display/Render/texture_2d.h"
#include "API/Display/Render/graphic_context.h"
#include "API/Display/TargetProviders/graphic_context_provider.h"
#include "API/Display/TargetProviders/frame_buffer_provider.h"
namespace clan
{
class FrameBuffer_Impl
{
public:
FrameBuffer_Impl() : provider(nullptr)
{
}
~FrameBuffer_Impl()
{
if (provider)
delete provider;
}
FrameBufferProvider *provider;
float pixel_ratio = 0.0f;
};
FrameBuffer::FrameBuffer()
{
}
FrameBuffer::FrameBuffer(GraphicContext &context)
: impl(std::make_shared<FrameBuffer_Impl>())
{
GraphicContextProvider *gc_provider = context.get_provider();
impl->provider = gc_provider->alloc_frame_buffer();
}
float FrameBuffer::get_pixel_ratio() const
{
return impl->pixel_ratio;
}
void FrameBuffer::throw_if_null() const
{
if (!impl)
throw Exception("FrameBuffer is null");
}
FrameBufferProvider *FrameBuffer::get_provider() const
{
return impl->provider;
}
Size FrameBuffer::get_size() const
{
return impl->provider->get_size();
}
FrameBufferBindTarget FrameBuffer::get_bind_target() const
{
return impl->provider->get_bind_target();
}
bool FrameBuffer::operator==(const FrameBuffer &other) const
{
return impl == other.impl;
}
void FrameBuffer::attach_color(int attachment_index, const RenderBuffer &render_buffer)
{
impl->provider->attach_color(attachment_index, render_buffer);
}
void FrameBuffer::attach_color(int attachment_index, const Texture1D &texture, int level)
{
impl->provider->attach_color(attachment_index, texture, level);
}
void FrameBuffer::attach_color(int attachment_index, const Texture1DArray &texture, int array_index, int level)
{
impl->provider->attach_color(attachment_index, texture, array_index, level);
}
void FrameBuffer::attach_color(int attachment_index, const Texture2D &texture, int level)
{
if (impl->pixel_ratio == 0.0f)
impl->pixel_ratio = texture.get_pixel_ratio();
impl->provider->attach_color(attachment_index, texture, level);
}
void FrameBuffer::attach_color(int attachment_index, const Texture2DArray &texture, int array_index, int level)
{
impl->provider->attach_color(attachment_index, texture, array_index, level);
}
void FrameBuffer::attach_color(int attachment_index, const Texture3D &texture, int depth, int level)
{
impl->provider->attach_color(attachment_index, texture, depth, level);
}
void FrameBuffer::attach_color(int attachment_index, const TextureCube &texture, TextureSubtype subtype, int level)
{
impl->provider->attach_color(attachment_index, texture, subtype, level);
}
void FrameBuffer::detach_color(int attachment_index)
{
impl->provider->detach_color(attachment_index);
}
void FrameBuffer::attach_stencil(const RenderBuffer &render_buffer)
{
impl->provider->attach_stencil(render_buffer);
}
void FrameBuffer::attach_stencil(const Texture2D &texture, int level)
{
if (impl->pixel_ratio == 0.0f)
impl->pixel_ratio = texture.get_pixel_ratio();
impl->provider->attach_stencil(texture, level);
}
void FrameBuffer::attach_stencil(const TextureCube &texture, TextureSubtype subtype, int level)
{
impl->provider->attach_stencil(texture, subtype, level);
}
void FrameBuffer::detach_stencil()
{
impl->provider->detach_stencil();
}
void FrameBuffer::attach_depth(const RenderBuffer &render_buffer)
{
impl->provider->attach_depth(render_buffer);
}
void FrameBuffer::attach_depth(const Texture2D &texture, int level)
{
if (impl->pixel_ratio == 0.0f)
impl->pixel_ratio = texture.get_pixel_ratio();
impl->provider->attach_depth(texture, level);
}
void FrameBuffer::attach_depth(const TextureCube &texture, TextureSubtype subtype, int level)
{
impl->provider->attach_depth(texture, subtype, level);
}
void FrameBuffer::detach_depth()
{
impl->provider->detach_depth();
}
void FrameBuffer::attach_depth_stencil(const RenderBuffer &render_buffer)
{
impl->provider->attach_depth_stencil(render_buffer);
}
void FrameBuffer::attach_depth_stencil(const Texture2D &texture, int level)
{
if (impl->pixel_ratio == 0.0f)
impl->pixel_ratio = texture.get_pixel_ratio();
impl->provider->attach_depth_stencil(texture, level);
}
void FrameBuffer::attach_depth_stencil(const TextureCube &texture, TextureSubtype subtype, int level)
{
impl->provider->attach_depth_stencil(texture, subtype, level);
}
void FrameBuffer::detach_depth_stencil()
{
impl->provider->detach_depth_stencil();
}
void FrameBuffer::set_bind_target(FrameBufferBindTarget target)
{
impl->provider->set_bind_target(target);
}
}
| 27.457547 | 116 | 0.74884 | [
"render"
] |
6bbb82589c2e6df10dc0e20794c7a24d3c0e6f51 | 6,779 | hpp | C++ | vector/sl-vector.hpp | brianwolfe/stl-learning | 6b05c0b4f1927f35238b90cf5989412a15575fbe | [
"MIT"
] | null | null | null | vector/sl-vector.hpp | brianwolfe/stl-learning | 6b05c0b4f1927f35238b90cf5989412a15575fbe | [
"MIT"
] | null | null | null | vector/sl-vector.hpp | brianwolfe/stl-learning | 6b05c0b4f1927f35238b90cf5989412a15575fbe | [
"MIT"
] | 1 | 2020-04-20T13:31:53.000Z | 2020-04-20T13:31:53.000Z |
#include <iostream>
// STL learning namespace
namespace stll
{
template <typename T> T min(const T & a, const T & b)
{
if (a < b)
{
return a;
}
return b;
}
template<typename T> class vector {
typedef T* iterator;
protected:
constexpr static size_t SCALE_FACTOR = 2;
T * m_data = nullptr;
size_t m_size = 0;
size_t m_capacity = 0;
void grow();
void _delete();
template<class ...Args> void unsafe_emplace_back(Args&&... args);
public:
/**
* Use a default constructor
*/
vector(void) = default;
/**
* Create a vector with count elements, initilized to val
*/
vector(size_t count, const T & val);
/**
* Copy constructor
*/
vector(const vector<T> & other);
/**
* Move constructor
*/
vector(vector<T> && other) noexcept;
/**
* Copy assignment operator
*/
vector<T> & operator=(const vector<T> & other);
/**
* Move assignment operator
*/
vector<T> & operator=(vector<T> && other) noexcept;
/**
* Free the constructor
*/
~vector();
void assign(typename vector<T>::iterator b, typename vector<T>::iterator e);
/**
* Construct a new element T with the provided arguments
*/
template<class ...Args> void emplace_back(Args&&... args);
/**
* Access a reference to the element stored at the provided index
*/
T & operator [](size_t index) const noexcept;
/**
*
*/
void pop_back(void) noexcept;
/**
*/
bool empty(void) const noexcept;
/**
*
*/
void ensure_capacity(size_t capacity);
iterator begin(void) const noexcept;
iterator end(void) const noexcept;
size_t size(void) const noexcept;
};
template<typename T>
vector<T>::vector(size_t count, const T & val) : vector()
{
std::cout << "Constructing vec" << std::endl;
// Keep valid empty data
if (count == 0)
{
return;
}
this->m_data = operator new(sizeof(T) * count);
this->m_size = 0;
this->m_capacity = count;
for (size_t i = 0; i < count; i++)
{
new(this->m_data + i) T(val);
}
this->m_size = count;
}
template<typename T>
vector<T>::vector(const vector<T> & other)
{
this->ensure_capacity(other.m_size);
for (auto a : other)
{
this->unsafe_emplace_back(a);
}
}
template<typename T>
vector<T>::vector(vector<T> && other) noexcept :
m_data{other.m_data}, m_size{other.m_size}, m_capacity{other.m_capacity}
{
other.m_data = nullptr;
other.m_size = 0;
other.m_capacity = 0;
}
template<typename T>
vector<T> & vector<T>::operator=(const vector<T> & other)
{
if (this == &other) return *this;
this->ensure_capacity(other.size());
size_t n = min<size_t>(other.m_size, this->m_size);
for (size_t i = 0; i < n; i++)
{
this->m_data[i] = other.m_data[i];
}
for (size_t i = n; i < other.m_size; i++)
{
this->unsafe_emplace_back(other.m_data[i]);
}
while(this->m_size > other.m_size)
{
this->pop_back();
}
return *this;
}
template<typename T>
void vector<T>::assign(vector<T>::iterator b, vector<T>::iterator e)
{
ensure_capacity(e - b);
size_t n_other = e - b;
size_t n = min<size_t>(e - b, this->size());
size_t i = 0;
auto t_it = this->begin();
auto o_it = b;
auto t_end = this->begin() + n;
while (t_it < t_end)
{
*t_it = *o_it;
++t_it;
++o_it;
}
i += n;
while (i < n_other)
{
this->unsafe_emplace_back(o_it);
++ i;
++ o_it;
}
while (i < this->m_size)
{
this->pop_back();
}
}
template<typename T>
vector<T> & vector<T>::operator=(vector<T> && other) noexcept
{
if (this == &other) return *this;
this->_delete();
this->m_data = other.m_data;
this->m_size = other.m_size;
this->m_capacity = other.m_capacity;
other.m_data = nullptr;
other.m_size = 0;
other.m_capacity = 0;
return *this;
}
template<typename T>
vector<T>::~vector()
{
this->_delete();
}
/**
* Trying to implement an emplace back
*/
template<typename T>
template<class ...Args>
void vector<T>::emplace_back(Args&&... args)
{
if (this->m_size == this->m_capacity)
{
this->grow();
}
// this->m_data[this->m_size] = T(args...);
// Use perfect forwarding to avoid move issues when using lvalues
unsafe_emplace_back(std::forward<Args...>(args...));
}
template<typename T>
template<class ...Args>
void vector<T>::unsafe_emplace_back(Args&&... args)
{
new(this->m_data + this->m_size) T(std::forward<Args...>(args...));
this->m_size ++;
}
/**
* Delete the last element in the vector
*/
template<typename T>
void vector<T>::pop_back(void) noexcept
{
// Need to guard this in debug mode
-- this->m_size;
this->m_data[this->m_size].~T();
}
/**
* Test if the vector is empty
*/
template<typename T>
bool vector<T>::empty(void) const noexcept
{
return this->m_size == 0;
}
/**
* Get and set operators
*/
template<typename T>
T & vector<T>::operator [](size_t index) const noexcept
{
// Need to guard this in debug mode
return this->m_data[index];
}
/*
*/
template<typename T>
void vector<T>::grow()
{
size_t new_capacity = (size_t)(this->m_size * SCALE_FACTOR);
if (new_capacity == 0)
{
new_capacity = 1;
}
ensure_capacity(new_capacity);
}
template<typename T>
void vector<T>::ensure_capacity(size_t new_capacity)
{
if (new_capacity < this->m_capacity) return;
// Check that new_size > m_size?
T * tmp_data = (T*) (operator new(sizeof(T) * new_capacity));
for (size_t i = 0; i < this->m_size; i++)
{
tmp_data[i] = std::move(this->m_data[i]);
}
operator delete(this->m_data);
this->m_data = tmp_data;
this->m_capacity = new_capacity;
}
template<typename T>
void vector<T>::_delete(void)
{
while (!this->empty())
{
this->pop_back();
}
operator delete(this->m_data);
this->m_capacity = 0;
this->m_size = 0;
this->m_data = nullptr;
}
template<typename T>
typename vector<T>::iterator vector<T>::begin(void) const noexcept
{
return this->m_data;
}
template<typename T>
typename vector<T>::iterator vector<T>::end(void) const noexcept
{
return this->m_data + this->m_size;
}
template<typename T>
size_t vector<T>::size(void) const noexcept
{
return this->m_size;
}
}
| 19.879765 | 84 | 0.56852 | [
"vector"
] |
6bbfa5689c2fe1cdf9e7bf9ff49c3a52aad0cda9 | 3,029 | cpp | C++ | iggcm-2016/src/framework/Mesh.cpp | davedissian/archive | a28072a70d7dc3bb88e9a268aea99667f656c100 | [
"MIT"
] | null | null | null | iggcm-2016/src/framework/Mesh.cpp | davedissian/archive | a28072a70d7dc3bb88e9a268aea99667f656c100 | [
"MIT"
] | null | null | null | iggcm-2016/src/framework/Mesh.cpp | davedissian/archive | a28072a70d7dc3bb88e9a268aea99667f656c100 | [
"MIT"
] | null | null | null | /*
* GL Framework
* Copyright (c) David Avedissian 2014-2015
*/
#include "Common.h"
#include "Mesh.h"
Mesh::Mesh(vector<GLfloat> vertexData, vector<VertexAttribute> layout)
: mVertexArrayObject(0),
mVertexBufferObject(0),
mElementBufferObject(0),
mVertexCount(0)
{
glGenVertexArrays(1, &mVertexArrayObject);
glBindVertexArray(mVertexArrayObject);
// Generate vertex buffer
glGenBuffers(1, &mVertexBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferObject);
glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), vertexData.data(),
GL_STATIC_DRAW);
// Calculate vertex size
uint vertexSize = 0;
for (auto i = layout.begin(); i != layout.end(); i++)
vertexSize += i->count;
// As we know the vertex size, set the vertex count
mVertexCount = vertexData.size() / vertexSize;
// Set up vertex layout
uint attributeCounter = 0;
uint offset = 0;
for (auto i = layout.begin(); i != layout.end(); i++)
{
glEnableVertexAttribArray(attributeCounter);
glVertexAttribPointer(attributeCounter, i->count, i->type, GL_FALSE,
vertexSize * sizeof(float), (void*)(offset * sizeof(float)));
attributeCounter++;
offset += i->count;
}
}
Mesh::Mesh(vector<GLfloat> vertexData, vector<GLuint> elementData,
vector<VertexAttribute> layout)
: mVertexArrayObject(0),
mVertexBufferObject(0),
mElementBufferObject(0),
mVertexCount(elementData.size())
{
glGenVertexArrays(1, &mVertexArrayObject);
glBindVertexArray(mVertexArrayObject);
// Generate vertex buffer
glGenBuffers(1, &mVertexBufferObject);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBufferObject);
glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), vertexData.data(),
GL_STATIC_DRAW);
// Generate element buffer
glGenBuffers(1, &mElementBufferObject);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mElementBufferObject);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementData.size() * sizeof(GLuint), elementData.data(),
GL_STATIC_DRAW);
// Calculate vertex size
uint vertexSize = 0;
for (auto i = layout.begin(); i != layout.end(); i++)
vertexSize += i->count;
// Set up vertex layout
uint attributeCounter = 0;
uint offset = 0;
for (auto i = layout.begin(); i != layout.end(); i++)
{
glEnableVertexAttribArray(attributeCounter);
glVertexAttribPointer(attributeCounter, i->count, i->type, GL_FALSE,
vertexSize * sizeof(float), (void*)(offset * sizeof(float)));
attributeCounter++;
offset += i->count;
}
}
Mesh::~Mesh()
{
}
void Mesh::Bind()
{
glBindVertexArray(mVertexArrayObject);
}
void Mesh::Draw()
{
if (mElementBufferObject != 0)
{
glDrawElements(GL_TRIANGLES, mVertexCount, GL_UNSIGNED_INT, 0);
}
else
{
glDrawArrays(GL_TRIANGLES, 0, mVertexCount);
}
}
| 29.125 | 98 | 0.653021 | [
"mesh",
"vector"
] |
6bc5f4f95862e3e940bacc79e4fb0fc3b58339f0 | 1,344 | cpp | C++ | aquifer/Convection/Convection.cpp | AleksZhuravlyov/oopmech | 4a53dc8fb2a94fa9de660e12ca51bcddc35b407c | [
"AFL-3.0"
] | null | null | null | aquifer/Convection/Convection.cpp | AleksZhuravlyov/oopmech | 4a53dc8fb2a94fa9de660e12ca51bcddc35b407c | [
"AFL-3.0"
] | null | null | null | aquifer/Convection/Convection.cpp | AleksZhuravlyov/oopmech | 4a53dc8fb2a94fa9de660e12ca51bcddc35b407c | [
"AFL-3.0"
] | null | null | null | #include "Convection.h"
Convection::Convection(Grid &grdPar, FuncPars &fPPar,
GetFromFile &dataFilePar) : ConvectionPars(grdPar, fPPar),
dataFile(dataFilePar),
dimCell(grd.cellsV.size()),
divergence(dimCell, 0),
aF(dimCell, 0),
aC(dimCell, 0),
aR(dimCell, 0),
aL(dimCell, 0),
aT(dimCell, 0),
aB(dimCell, 0) {}
Convection::~Convection() {}
void Convection::defineSchemeType() {
schemeType = dataFile.getWord<std::string>(schemeEqName);
schemeName = dataFile.getWord<std::string>(schemeEqName, 1);
if (schemeType == "implicit")
implicitFlag = true;
else if (schemeType == "explicit")
implicitFlag = false;
}
void Convection::calcСoefficients(const std::vector<double> &PPar, const std::vector<double> &SPar) {
P = PPar;
S = SPar;
defineSchemeType();
calcPars();
calcDivergence();
calcA();
} | 28.595745 | 101 | 0.428571 | [
"vector"
] |
6bcc35b74c3585e2884d60411bcf9375112a4cd1 | 3,224 | cc | C++ | dyvmsapi/src/model/ListHotlineTransferNumberRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | dyvmsapi/src/model/ListHotlineTransferNumberRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | dyvmsapi/src/model/ListHotlineTransferNumberRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/dyvmsapi/model/ListHotlineTransferNumberRequest.h>
using AlibabaCloud::Dyvmsapi::Model::ListHotlineTransferNumberRequest;
ListHotlineTransferNumberRequest::ListHotlineTransferNumberRequest() :
RpcServiceRequest("dyvmsapi", "2017-05-25", "ListHotlineTransferNumber")
{
setMethod(HttpRequest::Method::Post);
}
ListHotlineTransferNumberRequest::~ListHotlineTransferNumberRequest()
{}
long ListHotlineTransferNumberRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void ListHotlineTransferNumberRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
std::string ListHotlineTransferNumberRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void ListHotlineTransferNumberRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setParameter("AccessKeyId", accessKeyId);
}
std::string ListHotlineTransferNumberRequest::getHotlineNumber()const
{
return hotlineNumber_;
}
void ListHotlineTransferNumberRequest::setHotlineNumber(const std::string& hotlineNumber)
{
hotlineNumber_ = hotlineNumber;
setParameter("HotlineNumber", hotlineNumber);
}
int ListHotlineTransferNumberRequest::getPageSize()const
{
return pageSize_;
}
void ListHotlineTransferNumberRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::string ListHotlineTransferNumberRequest::getQualificationId()const
{
return qualificationId_;
}
void ListHotlineTransferNumberRequest::setQualificationId(const std::string& qualificationId)
{
qualificationId_ = qualificationId;
setParameter("QualificationId", qualificationId);
}
std::string ListHotlineTransferNumberRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void ListHotlineTransferNumberRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
long ListHotlineTransferNumberRequest::getOwnerId()const
{
return ownerId_;
}
void ListHotlineTransferNumberRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
int ListHotlineTransferNumberRequest::getPageNo()const
{
return pageNo_;
}
void ListHotlineTransferNumberRequest::setPageNo(int pageNo)
{
pageNo_ = pageNo;
setParameter("PageNo", std::to_string(pageNo));
}
| 27.322034 | 104 | 0.783189 | [
"model"
] |
6bcdc6e7b5da01ec5aba2e1866a5210648dbcfc9 | 9,525 | cpp | C++ | src/renderfamily.cpp | TheVaffel/Wingine | 17d5bf19a9c56a0e3ae6a84df2332319d82e9493 | [
"MIT"
] | 2 | 2020-12-01T15:13:08.000Z | 2021-11-11T16:10:10.000Z | src/renderfamily.cpp | TheVaffel/Wingine | 17d5bf19a9c56a0e3ae6a84df2332319d82e9493 | [
"MIT"
] | null | null | null | src/renderfamily.cpp | TheVaffel/Wingine | 17d5bf19a9c56a0e3ae6a84df2332319d82e9493 | [
"MIT"
] | null | null | null | #include "renderfamily.hpp"
#include "Wingine.hpp"
namespace wg {
RenderFamily::RenderFamily(Wingine& wing,
const Pipeline* pipeline,
bool clear,
int num_framebuffers) :
wing(&wing), pipeline(pipeline) {
if(num_framebuffers == 0) {
num_framebuffers = wing.getNumFramebuffers();
}
this->clears = clear;
this->num_buffers = num_framebuffers;
this->render_pass_type = pipeline->render_pass_type;
this->render_passes = std::vector<vk::RenderPass>(num_framebuffers);
for(int i = 0; i < num_framebuffers; i++) {
if(!clear) {
this->render_passes[i] = wing.compatibleRenderPassMap[this->render_pass_type];
} else {
this->render_passes[i] = wing.create_render_pass(this->render_pass_type,
clear);
}
}
vk::CommandPool pool = wing.getGraphicsCommandPool();
vk::Device device = wing.getDevice();
vk::CommandBufferAllocateInfo cbi;
cbi.setCommandPool(pool)
.setLevel(vk::CommandBufferLevel::ePrimary)
.setCommandBufferCount(1); // Premature optimization... etc.
this->commands = std::vector<Command>(this->num_buffers);
for(int i = 0; i < this->num_buffers; i++) {
commands[i].buffer = device.allocateCommandBuffers(cbi)[0];
commands[i].buffer
.reset(vk::CommandBufferResetFlagBits::eReleaseResources);
vk::FenceCreateInfo fci;
fci.setFlags(vk::FenceCreateFlagBits::eSignaled);
commands[i].fence =
device.createFence(fci);
}
}
void RenderFamily::startRecording(std::vector<Framebuffer*> framebuffers) {
if (framebuffers.size() == 0) {
this->framebuffers = wing->getFramebuffers();
} else {
this->framebuffers = framebuffers;
}
_wassert((int)this->framebuffers.size() == this->num_buffers,
"[RenderFamily::startRecording] Number of provided framebuffers and originally declared framebuffers differ");
for(int i = 0; i < this->num_buffers; i++) {
vk::CommandBufferBeginInfo begin;
vk::Rect2D renderRect;
renderRect.setOffset({0, 0})
.setExtent({this->framebuffers[i]->depthImage.width, this->framebuffers[i]->depthImage.height});
vk::RenderPassBeginInfo rpb;
rpb.setRenderPass(this->render_passes[i])
.setClearValueCount(0)
.setPClearValues(nullptr)
.setFramebuffer(this->framebuffers[i]->framebuffer)
.setRenderArea(renderRect);
// Size is number of attachments
std::vector<vk::ClearValue> clear_values;
if(this->clears) {
switch (this->render_pass_type) {
case renDepth:
clear_values.resize(1);
clear_values[0].depthStencil.depth = 1.0f;
clear_values[0].depthStencil.stencil = 0.0f;
break;
case renColorDepth:
clear_values.resize(2);
clear_values[0].color.setFloat32({0.3f, 0.3f,
0.3f, 1.0f});
clear_values[1].depthStencil.depth = 1.0f;
clear_values[1].depthStencil.stencil = 0.0f;
}
rpb.setClearValueCount(clear_values.size())
.setPClearValues(clear_values.data());
}
vk::Device device = this->wing->getDevice();
_wassert_result(device.waitForFences(1, &this->commands[i].fence, true, UINT64_MAX),
"wait for render family command finish");
this->commands[i].buffer.reset(vk::CommandBufferResetFlagBits::eReleaseResources);
this->commands[i].buffer.begin(begin);
this->commands[i].buffer.beginRenderPass(rpb, vk::SubpassContents::eInline);
this->commands[i].buffer.bindPipeline(vk::PipelineBindPoint::eGraphics, this->pipeline->pipeline);
}
}
void RenderFamily::recordDraw(const std::vector<const Buffer*>& vertex_buffers, const IndexBuffer* ind_buf,
const std::vector<ResourceSet*>& sets, int instanceCount){
for(int j = 0; j < this->num_buffers; j++) {
std::vector<vk::DescriptorSet> d_sets(sets.size());
for(unsigned int i = 0; i < sets.size(); i++) {
d_sets[i] = sets[i]->descriptor_set;
}
if (sets.size()) {
this->commands[j].buffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics,
this->pipeline->layout,
0, d_sets.size(),
d_sets.data(),
0, nullptr);
}
std::vector<vk::Buffer> vk_buffers(vertex_buffers.size());
std::vector<vk::DeviceSize> offsets(vertex_buffers.size());
for(unsigned int i = 0; i < vertex_buffers.size(); i++) {
vk_buffers[i] = vertex_buffers[i]->buffer;
offsets[i] = 0;
}
this->commands[j].buffer.bindVertexBuffers(0, vk_buffers.size(),
vk_buffers.data(),
offsets.data());
this->commands[j].buffer.bindIndexBuffer(ind_buf->buffer,
0, vk::IndexType::eUint32);
this->commands[j].buffer.drawIndexed(ind_buf->num_indices, instanceCount,
0, 0, 0);
}
}
void RenderFamily::endRecording() {
for(int i = 0; i < this->num_buffers; i++) {
this->commands[i].buffer.endRenderPass();
this->commands[i].buffer.end();
}
}
void RenderFamily::submit(const std::initializer_list<SemaphoreChain*>& wait_semaphores, int index) {
if (index == -1) {
index = this->wing->getCurrentFramebufferIndex();
}
_wassert(index <= this->num_buffers, "[RenderFamily::submit(int index)] Index too high. This could be because the RenderFamily instance is created with fewer buffers than there are frame buffers, and no index was explicitly set.");
this->submit_command(wait_semaphores, index);
}
void RenderFamily::submit_command(const std::initializer_list<SemaphoreChain*>& semaphores, int index) {
vk::Device device = this->wing->getDevice();
vk::Queue queue = this->wing->getGraphicsQueue();
std::vector<vk::PipelineStageFlags> stage_flags(semaphores.size());
for(unsigned int i = 0; i < semaphores.size(); i++) {
stage_flags[i] = vk::PipelineStageFlagBits::eTopOfPipe;
}
std::vector<vk::Semaphore> wait_sems(semaphores.size());
std::vector<vk::Semaphore> signal_sems(semaphores.size());
std::vector<vk::PipelineStageFlags> flags(semaphores.size());
std::vector<uint64_t> wait_vals(semaphores.size());
std::vector<uint64_t> signal_vals(semaphores.size());
int num_wait_sems = SemaphoreChain::getWaitSemaphores(wait_sems.data(), std::begin(semaphores), semaphores.size());
int num_signal_sems = SemaphoreChain::getSignalSemaphores(signal_sems.data(), std::begin(semaphores), semaphores.size());
SemaphoreChain::getSemaphoreWaitValues(wait_vals.data(), std::begin(semaphores), semaphores.size());
SemaphoreChain::getSemaphoreSignalValues(signal_vals.data(), std::begin(semaphores), semaphores.size());
SemaphoreChain::getWaitStages(flags.data(), std::begin(semaphores), semaphores.size());
vk::TimelineSemaphoreSubmitInfo tssi;
tssi.setSignalSemaphoreValueCount(num_signal_sems)
.setPSignalSemaphoreValues(signal_vals.data())
.setWaitSemaphoreValueCount(num_wait_sems)
.setPWaitSemaphoreValues(wait_vals.data());
vk::SubmitInfo si;
si.setCommandBufferCount(1)
.setPCommandBuffers(&this->commands[index].buffer)
.setPWaitDstStageMask(stage_flags.data())
.setSignalSemaphoreCount(num_signal_sems)
.setPSignalSemaphores(signal_sems.data())
.setWaitSemaphoreCount(num_wait_sems)
.setPWaitSemaphores(wait_sems.data())
.setPNext(&tssi);
SemaphoreChain::resetModifiers(std::begin(semaphores), semaphores.size());
// Ensure finished last submission
_wassert_result(device.waitForFences(1, &this->commands[index].fence, true, (uint64_t)1e9),
"wait for last submission in render family");
_wassert_result(device.resetFences(1, &this->commands[index].fence),
"reset fence in render family");
_wassert_result(queue.submit(1, &si, this->commands[index].fence),
"submitting render family command to queue");
}
};
| 42.146018 | 239 | 0.561575 | [
"render",
"vector"
] |
6bd54ee3b6bef9ba6d3d67d5ec2c289491edc3c0 | 5,465 | cpp | C++ | ProjectLunarPhase/MainF.cpp | Edgaru089/ProjectLunarPhase | bc8085e3b0ccc20c76cac7880afb0ab830be0e35 | [
"MIT"
] | null | null | null | ProjectLunarPhase/MainF.cpp | Edgaru089/ProjectLunarPhase | bc8085e3b0ccc20c76cac7880afb0ab830be0e35 | [
"MIT"
] | null | null | null | ProjectLunarPhase/MainF.cpp | Edgaru089/ProjectLunarPhase | bc8085e3b0ccc20c76cac7880afb0ab830be0e35 | [
"MIT"
] | null | null | null |
#include "Main.hpp"
const char projectName[] = "Project LunarPhase", stage[] = "Alpha";
const int majorVersion = 0, minorVersion = 0, patchVersion = 0;
const char completeServerName[] = "Project-LunarPhase/0.0.0.Alpha";
namespace {
mt19937 randomEngine((random_device())());
char decodeHex2(char high, char low) {
return (unsigned char)((((high >= 'A') ? (high - 'A' + 10) : (high - '0')) << 4) | ((low >= 'A') ? (low - 'A' + 10) : (low - '0')));
}
char encodeHex1(unsigned char c) {
return (c >= 0xa) ? ('A' + c - 0xa) : ('0' + c);
}
pair<char, char> encodeHex2(unsigned char c) {
return make_pair(encodeHex1((c & 0xf0) >> 4),
encodeHex1(c & 0xf));
}
double rand01() {
return uniform_real_distribution<double>(0.0, 1.0)(randomEngine);
}
// [x, y]
int rand(int x, int y) {
return uniform_int_distribution<int>(x, y)(randomEngine);
}
// A cache container for readFileBinaryCached
map<wstring, pair<chrono::steady_clock::time_point, string>> fileCache;
const auto reloadCachedFileDuration = chrono::seconds(3);
}
#ifdef _WIN32
string wstringToUtf8(const wstring& source) {
size_t size = WideCharToMultiByte(CP_UTF8, 0, source.data(), source.size(), NULL, NULL, NULL, NULL);
string buffer(size, '\0');
WideCharToMultiByte(CP_UTF8, 0, source.data(), source.size(), buffer.data(), buffer.size(), NULL, NULL);
return buffer;
}
wstring utf8ToWstring(const string& source) {
size_t size = MultiByteToWideChar(CP_UTF8, 0, source.data(), source.size(), NULL, NULL);
wstring buffer(size, L'\0');
MultiByteToWideChar(CP_UTF8, 0, source.data(), source.size(), buffer.data(), buffer.size());
return buffer;
}
wstring ansiToWstring(const string& source) {
size_t size = MultiByteToWideChar(CP_ACP, 0, source.data(), source.size(), NULL, NULL);
wstring buffer(size, L'\0');
MultiByteToWideChar(CP_ACP, 0, source.data(), source.size(), buffer.data(), buffer.size());
return buffer;
}
#elif
#pragma error("I'm too lazy to implement a cross-platform UTF-8 <-> wchar_t convertion")
#endif
string decodePercentEncoding(const string& source) {
string res;
int i = 0;
while (i < source.length()) {
if (source[i++] == '%') {
char c1 = source[i++];
char c2 = source[i++];
res.push_back(decodeHex2(c1, c2));
} else if (source[i - 1] == '+')
res.push_back(' ');
else
res.push_back(source[i - 1]);
}
return res;
}
string encodePercent(const string& source, bool encodeSlash) {
string res;
for (unsigned char i : source) {
if (isalnum(i) || i == '.' || i == '-' || i == '_' || i == '~' || (!encodeSlash&&i == '/'))
res.push_back(i);
else {
res.push_back('%');
auto&&[c1, c2] = encodeHex2(i);
res.push_back(c1);
res.push_back(c2);
}
}
return res;
}
map<string, string> decodeFormUrlEncoded(string body) {
map<string, string> ans;
int i = 0;
while (i < body.size()) {
pair<string, string> cur;
while (body[i] == '&') i++;
while (body[i] != '=')
cur.first.push_back(body[i++]);
while (body[i] == '=') i++;
while (i < body.size() && body[i] != '&')
cur.second.push_back(body[i++]);
ans.insert(make_pair(decodePercentEncoding(cur.first), decodePercentEncoding(cur.second)));
}
return ans;
}
string encodeCookieSequence(const vector<pair<string, string>>& cookies) {
string ans;
for (auto&[id, body] : cookies) {
if (!ans.empty())
ans += "; ";
ans += id + '=' + body;
}
return ans;
}
map<string, string> decodeCookieSequence(string body) {
map<string, string> ans;
int i = 0;
while (i < body.size()) {
pair<string, string> cur;
while (body[i] == ';') i++;
while (body[i] == ' ') i++;
while (body[i] != '=')
cur.first.push_back(body[i++]);
while (body[i] == '=') i++;
while (i < body.size() && body[i] != ';')
cur.second.push_back(body[i++]);
ans.insert(make_pair(decodePercentEncoding(cur.first), decodePercentEncoding(cur.second)));
}
return ans;
}
string readFileBinary(const wstring& filename) {
ifstream file(filename, ifstream::binary);
if (!file)
return string();
// Get the file size
file.ignore(numeric_limits<streamsize>::max());
size_t fileSize = (size_t)file.gcount();
file.seekg(0, ifstream::beg);
// Read
string res(fileSize, '\0');
file.read(res.data(), fileSize);
return res;
}
string readFileBinaryCached(const wstring& filename) {
auto i = fileCache.find(filename);
if (i == fileCache.end() || chrono::steady_clock::now() - i->second.first > reloadCachedFileDuration) {
// Load or reload the file
if (i == fileCache.end())
i = fileCache.insert(make_pair(filename, make_pair(chrono::steady_clock::now(), ""))).first;
else
i->second.first = chrono::steady_clock::now();
ifstream file(filename, ifstream::binary);
if (!file)
return string();
// Get the file size
file.ignore(numeric_limits<streamsize>::max());
size_t fileSize = (size_t)file.gcount();
file.seekg(0, ifstream::beg);
string& res = i->second.second;
res.clear(); res.resize(fileSize); res.shrink_to_fit();
file.read(res.data(), fileSize);
}
return i->second.second;
}
string toUppercase(const string& str) {
string ans;
for (char c : str) {
if (c > 0)
ans.push_back(toupper(c));
else
ans.push_back(c);
}
return ans;
}
string generateCookie(int length) {
string str;
str.reserve(length);
for (int i = 1; i <= length; i++) {
if (rand(0, 1)) // Uppercase
str.push_back('A' + rand(0, 25));
else // Lowercase
str.push_back('a' + rand(0, 25));
}
return str;
}
| 26.02381 | 134 | 0.640439 | [
"vector"
] |
6be0a3dfd1352d1a715f4dcc2287059e3eb1e17f | 16,479 | cpp | C++ | Unbound/RenderBackendVulkan.cpp | dreti-uoguelph/Unbound | ffbb4da324673095f4764b4275a88b1855d88800 | [
"MIT"
] | null | null | null | Unbound/RenderBackendVulkan.cpp | dreti-uoguelph/Unbound | ffbb4da324673095f4764b4275a88b1855d88800 | [
"MIT"
] | null | null | null | Unbound/RenderBackendVulkan.cpp | dreti-uoguelph/Unbound | ffbb4da324673095f4764b4275a88b1855d88800 | [
"MIT"
] | null | null | null | #pragma once
#include "stdafx.h"
#ifdef UNBOUND_BACKEND_VULKAN
#include "RenderBackendVulkan.h"
namespace Unbound
{
namespace Graphics
{
void RenderBackendVulkan::init()
{
vulkanInit();
}
void RenderBackendVulkan::drawFrame()
{
//Acquire an image from the swap chain
uint32_t imageIndex = 0;
VkResult result = vkAcquireNextImageKHR(devices.device, swapChain.swapChain, UINT64_MAX, semaphores.imageAcquiredSemaphore, VK_NULL_HANDLE, &imageIndex);
if (result == VK_ERROR_OUT_OF_DATE_KHR)
{
Vulkan::recreateSwapChain(devices, buffers, swapChain, pipeline, targetWindowInfo);
return;
}
else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
{
Logger::log("Error: could not acquire an image on the swap chain for rendering");
return;
}
//Submit the command buffer
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores = { semaphores.imageAcquiredSemaphore };
VkPipelineStageFlags waitStages = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &waitSemaphores;
submitInfo.pWaitDstStageMask = &waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &pipeline.commandBuffers[0][imageIndex];
VkSemaphore signalSemaphores = { semaphores.renderFinishedSemaphore };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &signalSemaphores;
if (vkQueueSubmit(pipeline.graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE) != VK_SUCCESS)
{
Logger::log("Error: could not submit command queue for rendering");
return;
}
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &signalSemaphores;
VkSwapchainKHR swapChains = { swapChain.swapChain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &swapChains;
presentInfo.pImageIndices = &imageIndex;
presentInfo.pResults = nullptr;
result = vkQueuePresentKHR(pipeline.presentQueue, &presentInfo);
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR)
{
Vulkan::recreateSwapChain(devices, buffers, swapChain, pipeline, targetWindowInfo);
}
else if (result != VK_SUCCESS)
{
Logger::log("Error: could not present swap chain image to window");
return;
}
if (debug.enableValidationLayers)
{
vkQueueWaitIdle(pipeline.presentQueue);
}
MemoryManager::get()->vertexStagingPool.flush();
MemoryManager::get()->indexStagingPool.flush();
MemoryManager::get()->textureStagingPool.flush();
}
void RenderBackendVulkan::close()
{
vkDeviceWaitIdle(devices.device);
Vulkan::destroyBuffers(devices, pipeline, buffers);
Vulkan::destroySemaphores(devices, semaphores);
Vulkan::cleanupSwapchain(devices, swapChain, pipeline);
vkDestroyDescriptorPool(devices.device, pipeline.descriptorPool, nullptr);
//Destroy the descriptor set
vkDestroyDescriptorSetLayout(devices.device, pipeline.descriptorLayout, nullptr);
vkDestroyCommandPool(devices.device, pipeline.commandPools[0], nullptr);
vkDestroyCommandPool(devices.device, pipeline.copyCommandPool, nullptr);
for (auto i : pipeline.shaderModules)
{
vkDestroyShaderModule(devices.device, i, nullptr);
}
vkDestroyDevice(devices.device, nullptr);
if (debug.enableValidationLayers)
{
Vulkan::DestroyDebugReportCallbackEXT(vulkanInstance.instance, debug.debugCallbackHandle, nullptr);
}
vkDestroySurfaceKHR(vulkanInstance.instance, swapChain.renderSurface, nullptr);
vkDestroyInstance(vulkanInstance.instance, nullptr);
}
//Call to add new shaders to the renderer. Not recommended to call this during runtime as it is quite slow
void RenderBackendVulkan::addShaders(std::vector<Graphics::Shader>& toAdd)
{
}
//Add new vertex geometry to the renderer
void RenderBackendVulkan::addGeometry(Mesh& toAdd)
{
//Update the mesh's buffer offsets
toAdd.bufferStartIndex = static_cast<uint32_t>(buffers.numIndices);
toAdd.vertexOffset = static_cast<uint32_t>(buffers.numVertices);
//Add the geometry data to the staging buffer
memcpy(MemoryManager::get()->vertexStagingPool.addData(toAdd.numVertices * sizeof(Vertex)), toAdd.vertices, toAdd.numVertices * sizeof(Vertex));
memcpy(MemoryManager::get()->indexStagingPool.addData(toAdd.numIndices * sizeof(uint32_t)), toAdd.indices, toAdd.numIndices * sizeof(uint32_t));
//Copy new vertices into the vertex buffer
Vulkan::updateVertexBuffer(devices, pipeline, buffers);
//Update the command buffers with any changes
updateCommandBuffers();
}
//Adds new image data to the render backend, generates required buffers and creates resources
void RenderBackendVulkan::addImageData(Image& toAdd)
{
Vulkan::createTextureImage(devices, swapChain, pipeline, buffers, toAdd, buffers.textureImages[buffers.nextFreeImageIndex], buffers.textureDeviceMemory[buffers.nextFreeImageIndex]);
buffers.textureImageViews[buffers.nextFreeImageIndex] = Vulkan::createImageView(devices, buffers.textureImages[buffers.nextFreeImageIndex], VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_ASPECT_COLOR_BIT);
//If the next image is free, then increment the next free image index. Otherwise, set it to the end index and increment that
if (buffers.textureImages[buffers.nextFreeImageIndex + 1] == NULL)
{
buffers.nextFreeImageIndex++;
buffers.endFreeImageIndex++;
}
else
{
buffers.nextFreeImageIndex = buffers.endFreeImageIndex;
buffers.endFreeImageIndex++;
}
if (pipeline.commandBuffers.size() > 0)
{
Vulkan::updateDescriptorSets(devices, pipeline, buffers);
updateCommandBuffers();
}
}
//Add terrain data to the render backend, using specialized buffers
void RenderBackendVulkan::addTerrainData(Terrain& toAdd)
{
//Add the geometry data to the staging buffers
for (uint32_t i = 0; i < toAdd.getNumChunks(); i++)
{
memcpy(MemoryManager::get()->vertexStagingPool.addData(toAdd.getNumVerticesPerChunk() * sizeof(Vertex)), (toAdd.getData() + i)->vertices, toAdd.getNumVerticesPerChunk() * sizeof(Vertex));
}
for (uint32_t i = 0; i < toAdd.getNumChunks(); i++)
{
memcpy(MemoryManager::get()->indexStagingPool.addData(toAdd.getNumIndicesPerChunk() * sizeof(uint32_t)), (toAdd.getData() + i)->indices, toAdd.getNumIndicesPerChunk() * sizeof(uint32_t));
}
buffers.terrainStartIndex = static_cast<uint32_t>(buffers.numIndices);
buffers.terrainVertexOffset = static_cast<uint32_t>(buffers.numVertices);
buffers.numTerrainIndices = toAdd.getNumIndices();
buffers.numTerrainVertices = toAdd.getNumVertices();
//Copy new vertices into the vertex buffer
Vulkan::updateVertexBuffer(devices, pipeline, buffers);
Logger::log("Loaded terrain into renderer...");
//Update the command buffers with any changes
updateCommandBuffers();
}
/*Update the structure sent to the vertex shader with new world, view and projection matrices*/
void RenderBackendVulkan::updateMatrices(const glm::mat4& world, const glm::mat4& view, const glm::mat4& projection)
{
buffers.matricesToSend = { view, projection };
Vulkan::updateUniformBuffer(buffers);
}
/*Update only the world matrix. This should usually be done once per object*/
void RenderBackendVulkan::updateWorldMatrix(const glm::mat4& world)
{
buffers.mainPushConstants.world = world;
}
/*Update only the view matrix. This only has to be done once per frame*/
void RenderBackendVulkan::updateViewMatrix(const glm::mat4& view)
{
buffers.matricesToSend.view = view;
Vulkan::updateUniformBuffer(buffers);
}
/*Update only the projection matrix. This only has to be done when camera properties change or when the window is resized*/
void RenderBackendVulkan::updateProjectionMatrix(const glm::mat4& projection)
{
buffers.matricesToSend.projection = projection;
Vulkan::updateUniformBuffer(buffers);
}
//Get the next available image index in the renderer, used to load images
const uint32_t & RenderBackendVulkan::getNextFreeImageIndex() const
{
return buffers.nextFreeImageIndex;
}
RenderBackendVulkan::RenderBackendVulkan(const WindowInfo& windowInfoToSet, const std::vector<Shader>& shadersToSet) : targetWindowInfo(const_cast<WindowInfo&>(windowInfoToSet)), pipeline(const_cast<std::vector<Graphics::Shader>&>(shadersToSet))
{
}
RenderBackendVulkan::~RenderBackendVulkan()
{
}
/*Calls other functions to fully initialize the vulkan backend.
Takes no arguments, but the render window and desired renderer
Settings should be loaded before this is called
*/
void RenderBackendVulkan::vulkanInit()
{
devices.deviceExtensionsToUse = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
Vulkan::createVulkanInstance(devices, vulkanInstance, debug, targetWindowInfo);
Vulkan::setupDebugCallback(vulkanInstance, debug);
createVulkanSurface();
Vulkan::initializePhysicalDevices(devices, swapChain, vulkanInstance);
Vulkan::createLogicalDevice(devices, swapChain, pipeline);
Vulkan::createSwapChain(devices, swapChain, targetWindowInfo);
swapChain.depthFormat = Vulkan::findDepthFormat(devices);
Vulkan::createTextureSamplers(devices, pipeline);
Vulkan::createRenderPass(devices, swapChain, pipeline);
createCommandPool();
Vulkan::createDescriptorPool(devices, buffers, pipeline);
Vulkan::createDescriptorSetLayout(devices, buffers, pipeline);
Vulkan::initializeGraphicsPipeline(devices, pipeline, swapChain);
Vulkan::createDepthBuffer(devices, buffers, swapChain, pipeline);
Vulkan::createFrameBuffers(devices, swapChain, pipeline);
Vulkan::createVertexBuffers(devices, buffers);
Vulkan::createIndexBuffers(devices, buffers);
Vulkan::createUniformBuffers(devices, buffers);
Vulkan::createImageBuffer(devices, pipeline, buffers);
Vulkan::createDescriptorSets(devices, pipeline, swapChain, buffers);
createCommandBuffers();
Vulkan::createSemaphores(devices, semaphores);
updateCommandBuffers();
initialized = true;
}
/*Creates the render surface that will be presented to*/
void RenderBackendVulkan::createVulkanSurface()
{
if (glfwCreateWindowSurface(vulkanInstance.instance, targetWindowInfo.window, nullptr, &swapChain.renderSurface) != VK_SUCCESS)
{
throw std::runtime_error("Could not get target render surface from glfw");
}
}
/*Create the command pool for rendering*/
void RenderBackendVulkan::createCommandPool()
{
//Create the main command pool and command pools for each thread
Vulkan::QueueFamilyIndices queueIndices = Vulkan::findQueueFamilies(devices.physicalDevice, swapChain);
VkCommandPoolCreateInfo poolCreateInfo = {};
poolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolCreateInfo.queueFamilyIndex = queueIndices.graphicsFamily;
poolCreateInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
for (uint32_t i = 0; i < pipeline.commandPools.size(); i++)
{
if (vkCreateCommandPool(devices.device, &poolCreateInfo, nullptr, &pipeline.commandPools[i]) != VK_SUCCESS)
{
throw std::runtime_error("Could not create command pool");
}
}
//Create the copy command pool
VkCommandPoolCreateInfo copyPoolCreateInfo = {};
copyPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
copyPoolCreateInfo.queueFamilyIndex = queueIndices.graphicsFamily;
copyPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
if (vkCreateCommandPool(devices.device, ©PoolCreateInfo, nullptr, &pipeline.copyCommandPool) != VK_SUCCESS)
{
throw std::runtime_error("Could not create command pool");
}
}
/*Create the command buffers for drawing to the screen*/
void RenderBackendVulkan::createCommandBuffers()
{
//Create command buffers for each image in the swapchain
pipeline.commandBuffers.resize(swapChain.frameBuffers.size());
VkCommandBufferAllocateInfo commandBufferInfo = {};
commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferInfo.commandPool = pipeline.commandPools[0];
commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferInfo.commandBufferCount = static_cast<uint32_t>(pipeline.commandBuffers[0].size());
if (vkAllocateCommandBuffers(devices.device, &commandBufferInfo, pipeline.commandBuffers[0].data()) != VK_SUCCESS)
{
Logger::log("Error: could not create command buffers for rendering");
throw std::runtime_error("Could not allocate command buffers for drawing to the screen");
}
updateCommandBuffers();
}
//Update the command buffers with new instructions
void RenderBackendVulkan::updateCommandBuffers()
{
vkQueueWaitIdle(pipeline.graphicsQueue);
vkDeviceWaitIdle(devices.device);
//Record the same intructions in each command buffer
for (size_t i = 0; i < pipeline.commandBuffers.size(); i++)
{
vkResetCommandBuffer(pipeline.commandBuffers[0][i], VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT);
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
beginInfo.pInheritanceInfo = nullptr;
if (vkBeginCommandBuffer(pipeline.commandBuffers[0][i], &beginInfo) != VK_SUCCESS)
{
Logger::log("Error: could not begin recording commands in command buffer for rendering");
return;
}
VkRenderPassBeginInfo renderBeginInfo = {};
renderBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderBeginInfo.renderPass = swapChain.mainRenderPass;
renderBeginInfo.framebuffer = swapChain.frameBuffers[i];
renderBeginInfo.renderArea.offset = { 0, 0 };
renderBeginInfo.renderArea.extent = swapChain.extent;
std::array<VkClearValue, 2> clearValues = {};
clearValues[0].color = { 0.0f, 0.0f, 0.0f, 1.0f };
clearValues[1].depthStencil = { 1.0f, 0 };
renderBeginInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
renderBeginInfo.pClearValues = clearValues.data();
vkCmdBeginRenderPass(pipeline.commandBuffers[0][i], &renderBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(pipeline.commandBuffers[0][i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.renderPipeline);
if (initialized)
{
//Bind the vertex buffer
VkBuffer vertexBuffers[] = { buffers.vertexBuffer };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(pipeline.commandBuffers[0][i], 0, 1, vertexBuffers, offsets);
//Bind the index buffer
vkCmdBindIndexBuffer(pipeline.commandBuffers[0][i], buffers.indexBuffer, 0, VK_INDEX_TYPE_UINT32);
//Bind the descriptor sets
vkCmdBindDescriptorSets(pipeline.commandBuffers[0][i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.pipelineLayout, 0, 1, &pipeline.descriptorSet, 0, nullptr);
//Start by drawing the terrain
updateWorldMatrix(glm::mat4());
buffers.mainPushConstants.albedoID = 0;
vkCmdPushConstants(pipeline.commandBuffers[0][i], pipeline.pipelineLayout, VK_SHADER_STAGE_ALL, 0, sizeof(Vulkan::MainPushConstant), &buffers.mainPushConstants);
vkCmdDrawIndexed(pipeline.commandBuffers[0][i], buffers.numTerrainIndices, 1, buffers.terrainStartIndex, buffers.terrainVertexOffset, 0);
for (auto m : *models)
{
//Update world matrix
updateWorldMatrix(m.transform.getTransformMatrix());
//Push constants
buffers.mainPushConstants.albedoID = m.material.albedo.getBoundID();
vkCmdPushConstants(pipeline.commandBuffers[0][i], pipeline.pipelineLayout, VK_SHADER_STAGE_ALL, 0, sizeof(Vulkan::MainPushConstant), &buffers.mainPushConstants);
//Draw the model
drawModel(m, pipeline.commandBuffers[0][i]);
}
}
vkCmdEndRenderPass(pipeline.commandBuffers[0][i]);
if (vkEndCommandBuffer(pipeline.commandBuffers[0][i]) != VK_SUCCESS)
{
Logger::log("Error: could not write render pass to command buffer");
return;
}
}
}
//Draw a model
void RenderBackendVulkan::drawModel(Model& toDraw, VkCommandBuffer& target)
{
//Draw all the model indices
vkCmdDrawIndexed(target, toDraw.mesh.numIndices, 1, toDraw.mesh.bufferStartIndex, toDraw.mesh.vertexOffset, 0);
}
}
}
#endif | 38.957447 | 247 | 0.75399 | [
"mesh",
"geometry",
"render",
"object",
"vector",
"model",
"transform"
] |
6be99e8238eca11f9ddfa5395bba239d458abc17 | 6,290 | cpp | C++ | test/unit-tests/array/partition/nvm_partition_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | test/unit-tests/array/partition/nvm_partition_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | test/unit-tests/array/partition/nvm_partition_test.cpp | YongJin-Cho/poseidonos | c07a0240316d4536aa09f22d7977604f3650d752 | [
"BSD-3-Clause"
] | null | null | null | #include "src/array/partition/nvm_partition.h"
#include <gtest/gtest.h>
#include "src/include/array_config.h"
#include "src/include/pos_event_id.h"
#include "test/unit-tests/array/ft/buffer_entry_mock.h"
namespace pos
{
static LogicalBlkAddr
buildValidLogicalBlkAddr(uint32_t totalStripes, uint32_t blksPerStripe)
{
LogicalBlkAddr lBlkAddr{
.stripeId = totalStripes / 2,
.offset = 0};
return lBlkAddr;
}
static LogicalBlkAddr
buildInvalidLogicalBlkAddr(uint32_t totalStripes)
{
LogicalBlkAddr lBlkAddr{
.stripeId = totalStripes + 1,
.offset = 0};
return lBlkAddr;
}
static LogicalWriteEntry
buildValidLogicalWriteEntry(uint32_t totalStripes, uint32_t blksPerStripe)
{
LogicalBlkAddr lBlkAddr{
.stripeId = totalStripes / 2,
.offset = 0};
std::list<BufferEntry>* fakeBuffers = new std::list<BufferEntry>;
MockBufferEntry mockBuffer(nullptr, 0, false);
fakeBuffers->push_back(mockBuffer);
LogicalWriteEntry lWriteEntry{
.addr = lBlkAddr,
.blkCnt = blksPerStripe / 2,
.buffers = fakeBuffers};
return lWriteEntry;
}
static LogicalWriteEntry
buildInvalidLogicalWriteEntry(uint32_t totalStripes, uint32_t blksPerStripe)
{
LogicalBlkAddr lBlkAddr{
.stripeId = totalStripes / 2,
.offset = 0};
LogicalWriteEntry lWriteEntry{
.addr = lBlkAddr,
.blkCnt = blksPerStripe + 1, // intentionally making it too big
.buffers = nullptr};
return lWriteEntry;
}
TEST(NvmPartition, NvmPartition_testIfConstructorInitializesLogicalSizeProperly)
{
// Given
PartitionPhysicalSize partPhySize{
.blksPerChunk = 100,
.chunksPerStripe = 10,
.stripesPerSegment = 5,
.totalSegments = 2};
vector<ArrayDevice*> devs;
// When
NvmPartition nvmPart("mock-array", PartitionType::META_NVM, partPhySize, devs);
// Then
const PartitionLogicalSize* pLogicalSize = nvmPart.GetLogicalSize();
ASSERT_EQ(1, pLogicalSize->minWriteBlkCnt);
ASSERT_EQ(partPhySize.blksPerChunk, pLogicalSize->blksPerChunk);
ASSERT_EQ(partPhySize.blksPerChunk * partPhySize.chunksPerStripe, pLogicalSize->blksPerStripe);
ASSERT_EQ(partPhySize.stripesPerSegment * partPhySize.totalSegments, pLogicalSize->totalStripes);
ASSERT_EQ(partPhySize.totalSegments, pLogicalSize->totalSegments);
ASSERT_EQ(partPhySize.stripesPerSegment, pLogicalSize->stripesPerSegment);
}
TEST(NvmPartition, Translate_testIfInvalidAddressReturnsError)
{
// Given
PartitionPhysicalSize partPhySize{
.blksPerChunk = 100,
.chunksPerStripe = 10,
.stripesPerSegment = 5,
.totalSegments = 2};
uint32_t totalStripes = partPhySize.stripesPerSegment * partPhySize.totalSegments;
uint32_t blksPerStripe = partPhySize.blksPerChunk * partPhySize.chunksPerStripe;
LogicalBlkAddr invalidAddr = buildInvalidLogicalBlkAddr(totalStripes);
vector<ArrayDevice*> devs;
NvmPartition nvmPart("mock-array", PartitionType::META_NVM, partPhySize, devs);
PhysicalBlkAddr ignored;
// When
int actual = nvmPart.Translate(ignored, invalidAddr);
// Then
ASSERT_EQ(EID(ARRAY_INVALID_ADDRESS_ERROR), actual);
}
TEST(NvmPartition, Translate_testIfValidAddressIsFilledIn)
{
// Given
PartitionPhysicalSize partPhySize{
.startLba = 8192,
.blksPerChunk = 100,
.chunksPerStripe = 10,
.stripesPerSegment = 5,
.totalSegments = 2};
uint32_t totalStripes = partPhySize.stripesPerSegment * partPhySize.totalSegments;
uint32_t blksPerStripe = partPhySize.blksPerChunk * partPhySize.chunksPerStripe;
LogicalBlkAddr validAddr = buildValidLogicalBlkAddr(totalStripes, blksPerStripe);
vector<ArrayDevice*> devs;
devs.push_back(nullptr); // putting dummy 'cause I'm not interested
NvmPartition nvmPart("mock-array", PartitionType::META_NVM, partPhySize, devs);
PhysicalBlkAddr dest;
// When
int actual = nvmPart.Translate(dest, validAddr);
// Then
ASSERT_EQ(0, actual);
int expectedSrcBlock = totalStripes / 2 * nvmPart.GetLogicalSize()->blksPerStripe;
int expectedSrcSector = expectedSrcBlock * ArrayConfig::SECTORS_PER_BLOCK;
int expectedDestSector = expectedSrcSector + partPhySize.startLba;
ASSERT_EQ(expectedDestSector, dest.lba);
}
TEST(NvmPartition, Convert_testIfInvalidEntryReturnsError)
{
// Given
PartitionPhysicalSize partPhySize{
.blksPerChunk = 100,
.chunksPerStripe = 10,
.stripesPerSegment = 5,
.totalSegments = 2};
uint32_t totalStripes = partPhySize.stripesPerSegment * partPhySize.totalSegments;
uint32_t blksPerStripe = partPhySize.blksPerChunk * partPhySize.chunksPerStripe;
LogicalWriteEntry invalidEntry = buildInvalidLogicalWriteEntry(totalStripes, blksPerStripe);
vector<ArrayDevice*> devs;
NvmPartition nvmPart("mock-array", PartitionType::META_NVM, partPhySize, devs);
std::list<PhysicalWriteEntry> ignored;
// When
int actual = nvmPart.Convert(ignored, invalidEntry);
// Then
ASSERT_EQ(EID(ARRAY_INVALID_ADDRESS_ERROR), actual);
}
TEST(NvmPartition, Convert_testIfValidEntryIsFilledIn)
{
// Given
PartitionPhysicalSize partPhySize{
.startLba = 8192,
.blksPerChunk = 100,
.chunksPerStripe = 10,
.stripesPerSegment = 5,
.totalSegments = 2};
uint32_t totalStripes = partPhySize.stripesPerSegment * partPhySize.totalSegments;
uint32_t blksPerStripe = partPhySize.blksPerChunk * partPhySize.chunksPerStripe;
LogicalWriteEntry validEntry = buildValidLogicalWriteEntry(totalStripes, blksPerStripe);
vector<ArrayDevice*> devs;
devs.push_back(nullptr); // 'cause I'm not interested
NvmPartition nvmPart("mock-array", PartitionType::META_NVM, partPhySize, devs);
std::list<PhysicalWriteEntry> dest;
// When
int actual = nvmPart.Convert(dest, validEntry);
// Then
ASSERT_EQ(1, dest.size());
PhysicalWriteEntry pWriteEntry = dest.front();
ASSERT_EQ(validEntry.blkCnt, pWriteEntry.blkCnt);
PhysicalBlkAddr phyBlkAddr = pWriteEntry.addr;
// The validation on phyBlkAddr will be skipped for now since it's already done as part of Translate() UT.
}
} // namespace pos
| 33.280423 | 110 | 0.727027 | [
"vector"
] |
6bea90344eb4c7dc6030da049b2f726a894b5ee5 | 150,417 | cpp | C++ | _vscp_common/restsrv.cpp | benys/vscpworks | 755a1733d0c55c8dd22d65e0e1ed1598311ef999 | [
"MIT"
] | 1 | 2022-01-24T20:21:09.000Z | 2022-01-24T20:21:09.000Z | _vscp_common/restsrv.cpp | benys/vscpworks | 755a1733d0c55c8dd22d65e0e1ed1598311ef999 | [
"MIT"
] | 1 | 2020-05-05T18:40:57.000Z | 2020-05-05T18:40:57.000Z | _vscp_common/restsrv.cpp | benys/vscpworks | 755a1733d0c55c8dd22d65e0e1ed1598311ef999 | [
"MIT"
] | 1 | 2020-05-05T08:07:32.000Z | 2020-05-05T08:07:32.000Z | // restsrv.cpp
//
// This file is part of the VSCP (http://www.vscp.org)
//
// The MIT License (MIT)
//
// Copyright (c) 2000-2018 Ake Hedman, Grodans Paradis AB <info@grodansparadis.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.
//
#ifdef __GNUG__
//#pragma implementation
#endif
#ifdef WIN32
#include <winsock2.h>
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/wx.h"
#include "wx/defs.h"
#include "wx/app.h"
#include <wx/xml/xml.h>
#include <wx/txtstrm.h>
#include <wx/platinfo.h>
#include <wx/filename.h>
#include <iostream>
#include <sstream>
#include <fstream>
#ifdef WIN32
#include <winsock2.h>
#include "canal_win32_ipc.h"
#else // UNIX
#define _POSIX
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include <syslog.h>
#include <sys/msg.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <string.h>
#include <netdb.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <net/if_arp.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <linux/sockios.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "wx/wx.h"
#include "wx/defs.h"
#include "wx/log.h"
#include "wx/socket.h"
#endif
#include <wx/config.h>
#include <wx/wfstream.h>
#include <wx/fileconf.h>
#include <wx/tokenzr.h>
#include <wx/listimpl.cpp>
#include <wx/xml/xml.h>
#include <wx/mimetype.h>
#include <wx/filename.h>
#include "web_css.h"
#include "web_js.h"
#include "web_template.h"
#include <json.hpp> // Needs C++11 -std=c++11
#include <vscp.h>
#include <vscphelper.h>
#include <vscpeventhelper.h>
#include <tables.h>
#include <vscp_aes.h>
#include <version.h>
#include <controlobject.h>
#include <variablecodes.h>
#include <actioncodes.h>
#include <devicelist.h>
#include <devicethread.h>
#include <dm.h>
#include <mdf.h>
#include <httpd.h>
#include <websrv.h>
#include <restsrv.h>
using namespace std;
// https://github.com/nlohmann/json
using json = nlohmann::json;
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
///////////////////////////////////////////////////
// GLOBALS
///////////////////////////////////////////////////
extern CControlObject *gpobj;
// Prototypes
void
restsrv_doStatus( struct web_connection *conn,
struct restsrv_session *pSession,
int format );
void
restsrv_doOpen( struct web_connection *conn,
struct restsrv_session *pSession,
int format );
void
restsrv_doClose( struct web_connection *conn,
struct restsrv_session *pSession,
int format );
void
restsrv_doSendEvent( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
vscpEvent *pEvent );
void
restsrv_doReceiveEvent( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
size_t count );
void
restsrv_doReceiveEvent( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
size_t count );
void
restsrv_doSetFilter( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
vscpEventFilter& vscpfilter );
void
restsrv_doClearQueue( struct web_connection *conn,
struct restsrv_session *pSession,
int format );
void
restsrv_doListVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strRegEx,
bool bShort );
void
restsrv_doListVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strRegEx,
bool bShort );
void
restsrv_doReadVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariableName );
void
restsrv_doWriteVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariableName,
wxString& strValue );
void
restsrv_doCreateVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariable,
wxString& strType,
wxString& strValue,
wxString& strPersistent,
wxString& strAccessRight,
wxString& strNote );
void
restsrv_doDeleteVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariable );
void
restsrv_doWriteMeasurement( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strDateTime,
wxString& strGuid,
wxString& strLevel,
wxString& strType,
wxString& strValue,
wxString& strUnit,
wxString& strSensorIdx,
wxString& strZone,
wxString& strSubZone,
wxString& strEventFormat );
void
websrc_renderTableData( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strName,
struct _vscpFileRecord *pRecords,
long nfetchedRecords );
void
restsrv_doFetchMDF( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strURL );
void
websrc_renderTableData( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strName,
struct _vscpFileRecord *pRecords,
long nfetchedRecords );
void
restsrv_doGetTableData( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strName,
wxString& strFrom,
wxString& strTo );
const char* rest_errors[][ REST_FORMAT_COUNT + 1 ] = {
{ REST_PLAIN_ERROR_SUCCESS, REST_CSV_ERROR_SUCCESS, REST_XML_ERROR_SUCCESS, REST_JSON_ERROR_SUCCESS, REST_JSONP_ERROR_SUCCESS },
{ REST_PLAIN_ERROR_GENERAL_FAILURE, REST_CSV_ERROR_GENERAL_FAILURE, REST_XML_ERROR_GENERAL_FAILURE, REST_JSON_ERROR_GENERAL_FAILURE, REST_JSONP_ERROR_GENERAL_FAILURE },
{ REST_PLAIN_ERROR_INVALID_SESSION, REST_CSV_ERROR_INVALID_SESSION, REST_XML_ERROR_INVALID_SESSION, REST_JSON_ERROR_INVALID_SESSION, REST_JSONP_ERROR_INVALID_SESSION },
{ REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, REST_CSV_ERROR_UNSUPPORTED_FORMAT, REST_XML_ERROR_UNSUPPORTED_FORMAT, REST_JSON_ERROR_UNSUPPORTED_FORMAT, REST_JSONP_ERROR_UNSUPPORTED_FORMAT },
{ REST_PLAIN_ERROR_COULD_NOT_OPEN_SESSION, REST_CSV_ERROR_COULD_NOT_OPEN_SESSION, REST_XML_ERROR_COULD_NOT_OPEN_SESSION, REST_JSON_ERROR_COULD_NOT_OPEN_SESSION, REST_JSONP_ERROR_COULD_NOT_OPEN_SESSION },
{ REST_PLAIN_ERROR_MISSING_DATA, REST_CSV_ERROR_MISSING_DATA, REST_XML_ERROR_MISSING_DATA, REST_JSON_ERROR_MISSING_DATA, REST_JSONP_ERROR_MISSING_DATA },
{ REST_PLAIN_ERROR_INPUT_QUEUE_EMPTY, REST_CSV_ERROR_INPUT_QUEUE_EMPTY, REST_XML_ERROR_INPUT_QUEUE_EMPTY, REST_JSON_ERROR_INPUT_QUEUE_EMPTY, REST_JSONP_ERROR_INPUT_QUEUE_EMPTY },
{ REST_PLAIN_ERROR_VARIABLE_NOT_FOUND, REST_CSV_ERROR_VARIABLE_NOT_FOUND, REST_XML_ERROR_VARIABLE_NOT_FOUND, REST_JSON_ERROR_VARIABLE_NOT_FOUND, REST_JSONP_ERROR_VARIABLE_NOT_FOUND },
{ REST_PLAIN_ERROR_VARIABLE_NOT_CREATED, REST_CSV_ERROR_VARIABLE_NOT_CREATED, REST_XML_ERROR_VARIABLE_NOT_CREATED, REST_JSON_ERROR_VARIABLE_NOT_CREATED, REST_JSONP_ERROR_VARIABLE_NOT_CREATED },
{ REST_PLAIN_ERROR_VARIABLE_FAIL_UPDATE, REST_CSV_ERROR_VARIABLE_FAIL_UPDATE, REST_XML_ERROR_VARIABLE_FAIL_UPDATE, REST_JSON_ERROR_VARIABLE_FAIL_UPDATE, REST_JSONP_ERROR_VARIABLE_FAIL_UPDATE },
{ REST_PLAIN_ERROR_NO_ROOM, REST_CSV_ERROR_NO_ROOM, REST_XML_ERROR_NO_ROOM, REST_JSON_ERROR_NO_ROOM, REST_JSONP_ERROR_NO_ROOM },
{ REST_PLAIN_ERROR_TABLE_NOT_FOUND, REST_CSV_ERROR_TABLE_NOT_FOUND, REST_XML_ERROR_TABLE_NOT_FOUND, REST_JSON_ERROR_TABLE_NOT_FOUND, REST_JSONP_ERROR_TABLE_NOT_FOUND, },
{ REST_PLAIN_ERROR_TABLE_NO_DATA, REST_CSV_ERROR_TABLE_NO_DATA, REST_XML_ERROR_TABLE_NO_DATA, REST_JSON_ERROR_TABLE_NO_DATA, REST_JSONP_ERROR_TABLE_NO_DATA },
{ REST_PLAIN_ERROR_TABLE_RANGE, REST_CSV_ERROR_TABLE_RANGE, REST_XML_ERROR_TABLE_RANGE, REST_JSON_ERROR_TABLE_RANGE, REST_JSONP_ERROR_TABLE_RANGE },
{ REST_PLAIN_ERROR_INVALID_USER, REST_CSV_ERROR_INVALID_USER, REST_XML_ERROR_INVALID_USER, REST_JSON_ERROR_INVALID_USER, REST_JSONP_ERROR_INVALID_USER },
{ REST_PLAIN_ERROR_INVALID_ORIGIN, REST_CSV_ERROR_INVALID_ORIGIN, REST_XML_ERROR_INVALID_ORIGIN, REST_JSON_ERROR_INVALID_ORIGIN, REST_JSONP_ERROR_INVALID_ORIGIN },
{ REST_PLAIN_ERROR_INVALID_PASSWORD, REST_CSV_ERROR_INVALID_PASSWORD, REST_XML_ERROR_INVALID_PASSWORD, REST_JSON_ERROR_INVALID_PASSWORD, REST_JSONP_ERROR_INVALID_PASSWORD },
{ REST_PLAIN_ERROR_MEMORY, REST_CSV_ERROR_MEMORY, REST_XML_ERROR_MEMORY, REST_JSON_ERROR_MEMORY, REST_JSONP_ERROR_MEMORY },
{ REST_PLAIN_ERROR_VARIABLE_NOT_DELETE, REST_CSV_ERROR_VARIABLE_NOT_DELETE, REST_XML_ERROR_VARIABLE_NOT_DELETE, REST_JSON_ERROR_VARIABLE_NOT_DELETE, REST_JSONP_ERROR_VARIABLE_NOT_DELETE },
};
//-----------------------------------------------------------------------------
// REST
//-----------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// restsrv_error
//
void
restsrv_error( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
int errorcode)
{
char buf[2048];
int returncode = 200;
if ( REST_FORMAT_PLAIN == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_PLAIN );
web_write( conn,
rest_errors[errorcode][REST_FORMAT_PLAIN],
strlen( rest_errors[errorcode][REST_FORMAT_PLAIN] ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_CSV == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_CSV );
web_write( conn,
rest_errors[errorcode][REST_FORMAT_CSV],
strlen( rest_errors[errorcode][REST_FORMAT_CSV] ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_XML == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_XML );
web_write( conn, XML_HEADER, strlen( XML_HEADER ) );
web_write( conn,
rest_errors[errorcode][REST_FORMAT_XML],
strlen( rest_errors[errorcode][REST_FORMAT_XML] ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_JSON == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_JSON );
web_write( conn,
rest_errors[errorcode][REST_FORMAT_JSON],
strlen( rest_errors[errorcode][REST_FORMAT_JSON] ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_JSONP == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_JSONP );
web_write( conn,
rest_errors[errorcode][REST_FORMAT_JSONP],
strlen( rest_errors[errorcode][REST_FORMAT_JSONP] ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_PLAIN );
web_write( conn,
REST_PLAIN_ERROR_UNSUPPORTED_FORMAT,
strlen( REST_PLAIN_ERROR_UNSUPPORTED_FORMAT ) );
web_write( conn, "", 0 ); // Terminator
return;
}
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_sendHeader
//
void
restsrv_sendHeader( struct web_connection *conn,
int format,
int returncode )
{
if ( REST_FORMAT_PLAIN == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_PLAIN );
}
else if ( REST_FORMAT_CSV == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_CSV );
}
else if ( REST_FORMAT_XML == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_XML );
}
else if ( REST_FORMAT_JSON == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_JSON );
}
else if ( REST_FORMAT_JSONP == format ) {
websrv_sendheader( conn, returncode, REST_MIME_TYPE_JSONP );
}
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_get_session
//
struct restsrv_session *
restsrv_get_session( struct web_connection *conn,
wxString& sid )
{
const struct restsrv_session *pSession = NULL;
const struct web_request_info *reqinfo;
// Check pointers
if ( !conn ||
!( reqinfo = web_get_request_info( conn ) ) ) {
return NULL;
}
if ( 0 == sid.Length() ) return NULL;
// find existing session
gpobj->m_restSessionMutex.Lock();
RESTSESSIONLIST::iterator iter;
for ( iter = gpobj->m_rest_sessions.begin();
iter != gpobj->m_rest_sessions.end();
++iter ) {
struct restsrv_session *pSession = *iter;
if ( 0 == strcmp( (const char *)sid.mbc_str(),
pSession->m_sid ) ) {
pSession->m_lastActiveTime = time( NULL );
gpobj->m_restSessionMutex.Unlock();
return pSession;
}
}
gpobj->m_restSessionMutex.Unlock();
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_add_session
//
restsrv_session *
restsrv_add_session( struct web_connection *conn, CUserItem *pUserItem )
{
char buf[512];
wxString user;
struct restsrv_session *pSession;
const struct web_request_info *reqinfo;
// Check pointers
if ( !conn ||
!( reqinfo = web_get_request_info( conn ) ) ) {
return 0;
}
// Parse "Authorization:" header, fail fast on parse error
/*const char *pheader = web_get_header( conn, "Authorization" );
if ( NULL == pheader ) return NULL;
wxArrayString valarray;
wxString header = wxString::FromUTF8( pheader );
websrv_parseHeader( valarray, header );
// Get username
if ( !websrv_getHeaderElement( valarray,
"username",
user ) ) {
return NULL;
}*/
// Create fresh session
pSession = new struct restsrv_session;
if ( NULL == pSession ) {
return NULL;
}
memset( pSession, 0, sizeof( websrv_session ) );
// Generate a random session ID
unsigned char iv[16];
char hexiv[33];
getRandomIV( iv, 16 ); // Generate 16 random bytes
memset( hexiv, 0, sizeof(hexiv) );
vscp_byteArray2HexStr( hexiv, iv, 16 );
memset( pSession->m_sid, 0, sizeof( pSession->m_sid ) );
memcpy( pSession->m_sid, hexiv, 32 );
pSession->m_lastActiveTime = time( NULL );
pSession->m_pClientItem = new CClientItem(); // Create client
if ( NULL == pSession->m_pClientItem ) {
gpobj->logMsg(_("[restsrv] New session: Unable to create client object."));
delete pSession;
return NULL;
}
// Set client data
pSession->m_pClientItem->bAuthenticated = true; // Authenticated
pSession->m_pClientItem->m_pUserItem = pUserItem;
vscp_clearVSCPFilter(&pSession->m_pClientItem->m_filterVSCP); // Clear filter
pSession->m_pClientItem->m_bOpen = false; // Start out closed
pSession->m_pClientItem->m_type = CLIENT_ITEM_INTERFACE_TYPE_CLIENT_WEBSOCKET;
pSession->m_pClientItem->m_strDeviceName = _("Internal REST server client.");
pSession->m_pClientItem->m_strDeviceName += _("|Started at ");
wxDateTime now = wxDateTime::Now();
pSession->m_pClientItem->m_strDeviceName += now.FormatISODate();
pSession->m_pClientItem->m_strDeviceName += _(" ");
pSession->m_pClientItem->m_strDeviceName += now.FormatISOTime();
// Add the client to the Client List
gpobj->m_wxClientMutex.Lock();
if ( !gpobj->addClient( pSession->m_pClientItem ) ) {
// Failed to add client
delete pSession->m_pClientItem;
pSession->m_pClientItem = NULL;
gpobj->m_wxClientMutex.Unlock();
gpobj->logMsg( _("REST server: Failed to add client. Terminating thread.") );
return NULL;
}
gpobj->m_wxClientMutex.Unlock();
// Add to linked list
gpobj->m_restSessionMutex.Lock();
gpobj->m_rest_sessions.Append( pSession );
gpobj->m_restSessionMutex.Unlock();
return pSession;
}
///////////////////////////////////////////////////////////////////////////////
// websrv_expire_sessions
//
void
restsrv_expire_sessions( struct web_connection *conn )
{
time_t now;
now = time( NULL );
gpobj->m_restSessionMutex.Lock();
RESTSESSIONLIST::iterator iter;
for ( iter = gpobj->m_rest_sessions.begin();
iter != gpobj->m_rest_sessions.end();
++iter ) {
struct restsrv_session *pSession = *iter;
if ( ( now - pSession->m_lastActiveTime ) > ( 60 * 60 ) ) {
gpobj->m_rest_sessions.DeleteContents( true );
gpobj->m_rest_sessions.DeleteObject( pSession );
}
}
gpobj->m_restSessionMutex.Unlock();
}
// Hash with key value pairs
WX_DECLARE_STRING_HASH_MAP( wxString, hashArgs );
///////////////////////////////////////////////////////////////////////////////
// websrv_restapi
//
int
websrv_restapi( struct web_connection *conn, void *cbdata )
{
char bufBody[32000]; // Buffer for body (POST) data
int len_post_data;
const char *pParams = NULL; // Pointer to query data or POST data
int lenParam = 0;
char buf[2048];
char date[64];
wxString str;
time_t curtime = time(NULL);
long format = REST_FORMAT_PLAIN;
hashArgs keypairs;
struct web_context * ctx;
const struct web_request_info *reqinfo;
struct restsrv_session *pSession = NULL;
CUserItem *pUserItem = NULL;
memset( bufBody, 0, sizeof( bufBody ) );
// Check pointer
if ( !conn ||
!( ctx = web_get_context( conn ) ) ||
!( reqinfo = web_get_request_info( conn ) ) ) {
return WEB_ERROR;
}
// Get method
char method[33];
memset( method, 0, sizeof( method ) );
strncpy( method,
reqinfo->request_method,
strlen( reqinfo->request_method ) );
// Make string with GMT time
vscp_getTimeString( date, sizeof(date), &curtime );
// Set defaults
keypairs[_("FORMAT")] = _("plain");
keypairs[_("OP")] = _("open");
if ( NULL != strstr( method, ("POST") ) ) {
const char *pHeader;
// read POST data
len_post_data = web_read( conn, bufBody, sizeof( bufBody ) );
// user
if ( NULL != ( pHeader = web_get_header( conn, "vscpuser" ) ) ) {
memset( buf, 0, sizeof( buf ) );
strncpy( buf, pHeader, MIN( sizeof( buf )-1, strlen( pHeader ) ) );
keypairs[_("VSCPUSER")] = wxString::FromUTF8( buf );
}
// password
if ( NULL != ( pHeader = web_get_header( conn, "vscpsecret" ) ) ) {
memset( buf, 0, sizeof( buf ) );
strncpy( buf, pHeader, MIN( sizeof( buf )-1, strlen( pHeader ) ) );
keypairs[_("VSCPSECRET")] = wxString::FromUTF8( buf );
}
// session
if ( NULL != ( pHeader = web_get_header( conn, "vscpsession" ) ) ) {
memset( buf, 0, sizeof( buf ) );
strncpy( buf, pHeader, MIN( sizeof( buf )-1, strlen( pHeader ) ) );
keypairs[_("VSCPSESSION")] = wxString::FromUTF8( buf );
}
pParams = bufBody; // Parameters is in the body
lenParam = len_post_data;
}
else {
// get parameters for get
if ( 0 < web_get_var( reqinfo->query_string,
strlen( reqinfo->query_string ),
"vscpuser",
buf,
sizeof( buf ) ) ) {
keypairs[ _("VSCPUSER") ] = wxString::FromUTF8( buf );
}
if ( 0 < web_get_var( reqinfo->query_string,
strlen( reqinfo->query_string ),
"vscpsecret",
buf,
sizeof( buf ) ) ) {
keypairs[ _("VSCPSECRET") ] = wxString::FromUTF8( buf );
}
if ( 0 < web_get_var( reqinfo->query_string,
strlen( reqinfo->query_string ),
"vscpsession",
buf,
sizeof( buf ) ) ) {
keypairs[ _("VSCPSESSION") ] = wxString::FromUTF8( buf );
}
pParams = reqinfo->query_string; // Parameters is in query string
lenParam = strlen( reqinfo->query_string );
}
// format
if ( 0 < web_get_var( pParams, lenParam, "format", buf, sizeof( buf ) ) ) {
keypairs[_("FORMAT")] = wxString::FromUTF8( buf );
}
// op
if ( 0 < web_get_var( pParams, lenParam, "op", buf, sizeof(buf) ) ) {
keypairs[_("OP")] = wxString::FromUTF8( buf );
}
// vscpevent
if ( 0 < web_get_var( pParams, lenParam, "vscpevent", buf, sizeof(buf) ) ) {
keypairs[_("VSCPEVENT")] = wxString::FromUTF8( buf );
}
// count
if ( 0 < web_get_var( pParams, lenParam, "count", buf, sizeof(buf) ) ) {
keypairs[_("COUNT")] = wxString::FromUTF8( buf );
}
// vscpfilter
if ( 0 < web_get_var( pParams, lenParam, "vscpfilter", buf, sizeof(buf) ) ) {
keypairs[_("VSCPFILTER")] = wxString::FromUTF8( buf );
}
// vscpmask
if ( 0 < web_get_var( pParams, lenParam, "vscpmask", buf, sizeof( buf ) ) ) {
keypairs[ _( "VSCPMASK" ) ] = wxString::FromUTF8( buf );
}
// variable
if ( 0 < web_get_var( pParams, lenParam, "variable", buf, sizeof(buf) ) ) {
keypairs[_("VARIABLE")] = wxString::FromUTF8( buf );
}
// value
if ( 0 < web_get_var( pParams, lenParam, "value", buf, sizeof( buf ) ) ) {
keypairs[ _( "VALUE" ) ] = wxString::FromUTF8( buf );
}
// type (number or string)
if ( 0 < web_get_var( pParams, lenParam, "type", buf, sizeof(buf) ) ) {
keypairs[_("TYPE")] = wxString::FromUTF8( buf );
}
// persistent
if ( 0 < web_get_var( pParams, lenParam, "persistent", buf, sizeof( buf ) ) ) {
keypairs[ _( "PERSISTENT" ) ] = wxString::FromUTF8( buf );
}
// access-right (hex or decimal)
if ( 0 < web_get_var( pParams, lenParam, "accessright", buf, sizeof( buf ) ) ) {
keypairs[ _( "ACCESSRIGHT" ) ] = wxString::FromUTF8( buf );
}
// note
if ( 0 < web_get_var( pParams, lenParam, "note", buf, sizeof( buf ) ) ) {
keypairs[ _( "NOTE" ) ] = wxString::FromUTF8( buf );
}
// listlong
if ( 0 < web_get_var( pParams, lenParam, "listlong", buf, sizeof( buf ) ) ) {
keypairs[ _( "LISTLONG" ) ] = wxString::FromUTF8( buf );
}
// regex
if ( 0 < web_get_var( pParams, lenParam, "regex", buf, sizeof( buf ) ) ) {
keypairs[ _( "REGEX" ) ] = wxString::FromUTF8( buf );
}
// unit
if ( 0 < web_get_var( pParams, lenParam, "unit", buf, sizeof(buf) ) ) {
keypairs[_("UNIT")] = wxString::FromUTF8( buf );
}
// sensoridx
if ( 0 < web_get_var( pParams, lenParam, "sensoridx", buf, sizeof(buf) ) ) {
keypairs[_("SENSORINDEX")] = wxString::FromUTF8( buf );
}
// level ( VSCP level 1 or 2 )
if ( 0 < web_get_var( pParams, lenParam, "level", buf, sizeof( buf ) ) ) {
keypairs[ _( "LEVEL" ) ] = wxString::FromUTF8( buf );
}
// zone
if ( 0 < web_get_var( pParams, lenParam, "zone", buf, sizeof( buf ) ) ) {
keypairs[ _( "ZONE" ) ] = wxString::FromUTF8( buf );
}
// subzone
if ( 0 < web_get_var( pParams, lenParam, "subzone", buf, sizeof( buf ) ) ) {
keypairs[ _( "SUBZONE" ) ] = wxString::FromUTF8( buf );
}
// guid
if ( 0 < web_get_var( pParams, lenParam, "guid", buf, sizeof( buf ) ) ) {
keypairs[ _( "GUID" ) ] = wxString::FromUTF8( buf );
}
// name
if ( 0 < web_get_var( pParams, lenParam, "name", buf, sizeof(buf) ) ) {
keypairs[_("NAME")] = wxString::FromUTF8( buf );
}
// from
if ( 0 < web_get_var( pParams, lenParam, "from", buf, sizeof(buf) ) ) {
keypairs[_("FROM")] = wxString::FromUTF8( buf );
}
// to
if ( 0 < web_get_var( pParams, lenParam, "to", buf, sizeof(buf) ) ) {
keypairs[_("TO")] = wxString::FromUTF8( buf );
}
// url
if ( 0 < web_get_var( pParams, lenParam, "url", buf, sizeof( buf ) ) ) {
keypairs[ _( "URL" ) ] = wxString::FromUTF8( buf );
}
// eventformat
if ( 0 < web_get_var( pParams, lenParam, "eventformat", buf, sizeof( buf ) ) ) {
keypairs[ _( "EVENTFORMAT" ) ] = wxString::FromUTF8( buf );
}
// datetime
if ( 0 < web_get_var( pParams, lenParam, "datetime", buf, sizeof( buf ) ) ) {
keypairs[ _( "DATETIME" ) ] = wxString::FromUTF8( buf );
}
// Get format
if ( _("PLAIN") == keypairs[_("FORMAT")].Upper() ) {
format = REST_FORMAT_PLAIN;
}
else if ( _("CSV") == keypairs[_("FORMAT")].Upper() ) {
format = REST_FORMAT_CSV;
}
else if ( _("XML") == keypairs[_("FORMAT")].Upper() ) {
format = REST_FORMAT_XML;
}
else if ( _("JSON") == keypairs[_("FORMAT")].Upper() ) {
format = REST_FORMAT_JSON;
}
else if ( _("JSONP") == keypairs[_("FORMAT")].Upper() ) {
format = REST_FORMAT_JSONP;
}
else if ( _("") != keypairs[_("FORMAT")].Upper() ) {
keypairs[_("FORMAT")].ToLong( &format );
}
else {
websrv_sendheader( conn, 400, "text/plain" );
web_write( conn,
REST_PLAIN_ERROR_UNSUPPORTED_FORMAT,
strlen( REST_PLAIN_ERROR_UNSUPPORTED_FORMAT ) );
web_write( conn, "", 0 ); // Terminator
return WEB_ERROR;
}
// If we have a session key we try to get the session
if ( _("") != keypairs[_("VSCPSESSION")] ) {
// Get session
pSession = restsrv_get_session( conn, keypairs[_("VSCPSESSION")] );
}
if ( NULL == pSession ) {
// Get user
pUserItem = gpobj->m_userList.getUser( keypairs[_("VSCPUSER")] );
// Check if user is valid
if ( NULL == pUserItem ) {
wxString strErr =
wxString::Format( _("[REST Client] Host [%s] Invalid user [%s]\n"),
wxString::FromUTF8( reqinfo->remote_addr ).mbc_str(),
(const char *)keypairs[_("VSCPUSER")].mbc_str() );
gpobj->logMsg( strErr, DAEMON_LOGMSG_NORMAL, DAEMON_LOGTYPE_SECURITY );
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_USER );
return WEB_ERROR;
}
// Check if remote ip is valid
bool bValidHost;
gpobj->m_mutexUserList.Lock();
bValidHost = ( 1 == pUserItem->isAllowedToConnect( inet_addr( reqinfo->remote_addr ) ) );
gpobj->m_mutexUserList.Unlock();
if (!bValidHost) {
wxString strErr =
wxString::Format( _("[REST Client] Host [%s] NOT allowed to connect. User [%s]\n"),
wxString::FromUTF8( reqinfo->remote_addr ).mbc_str(),
(const char *)keypairs[_("VSCPUSER")].mbc_str() );
gpobj->logMsg ( strErr, DAEMON_LOGMSG_NORMAL, DAEMON_LOGTYPE_SECURITY );
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN );
return WEB_ERROR;
}
// Is this an authorised user?
gpobj->m_mutexUserList.Lock();
CUserItem *pValidUser =
gpobj->m_userList.validateUser( keypairs[_("VSCPUSER")],
keypairs[_("VSCPSECRET")] );
gpobj->m_mutexUserList.Unlock();
if ( NULL == pValidUser ) {
wxString strErr =
wxString::Format( _("[REST Client] User [%s] NOT allowed to connect. Client [%s]\n"),
(const char *)keypairs[_("VSCPUSER")].mbc_str(),
wxString::FromUTF8( reqinfo->remote_addr ).mbc_str() );
gpobj->logMsg ( strErr, DAEMON_LOGMSG_NORMAL, DAEMON_LOGTYPE_SECURITY );
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_PASSWORD );
return WEB_ERROR;
}
if ( NULL == ( pSession = restsrv_add_session( conn, pUserItem ) ) ) {
// Hm,,, did not work out well...
wxString strErr =
wxString::Format( _("[REST Client] Unable to create new session for user [%s]\n"),
(const char *)keypairs[_("VSCPUSER")].mbc_str() );
gpobj->logMsg ( strErr, DAEMON_LOGMSG_NORMAL, DAEMON_LOGTYPE_GENERAL );
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN );
return WEB_ERROR;
}
// Only the "open" command is allowed here
if ( ( _("1") == keypairs[_("OP")] ) ||
( _("OPEN") == keypairs[_("OP")].Upper() ) ) {
restsrv_doOpen( conn, pSession, format );
return WEB_OK;
}
// !!! No meaning to go further - end it here !!!
wxString strErr =
wxString::Format( _("[REST Client] Unable to create new session for user [%s]\n"),
(const char *)keypairs[_("VSCPUSER")].mbc_str() );
gpobj->logMsg ( strErr, DAEMON_LOGMSG_NORMAL, DAEMON_LOGTYPE_GENERAL );
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN );
return WEB_ERROR;
}
// Check if remote ip is valid
bool bValidHost;
gpobj->m_mutexUserList.Lock();
bValidHost =
( 1 == pSession->m_pClientItem->m_pUserItem->isAllowedToConnect( inet_addr( reqinfo->remote_addr ) ) );
gpobj->m_mutexUserList.Unlock();
if ( !bValidHost ) {
wxString strErr =
wxString::Format( _("[REST Client] Host [%s] NOT allowed to connect. User [%s]\n"),
wxString::FromUTF8( reqinfo->remote_addr ).mbc_str(),
(const char *)keypairs[_("VSCPUSER")].mbc_str() );
gpobj->logMsg ( strErr, DAEMON_LOGMSG_NORMAL, DAEMON_LOGTYPE_SECURITY );
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_ORIGIN );
return WEB_ERROR;
}
// ------------------------------------------------------------------------
// * * * User is validated * * *
// ------------------------------------------------------------------------
wxString strErr =
wxString::Format( _("[REST Client] User [%s] Host [%s] allowed to connect. \n"),
(const char *)keypairs[_("VSCPUSER")].mbc_str() ,
wxString::FromUTF8( reqinfo->remote_addr ).mbc_str() );
gpobj->logMsg ( strErr, DAEMON_LOGMSG_NORMAL, DAEMON_LOGTYPE_SECURITY );
// *************************************************************
// * * * * * * * * Status (hold session open) * * * * * * * *
// *************************************************************
if ( ( _("0") == keypairs[_("OP")] ) ||
( _("STATUS") == keypairs[_("OP")].Upper() ) ) {
restsrv_doStatus( conn, pSession, format );
}
// ********************************************
// * * * * * * * * open session * * * * * * * *
// ********************************************
else if ( ( _("1") == keypairs[_("OP")] ) ||
( _("OPEN") == keypairs[_("OP")].Upper() ) ) {
restsrv_doOpen( conn, pSession, format );
}
// **********************************************
// * * * * * * * * close session * * * * * * * *
// **********************************************
else if ( ( _("2") == keypairs[_("OP")] ) ||
( _("CLOSE") == keypairs[_("OP")].Upper() ) ) {
restsrv_doClose( conn, pSession, format );
}
// ********************************************
// * * * * * * * * Send event * * * * * * * *
// ********************************************
else if ( ( _("3") == keypairs[_("OP")] ) ||
( _("SENDEVENT") == keypairs[_("OP")].Upper() ) ) {
vscpEvent vscpevent;
if ( _("") != keypairs[_("VSCPEVENT")] ) {
vscp_setVscpEventFromString( &vscpevent, keypairs[_("VSCPEVENT")] );
restsrv_doSendEvent( conn, pSession, format, &vscpevent );
}
else {
// Parameter missing - No Event
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// ********************************************
// * * * * * * * * Read event * * * * * * * *
// ********************************************
else if ( ( _("4") == keypairs[_("OP")] ) ||
( _("READEVENT") == keypairs[_("OP")].Upper() ) ) {
long count = 1;
if ( _("") != keypairs[_("COUNT")].Upper() ) {
keypairs[_("COUNT")].ToLong( &count );
}
restsrv_doReceiveEvent( conn, pSession, format, count );
}
// **************************************************
// * * * * * * * * Set filter * * * * * * * *
// **************************************************
else if ( ( _("5") == keypairs[_("OP")] ) ||
( _("SETFILTER") == keypairs[_("OP")].Upper() ) ) {
vscpEventFilter vscpfilter;
vscp_clearVSCPFilter( &vscpfilter );
if ( _("") != keypairs[_("VSCPFILTER")] ) {
vscp_readFilterFromString( &vscpfilter, keypairs[_("VSCPFILTER")] );
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_MISSING_DATA );
}
if ( _( "" ) != keypairs[ _("VSCPMASK") ] ) {
vscp_readMaskFromString( &vscpfilter, keypairs[ _( "VSCPMASK" ) ] );
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_MISSING_DATA );
}
restsrv_doSetFilter( conn, pSession, format, vscpfilter );
}
// ****************************************************
// * * * * * * * * clear input queue * * * * * * * *
// ****************************************************
else if ( ( _("6") == keypairs[_("OP")] ) ||
( _("CLEARQUEUE") == keypairs[_("OP")].Upper() ) ) {
restsrv_doClearQueue( conn, pSession, format );
}
// ****************************************************
// * * * * * * * * list variables * * * * * * * *
// ****************************************************
else if ( ( _("12") == keypairs[_("OP")] ) ||
( _("LISTVAR") == keypairs[_("OP")].Upper() ) ) {
bool bShort = true;
if ( wxNOT_FOUND !=
keypairs[ _( "LISTLONG" ) ].Upper().Find( _("TRUE") ) ) {
bShort = false;
}
restsrv_doListVariable( conn,
pSession,
format,
keypairs[_("REGEX")],
bShort );
}
// ****************************************************
// * * * * * * * * read variable value * * * * * * * *
// ****************************************************
else if ( ( _("7") == keypairs[_("OP")] ) ||
( _("READVAR") == keypairs[_("OP")].Upper() ) ) {
if ( _("") != keypairs[_("VARIABLE")] ) {
restsrv_doReadVariable( conn,
pSession,
format,
keypairs[_("VARIABLE")] );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// *****************************************************
// * * * * * * * * Write variable value * * * * * * * *
// *****************************************************
else if ( ( _("8") == keypairs[_("OP")] ) ||
( _("WRITEVAR") == keypairs[_("OP")].Upper() ) ) {
if ( _("") != keypairs[_("VARIABLE")] ) {
restsrv_doWriteVariable( conn,
pSession,
format,
keypairs[_("VARIABLE")],
keypairs[ _( "VALUE" ) ] );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// *****************************************************
// * * * * * * * * Create variable * * * * * * * *
// *****************************************************
else if ( ( _("9") == keypairs[_("OP")] ) ||
( _("CREATEVAR") == keypairs[_("OP")].Upper() ) ) {
if ( _("") != keypairs[_("VARIABLE")] ) {
restsrv_doCreateVariable( conn,
pSession,
format,
keypairs[_("VARIABLE")],
keypairs[ _( "TYPE" ) ],
keypairs[ _( "VALUE" ) ],
keypairs[ _( "PERISTENT" ) ],
keypairs[ _( "ACCESSRIGHT" ) ],
keypairs[ _( "NOTE" ) ] );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// *****************************************************
// * * * * * * * * Delete variable * * * * * * * *
// *****************************************************
else if ( ( _("10") == keypairs[_("OP")] ) ||
( _("DELETEVAR") == keypairs[_("OP")].Upper() ) ) {
if ( _("") != keypairs[_("VARIABLE")] ) {
restsrv_doDeleteVariable( conn,
pSession,
format,
keypairs[ _("VARIABLE") ] );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// *************************************************
// * * * * * * * * Send measurement * * * * * * * *
// *************************************************
// value,unit=0,sensor=0
//
else if ( ( _("10") == keypairs[_("OP")] ) ||
( _("MEASUREMENT") == keypairs[_("OP")].Upper() ) ) {
if ( ( _("") != keypairs[_("VALUE")] ) &&
( _("") != keypairs[_("TYPE")]) ) {
restsrv_doWriteMeasurement( conn, pSession, format,
keypairs[ _("DATETIME" ) ],
keypairs[ _("GUID" ) ],
keypairs[ _("LEVEL") ],
keypairs[ _("TYPE") ],
keypairs[ _("VALUE") ],
keypairs[ _("UNIT") ],
keypairs[ _("SENSORIDX") ],
keypairs[ _( "ZONE" ) ],
keypairs[ _( "SUBZONE" ) ],
keypairs[ _( "SUBZONE" ) ] );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// *******************************************
// * * * * * * * * Table read * * * * * * * *
// *******************************************
else if ( ( _("11") == keypairs[_("OP")] ) ||
( _("TABLE") == keypairs[_("OP")].Upper() ) ) {
if ( _("") != keypairs[_("NAME")] ) {
restsrv_doGetTableData( conn,
pSession,
format,
keypairs[_("NAME")],
keypairs[_("FROM")],
keypairs[_("TO")] );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// *******************************************
// * * * * * * * * Fetch MDF * * * * * * * *
// *******************************************
else if ( ( _( "12" ) == keypairs[ _( "OP" ) ] ) ||
( _( "MDF" ) == keypairs[ _( "OP" ) ].Upper() ) ) {
if ( _( "" ) != keypairs[ _( "URL" ) ] ) {
restsrv_doFetchMDF( conn,
pSession,
format,
keypairs[ _( "URL" ) ] );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
}
// Unrecognised operation
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_MISSING_DATA );
}
return WEB_OK;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doOpen
//
void
restsrv_doOpen( struct web_connection *conn,
struct restsrv_session *pSession,
int format )
{
char buf[ 2048 ];
char wrkbuf[ 256 ];
if ( NULL != pSession ) {
// OK session
// Note activity
pSession->m_lastActiveTime = time( NULL );
// Mark interface as open
pSession->m_pClientItem->m_bOpen = true;
if ( REST_FORMAT_PLAIN == format ) {
websrv_sendSetCookieHeader( conn,
200,
REST_MIME_TYPE_PLAIN,
pSession->m_sid );
#ifdef WIN32
int n = _snprintf( wrkbuf,
sizeof( wrkbuf ),
"1 1 Success vscpsession=%s nEvents=%zd",
pSession->sid,
pSession->pClientItem->m_clientInputQueue.GetCount() );
#else
int n = snprintf( wrkbuf,
sizeof( wrkbuf ),
"1 1 Success vscpsession=%s nEvents=%lu",
pSession->m_sid,
pSession->m_pClientItem->m_clientInputQueue.GetCount() );
#endif
web_write( conn, wrkbuf, n );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_CSV == format ) {
websrv_sendSetCookieHeader( conn,
200,
REST_MIME_TYPE_CSV,
pSession->m_sid );
#ifdef WIN32
int n = _snprintf( wrkbuf,
sizeof( wrkbuf ),
"success-code,error-code,message,description,"
"vscpsession,nEvents\r\n1,1,Success,Success. 1,1"
",Success,Success,%s,%zd",
pSession->sid,
pSession->pClientItem->m_clientInputQueue.GetCount() );
#else
int n = snprintf( wrkbuf,
sizeof( wrkbuf ),
"success-code,error-code,message,description,"
"vscpsession,nEvents\r\n1,1,Success,Success. 1,1,"
"Success,Success,%s,%lu",
pSession->m_sid,
pSession->m_pClientItem->m_clientInputQueue.GetCount() );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_XML == format ) {
websrv_sendSetCookieHeader( conn,
200,
REST_MIME_TYPE_XML,
pSession->m_sid );
#ifdef WIN32
int n = _snprintf( wrkbuf,
sizeof( wrkbuf ),
"<vscp-rest success = \"true\" code = "
"\"1\" message = \"Success.\" description = "
"\"Success.\" ><vscpsession>%s</vscpsession>"
"<nEvents>%zd</nEvents></vscp-rest>",
pSession->sid,
pSession->pClientItem->m_clientInputQueue.GetCount() );
#else
int n = snprintf( wrkbuf,
sizeof( wrkbuf ),
"<vscp-rest success = \"true\" code = \"1\" "
"message = \"Success.\" description = \"Success.\" "
"><vscpsession>%s</vscpsession><nEvents>%lu"
"</nEvents></vscp-rest>",
pSession->m_sid,
pSession->m_pClientItem->m_clientInputQueue.GetCount() );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_JSON == format ) {
json output;
websrv_sendSetCookieHeader( conn,
200,
REST_MIME_TYPE_JSON,
pSession->m_sid );
output["success"] = true;
output["code"] = 1;
output["message"] = "success";
output["description"] = "Success";
output["vscpsession"] = pSession->m_sid;
output["nEvents"] = pSession->m_pClientItem->m_clientInputQueue.GetCount();
std::string s = output.dump();
web_write( conn, s.c_str(), s.length() );
return;
}
else if ( REST_FORMAT_JSONP == format ) {
json output;
websrv_sendSetCookieHeader( conn,
200,
REST_MIME_TYPE_JSONP,
pSession->m_sid );
// Write JSONP start block
web_write( conn,
REST_JSONP_START,
strlen( REST_JSONP_START ) );
output["success"] = true;
output["code"] = 1;
output["message"] = "success";
output["description"] = "Success";
output["vscpsession"] = pSession->m_sid;
output["nEvents"] = pSession->m_pClientItem->m_clientInputQueue.GetCount();
std::string s = output.dump();
web_write( conn, s.c_str(), s.length() );
// Write JSONP end block
web_write( conn,
REST_JSONP_END,
strlen( REST_JSONP_END ) );
return;
}
else {
websrv_sendheader( conn, 400, REST_MIME_TYPE_PLAIN );
web_write( conn,
REST_PLAIN_ERROR_UNSUPPORTED_FORMAT,
strlen( REST_PLAIN_ERROR_UNSUPPORTED_FORMAT ) );
return;
}
}
else { // Unable to create session
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doClose
//
void
restsrv_doClose( struct web_connection *conn,
struct restsrv_session *pSession,
int format )
{
char buf[ 2048 ];
char wrkbuf[ 256 ];
if ( NULL != pSession ) {
char sid[ 32 + 1 ];
memset( sid, 0, sizeof( sid ) );
memcpy( sid, pSession->m_sid, sizeof( sid ) );
// We should close the session
// Mark as closed
pSession->m_pClientItem->m_bOpen = false;
// Note activity
pSession->m_lastActiveTime = time( NULL );
if ( REST_FORMAT_PLAIN == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_PLAIN );
web_write( conn, REST_PLAIN_ERROR_SUCCESS, strlen( REST_PLAIN_ERROR_SUCCESS ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_CSV == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_CSV );
#ifdef WIN32
int n = _snprintf( wrkbuf, sizeof( wrkbuf ), REST_CSV_ERROR_SUCCESS );
#else
int n = snprintf( wrkbuf, sizeof( wrkbuf ), REST_CSV_ERROR_SUCCESS );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_XML == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_XML );
#ifdef WIN32
int n = _snprintf( wrkbuf, sizeof( wrkbuf ), REST_XML_ERROR_SUCCESS );
#else
int n = snprintf( wrkbuf, sizeof( wrkbuf ), REST_XML_ERROR_SUCCESS );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_JSON == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSON );
#ifdef WIN32
int n = _snprintf( wrkbuf, sizeof( wrkbuf ), REST_JSON_ERROR_SUCCESS );
#else
int n = snprintf( wrkbuf, sizeof( wrkbuf ), REST_JSON_ERROR_SUCCESS );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_JSONP == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSONP );
#ifdef WIN32
int n = _snprintf( wrkbuf, sizeof( wrkbuf ), REST_JSONP_ERROR_SUCCESS );
#else
int n = snprintf( wrkbuf, sizeof( wrkbuf ), REST_JSONP_ERROR_SUCCESS );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else {
websrv_sendheader( conn, 400, REST_MIME_TYPE_PLAIN );
web_write( conn,
REST_PLAIN_ERROR_UNSUPPORTED_FORMAT,
strlen( REST_PLAIN_ERROR_UNSUPPORTED_FORMAT ) );
web_write( conn, "", 0 ); // Terminator
return;
}
}
else { // session not found
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doStatus
//
void
restsrv_doStatus( struct web_connection *conn,
struct restsrv_session *pSession,
int format )
{
char buf[ 2048 ];
char wrkbuf[ 256 ];
if ( NULL != pSession ) {
// Note activity
pSession->m_lastActiveTime = time( NULL );
if ( REST_FORMAT_PLAIN == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_PLAIN );
web_write( conn,
REST_PLAIN_ERROR_SUCCESS,
strlen( REST_PLAIN_ERROR_SUCCESS ) );
memset( buf, 0, sizeof( buf ) );
#ifdef WIN32
int n = _snprintf( wrkbuf,
sizeof( wrkbuf ),
"vscpsession=%s nEvents=%zd",
pSession->sid,
pSession->pClientItem->m_clientInputQueue.GetCount() );
#else
int n = snprintf( wrkbuf,
sizeof( wrkbuf ),
"1 1 Success vscpsession=%s nEvents=%lu",
pSession->m_sid,
pSession->m_pClientItem->m_clientInputQueue.GetCount() );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_CSV == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_CSV );
#ifdef WIN32
int n = _snprintf( wrkbuf,
sizeof( wrkbuf ),
"success-code,error-code,message,description,vscpsession,nEvents\r\n1,1,Success,Success. 1,1,Success,Sucess,%s,%zd",
pSession->sid,
pSession->pClientItem->m_clientInputQueue.GetCount() );
#else
int n = snprintf( wrkbuf,
sizeof( wrkbuf ),
"success-code,error-code,message,description,vscpsession,nEvents\r\n1,1,Success,Success. 1,1,Success,Sucess,%s,%lu",
pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.GetCount() );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( REST_FORMAT_XML == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_XML );
#ifdef WIN32
int n = _snprintf( wrkbuf,
sizeof( wrkbuf ),
"<vscp-rest success = \"true\" code = \"1\" message = \"Success.\" description = \"Success.\" ><vscpsession>%s</vscpsession><nEvents>%zd</nEvents></vscp-rest>",
pSession->sid,
pSession->pClientItem->m_clientInputQueue.GetCount() );
#else
int n = snprintf( wrkbuf,
sizeof( wrkbuf ),
"<vscp-rest success = \"true\" code = \"1\" message = \"Success.\" description = \"Success.\" ><vscpsession>%s</vscpsession><nEvents>%lu</nEvents></vscp-rest>",
pSession->m_sid, pSession->m_pClientItem->m_clientInputQueue.GetCount() );
#endif
web_write( conn, wrkbuf, strlen( wrkbuf ) );
web_write( conn, "", 0 ); // Terminator
return;
}
else if ( ( REST_FORMAT_JSON == format ) ||
( REST_FORMAT_JSONP == format ) ) {
json output;
if ( REST_FORMAT_JSON == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSON );
}
else {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSONP );
// Write JSONP start block
web_write( conn,
REST_JSONP_START,
strlen( REST_JSONP_START ) );
}
output["success"] = true;
output["code"] = 1;
output["message"] = "success";
output["description"] = "Success";
output["vscpsession"] = pSession->m_sid;
output["nEvents"] = pSession->m_pClientItem->m_clientInputQueue.GetCount();
std::string s = output.dump();
web_write( conn, s.c_str(), s.length() );
if ( REST_FORMAT_JSONP == format ) {
// Write JSONP end block
web_write( conn,
REST_JSONP_END,
strlen( REST_JSONP_END ) );
}
return;
}
else {
websrv_sendheader( conn, 400, REST_MIME_TYPE_PLAIN );
web_write( conn, REST_PLAIN_ERROR_UNSUPPORTED_FORMAT, strlen( REST_PLAIN_ERROR_UNSUPPORTED_FORMAT ) );
web_write( conn, "", 0 ); // Terminator
return;
}
} // No session
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doSendEvent
//
void
restsrv_doSendEvent( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
vscpEvent *pEvent )
{
bool bSent = false;
// Check pointer
if (NULL == conn) return;
if ( NULL != pSession ) {
// Level II events between 512-1023 is recognised by the daemon and
// sent to the correct interface as Level I events if the interface
// is addressed by the client.
if ( ( pEvent->vscp_class <= 1023 ) &&
( pEvent->vscp_class >= 512 ) &&
( pEvent->sizeData >= 16 ) ) {
// This event should be sent to the correct interface if it is
// available on this machine. If not it should be sent to
// the rest of the network as normal
cguid destguid;
destguid.getFromArray( pEvent->pdata );
destguid.setAt(0,0);
destguid.setAt(1,0);
if ( NULL != pSession->m_pClientItem ) {
// Set client id
pEvent->obid = pSession->m_pClientItem->m_clientID;
// Check if filtered out
if ( vscp_doLevel2Filter( pEvent, &pSession->m_pClientItem->m_filterVSCP ) ) {
// Lock client
gpobj->m_wxClientMutex.Lock();
// If the client queue is full for this client then the
// client will not receive the message
if (pSession->m_pClientItem->m_clientInputQueue.GetCount() <=
gpobj->m_maxItemsInClientReceiveQueue) {
vscpEvent *pNewEvent = new( vscpEvent );
if ( NULL != pNewEvent ) {
vscp_copyVSCPEvent(pNewEvent, pEvent);
// Add the new event to the input queue
pSession->m_pClientItem->m_mutexClientInputQueue.Lock();
pSession->m_pClientItem->m_clientInputQueue.Append( pNewEvent );
pSession->m_pClientItem->m_semClientInputQueue.Post();
bSent = true;
}
else {
bSent = false;
}
}
else {
// Overrun - No room for event
//vscp_deleteVSCPevent( pEvent );
bSent = true;
}
// Unlock client
gpobj->m_wxClientMutex.Unlock();
} // filter
} // Client found
}
if ( !bSent ) {
if ( NULL != pSession->m_pClientItem ) {
// Set client id
pEvent->obid = pSession->m_pClientItem->m_clientID;
// There must be room in the send queue
if (gpobj->m_maxItemsInClientReceiveQueue >
gpobj->m_clientOutputQueue.GetCount()) {
vscpEvent *pNewEvent = new( vscpEvent );
if ( NULL != pNewEvent ) {
vscp_copyVSCPEvent(pNewEvent, pEvent);
gpobj->m_mutexClientOutputQueue.Lock();
gpobj->m_clientOutputQueue.Append(pNewEvent);
gpobj->m_semClientOutputQueue.Post();
gpobj->m_mutexClientOutputQueue.Unlock();
bSent = true;
}
else {
bSent = false;
}
restsrv_error( conn, pSession, format, REST_ERROR_CODE_SUCCESS );
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_NO_ROOM );
vscp_deleteVSCPevent( pEvent );
bSent = false;
}
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE );
vscp_deleteVSCPevent( pEvent );
bSent = false;
}
} // not sent
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
bSent = false;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doReceiveEvent
//
void
restsrv_doReceiveEvent( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
size_t count )
{
// Check pointer
if (NULL == conn) return;
if ( NULL != pSession ) {
if ( !pSession->m_pClientItem->m_clientInputQueue.empty() ) {
char buf[32000];
char wrkbuf[32000];
wxString out;
size_t cntAvailable =
pSession->m_pClientItem->m_clientInputQueue.GetCount();
// Plain
if ( REST_FORMAT_PLAIN == format ) {
// Send header
websrv_sendheader( conn, 200, REST_MIME_TYPE_PLAIN );
if ( pSession->m_pClientItem->m_bOpen && cntAvailable ) {
sprintf( wrkbuf, "1 1 Success \r\n");
web_write( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
#if WIN32
"%zd events requested of %zd available "
"(unfiltered) %zu will be retrieved\r\n",
#else
"%zd events requested of %zd available "
"(unfiltered) %lu will be retrieved\r\n",
#endif
count,
pSession->m_pClientItem->m_clientInputQueue.GetCount(),
MIN( count, cntAvailable ) );
web_write( conn, wrkbuf, strlen( wrkbuf ) );
for ( unsigned int i=0; i<MIN( count, cntAvailable ); i++ ) {
CLIENTEVENTLIST::compatibility_iterator nodeClient;
vscpEvent *pEvent;
pSession->m_pClientItem->m_mutexClientInputQueue.Lock();
nodeClient = pSession->m_pClientItem->m_clientInputQueue.GetFirst();
pEvent = nodeClient->GetData();
pSession->m_pClientItem->m_clientInputQueue.DeleteNode( nodeClient );
pSession->m_pClientItem->m_mutexClientInputQueue.Unlock();
if (NULL != pEvent) {
if ( vscp_doLevel2Filter( pEvent,
&pSession->m_pClientItem->m_filterVSCP ) ) {
wxString str;
if ( vscp_writeVscpEventToString( pEvent, str ) ) {
// Write it out
strcpy((char *) wrkbuf, (const char*) "- ");
strcat((char *) wrkbuf,
(const char*) str.mb_str(wxConvUTF8));
strcat((char *) wrkbuf, "\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
else {
strcpy((char *) wrkbuf,
"- Malformed event (internal error)\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
else {
strcpy((char *) wrkbuf, "- Event filtered out\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
// Remove the event
vscp_deleteVSCPevent(pEvent);
} // Valid pEvent pointer
else {
strcpy((char *) wrkbuf,
"- Event could not be fetched (internal error)\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
} // for
}
else { // no events available
sprintf( wrkbuf, REST_PLAIN_ERROR_INPUT_QUEUE_EMPTY"\r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
// CSV
else if ( REST_FORMAT_CSV == format ) {
// Send header
websrv_sendheader( conn, 200, /*REST_MIME_TYPE_CSV*/ REST_MIME_TYPE_PLAIN );
if ( pSession->m_pClientItem->m_bOpen && cntAvailable ) {
sprintf( wrkbuf, "success-code,error-code,message,"
"description,Event\r\n1,1,Success,Success."
",NULL\r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf( wrkbuf,
#if WIN32
"1,2,Info,%zd events requested of %d available "
"(unfiltered) %zu will be retrieved,NULL\r\n",
#else
"1,2,Info,%zd events requested of %lu available "
"(unfiltered) %lu will be retrieved,NULL\r\n",
#endif
count,
(unsigned long)cntAvailable,
(unsigned long)MIN( count, cntAvailable ) );
web_write( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"1,4,Count,%zu,NULL\r\n",
MIN( count, cntAvailable ) );
web_write( conn, wrkbuf, strlen( wrkbuf ) );
for ( unsigned int i=0; i<MIN( count, cntAvailable ); i++ ) {
CLIENTEVENTLIST::compatibility_iterator nodeClient;
vscpEvent *pEvent;
pSession->m_pClientItem->m_mutexClientInputQueue.Lock();
nodeClient = pSession->m_pClientItem->m_clientInputQueue.GetFirst();
pEvent = nodeClient->GetData();
pSession->m_pClientItem->m_clientInputQueue.DeleteNode(nodeClient);
pSession->m_pClientItem->m_mutexClientInputQueue.Unlock();
if ( NULL != pEvent ) {
if ( vscp_doLevel2Filter( pEvent,
&pSession->m_pClientItem->m_filterVSCP ) ) {
wxString str;
if ( vscp_writeVscpEventToString(pEvent, str) ) {
// Write it out
memset((char *) wrkbuf, 0, sizeof( wrkbuf ));
strcpy((char *) wrkbuf, (const char*) "1,3,Data,Event,");
strcat((char *) wrkbuf, (const char*) str.mb_str(wxConvUTF8));
strcat((char *) wrkbuf, "\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
else {
strcpy((char *) wrkbuf,
"1,2,Info,Malformed event (internal "
"error)\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
else {
strcpy((char *) wrkbuf,
"1,2,Info,Event filtered out\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
// Remove the event
vscp_deleteVSCPevent( pEvent );
} // Valid pEvent pointer
else {
strcpy((char *) wrkbuf,
"1,2,Info,Event could not be fetched "
"(internal error)\r\n" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
} // for
}
else { // no events available
sprintf( wrkbuf, REST_CSV_ERROR_INPUT_QUEUE_EMPTY"\r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
// XML
else if ( REST_FORMAT_XML == format ) {
int filtered = 0;
int errors = 0;
// Send header
websrv_sendheader( conn, 200, REST_MIME_TYPE_XML );
if ( pSession->m_pClientItem->m_bOpen && cntAvailable ) {
sprintf( wrkbuf,
XML_HEADER"<vscp-rest success = \"true\" "
"code = \"1\" message = \"Success\" "
"description = \"Success.\" >");
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf( wrkbuf,
"<info>%zd events requested of %lu available "
"(unfiltered) %zu will be retrieved</info>",
count,
cntAvailable,
MIN(count, cntAvailable ) );
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf( wrkbuf,
"<count>%zu</count>",
MIN( count, cntAvailable ) );
web_write( conn, wrkbuf, strlen( wrkbuf ) );
for ( unsigned int i=0; i<MIN( (unsigned long)count,
cntAvailable ); i++ ) {
CLIENTEVENTLIST::compatibility_iterator nodeClient;
vscpEvent *pEvent;
pSession->m_pClientItem->m_mutexClientInputQueue.Lock();
nodeClient = pSession->m_pClientItem->m_clientInputQueue.GetFirst();
pEvent = nodeClient->GetData();
pSession->m_pClientItem->m_clientInputQueue.DeleteNode(nodeClient);
pSession->m_pClientItem->m_mutexClientInputQueue.Unlock();
if (NULL != pEvent) {
if ( vscp_doLevel2Filter( pEvent,
&pSession->m_pClientItem->m_filterVSCP ) ) {
wxString str;
// Write it out
strcpy( (char *)wrkbuf, (const char*) "<event>");
// head
strcat((char *)wrkbuf, (const char*) "<head>");
strcat((char *)wrkbuf,
wxString::Format( _("%d"),
pEvent->head ).mbc_str() );
strcat((char *)wrkbuf, (const char*) "</head>");
// class
strcat((char *)wrkbuf, (const char*) "<vscpclass>");
strcat((char *)wrkbuf,
wxString::Format( _("%d"),
pEvent->vscp_class ).mbc_str() );
strcat((char *)wrkbuf, (const char*) "</vscpclass>");
// type
strcat((char *)wrkbuf, (const char*) "<vscptype>");
strcat((char *)wrkbuf,
wxString::Format( _("%d"),
pEvent->vscp_type ).mbc_str() );
strcat((char *)wrkbuf, (const char*) "</vscptype>");
// obid
strcat((char *)wrkbuf, (const char*) "<obid>");
strcat((char *)wrkbuf,
wxString::Format( _("%lu"),
pEvent->obid ).mbc_str() );
strcat((char *)wrkbuf, (const char*) "</obid>");
// datetime
strcat((char *)wrkbuf, (const char*) "<datetime>");
wxString dt;
vscp_getDateStringFromEvent( pEvent, dt );
strcat( (char *)wrkbuf,
wxString::Format( _("%%s"),
(const char *)dt.mbc_str() ) );
strcat((char *)wrkbuf, (const char*) "</datetime>");
// timestamp
strcat((char *)wrkbuf, (const char*) "<timestamp>");
strcat((char *)wrkbuf,
wxString::Format( _("%lu"),
pEvent->timestamp ).mbc_str() );
strcat((char *)wrkbuf, (const char*) "</timestamp>");
// guid
strcat((char *)wrkbuf, (const char*) "<guid>");
vscp_writeGuidToString( pEvent, str);
strcat((char *)wrkbuf, (const char *)str.mbc_str() );
strcat((char *)wrkbuf, (const char*) "</guid>");
// sizedate
strcat((char *)wrkbuf, (const char*) "<sizedata>");
strcat((char *)wrkbuf,
wxString::Format( _("%d"),
pEvent->sizeData ).mbc_str() );
strcat((char *)wrkbuf, (const char*) "</sizedata>");
// data
strcat((char *)wrkbuf, (const char*) "<data>");
vscp_writeVscpDataToString( pEvent, str);
strcat((char *)wrkbuf, (const char *)str.mbc_str() );
strcat((char *)wrkbuf, (const char*) "</data>");
if ( vscp_writeVscpEventToString( pEvent, str ) ) {
strcat( ( char * )wrkbuf, ( const char* ) "<raw>" );
strcat( ( char * )wrkbuf, ( const char* )str.mbc_str() );
strcat( ( char * )wrkbuf, ( const char* ) "</raw>" );
}
strcat((char *)wrkbuf, "</event>" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
else {
filtered++;
}
// Remove the event
vscp_deleteVSCPevent(pEvent);
} // Valid pEvent pointer
else {
errors++;
}
} // for
strcpy((char *) wrkbuf, (const char*) "<filtered>");
strcat((char *) wrkbuf, wxString::Format( _("%d"), filtered ).mbc_str() );
strcat((char *) wrkbuf, (const char*) "</filtered>");
strcat((char *) wrkbuf, (const char*) "<errors>");
strcat((char *) wrkbuf, wxString::Format( _("%d"), errors ).mbc_str() );
strcat((char *) wrkbuf, (const char*) "</errors>");
web_write( conn, wrkbuf, strlen( wrkbuf ) );
// End tag
strcpy((char *) wrkbuf, "</vscp-rest>" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
else { // no events available
sprintf( wrkbuf, REST_XML_ERROR_INPUT_QUEUE_EMPTY"\r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
// JSON / JSONP
else if ( ( REST_FORMAT_JSON == format ) ||
( REST_FORMAT_JSONP == format ) ) {
int sentEvents = 0;
int filtered = 0;
int errors = 0;
json output;
// Send header
if ( REST_FORMAT_JSONP == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSONP );
}
else {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSON );
}
if ( pSession->m_pClientItem->m_bOpen && cntAvailable ) {
// typeof handler === 'function' &&
if ( REST_FORMAT_JSONP == format ) {
wxString str = _("typeof handler === 'function' && handler(");
web_write( conn, (const char *)str.mbc_str(), str.Length() );
}
output["success"] = true;
output["code"] = 1;
output["message"] = "success";
output["description"] = "Success";
output["info"] =
(const char *)wxString::Format(
"%zd events requested of %lu available "
"(unfiltered) %zd will be retrieved",
count,
cntAvailable,
MIN( count, cntAvailable ) ).mbc_str();
for ( unsigned int i=0; i<MIN( count, cntAvailable ); i++ ) {
CLIENTEVENTLIST::compatibility_iterator nodeClient;
vscpEvent *pEvent;
pSession->m_pClientItem->m_mutexClientInputQueue.Lock();
nodeClient = pSession->m_pClientItem->m_clientInputQueue.GetFirst();
pEvent = nodeClient->GetData();
pSession->m_pClientItem->m_clientInputQueue.DeleteNode(nodeClient);
pSession->m_pClientItem->m_mutexClientInputQueue.Unlock();
if ( NULL != pEvent ) {
if ( vscp_doLevel2Filter( pEvent,
&pSession->m_pClientItem->m_filterVSCP ) ) {
wxString str;
json ev;
ev["head"] = pEvent->head;
ev["vscpclass"] = pEvent->vscp_class;
ev["vscptype"] = pEvent->vscp_type;
vscp_getDateStringFromEvent( pEvent, str );
ev["datetime"] = (const char *)str.mbc_str();
ev["timestamp"] = pEvent->timestamp;
ev["obid"] = pEvent->obid;
vscp_writeGuidToString( pEvent, str);
ev["guid"] = (const char *)str.mbc_str();
ev["sizedata"] = pEvent->sizeData;
ev["data"] = json::array();
for ( uint16_t j=0; j<pEvent->sizeData; j++ ) {
ev["data"].push_back( pEvent->pdata[j] );
}
// Add event to event array
output["event"].push_back( ev );
sentEvents++;
}
else {
filtered++;
}
// Remove the event
vscp_deleteVSCPevent( pEvent );
} // Valid pEvent pointer
else {
errors++;
}
} // for
// Mark end
output["count"] = sentEvents;
output["filtered"] = filtered;
output["errors"] = errors;
std::string s = output.dump();
web_write( conn, s.c_str(), s.length() );
if ( REST_FORMAT_JSONP == format ) {
web_write( conn, ");", 2 );
}
} // if open and data
else { // no events available
if ( REST_FORMAT_JSON == format ) {
sprintf( wrkbuf, REST_JSON_ERROR_INPUT_QUEUE_EMPTY"\r\n");
}
else {
sprintf( wrkbuf, REST_JSONP_ERROR_INPUT_QUEUE_EMPTY"\r\n");
}
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
} // format
web_write( conn, "", 0 );
}
else { // Queue is empty
restsrv_error( conn, pSession, format, RESR_ERROR_CODE_INPUT_QUEUE_EMPTY );
}
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doSetFilter
//
void
restsrv_doSetFilter( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
vscpEventFilter& vscpfilter )
{
if ( NULL != pSession ) {
pSession->m_pClientItem->m_mutexClientInputQueue.Lock();
memcpy( &pSession->m_pClientItem->m_filterVSCP,
&vscpfilter,
sizeof( vscpEventFilter ) );
pSession->m_pClientItem->m_mutexClientInputQueue.Unlock();
restsrv_error( conn, pSession, format, REST_ERROR_CODE_SUCCESS );
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doClearQueue
//
void
restsrv_doClearQueue( struct web_connection *conn,
struct restsrv_session *pSession,
int format )
{
// Check pointer
if (NULL == conn) return;
if ( NULL != pSession ) {
CLIENTEVENTLIST::iterator iterVSCP;
pSession->m_pClientItem->m_mutexClientInputQueue.Lock();
for ( iterVSCP = pSession->m_pClientItem->m_clientInputQueue.begin();
iterVSCP != pSession->m_pClientItem->m_clientInputQueue.end();
++iterVSCP) {
vscpEvent *pEvent = *iterVSCP;
vscp_deleteVSCPevent(pEvent);
}
pSession->m_pClientItem->m_clientInputQueue.Clear();
pSession->m_pClientItem->m_mutexClientInputQueue.Unlock();
restsrv_error( conn, pSession, format, REST_ERROR_CODE_SUCCESS );
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doCreateVariable
//
void
restsrv_doCreateVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariable,
wxString& strType,
wxString& strValue,
wxString& strPersistent,
wxString& strAccessRight,
wxString& strNote )
{
int type = VSCP_DAEMON_VARIABLE_CODE_STRING;
bool bPersistence = false;
uint32_t accessright = 0x700;
wxStringTokenizer tkz( strVariable, _(";") );
// Check pointer
if (NULL == conn) {
return;
}
// Get type
if ( strType.IsNumber() ) {
type = vscp_readStringValue( strType );
}
else {
type = CVSCPVariable::getVariableTypeFromString( strType );
}
// Get persistence
strPersistent.Trim();
strPersistent.Trim( false );
strPersistent.MakeUpper();
if ( wxNOT_FOUND != strPersistent.Find( _( "TRUE" ) ) ) {
bPersistence = true;
}
// Get access rights
strAccessRight.Trim();
strAccessRight.Trim( false );
if ( !strAccessRight.IsEmpty() ) {
accessright = vscp_readStringValue( strAccessRight );
}
if ( NULL != pSession ) {
// Add the variable
if ( !gpobj->m_variables.add( strVariable,
strValue,
type,
pSession->m_pClientItem->m_pUserItem->getUserID(),
bPersistence,
accessright,
strNote ) ) {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_VARIABLE_NOT_CREATED );
return;
}
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_SUCCESS );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doReadVariable
//
void
restsrv_doReadVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariableName )
{
char buf[512];
char wrkbuf[512];
// Check pointer
if (NULL == conn) return;
if ( NULL != pSession ) {
CVSCPVariable variable;
if ( 0 == gpobj->m_variables.find( strVariableName, variable ) ) {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_VARIABLE_NOT_FOUND );
return;
}
if ( REST_FORMAT_PLAIN == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_PLAIN );
sprintf( wrkbuf, "1 1 Success \r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf( wrkbuf,
"name=%s type=%d user=%lu access-right=%03X "
"persistent=%s last-change='%s' value='%s' "
"note='%s'\r\n",
(const char *)variable.getName().mbc_str(),
variable.getType(),
(unsigned long)variable.getOwnerID(),
variable.getAccessRights(),
variable.isPersistent() ? "true" : "false",
(const char *)variable.getLastChange().FormatISOCombined().mbc_str(),
(const char *)variable.getValue().mbc_str(),
(const char *)variable.getNote().mbc_str() );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
else if ( REST_FORMAT_CSV == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_CSV );
sprintf( wrkbuf,
"success-code,error-code,message,description,name,type,user,"
"access-right,persistent,last-change,value,note\r\n1,1,Success,"
"Success.,%s,%d,%lu,%03X,%s,%s,'%s','%s'\r\n",
(const char *)strVariableName.mbc_str(),
variable.getType(),
(unsigned long)variable.getOwnerID(),
variable.getAccessRights(),
variable.isPersistent() ? "true" : "false",
(const char *)variable.getLastChange().FormatISOCombined().mbc_str(),
(const char *)variable.getValue().mbc_str(),
(const char *)variable.getNote().mbc_str() );
web_write( conn, wrkbuf, strlen( wrkbuf ) );
}
else if ( REST_FORMAT_XML == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_XML );
sprintf( wrkbuf,
XML_HEADER"<vscp-rest success = \"true\" code "
"= \"1\" message = \"Success\" description = \"Success.\" >");
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf( wrkbuf,
"<variable name=\"%s\" typecode=\"%d\" type=\"%s\" "
"user=\"%lu\" access-right=\"%03X\" persistent=\"%s\" "
"last-change=\"%s\" >",
(const char *)variable.getName().mbc_str(),
variable.getType(),
variable.getVariableTypeAsString( variable.getType() ),
(unsigned long)variable.getOwnerID(),
variable.getAccessRights(),
variable.isPersistent() ? "true" : "false",
(const char *)variable.getLastChange().FormatISOCombined().mbc_str() );
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf((char *) wrkbuf,
"<name>%s</name><value>%s</value><note>%s</note>",
(const char *)variable.getName().mbc_str(),
(const char *)variable.getValue().mbc_str(),
(const char *)variable.getNote().mbc_str() );
web_write( conn, wrkbuf, strlen( wrkbuf) );
// End tag
strcpy((char *) wrkbuf, "</variable>" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
// End tag
strcpy((char *) wrkbuf, "</vscp-rest>" );
web_write( conn, wrkbuf, strlen( wrkbuf));
}
else if ( ( REST_FORMAT_JSON == format ) ||
( REST_FORMAT_JSONP == format ) ) {
wxString wxstr;
json output;
if ( REST_FORMAT_JSONP == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSONP );
}
else {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSON );
}
if ( pSession->m_pClientItem->m_bOpen ) {
if ( REST_FORMAT_JSONP == format ) {
// Write JSONP start block
web_write( conn,
REST_JSONP_START,
strlen( REST_JSONP_START ) );
}
output["success"] = true;
output["code"] = 1;
output["message"] = "success";
output["description"] = "Success";
output["varname"] = (const char *)variable.getName().mbc_str();
output["vartype"] = variable.getVariableTypeAsString( variable.getType() );
output["vartypecode"] = variable.getType();
output["varuser"] = variable.getOwnerID();
output["varaccessright"] = variable.getAccessRights();
output["varpersistence"] = variable.isPersistent();
output["varlastchange"] =
(const char *)variable.getLastChange().FormatISOCombined().mbc_str();
output["varvalue"] = (const char *)variable.getValue().mbc_str();
output["varnote"] = (const char *)variable.getNote().mbc_str();
std::string s = output.dump();
web_write( conn, s.c_str(), s.length() );
if ( REST_FORMAT_JSONP == format ) {
// Write JSONP end block
web_write( conn,
REST_JSONP_END,
strlen( REST_JSONP_END ) );
}
}
}
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doListVariable
//
void
restsrv_doListVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strRegEx,
bool bShort )
{
char wrkbuf[8192];
// Check pointer
if (NULL == conn) return;
strRegEx.Trim();
if ( NULL != pSession ) {
wxArrayString variable_array;
if ( !gpobj->m_variables.getVarlistFromRegExp( variable_array, strRegEx ) ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_VARIABLE_NOT_FOUND );
return;
}
if ( REST_FORMAT_PLAIN == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_PLAIN );
sprintf( wrkbuf, "1 1 Success \r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
for ( unsigned int i=0; i<variable_array.GetCount(); i++ ) {
CVSCPVariable variable;
if ( 0 == gpobj->m_variables.find( variable_array[ i ], variable ) ) {
continue;
}
if ( bShort ) {
sprintf( wrkbuf,
"name=%s type=%d user=%lu access-right=%03X last-change='%s' persistent=%s\r\n",
(const char *)variable.getName().mbc_str(),
variable.getType(),
(unsigned long)variable.getOwnerID(),
variable.getAccessRights(),
(const char *)variable.getLastChange().FormatISOCombined().mbc_str(),
variable.isPersistent() ? "true" : "false" );
}
else {
sprintf( wrkbuf,
"name=%s type=%d user=%lu access-right=%03X last-change='%s' persistent=%s value=%s note=%s\r\n",
(const char *)variable.getName().mbc_str(),
variable.getType(),
(unsigned long)variable.getOwnerID(),
variable.getAccessRights(),
(const char *)variable.getLastChange().FormatISOCombined().mbc_str(),
variable.isPersistent() ? "true" : "false",
(const char *)variable.getValue( true ).mbc_str(),
(const char *)variable.getNote( true ).mbc_str() );
}
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
else if ( REST_FORMAT_CSV == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_CSV );
if ( pSession->m_pClientItem->m_bOpen && variable_array.GetCount() ) {
sprintf( wrkbuf, "success-code,error-code,message,description,Variable\r\n1,1,Success,Success.,NULL\r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf( wrkbuf,
"1,2,Info,%zd variables found,NULL\r\n",
variable_array.GetCount() );
web_write( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"1,5,Count,%zu,NULL\r\n",
variable_array.GetCount() );
web_write( conn, wrkbuf, strlen( wrkbuf ) );
for ( unsigned int i=0; i<variable_array.GetCount(); i++ ) {
CVSCPVariable variable;
if ( 0 == gpobj->m_variables.find( variable_array[ i ], variable ) ) {
continue;
}
if ( bShort ) {
sprintf( wrkbuf,
"1,3,Data,Variable,%s\r\n",
(const char *)variable.getAsString( true ).mbc_str() );
}
else {
sprintf( wrkbuf,
"1,3,Data,Variable,%s\r\n",
(const char *)variable.getAsString( false ).mbc_str() );
}
web_write( conn, wrkbuf, strlen( wrkbuf ) );
} // for
}
else { // no events available
sprintf( wrkbuf, REST_CSV_ERROR_INPUT_QUEUE_EMPTY"\r\n");
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
else if ( REST_FORMAT_XML == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_XML );
sprintf( wrkbuf, XML_HEADER"<vscp-rest success = \"true\" code = \"1\" message = \"Success\" description = \"Success.\" >");
web_write( conn, wrkbuf, strlen( wrkbuf) );
sprintf( wrkbuf, "<count>%zu</count>",variable_array.GetCount() );
for ( unsigned int i=0; i<variable_array.GetCount(); i++ ) {
CVSCPVariable variable;
if ( 0 == gpobj->m_variables.find( variable_array[ i ], variable ) ) {
continue;
}
sprintf( wrkbuf,
"<variable name=\"%s\" typecode=\"%d\" type=\"%s\" user=\"%lu\" access-right=\"%03X\" persistent=\"%s\" last-change=\"%s\" >",
(const char *)variable.getName().mbc_str(),
variable.getType(),
variable.getVariableTypeAsString( variable.getType() ),
(unsigned long)variable.getOwnerID(),
variable.getAccessRights(),
variable.isPersistent() ? "true" : "false",
(const char *)variable.getLastChange().FormatISOCombined().mbc_str() );
web_write( conn, wrkbuf, strlen( wrkbuf) );
if ( !bShort ) {
sprintf((char *) wrkbuf,
"<name>%s</name><value>%s</value><note>%s</note>",
(const char *)variable.getName().mbc_str(),
(const char *)variable.getValue(true).mbc_str(),
(const char *)variable.getNote(true).mbc_str() );
web_write( conn, wrkbuf, strlen( wrkbuf) );
}
}
// End tag
strcpy((char *) wrkbuf, "</variable>" );
web_write( conn, wrkbuf, strlen( wrkbuf) );
// End tag
strcpy((char *) wrkbuf, "</vscp-rest>" );
web_write( conn, wrkbuf, strlen( wrkbuf));
}
else if ( ( REST_FORMAT_JSON == format ) ||
( REST_FORMAT_JSONP == format ) ) {
json output;
wxString wxstr;
if ( REST_FORMAT_JSONP == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSONP );
}
else {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSON );
}
if ( pSession->m_pClientItem->m_bOpen ) {
if ( REST_FORMAT_JSONP == format ) {
// Write JSONP start block
web_write( conn,
REST_JSONP_START,
strlen( REST_JSONP_START ) );
}
output["success"] = true;
output["code"] = 1;
output["message"] = "success";
output["description"] = "Success";
output["info"] =
(const char *)wxString::Format( _("\"%zd variables will be retrieved\""),
variable_array.Count() );
output["variable"] = json::array();
uint32_t cntVariable = 0;
uint32_t cntErrors = 0;
for ( unsigned int i=0; i<variable_array.GetCount(); i++ ) {
CVSCPVariable variable;
json var;
if ( 0 == gpobj->m_variables.find( variable_array[ i ], variable ) ) {
cntErrors++;
continue;
}
var["success"] = true;
var["code"] = 1;
var["message"] = "success";
var["description"] = "Success";
var["varname"] = (const char *)variable.getName().mbc_str();
var["vartype"] = variable.getVariableTypeAsString( variable.getType() );
var["vartypecode"] = variable.getType();
var["varuser"] = variable.getOwnerID();
var["varaccessright"] = variable.getAccessRights();
var["varpersistence"] = variable.isPersistent();
var["varlastchange"] =
(const char *)variable.getLastChange().FormatISOCombined().mbc_str();
if ( !bShort ) {
var["varvalue"] = (const char *)variable.getValue(true).mbc_str();
var["varnote"] = (const char *)variable.getNote(true).mbc_str();
}
// Add event to event array
output["variable"].push_back( var );
cntVariable++;
} // for
// Mark end
output["count"] = cntVariable;
output["errors"] = cntErrors;
std::string s = output.dump();
web_write( conn, s.c_str(), s.length() );
if ( REST_FORMAT_JSONP == format ) {
// Write JSONP end block
web_write( conn,
REST_JSONP_END,
strlen( REST_JSONP_END ) );
}
}
}
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doWriteVariable
//
void
restsrv_doWriteVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariableName,
wxString& strValue )
{
wxString strName;
// Check pointer
if (NULL == conn) {
return;
}
if ( NULL != pSession ) {
// Get variable name
CVSCPVariable variable;
if ( 0 == gpobj->m_variables.find( strVariableName, variable ) ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_VARIABLE_NOT_FOUND );
return;
}
// Set variable value
if ( !variable.setValueFromString( variable.getType(), strValue ) ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_MISSING_DATA );
return;
}
if ( !gpobj->m_variables.update( variable ) ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_VARIABLE_FAIL_UPDATE );
return;
}
restsrv_error( conn, pSession, format, REST_ERROR_CODE_SUCCESS );
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doDeleteVariable
//
void
restsrv_doDeleteVariable( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strVariable )
{
int type = VSCP_DAEMON_VARIABLE_CODE_STRING;
bool bPersistence = false;
wxStringTokenizer tkz( strVariable, _(";") );
// Check pointer
if (NULL == conn) {
return;
}
if ( NULL != pSession ) {
// Add the variable
if ( !gpobj->m_variables.remove( strVariable ) ) {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_VARIABLE_NOT_DELETED );
return;
}
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_SUCCESS );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doWriteMeasurement
//
void
restsrv_doWriteMeasurement( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strDateTime,
wxString& strGuid,
wxString& strLevel,
wxString& strType,
wxString& strValue,
wxString& strUnit,
wxString& strSensorIdx,
wxString& strZone,
wxString& strSubZone,
wxString& strEventFormat )
{
if ( NULL != pSession ) {
double value = 0;
uint8_t guid[ 16 ];
long level = 2;
long unit;
long vscptype;
long sensoridx;
long zone;
long subzone;
long eventFormat = 0; // float
uint8_t data[ VSCP_MAX_DATA ];
uint16_t sizeData;
memset( guid, 0, 16 );
vscp_getGuidFromStringToArray( guid, strGuid );
strValue.Trim();
strValue.Trim(false);
strValue.ToDouble( &value ); // Measurement value
strUnit.ToLong( &unit ); // Measurement unit
strSensorIdx.ToLong( &sensoridx ); // Sensor index
strType.ToLong( &vscptype ); // VSCP event type
strZone.ToLong( &zone ); // VSCP event type
zone &= 0xff;
strSubZone.ToLong( &subzone ); // VSCP event type
subzone &= 0xff;
// datetime
wxDateTime dt;
if ( !dt.ParseISOCombined( strDateTime ) ) {
dt = wxDateTime::UNow();
}
strLevel.ToLong( &level ); // Level I or Level II (default)
if ( ( level > 2 ) || ( level < 1 ) ) {
level = 2;
}
strEventFormat.Trim();
strEventFormat.Trim( false );
strEventFormat.MakeUpper();
if ( wxNOT_FOUND != strEventFormat.Find( _( "STRING" ) ) ) {
eventFormat = 1;
}
// Range checks
if ( 1 == level ) {
if ( unit > 3 ) unit = 0;
if ( sensoridx > 7 ) sensoridx = 0;
if ( vscptype > 512 ) vscptype -= 512;
}
else if ( 2 == level ) {
if ( unit > 255 ) unit &= 0xff;
if ( sensoridx > 255 ) sensoridx &= 0xff;
}
if ( 1 == level ) {
if ( 0 == eventFormat ) {
// Floating point
if ( vscp_convertFloatToFloatEventData( data,
&sizeData,
value,
unit,
sensoridx ) ) {
if ( sizeData > 8 ) sizeData = 8;
vscpEvent *pEvent = new vscpEvent;
if ( NULL == pEvent ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE );
return;
}
pEvent->pdata = NULL;
pEvent->head = VSCP_PRIORITY_NORMAL;
pEvent->timestamp = 0; // Let interface fill in
memcpy( pEvent->GUID, guid, 16 );
pEvent->sizeData = sizeData;
if ( sizeData > 0 ) {
pEvent->pdata = new uint8_t[ sizeData ];
memcpy( pEvent->pdata, data, sizeData );
}
pEvent->vscp_class = VSCP_CLASS1_MEASUREMENT;
pEvent->vscp_type = vscptype;
restsrv_doSendEvent( conn, pSession, format, pEvent );
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_GENERAL_FAILURE );
}
}
else {
// String
vscpEvent *pEvent = new vscpEvent;
if ( NULL == pEvent ) {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_GENERAL_FAILURE );
return;
}
pEvent->pdata = NULL;
if ( vscp_makeStringMeasurementEvent( pEvent,
value,
unit,
sensoridx ) ) {
}
else {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_GENERAL_FAILURE );
}
}
}
else { // Level II
if ( 0 == eventFormat ) {
// Floating point
vscpEvent *pEvent = new vscpEvent;
if ( NULL == pEvent ) {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_GENERAL_FAILURE );
return;
}
pEvent->pdata = NULL;
pEvent->obid = 0;
pEvent->head = VSCP_PRIORITY_NORMAL;
pEvent->timestamp = 0; // Let interface fill in
memcpy( pEvent->GUID, guid, 16 );
pEvent->head = 0;
pEvent->vscp_class = VSCP_CLASS2_MEASUREMENT_FLOAT;
pEvent->vscp_type = vscptype;
pEvent->timestamp = 0;
pEvent->sizeData = 12;
data[ 0 ] = sensoridx;
data[ 1 ] = zone;
data[ 2 ] = subzone;
data[ 3 ] = unit;
memcpy( data + 4, ( uint8_t * )&value, 8 ); // copy in double
uint64_t temp = wxUINT64_SWAP_ON_LE( *(data + 4) );
memcpy( data+4, (void *)&temp, 8 );
// Copy in data
pEvent->pdata = new uint8_t[ 4 + 8 ];
if ( NULL == pEvent->pdata ) {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_GENERAL_FAILURE );
delete pEvent;
return;
}
memcpy( pEvent->pdata, data, 4 + 8 );
restsrv_doSendEvent( conn, pSession, format, pEvent );
}
else {
// String
vscpEvent *pEvent = new vscpEvent;
pEvent->pdata = NULL;
pEvent->obid = 0;
pEvent->head = VSCP_PRIORITY_NORMAL;
pEvent->timestamp = 0; // Let interface fill in
memcpy( pEvent->GUID, guid, 16 );
pEvent->head = 0;
pEvent->vscp_class = VSCP_CLASS2_MEASUREMENT_STR;
pEvent->vscp_type = vscptype;
pEvent->timestamp = 0;
pEvent->sizeData = 12;
data[ 0 ] = sensoridx;
data[ 1 ] = zone;
data[ 2 ] = subzone;
data[ 3 ] = unit;
pEvent->pdata = new uint8_t[ 4 + strValue.Length() ];
if ( NULL == pEvent->pdata ) {
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_GENERAL_FAILURE );
delete pEvent;
return;
}
memcpy( data + 4,
strValue.mbc_str(),
strValue.Length() ); // copy in double
restsrv_doSendEvent( conn, pSession, format, pEvent );
}
}
restsrv_error( conn, pSession, format, REST_ERROR_CODE_SUCCESS );
}
else {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_INVALID_SESSION );
}
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doGetTableData
//
void
websrc_renderTableData( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strName,
struct _vscpFileRecord *pRecords,
long nfetchedRecords )
{
/*
char buf[ 2048 ];
char wrkbuf[ 2048 ];
long nRecords = 0;
if ( REST_FORMAT_PLAIN == format ) {
// Send header
websrv_sendheader( conn, 200, REST_MIME_TYPE_PLAIN );
sprintf( wrkbuf,
"1 1 Success\r\n%ld records will be returned from table %s.\r\n",
nfetchedRecords,
( const char * )strName.mbc_str() );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime =
dt.FormatISODate() + _( " " ) + dt.FormatISOTime();
sprintf( wrkbuf,
"%ld - Date=%s,Value=%f\r\n",
i,
( const char * )strDateTime.mbc_str(),
pRecords->measurement );
web_printf( conn, wrkbuf, strlen( wrkbuf ));
}
}
else if ( REST_FORMAT_CSV == format ) {
// Send header
websrv_sendheader( conn, 200, REST_MIME_TYPE_CSV );
sprintf( wrkbuf,
"success-code, error-code, message, description, EvenL\r\n1, 1, Success, Success., NULL\r\n" );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"1, 2, Info, Success %ld records will be returned from table %s.,NULL\r\n",
nfetchedRecords,
( const char * )strName.mbc_str() );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"1, 4, Count, %ld, NULL\r\n",
nfetchedRecords );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime = dt.FormatISODate() + _( " " ) + dt.FormatISOTime();
sprintf( wrkbuf,
"1,3,Data,Table,%ld - Date=%s,Value=%f\r\n",
i,
( const char * )strDateTime.mbc_str(),
pRecords->measurement );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
}
else if ( REST_FORMAT_XML == format ) {
// Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_XML );
sprintf( wrkbuf,
"<vscp-rest success=\"true\" code=\"1\" message=\"Success\" description=\"Success.\">\r\n" );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"<count>%ld</count>\r\n<info>Fetched %ld elements of table %s</info>\r\n",
nfetchedRecords,
nfetchedRecords,
( const char * )strName.mbc_str() );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime = dt.FormatISODate() + _( " " ) + dt.FormatISOTime();
sprintf( wrkbuf,
"<data id=\"%ld\" date=\"%s\" value=\"%f\"></data>\r\n",
i,
( const char * )strDateTime.mbc_str(),
pRecords->measurement );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
sprintf( wrkbuf,
"</vscp-rest>\r\n" );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
else if ( ( REST_FORMAT_JSON == format ) || ( REST_FORMAT_JSONP == format ) ) {
if ( REST_FORMAT_JSON == format ) {
// Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_JSON );
}
else { // Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_JSONP );
}
memset( buf, 0, sizeof( buf ) );
char *p = wrkbuf;
if ( REST_FORMAT_JSONP == format ) {
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "typeof handler === 'function' && handler(", 41 );
}
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p,
"{\"success\":true,\"code\":1,\"message\":\"success\",\"description\":\"Success\",",
strlen( "{\"success\":true,\"code\":1,\"message\":\"success\",\"description\":\"Success\"," ) );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "info", 4 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
{
char buf2[ 200 ];
sprintf( buf2,
"\"%ld rows will be retreived from table %s\"",
nfetchedRecords,
( const char * )strName.mbc_str() );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, buf2, strlen( buf2 ) );
}
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "table", 5 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":[", 2 );
memset( buf, 0, sizeof( buf ) );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
p = wrkbuf;
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime = dt.FormatISODate() + _("T") + dt.FormatISODate(); //dt.git pull();
memset( wrkbuf, 0, sizeof( wrkbuf ) );
p = wrkbuf;
sprintf( buf,
"{\"id\":%ld,\"date\":\"%s\",\"value\":%f}",
i,
( const char * )strDateTime.mbc_str(),
pRecords->measurement );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, buf, strlen( buf ) );
if ( i < ( nfetchedRecords - 1 ) ) {
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
}
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
memset( wrkbuf, 0, sizeof( wrkbuf ) );
p = wrkbuf;
// Mark end
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "],", 2 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "count", 5 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
p += json_emit_long( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, nfetchedRecords );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "filtered", 8 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
p += json_emit_long( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, 0 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "errors", 6 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
p += json_emit_long( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, 0 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "}", 1 );
if ( REST_FORMAT_JSONP == format ) {
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ");", 2 );
}
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
web_printf( conn, "", 0 ); // Terminator
*/
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_rest_doGetTableData
//
void
restsrv_doGetTableData( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strName,
wxString& strFrom,
wxString& strTo )
{
/*
//char buf[ 2048 ];
//char wrkbuf[ 2048 ];
long nRecords = 0;
// Check pointer
if ( NULL == conn ) return;
if ( NULL != pSession ) {
// We need 'tablename' and optionally 'from' and 'to'
CVSCPTable *ptblItem = NULL;
gpobj->m_mutexTableList.Lock();
listVSCPTables::iterator iter;
for ( iter = gpobj->m_listTables.begin(); iter != gpobj->m_listTables.end(); ++iter ) {
ptblItem = *iter;
if ( 0 == strcmp( ptblItem->m_vscpFileHead.nameTable, ( const char * )strName.mbc_str() ) ) {
break;
}
ptblItem = NULL;
}
gpobj->m_mutexTableList.Unlock();
// If found pTable should not be NULL
if ( NULL == ptblItem ) {
restsrv_rest_error( nc, pSession, format, REST_ERROR_CODE_TABLE_NOT_FOUND );
return;
}
// Get data from table
int nRange = 0; // 2 if to + from, 1 if from, 0 if non of them
wxDateTime timeFrom = wxDateTime::Now();
wxDateTime timeTo = wxDateTime::Now();
// Get from-date for range
strFrom.Trim();
if ( strFrom.Length() ) {
timeFrom.ParseDateTime( strFrom );
//wxstr = timeFrom.FormatISODate() + _( " " ) + timeFrom.FormatISOTime();
nRange++; // Start date entered
}
// Get to-date for range
strTo.Trim();
if ( strTo.Length() ) {
timeTo.ParseDateTime( strTo );
//wxstr = timeTo.FormatISODate() + _( " " ) + timeTo.FormatISOTime();
nRange++; // End date entered
}
// Check range
if ( ( nRange > 1 ) && timeTo.IsEarlierThan( timeFrom ) ) {
restsrv_rest_error( nc, pSession, format, REST_ERROR_CODE_TABLE_RANGE );
return;
}
///////////////////////////////////////////////////////////////////////
// Dynamic table
///////////////////////////////////////////////////////////////////////
if ( VSCP_TABLE_DYNAMIC == ptblItem->m_vscpFileHead.type ) {
uint64_t start, end;
if ( 0 == nRange ) {
// Neither 'from' or 'to' given
// Use value from header
start = ptblItem->getTimeStampStart();
end = ptblItem->getTimeStampEnd();
}
else if ( 1 == nRange ) {
// From given but no end
start = timeFrom.GetTicks();
end = ptblItem->getTimeStampEnd();
}
else {
// range given
start = timeFrom.GetTicks();
end = timeTo.GetTicks();
}
// Fetch number of records in set
ptblItem->m_mutexThisTable.Lock();
long nRecords = ptblItem->getRangeOfData( start, end );
ptblItem->m_mutexThisTable.Unlock();
if ( 0 == nRecords ) {
restsrv_rest_error( nc, pSession, format, REST_ERROR_CODE_TABLE_NO_DATA );
return;
}
struct _vscpFileRecord *pRecords = new struct _vscpFileRecord[ nRecords ];
if ( NULL == pRecords ) {
restsrv_rest_error( nc, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE );
return;
}
ptblItem->m_mutexThisTable.Lock();
long nfetchedRecords = ptblItem->getRangeOfData( start,
end,
( void * )pRecords,
nRecords* sizeof( struct _vscpFileRecord ) );
ptblItem->m_mutexThisTable.Unlock();
if ( 0 == nfetchedRecords ) {
delete[] pRecords;
restsrv_rest_error( nc, pSession, format, REST_ERROR_CODE_TABLE_NO_DATA );
return;
}
wxDateTime dtStart;
dtStart.Set( ( time_t )ptblItem->getTimeStampStart() );
wxString strDateTimeStart = dtStart.FormatISODate() + _( "T" ) + dtStart.FormatISOTime();
wxDateTime dtEnd;
dtEnd.Set( ( time_t )ptblItem->getTimeStampEnd() );
wxString strDateTimeEnd = dtEnd.FormatISODate() + _( "T" ) + dtEnd.FormatISOTime();
// Output table data
websrc_rest_renderTableData( nc,
pSession,
format,
strName,
pRecords,
nfetchedRecords );
if ( REST_FORMAT_PLAIN == format ) {
// Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_PLAIN );
sprintf( wrkbuf,
"1 1 Success\r\n%ld records will be returned from table %s.\r\n",
nfetchedRecords,
(const char *)strName.mbc_str() );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime = dt.FormatISODate() + _( " " ) + dt.FormatISOTime();
sprintf( wrkbuf,
"%ld - Date=%s,Value=%f\r\n",
i,
(const char *)strDateTime.mbc_str(),
pRecords->measurement );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
}
else if ( REST_FORMAT_CSV == format ) {
// Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_CSV );
sprintf( wrkbuf,
"success-code, error-code, message, description, EvenL\r\n1, 1, Success, Success., NULL\r\n" );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"1, 2, Info, Success %d records will be returned from table %s.,NULL\r\n",
nfetchedRecords,
( const char * )strName.mbc_str() );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"1, 4, Count, %d, NULL\r\n",
nfetchedRecords );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime = dt.FormatISODate() + _( " " ) + dt.FormatISOTime();
sprintf( wrkbuf,
"1,3,Data,Table,%d - Date=%s,Value=%f\r\n",
i,
( const char * )strDateTime.mbc_str(),
pRecords->measurement );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
}
else if ( REST_FORMAT_XML == format ) {
// Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_XML );
sprintf( wrkbuf,
"<vscp-rest success=\"true\" code=\"1\" message=\"Success\" description=\"Success.\">\r\n" );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
sprintf( wrkbuf,
"<count>%d</count>\r\n<info>Fetched %d elements of table %s</info>\r\n",
nfetchedRecords,
nfetchedRecords,
( const char * )strName.mbc_str() );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime = dt.FormatISODate() + _( " " ) + dt.FormatISOTime();
sprintf( wrkbuf,
"<data id=\"%d\" date=\"%s\" value=\"%f\"></data>\r\n",
i,
( const char * )strDateTime.mbc_str(),
pRecords->measurement );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
sprintf( wrkbuf,
"</vscp-rest>\r\n" );
web_printf( conn, wrkbuf, strlen( wrkbuf ));
}
else if ( ( REST_FORMAT_JSON == format ) || ( REST_FORMAT_JSONP == format ) ) {
if ( REST_FORMAT_JSON == format ) {
// Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_JSON );
}
else { // Send header
restsrv_sendHeader( conn, 200, REST_MIME_TYPE_JSONP );
}
char *p = wrkbuf;
if ( REST_FORMAT_JSONP == format ) {
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "typeof handler === 'function' && handler(", 41 );
}
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p,
"{\"success\":true,\"code\":1,\"message\":\"success\",\"description\":\"Success\",",
strlen( "{\"success\":true,\"code\":1,\"message\":\"success\",\"description\":\"Success\"," ) );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "info", 4 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
{
char buf2[ 200 ];
sprintf( buf2,
"\"%d rows will be retreived from table %s\"",
nfetchedRecords,
( const char * )strName.mbc_str() );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, buf2, strlen( buf2 ) );
}
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "table", 5 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":[", 2 );
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
p = wrkbuf;
for ( long i = 0; i < nfetchedRecords; i++ ) {
wxDateTime dt;
dt.Set( ( time_t )pRecords[ i ].timestamp );
wxString strDateTime = dt.FormatISOCombined();
memset( wrkbuf, 0, sizeof( wrkbuf ) );
p = wrkbuf;
sprintf( buf,
"{\"id\":%d,\"date\":\"%s\",\"value\":%f}",
i,
( const char * )strDateTime.mbc_str(),
pRecords->measurement );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, buf, strlen( buf ) );
if ( i < ( nfetchedRecords - 1 ) ) {
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
}
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
memset( wrkbuf, 0, sizeof( wrkbuf ) );
p = wrkbuf;
// Mark end
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "],", 2 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "count", 5 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
p += json_emit_long( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, nfetchedRecords );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "filtered", 8 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
p += json_emit_long( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, 0 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ",", 1 );
p += json_emit_quoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "errors", 6 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ":", 1 );
p += json_emit_long( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, 0 );
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, "}", 1 );
if ( REST_FORMAT_JSONP == format ) {
p += json_emit_unquoted_str( p, &wrkbuf[ sizeof( wrkbuf ) ] - p, ");", 2 );
}
web_printf( conn, wrkbuf, strlen( wrkbuf ) );
}
web_printf( conn, "", 0 ); // Terminator
// De allocate storage
delete[] pRecords;
}
///////////////////////////////////////////////////////////////////////
// Static table
///////////////////////////////////////////////////////////////////////
else if ( VSCP_TABLE_STATIC == ptblItem->m_vscpFileHead.type ) {
// Fetch number of records in set
ptblItem->m_mutexThisTable.Lock();
long nRecords = ptblItem->getStaticRequiredBuffSize();
ptblItem->m_mutexThisTable.Unlock();
if ( nRecords > 0 ) {
struct _vscpFileRecord *pRecords = new struct _vscpFileRecord[ nRecords ];
if ( NULL == pRecords ) {
restsrv_rest_error( nc, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE );
return;
}
// Fetch data
long nfetchedRecords = ptblItem->getStaticData( pRecords, sizeof( pRecords ) );
// Output table data
websrc_rest_renderTableData( nc,
pSession,
format,
strName,
pRecords,
nfetchedRecords );
// First send start post with number if records
mg_printf_websocket_frame( nc,
WEBSOCKET_OP_TEXT,
"+;GT;START;%d",
nfetchedRecords );
// Then send measurement records
for ( long i = 0; i<nfetchedRecords; i++ ) {
mg_printf_websocket_frame( nc,
WEBSOCKET_OP_TEXT,
"+;GT;%d;%d;%f",
i, pRecords[ i ].timestamp, pRecords[ i ].measurement );
}
// Last send end post with number if records
mg_printf_websocket_frame( nc,
WEBSOCKET_OP_TEXT,
"+;GT;END;%d",
nfetchedRecords );
// Deallocate storage
delete[] pRecords;
web_printf( conn, "", 0 ); // Terminator
}
}
// No records
else {
restsrv_rest_error( nc, pSession, format, REST_ERROR_CODE_TABLE_NO_DATA );
return;
}
}
*/
return;
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_convertXML2JSON
//
// XML to JSON convert
//
void restsrv_convertXML2JSON( const char *input, const char *output )
{
ifstream is( input );
ostringstream oss;
oss << is.rdbuf();
// TODO
string json_str; // = xml2json( oss.str().data() );
ofstream myfile;
myfile.open( output );
myfile << json_str << endl;
myfile.close();
}
///////////////////////////////////////////////////////////////////////////////
// restsrv_doFetchMDF
//
void
restsrv_doFetchMDF( struct web_connection *conn,
struct restsrv_session *pSession,
int format,
wxString& strURL )
{
CMDF mdf;
if ( mdf.load( strURL, false, true ) ) {
// Loaded OK
if ( REST_FORMAT_PLAIN == format ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE );
}
else if ( REST_FORMAT_CSV == format ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE );
}
else if ( REST_FORMAT_XML == format ) {
// Send header
websrv_sendheader( conn, 200, REST_MIME_TYPE_XML );
char buf[ 5000 ], wrkbuf[ 2000 ];
ssize_t ss;
wxFile file( mdf.getTempFilePath() );
while ( !file.Eof() ) {
ss = file.Read( wrkbuf, sizeof( wrkbuf ) );
web_write( conn, wrkbuf, ss );
}
file.Close();
web_write( conn, "", 0 ); // Terminator
}
else if ( ( REST_FORMAT_JSON == format ) || ( REST_FORMAT_JSONP == format ) ) {
char buf[ 5000 ], wrkbuf[ 2000 ];
wxString tempFileName = wxFileName::CreateTempFileName( _("__vscp__xml__") );
if ( 0 == tempFileName.Length() ) {
restsrv_error( conn, pSession, format, REST_ERROR_CODE_GENERAL_FAILURE );
}
std::string tempfile_out = std::string( tempFileName.mb_str() );
std::string tempfile_mdf = std::string( mdf.getTempFilePath().mb_str() );
// Convert to JSON
restsrv_convertXML2JSON( (const char *)tempFileName.mbc_str(),
(const char *)mdf.getTempFilePath().mbc_str() );
// Send header
if ( REST_FORMAT_JSON == format ) {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSON );
}
else {
websrv_sendheader( conn, 200, REST_MIME_TYPE_JSONP );
}
if ( REST_FORMAT_JSONP == format ) {
web_write( conn, "typeof handler === 'function' && handler(", 41 );
}
ssize_t ss;
wxString wxpath( tempfile_out.c_str(), wxConvUTF8 ); // Needed for 2.8.12
wxFile file( wxpath );
while ( !file.Eof() ) {
ss = file.Read( wrkbuf, sizeof( wrkbuf ) );
web_write( conn, wrkbuf, ss );
}
file.Close();
if ( REST_FORMAT_JSONP == format ) {
web_write( conn, ");", 2 );
}
web_write( conn, "", 0 ); // Terminator
}
}
else {
// Failed to load
restsrv_error( conn,
pSession,
format,
REST_ERROR_CODE_GENERAL_FAILURE );
}
return;
}
| 38.440327 | 217 | 0.445468 | [
"object"
] |
6bf12a060dcd1cca8dd9f664f56a2dbbf1d70179 | 2,050 | cc | C++ | tests/cpp/data/test_gradient_index.cc | hmchen-github/xgboost | af0cf88921f4d80a2a338e40f2620c9579afa100 | [
"Apache-2.0"
] | 1 | 2022-01-04T23:38:14.000Z | 2022-01-04T23:38:14.000Z | tests/cpp/data/test_gradient_index.cc | Nihilitior/xgboost | 7366d3b20cad8e28ecef67d5130c71e81bb0b088 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:21:59.000Z | 2022-01-07T04:58:09.000Z | tests/cpp/data/test_gradient_index.cc | Nihilitior/xgboost | 7366d3b20cad8e28ecef67d5130c71e81bb0b088 | [
"Apache-2.0"
] | 1 | 2018-12-09T14:30:38.000Z | 2018-12-09T14:30:38.000Z | /*!
* Copyright 2021-2022 XGBoost contributors
*/
#include <gtest/gtest.h>
#include <xgboost/data.h>
#include "../../../src/data/gradient_index.h"
#include "../helpers.h"
namespace xgboost {
namespace data {
TEST(GradientIndex, ExternalMemory) {
std::unique_ptr<DMatrix> dmat = CreateSparsePageDMatrix(10000);
std::vector<size_t> base_rowids;
std::vector<float> hessian(dmat->Info().num_row_, 1);
for (auto const &page : dmat->GetBatches<GHistIndexMatrix>({64, hessian, true})) {
base_rowids.push_back(page.base_rowid);
}
size_t i = 0;
for (auto const &page : dmat->GetBatches<SparsePage>()) {
ASSERT_EQ(base_rowids[i], page.base_rowid);
++i;
}
base_rowids.clear();
for (auto const &page : dmat->GetBatches<GHistIndexMatrix>({64, hessian, false})) {
base_rowids.push_back(page.base_rowid);
}
i = 0;
for (auto const &page : dmat->GetBatches<SparsePage>()) {
ASSERT_EQ(base_rowids[i], page.base_rowid);
++i;
}
}
TEST(GradientIndex, FromCategoricalBasic) {
size_t constexpr kRows = 1000, kCats = 13, kCols = 1;
size_t max_bins = 8;
auto x = GenerateRandomCategoricalSingleColumn(kRows, kCats);
auto m = GetDMatrixFromData(x, kRows, 1);
auto &h_ft = m->Info().feature_types.HostVector();
h_ft.resize(kCols, FeatureType::kCategorical);
BatchParam p(max_bins, 0.8);
GHistIndexMatrix gidx;
gidx.Init(m.get(), max_bins, p.sparse_thresh, false, common::OmpGetNumThreads(0), {});
auto x_copy = x;
std::sort(x_copy.begin(), x_copy.end());
auto n_uniques = std::unique(x_copy.begin(), x_copy.end()) - x_copy.begin();
ASSERT_EQ(n_uniques, kCats);
auto const &h_cut_ptr = gidx.cut.Ptrs();
auto const &h_cut_values = gidx.cut.Values();
ASSERT_EQ(h_cut_ptr.size(), 2);
ASSERT_EQ(h_cut_values.size(), kCats);
auto const &index = gidx.index;
for (size_t i = 0; i < x.size(); ++i) {
auto bin = index[i];
auto bin_value = h_cut_values.at(bin);
ASSERT_EQ(common::AsCat(x[i]), common::AsCat(bin_value));
}
}
} // namespace data
} // namespace xgboost
| 28.472222 | 88 | 0.678537 | [
"vector"
] |
6bf284ccfd226f9de55f285a14e1666d37ed79e6 | 1,475 | cc | C++ | optickscore/tests/MockSensorLibTest.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 11 | 2020-07-05T02:39:32.000Z | 2022-03-20T18:52:44.000Z | optickscore/tests/MockSensorLibTest.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | null | null | null | optickscore/tests/MockSensorLibTest.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 4 | 2020-09-03T20:36:32.000Z | 2022-01-19T07:42:21.000Z | #include "OPTICKS_LOG.hh"
#include "SensorLib.hh"
#include "SphereOfTransforms.hh"
#include "MockSensorLib.hh"
int main(int argc, char** argv)
{
OPTICKS_LOG(argc, argv);
unsigned num_cat = argc > 1 ? atoi(argv[1]) : 2 ; // use 0 to model the case of having no angular efficiency
// match OSensorLibGeoTest to mock the corresponding number of sensors
unsigned num_theta = 64+1 ;
unsigned num_phi = 128 ;
unsigned num_sensor = SphereOfTransforms::NumTransforms(num_theta, num_phi);
LOG(info)
<< " num_theta " << num_theta
<< " num_phi " << num_phi
<< " num_sensor " << num_sensor
<< " num_cat " << num_cat
<< ( num_cat == 0 ? " NO ANGULAR EFFICIENCY " : " with angular efficiency " )
;
SensorLib* senlib = MockSensorLib::Make(num_cat, num_sensor);
assert( senlib->getNumSensor() == num_sensor );
const char* dir = "$TMP/optickscore/tests/MockSensorLibTest" ;
senlib->save( dir );
SensorLib* senlib2 = SensorLib::Load(dir) ;
if( senlib2 == NULL )
{
LOG(fatal) << " FAILED to load from " << dir ;
return 0 ;
}
assert( senlib2->getNumSensor() == num_sensor );
unsigned modulo = 100 ;
senlib2->dump("MockSensorLibTest", modulo);
LOG(info) << dir ;
LOG(info) << senlib->desc() ;
LOG(info) << senlib2->desc() ;
senlib2->close();
return 0 ;
}
// om-;TEST=MockSensorLibTest om-t
| 25.431034 | 115 | 0.6 | [
"model"
] |
6bfb1ca047028aac4a36dbba1c72e3633ad09e60 | 3,346 | cpp | C++ | src/ResourceLoader.cpp | PixelArtDragon/PolisEngine | be3446937eade8457e93db64b59d57bb110aefdd | [
"MIT"
] | null | null | null | src/ResourceLoader.cpp | PixelArtDragon/PolisEngine | be3446937eade8457e93db64b59d57bb110aefdd | [
"MIT"
] | null | null | null | src/ResourceLoader.cpp | PixelArtDragon/PolisEngine | be3446937eade8457e93db64b59d57bb110aefdd | [
"MIT"
] | null | null | null | #include "ResourceLoader.h"
#include "entt/core/hashed_string.hpp"
#include "TextureLoader.h"
#include "MeshLoader.h"
#include "ShaderLoader.h"
#include "ShaderProgramLoader.h"
#include "FontLoader.h"
constexpr auto quad_identifier = entt::hashed_string("quad");
constexpr auto cube_identifier = entt::hashed_string("cube");
constexpr auto cylinder_identifier = entt::hashed_string("cylinder");
constexpr auto sphere_identifier = entt::hashed_string("sphere");
constexpr auto sphere_file = "Meshes/Sphere.obj";
constexpr auto cube_file = "Meshes/Cube.obj";
constexpr auto cylinder_file = "Meshes/Cylinder.obj";
void ResourceLoader::LoadDefaultResources() {
auto quad_vertices = std::vector<Vertex>{
Vertex(glm::vec3(-0.5, -0.5, 0), glm::vec3(0,0,1), glm::vec2(0,0)),
Vertex(glm::vec3(0.5, -0.5, 0), glm::vec3(0,0,1), glm::vec2(1,0)),
Vertex(glm::vec3(-0.5, 0.5, 0), glm::vec3(0,0,1), glm::vec2(0,1)),
Vertex(glm::vec3(0.5, 0.5, 0), glm::vec3(0,0,1), glm::vec2(1,1))
};
auto quad_triangles = std::vector<unsigned int>{
0, 1, 2,
2, 1, 3
};
loaded_meshes.load<MeshLoader>(quad_identifier, "quad", quad_vertices, quad_triangles);
loaded_meshes.load<MeshLoader>(sphere_identifier, sphere_file)->name = "sphere";
loaded_meshes.load<MeshLoader>(cylinder_identifier, cylinder_file)->name = "cylinder";
loaded_meshes.load<MeshLoader>(cube_identifier, cube_file)->name = "cube";
}
entt::resource_handle<Mesh> ResourceLoader::LoadMesh(const std::string& name, const std::vector<Vertex> vertices, const std::vector<unsigned int> triangles) {
return loaded_meshes.load<MeshLoader>(entt::hashed_string(name.c_str()), name, vertices, triangles);
}
entt::resource_handle<Texture> ResourceLoader::LoadTexture(const std::string& filename) {
return loaded_textures.load<TextureLoader>(entt::hashed_string(filename.c_str()), filename);
}
entt::resource_handle<Mesh> ResourceLoader::LoadMesh(const std::string& filename) {
return loaded_meshes.load<MeshLoader>(entt::hashed_string(filename.c_str()), filename);
}
entt::resource_handle<Mesh> ResourceLoader::Primitive(MeshPrimitive shape) {
switch (shape) {
case MeshPrimitive::Quad: return loaded_meshes.handle(quad_identifier);
case MeshPrimitive::Cube: return loaded_meshes.handle(cube_identifier);
case MeshPrimitive::Cylinder: return loaded_meshes.handle(cylinder_identifier);
case MeshPrimitive::Sphere: return loaded_meshes.handle(sphere_identifier);
default: return loaded_meshes.handle(quad_identifier);
}
}
entt::resource_handle<Shader> ResourceLoader::LoadShader(const std::string& filename, ShaderType shader_type) {
return loaded_shaders.load<ShaderLoader>(entt::hashed_string(filename.c_str()), filename, shader_type);
}
entt::resource_handle<ShaderProgram> ResourceLoader::LoadShaderProgram(const std::string& name, const std::string& vertex_shader, const std::string& fragment_shader) {
auto vert_shader = LoadShader(vertex_shader, VertexShader);
auto frag_shader = LoadShader(fragment_shader, FragmentShader);
return loaded_shader_programs.load<ShaderProgramLoader>(entt::hashed_string(name.c_str()), name, vert_shader.get(), frag_shader.get());
}
entt::resource_handle<Font> ResourceLoader::LoadFont(const std::string& file_name) {
return loaded_fonts.load<FontLoader>(entt::hashed_string(file_name.c_str()), file_name);
}
| 46.472222 | 167 | 0.761805 | [
"mesh",
"shape",
"vector"
] |
6bfff20515699519d09b45c17766f73b5d0325ba | 6,687 | cpp | C++ | rts/database/DatabasePartition.cpp | gh-rdf3x/gh-rdf3x | 4184d355b922d9d2f1aa63a36461bf889617928c | [
"Xnet",
"X11"
] | 40 | 2015-02-17T03:27:19.000Z | 2022-03-24T15:17:38.000Z | rts/database/DatabasePartition.cpp | gh-rdf3x/gh-rdf3x | 4184d355b922d9d2f1aa63a36461bf889617928c | [
"Xnet",
"X11"
] | 3 | 2016-02-22T17:36:59.000Z | 2020-04-09T14:45:15.000Z | rts/database/DatabasePartition.cpp | gh-rdf3x/gh-rdf3x | 4184d355b922d9d2f1aa63a36461bf889617928c | [
"Xnet",
"X11"
] | 15 | 2015-01-15T20:39:48.000Z | 2020-11-11T03:07:11.000Z | #include "rts/database/DatabasePartition.hpp"
#include "rts/buffer/BufferReference.hpp"
#include "rts/partition/Partition.hpp"
#include "rts/segment/AggregatedFactsSegment.hpp"
#include "rts/segment/DictionarySegment.hpp"
#include "rts/segment/ExactStatisticsSegment.hpp"
#include "rts/segment/FactsSegment.hpp"
#include "rts/segment/FullyAggregatedFactsSegment.hpp"
#include "rts/segment/SegmentInventorySegment.hpp"
#include "rts/segment/SpaceInventorySegment.hpp"
#include "rts/segment/PredicateSetSegment.hpp"
#include <cassert>
//---------------------------------------------------------------------------
// RDF-3X
// (c) 2008 Thomas Neumann. Web site: http://www.mpi-inf.mpg.de/~neumann/rdf3x
//
// This work is licensed under the Creative Commons
// Attribution-Noncommercial-Share Alike 3.0 Unported License. To view a copy
// of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
// or send a letter to Creative Commons, 171 Second Street, Suite 300,
// San Francisco, California, 94105, USA.
//---------------------------------------------------------------------------
using namespace std;
//---------------------------------------------------------------------------
DatabasePartition::DatabasePartition(BufferManager& bufferManager,Partition& partition)
: bufferManager(bufferManager),partition(partition)
// Constructor
{
}
//---------------------------------------------------------------------------
DatabasePartition::~DatabasePartition()
// Destructor
{
for (vector<pair<Segment*,unsigned> >::iterator iter=segments.begin(),limit=segments.end();iter!=limit;++iter)
delete (*iter).first;
}
//---------------------------------------------------------------------------
void DatabasePartition::create()
// Initialize a new partition with a space inventory and a segment inventory
{
assert(segments.empty());
// Ensure a sufficient partition size
if (partition.getSize()<(SegmentInventorySegment::root+1)) {
unsigned start,len;
if (!partition.grow((SegmentInventorySegment::root+1)-partition.getSize(),start,len))
assert(false&&"increasing the partition failed");
}
// Create a space inventory
SpaceInventorySegment* spaceInv=new SpaceInventorySegment(*this);
spaceInv->id=0;
spaceInv->formatRoot();
spaceInv->insertInterval(0,SpaceInventorySegment::root,SpaceInventorySegment::root);
segments.push_back(pair<Segment*,unsigned>(spaceInv,Tag_SpaceInventory));
// Create a segment inventory
SegmentInventorySegment* segInv=new SegmentInventorySegment(*this);
segInv->id=1;
spaceInv->insertInterval(1,SegmentInventorySegment::root,SegmentInventorySegment::root);
segInv->addSegment(Segment::Type_SpaceInventory,Tag_SpaceInventory);
segInv->addSegment(Segment::Type_SegmentInventory,Tag_SegmentInventory);
segments.push_back(pair<Segment*,unsigned>(segInv,Tag_SegmentInventory));
}
//---------------------------------------------------------------------------
void DatabasePartition::open()
// Open an existing partition, reconstruct segments as required
{
assert(segments.empty());
// Retrieve all segment types
vector<pair<Segment::Type,unsigned> > segmentTypes;
SegmentInventorySegment::openPartition(*this,segmentTypes);
// Reconstruct segments
unsigned id=0;
for (vector<pair<Segment::Type,unsigned> >::const_iterator iter=segmentTypes.begin(),limit=segmentTypes.end();iter!=limit;++iter) {
Segment* seg=0;
switch ((*iter).first) {
case Segment::Unused: segments.push_back(pair<Segment*,unsigned>(0,0)); continue;
case Segment::Type_SpaceInventory: seg=new SpaceInventorySegment(*this); break;
case Segment::Type_SegmentInventory: seg=new SegmentInventorySegment(*this); break;
case Segment::Type_Facts: seg=new FactsSegment(*this); break;
case Segment::Type_AggregatedFacts: seg=new AggregatedFactsSegment(*this); break;
case Segment::Type_FullyAggregatedFacts: seg=new FullyAggregatedFactsSegment(*this); break;
case Segment::Type_Dictionary: seg=new DictionarySegment(*this); break;
case Segment::Type_ExactStatistics: seg=new ExactStatisticsSegment(*this); break;
case Segment::Type_BTree: break; // Pseudo-Type
case Segment::Type_PredicateSet: seg=new PredicateSetSegment(*this); break;
}
assert(seg);
seg->id=id++;
segments.push_back(pair<Segment*,unsigned>(seg,(*iter).second));
}
// Refresh the stored info
for (vector<pair<Segment*,unsigned> >::const_iterator iter=segments.begin(),limit=segments.end();iter!=limit;++iter)
(*iter).first->refreshInfo();
}
//---------------------------------------------------------------------------
BufferRequest DatabasePartition::readShared(unsigned page) const
// Read a specific page
{
return BufferRequest(bufferManager,partition,page);
}
//---------------------------------------------------------------------------
BufferRequestExclusive DatabasePartition::readExclusive(unsigned page)
// Read a specific page
{
return BufferRequestExclusive(bufferManager,partition,page);
}
//---------------------------------------------------------------------------
BufferRequestModified DatabasePartition::modifyExclusive(unsigned page)
// Read a specific page
{
return BufferRequestModified(bufferManager,partition,page);
}
//---------------------------------------------------------------------------
SpaceInventorySegment* DatabasePartition::getSpaceInventory()
// Get the space inventory
{
return static_cast<SpaceInventorySegment*>(segments[0].first);
}
//---------------------------------------------------------------------------
SegmentInventorySegment* DatabasePartition::getSegmentInventory()
// Get the segment inventory
{
return static_cast<SegmentInventorySegment*>(segments[1].first);
}
//---------------------------------------------------------------------------
void DatabasePartition::addSegment(Segment* seg,unsigned tag)
// Add a segment
{
seg->id=getSegmentInventory()->addSegment(seg->getType(),tag);
while (seg->id>=segments.size())
segments.push_back(pair<Segment*,unsigned>(0,0));
segments[seg->id].first=seg;
segments[seg->id].second=tag;
}
//---------------------------------------------------------------------------
Segment* DatabasePartition::lookupSegmentBase(unsigned tag)
// Lookup the first segment with this tag
{
for (vector<pair<Segment*,unsigned> >::const_iterator iter=segments.begin(),limit=segments.end();iter!=limit;++iter)
if ((*iter).second==tag)
return (*iter).first;
return 0;
}
//---------------------------------------------------------------------------
| 44.58 | 134 | 0.625991 | [
"vector"
] |
d40fd3f1df43f6a1f8f32d2842acc8a99be63642 | 2,040 | cpp | C++ | uhk/acm4414.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm4414.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | uhk/acm4414.cpp | Hyyyyyyyyyy/acm | d7101755b2c2868d51bb056f094e024d0333b56f | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <cctype>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <string>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define foR for
#define for9 for
#define retunr return
#define reutrn return
#define reutnr return
#define retrun return
const int inf = (1 << 31) - 1;
const ll INF = (1ll << 63) - 1;
const double PI = acos(-1.0);
const double eps = 1e-7;
const ll MOD = 1000000007ll;
const int maxn = 50 + 100;
const int maxm = 1000000 + 100;
char ar[maxn][maxn];
int N;
bool check(int r, int c, int cnt)
{
if (r + cnt > N || c + cnt > N || r - cnt < 1 || c - cnt < 1)
return false;
if (ar[r + cnt][c] == '#' && ar[r - cnt][c] == '#' && ar[r][c + cnt] == '#' && ar[r][c - cnt] == '#')
return true;
return false;
}
bool solve(int r, int c)
{
int i, j, k;
int cnt = 1;
while (check(r, c, cnt))
{
cnt++;
}
if (cnt <= 1)
return false;
if (r + cnt <= N)
{
if (ar[r + cnt][c] == '#')
return false;
}
if (r - cnt >= 1)
{
if (ar[r - cnt][c] == '#')
return false;
}
if (c + cnt <= N)
{
if (ar[r][c + cnt] == '#')
return false;
}
if (c - cnt >= 1)
{
if (ar[r][c - cnt] == '#')
return false;
}
cnt--;
for (i = 1; i <= cnt; i++)
{
if (ar[r - 1][c - i] == '#' || ar[r - 1][c + i] == '#')
return false;
if (ar[r + 1][c - i] == '#' || ar[r + 1][c + i] == '#')
return false;
if (ar[r - i][c - 1] == '#' || ar[r+i][c-1] == '#')
return false;
if (ar[r-i][c+1] == '#' || ar[r+i][c+1] == '#')
return false;
}
return true;
}
int main()
{
int i, j, k;
while (scanf("%d", &N) != EOF && N)
{
for (i = 1; i <= N; i++)
{
scanf("%s", ar[i] + 1);
}
int res = 0;
for (i = 1; i <= N; i++)
{
for (j = 1; j <= N; j++)
{
if (ar[i][j] == 'o')
continue;
if (solve(i, j))
res++;
}
}
printf("%d\n", res);
}
return 0;
}
//4414 找十字架,模拟 | 18.715596 | 102 | 0.495098 | [
"vector"
] |
d41856a8a32d2b6d3c7fbf2ee35cd595cacc8374 | 8,495 | cpp | C++ | Src/Basler/Samples/Cpp/CustomGrabLoop2/customgrabloop2.cpp | jjuiddong/KinectDepthCamera | 11989a4a47728619b10e7c1012a12b94157670c4 | [
"MIT"
] | 1 | 2019-03-17T14:03:14.000Z | 2019-03-17T14:03:14.000Z | Src/Basler/Samples/Cpp/CustomGrabLoop2/customgrabloop2.cpp | jjuiddong/KinectDepthCamera | 11989a4a47728619b10e7c1012a12b94157670c4 | [
"MIT"
] | null | null | null | Src/Basler/Samples/Cpp/CustomGrabLoop2/customgrabloop2.cpp | jjuiddong/KinectDepthCamera | 11989a4a47728619b10e7c1012a12b94157670c4 | [
"MIT"
] | null | null | null | /*
Access to ToF cameras is provided by a GenICam-compliant GenTL Producer. A GenTL Producer is a dynamic library
implementing a standardized software interface for accessing the camera.
The software interacting with the GentL Producer is called a GenTL Consumer. Using this terminology,
this sample is a GenTL Consumer, too.
As part of the suite of sample programs, Basler provides the ConsumerImplHelper C++ template library that serves as
an implementation helper for GenTL consumers.
The GenICam GenApi library is used to access the camera parameters.
For more details about GenICam, GenTL, and GenApi, refer to the http://www.emva.org/standards-technology/genicam/ website.
The GenICam GenApi standard document can be downloaded from http://www.emva.org/wp-content/uploads/GenICam_Standard_v2_0.pdf
The GenTL standard document can be downloaded from http://www.emva.org/wp-content/uploads/GenICam_GenTL_1_5.pdf
This sample illustrates how to grab images from a ToF camera and how to access the image and depth data. Different from the
FirstSample sample, user-provided buffers and a user-provided grab loop are used here.
The GenApi sample, which is part of the Basler ToF samples, illustrates in more detail how to configure a camera.
*/
#include "stdafx.h"
#include <ConsumerImplHelper/ToFCamera.h>
#include <iostream>
#include <iomanip>
#if defined (_MSC_VER) && defined (_WIN32)
// You have to delay load the GenApi libraries used for configuring the camera device.
// Refer to the project settings to see how to instruct the linker to delay load DLLs.
// ("Properties->Linker->Input->Delay Loaded Dlls" resp. /DELAYLOAD linker option).
# pragma message( "Remember to delayload these libraries (/DELAYLOAD linker option):")
# pragma message( " /DELAYLOAD:\"" DLL_NAME("GCBase") "\"")
# pragma message( " /DELAYLOAD:\"" DLL_NAME("GenApi") "\"")
#endif
using namespace GenTLConsumerImplHelper;
using namespace std;
/* Allocator class used by the CToFCamera class for allocating memory buffers
used for grabbing. This custom allocator allocates buffers on the C++ heap.
If the application doesn't provide an allocator, a default one is used
that allocates memory on the heap. */
class CustomAllocator : public BufferAllocator
{
public:
virtual void* AllocateBuffer(size_t size_by) { return new char[size_by]; }
virtual void FreeBuffer(void* pBuffer) { delete[] static_cast<char*>(pBuffer); }
virtual void Delete() { delete this; }
};
class Sample
{
public:
int run();
private:
void setupCamera();
void processData(const GrabResult& grabResult);
private:
CToFCamera m_Camera;
};
void Sample::setupCamera()
{
m_Camera.OpenFirstCamera();
cout << "Connected to camera " << m_Camera.GetCameraInfo().strDisplayName << endl;
// Enable 3D (point cloud) data, intensity data, and confidence data
GenApi::CEnumerationPtr ptrComponentSelector = m_Camera.GetParameter("ComponentSelector");
GenApi::CBooleanPtr ptrComponentEnable = m_Camera.GetParameter("ComponentEnable");
GenApi::CEnumerationPtr ptrPixelFormat = m_Camera.GetParameter("PixelFormat");
// Enable range data
ptrComponentSelector->FromString("Range");
ptrComponentEnable->SetValue(true);
// Range information can be sent either as a 16-bit grey value image or as 3D coordinates (point cloud). For this sample, we want to acquire 3D coordinates.
// Note: To change the format of an image component, the Component Selector must first be set to the component
// you want to configure (see above).
// To use 16-bit integer depth information, choose "Mono16" instead of "Coord3D_ABC32f".
ptrPixelFormat->FromString("Coord3D_ABC32f");
ptrComponentSelector->FromString("Intensity");
ptrComponentEnable->SetValue(true);
ptrComponentSelector->FromString("Confidence");
ptrComponentEnable->SetValue(true);
}
int Sample::run()
{
const size_t nBuffers = 3; // Number of buffers to be used for grabbing.
const size_t nImagesToGrab = 10; // Number of images to grab.
size_t nImagesGrabbed = 0;
try
{
//
// Open and parameterize the camera.
//
setupCamera();
//
// Grab and process images
//
// Let the camera class use our allocator.
// When the application doesn't provide an allocator, a default one that allocates memory buffers
// on the heap will be used automatically.
m_Camera.SetBufferAllocator(new CustomAllocator(), true); // m_Camera takes ownership and will clean-up allocator.
// Allocate the memory buffers and prepare image acquisition.
m_Camera.PrepareAcquisition(nBuffers);
// Enqueue all buffers to be filled with image data.
for (size_t i = 0; i < nBuffers; ++i)
{
m_Camera.QueueBuffer(i);
}
// Start the acquisition engine.
m_Camera.StartAcquisition();
// Now, the acquisition can be started on the camera.
m_Camera.IssueAcquisitionStartCommand(); // The camera continuously sends data now.
// Enter the grab loop
do
{
GrabResult grabResult;
// Wait up to 1000 ms for the next grabbed buffer available in the
// acquisition engine's output queue.
m_Camera.GetGrabResult(grabResult, 1000);
// Check whether a buffer has been grabbed successfully.
if (grabResult.status == GrabResult::Timeout)
{
cerr << "Timeout occurred." << endl;
// The timeout might be caused by a removal of the camera. Check if the camera
// is still connected.
if (!m_Camera.IsConnected())
{
cerr << "Camera has been removed." << endl;
}
break; // exit loop
}
if (grabResult.status != GrabResult::Ok)
{
cerr << "Failed to grab image." << endl;
break; // exit loop
}
nImagesGrabbed++;
// We can process the buffer now. The buffer will not be overwritten with new data until
// it is explicitly placed in the acquisition engine's input queue again.
processData(grabResult);
// We finished processing the data, put the buffer back into the acquisition
// engine's input queue to be filled with new image data.
m_Camera.QueueBuffer(grabResult.hBuffer);
} while (nImagesGrabbed < nImagesToGrab);
// Stop the camera
m_Camera.IssueAcquisitionStopCommand();
// Stop the acquisition engine and release memory buffers and other resources used for grabbing.
m_Camera.FinishAcquisition();
// Close the connection to the camera
m_Camera.Close();
}
catch (const GenICam::GenericException& e)
{
cerr << "Exception occurred: " << e.GetDescription() << endl;
// After successfully opening the camera, the IsConnected method can be used
// to check if the device is still connected.
if (m_Camera.IsOpen() && !m_Camera.IsConnected())
{
cerr << "Camera has been removed." << endl;
}
return EXIT_FAILURE;
}
return nImagesGrabbed == nImagesToGrab ? EXIT_SUCCESS : EXIT_FAILURE;
}
void Sample::processData(const GrabResult& grabResult)
{
BufferParts parts;
m_Camera.GetBufferParts(grabResult, parts);
// Retrieve the values for the center pixel
const int width = (int)parts[0].width;
const int height = (int)parts[0].height;
const int x = (int)(0.5 * width);
const int y = (int)(0.5 * height);
CToFCamera::Coord3D *p3DCoordinate = (CToFCamera::Coord3D*) parts[0].pData + y * width + x;
uint16_t *pIntensity = (uint16_t*)parts[1].pData + y * width + x;
uint16_t *pConfidence = (uint16_t*)parts[2].pData + y * width + x;
cout.setf(ios_base::fixed);
cout.precision(1);
if (p3DCoordinate->IsValid())
cout << "x=" << setw(6) << p3DCoordinate->x << " y=" << setw(6) << p3DCoordinate->y << " z=" << setw(6) << p3DCoordinate->z;
else
cout << "x= n/a y= n/a z= n/a";
cout << " intensity=" << setw(5) << *pIntensity << " confidence=" << setw(5) << *pConfidence << endl;
}
int main(int argc, char* argv[])
{
int exitCode = EXIT_SUCCESS;
try
{
CToFCamera::InitProducer();
Sample processing;
exitCode = processing.run();
}
catch (GenICam::GenericException& e)
{
cerr << "Exception occurred: " << endl << e.GetDescription() << endl;
exitCode = EXIT_FAILURE;
}
// Release the GenTL producer and all of its resources.
// Note: Don't call TerminateProducer() until the destructor of the CToFCamera
// class has been called. The destructor may require resources which may not
// be available anymore after TerminateProducer() has been called.
if (CToFCamera::IsProducerInitialized())
CToFCamera::TerminateProducer(); // Won't throw any exceptions
cout << endl << "Press Enter to exit." << endl;
while (cin.get() != '\n');
return exitCode;
}
| 34.673469 | 157 | 0.723014 | [
"3d"
] |
d41b6c57401e6816a864672e11b147ea140b79b4 | 1,323 | cpp | C++ | mock_data/rand_spending_generator.cpp | ArabicaCapitalOne/arabica_backend | 8810f2907ed2fff2adb033119a42a046bec68240 | [
"MIT"
] | null | null | null | mock_data/rand_spending_generator.cpp | ArabicaCapitalOne/arabica_backend | 8810f2907ed2fff2adb033119a42a046bec68240 | [
"MIT"
] | null | null | null | mock_data/rand_spending_generator.cpp | ArabicaCapitalOne/arabica_backend | 8810f2907ed2fff2adb033119a42a046bec68240 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <cstdio>
using namespace std;
void output(int year, int month, int day, vector<string> &merchant_id) {
cout << "{\n";
int index = rand() % 300;
cout << " \"merchant_id\": " << "\"" << merchant_id[index] << "\"," << endl;
cout << " \"medium\": " << "\"balance\"," << endl;
printf(" \"purchase_date\": \"%d-%02d-%02d\",\n", year, month, day);
// cout << " \"purchase_date\": " << "\"" << year << "-" << month << "-" << day << "\",\n";
int a = rand() % 50;
int b = rand() % 10;
int c = rand() % 10;
cout << " \"amount\": " << a << "." << b << c << ",\n";
cout << " \"description\": " << "\"string\"\n";
cout << "},\n\n";
}
int main (){
vector<string> merchant_id;
ifstream fin("test.txt");
string id;
while (fin >> id) {
merchant_id.push_back(id);
}
cout << "[\n";
for (int year = 2012; year < 2017; ++year) {
for (int month = 1; month <= 12; ++month) {
int num = rand() % 50 + 10;
for (int count = 0; count < num; ++count) {
int day = 0;
if (month == 2)
day = rand() % 28 + 1;
else if (month==4 || month==6 || month==9 || month==11)
day = rand() % 30 + 1;
else
day = rand() % 31 + 1;
output (year, month, day, merchant_id);
}
}
}
cout << "\n]\n";
return 0;
}
| 23.625 | 92 | 0.499622 | [
"vector"
] |
d42277ebb464016b89c2d20206215eaabb58b45e | 4,975 | cpp | C++ | Gems/NvCloth/Code/Source/Editor/MeshNodeHandler.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-12T14:13:45.000Z | 2022-03-12T14:13:45.000Z | Gems/NvCloth/Code/Source/Editor/MeshNodeHandler.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 3 | 2021-09-08T03:41:27.000Z | 2022-03-12T01:01:29.000Z | Gems/NvCloth/Code/Source/Editor/MeshNodeHandler.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 <AzToolsFramework/AssetBrowser/AssetBrowserBus.h>
#include <AtomLyIntegration/CommonFeatures/Mesh/MeshComponentBus.h>
#include <Editor/PropertyTypes.h>
#include <Editor/MeshNodeHandler.h>
namespace NvCloth
{
namespace Editor
{
AZ::u32 MeshNodeHandler::GetHandlerName() const
{
return MeshNodeSelector;
}
QWidget* MeshNodeHandler::CreateGUI(QWidget* parent)
{
widget_t* picker = new widget_t(parent);
// Set edit button appearance to go to Scene Settings dialog
picker->GetEditButton()->setToolTip("Open Scene Settings to setup Cloth Modifiers");
picker->GetEditButton()->setText("");
picker->GetEditButton()->setEnabled(false);
connect(picker->GetComboBox(),
&QComboBox::currentTextChanged, this,
[picker]()
{
AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestWrite, picker);
});
connect(picker->GetEditButton(),
&QToolButton::clicked, this,
[this, picker]()
{
OnEditButtonClicked(picker);
});
return picker;
}
bool MeshNodeHandler::IsDefaultHandler() const
{
return true;
}
void MeshNodeHandler::ConsumeAttribute(widget_t* GUI, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue, [[maybe_unused]] const char* debugName)
{
if (attrib == AZ::Edit::UIHandlers::EntityId)
{
AZ::EntityId value;
if (attrValue->Read<AZ::EntityId>(value))
{
GUI->SetEntityId(value);
}
else
{
AZ_WarningOnce("MeshNodeHandler", false, "Failed to read 'EntityId' attribute from property '%s'. Expected entity id.", debugName);
}
}
else if (attrib == AZ::Edit::Attributes::StringList)
{
AZStd::vector<AZStd::string> value;
if (attrValue->Read<AZStd::vector<AZStd::string>>(value))
{
QSignalBlocker signalBlocker(GUI->GetComboBox());
GUI->GetComboBox()->clear();
for (const auto& item : value)
{
GUI->GetComboBox()->addItem(item.c_str());
}
bool hasAsset = GetMeshAsset(GUI->GetEntityId()).Get() != nullptr;
GUI->GetEditButton()->setEnabled(hasAsset);
}
else
{
AZ_WarningOnce("MeshNodeHandler", false, "Failed to read 'StringList' attribute from property '%s'. Expected string vector.", debugName);
}
}
}
void MeshNodeHandler::WriteGUIValuesIntoProperty([[maybe_unused]] size_t index, widget_t* GUI, property_t& instance, [[maybe_unused]] AzToolsFramework::InstanceDataNode* node)
{
instance = GUI->GetComboBox()->currentText().toUtf8().data();
}
bool MeshNodeHandler::ReadValuesIntoGUI([[maybe_unused]] size_t index, widget_t* GUI, const property_t& instance, [[maybe_unused]] AzToolsFramework::InstanceDataNode* node)
{
QSignalBlocker signalBlocker(GUI->GetComboBox());
GUI->GetComboBox()->setCurrentText(instance.c_str());
return true;
}
void MeshNodeHandler::OnEditButtonClicked(widget_t* GUI)
{
AZ::Data::Asset<AZ::Data::AssetData> meshAsset = GetMeshAsset(GUI->GetEntityId());
if (meshAsset)
{
// Open the asset with the preferred asset editor, which for Mesh and Actor Assets it's Scene Settings.
bool handled = false;
AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Broadcast(
&AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotifications::OpenAssetInAssociatedEditor, meshAsset.GetId(), handled);
}
}
AZ::Data::Asset<AZ::Data::AssetData> MeshNodeHandler::GetMeshAsset(const AZ::EntityId entityId) const
{
AZ::Data::Asset<AZ::RPI::ModelAsset> modelAsset;
AZ::Render::MeshComponentRequestBus::EventResult(
modelAsset, entityId, &AZ::Render::MeshComponentRequestBus::Events::GetModelAsset);
return modelAsset;
}
} // namespace Editor
} // namespace NvCloth
#include <Source/Editor/moc_MeshNodeHandler.cpp>
| 38.867188 | 183 | 0.577889 | [
"mesh",
"render",
"vector",
"3d"
] |
2d6d6cfe0b7b2140829e2beccbadbe63649abf16 | 20,326 | cpp | C++ | src/Parser/Parser.cpp | PMFU/Vic2-Save-Analyzer | 452d0c8aacdf75094586e4d79fb9ab29f743ef80 | [
"MIT"
] | null | null | null | src/Parser/Parser.cpp | PMFU/Vic2-Save-Analyzer | 452d0c8aacdf75094586e4d79fb9ab29f743ef80 | [
"MIT"
] | null | null | null | src/Parser/Parser.cpp | PMFU/Vic2-Save-Analyzer | 452d0c8aacdf75094586e4d79fb9ab29f743ef80 | [
"MIT"
] | null | null | null | #include "Parser.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <Types/nlohmann/json.h>
static const std::vector<char> tokenSplitter =
{
'{', '}', '"', ']', '[', '\n', '=', '(', ')' //, ' '
};
static const std::string tokenSplitterStr =
{
'{', '}', '"', '[', ']', '\n', '=', '(', ')' //, ' '
};
static inline bool contains(const std::string& parentString, const std::string& containStr)
{
if(parentString.empty() || containStr.empty())
{
return false;
}
if(parentString.find(containStr) != std::string::npos)
{
return true;
}
else
{
return false;
}
}
static inline bool lineContainsWarStart(const std::string& containStr)
{
const std::string str("previous_");
if(containStr.find(str) != std::string::npos)
{
return true;
}
else
{
return false;
}
}
static bool getDateFromPdxString(const std::string& suspectString, Date& d)
{
bool result = false;
if(!contains(suspectString, "battle"))
{
if(suspectString.length() < 12)
{
int year = 0;
int month = 0;
int day = 0;
int indexPoint = suspectString.find_first_of('.');
if(indexPoint == std::string::npos)
{
std::cout << "Date String Parsing Issue! |" << suspectString << "|\n";
result = false;
return result;
}
year = std::stoi(suspectString.substr(0, indexPoint)); // Year
auto monthdaystr = suspectString.substr(indexPoint + 1, suspectString.length() - (indexPoint + 1));
indexPoint = monthdaystr.find_first_of('.');
if(indexPoint == std::string::npos)
{
std::cout << "Date String Parsed Wrong! |" << suspectString << "|\n";
result = false;
return result;
}
result = true;
month = std::stoi(monthdaystr.substr(0, indexPoint));
day = std::stoi(monthdaystr.substr(indexPoint + 1, monthdaystr.length() - (indexPoint + 1)));
d = Date(year, month, day);
}
}
return result;
}
Savegame loadSavegame(const std::string& filepath)
{
std::ifstream file(filepath);
if(!file.is_open())
{
std::cout << "Could not open the file!\n";
}
std::stringstream stream;
stream << file.rdbuf();
file.close();
std::cout << "The stream has been loaded. There are " << stream.str().length() << " characters.\n";
Date d;
std::vector<std::vector<std::string>> info;
for(std::string buffer; std::getline(stream, buffer, '\n'); )
{
if(lineContainsWarStart(buffer))
{
std::cout << "Found War!\n";
std::vector<std::string> lines;
std::getline(stream, buffer, '\n');
buffer.push_back('\n');
while((!lineContainsWarStart(buffer)) && (buffer != "}\n"))
{
lines.emplace_back(buffer);
if(std::getline(stream, buffer, '\n'))
{
buffer.push_back('\n');
}
else
{
buffer.push_back('\n');
buffer.push_back('\0');
break;
}
}
lines.emplace_back(buffer);
info.emplace_back(lines);
}
}
//This can be parallelized as long as the order for [warTokens] tokens is the same
std::vector<std::vector<std::string>> warsTokens;
for(const auto& wars : info)
{
std::vector<std::string> warTokensVec;
for(const auto& lines : wars)
{
auto tokenLine = tokenizeLine(lines);
for(const auto& tok : tokenLine)
{
warTokensVec.emplace_back(tok);
}
}
if(!warTokensVec.empty())
{
warsTokens.push_back(warTokensVec);
std::cout << "Made a war token list.\n";
}
}
Savegame savegame;
for(const auto& wtoken : warsTokens)
{
if(wtoken.size() == 0)
{
continue;
}
else
{
savegame.addWar(convertToWar(wtoken));
std::cout << "Made a war.\n";
}
}
return savegame;
}
Savegame loadSavegameFromString(const std::string& fileStream)
{
std::stringstream stream;
stream.str(fileStream);
std::cout << "The stream has been loaded. There are " << stream.str().length() << " characters.\n";
Date d;
std::vector<std::vector<std::string>> info;
for(std::string buffer; std::getline(stream, buffer, '\n'); )
{
if(lineContainsWarStart(buffer))
{
std::cout << "Found War!\n";
std::vector<std::string> lines;
std::getline(stream, buffer, '\n');
buffer.push_back('\n');
while((!lineContainsWarStart(buffer)) && (buffer != "}\n"))
{
lines.emplace_back(buffer);
if(std::getline(stream, buffer, '\n'))
{
buffer.push_back('\n');
}
else
{
buffer.push_back('\n');
buffer.push_back('\0');
break;
}
}
lines.emplace_back(buffer);
info.emplace_back(lines);
}
}
//This can be parallelized as long as the order for [warTokens] tokens is the same
std::vector<std::vector<std::string>> warsTokens;
for(const auto& wars : info)
{
std::vector<std::string> warTokensVec;
for(const auto& lines : wars)
{
auto tokenLine = tokenizeLine(lines);
for(const auto& tok : tokenLine)
{
warTokensVec.emplace_back(tok);
}
}
if(!warTokensVec.empty())
{
warsTokens.push_back(warTokensVec);
std::cout << "Made a war token list.\n";
}
}
Savegame savegame;
for(const auto& wtoken : warsTokens)
{
if(wtoken.size() == 0)
{
continue;
}
else
{
savegame.addWar(convertToWar(wtoken));
std::cout << "Made a war.\n";
}
}
return savegame;
}
static inline bool isToken(const char c) noexcept
{
return (tokenSplitterStr.find(c) != std::string::npos);
}
std::vector<std::string> tokenizeLine(const std::string& line)
{
std::vector<std::string> tokens;
std::string curToken;
//For every character in the line, check if it's a token splitter
//If it splits the token, then push the existing token to the vector, and then the token splitter
for(const char c : line)
{
if(!isToken(c))
{
curToken.push_back(c);
}
else
{
//Push the current string token to the vector
if(!curToken.empty())
{
tokens.emplace_back(curToken);
}
curToken.clear();
//Put the token splitting character into the vector
const std::string tokenChar(1, c);
tokens.emplace_back(tokenChar);
}
}
//Another check in case of unfinished token or smth
if(!curToken.empty())
{
tokens.emplace_back(curToken);
curToken.clear();
}
return tokens;
}
War convertToWar(const std::vector<std::string>& tokenStream)
{
War w;
//All the strings for the actions/commands/keywords relevant
const std::string battle = "battle";
const std::string name = "name";
const std::string history = "history";
const std::string original_wargoal = "original_wargoal";
const std::string original_defender = "original_defender";
const std::string original_attacker = "original_attacker";
const std::string casus_belli = "casus_belli";
const std::string actor = "actor";
const std::string receiver = "receiver";
const std::string action = "action";
//Scope and Flags
int scopeDepth = 0; //Everytime there is '{', increment, and when '}', decrement
int bracketDepth = 0; //Everytime there is '[', increment, and when ']', decrement
int parenthesisDepth = 0; //Everytime there is '(', increment, and when ')', decrement
bool isLeftOperand = true;
bool isBattle = false;
int curBattleScope = 9999;
std::vector<std::string> battleStream;
/*bool isHistory = false;
int curHistoryScope = 9999;
std::vector<std::string> historyStream;*/
std::string stringliteral;
std::string currentSection;
for(auto index = 0; index < tokenStream.size(); ++index)
{
const auto& tkn = tokenStream[index];
if(tkn.empty())
{
continue;
}
std::string token;
if(tkn.at(0) == '\t')
{
auto x = tkn.find_first_not_of('\t');
if(x == std::string::npos) { continue; }
token = tkn.substr(x, tkn.length() - x);
}
else
{
token = tkn;
}
if(isToken(token.at(0)))
{
if(isBattle)
{
battleStream.emplace_back(token);
}
switch (token.at(0))
{ //Begin Switch
case '"':
{
stringliteral.clear();
index += 1;
while(tokenStream[index].at(0) != '"')
{
//Add the token to the battle stream if in it
if(isBattle)
{
battleStream.emplace_back(tokenStream[index]);
}
//Add the token to the string literal string
stringliteral.append(tokenStream[index]);
index += 1;
}
if(isBattle)
{
battleStream.emplace_back("\"");
}
break;
}
case '(':
{
parenthesisDepth += 1;
break;
}
case ')':
{
parenthesisDepth -= 1;
break;
}
case '[':
{
bracketDepth += 1;
break;
}
case ']':
{
bracketDepth -= 1;
break;
}
case '{':
{
scopeDepth += 1;
break;
}
case '}':
{
scopeDepth -= 1;
//End the battle token stream
if((curBattleScope - 1) == scopeDepth)
{
isBattle = false;
curBattleScope = 9999;
/*if(battleStream.empty()) //(curBattleScope - 1) >= scopeDepth
{
break;
}*/
if(battleStream.at(0) == battle || battleStream.at(0) == "{")
{
w.battles.emplace_back(convertToBattle(battleStream));
battleStream.clear();
}
else
{
//std::cout << "battle stream token 1: |" << battleStream.at(0) << "|\n";
battleStream.clear();
break;
}
}
break;
}
//Others
case '\n':
{
isLeftOperand = true;
if(isBattle)
{
break;
}
else if(currentSection == name) { w.name = stringliteral; /*break;*/ }
else if(currentSection == action) //Starting date for war
{
if(!getDateFromPdxString(stringliteral, w.start))
{
std::cout << "Issue with getting the date for the war start.\n";
}
//break;
}
else if(currentSection == battle) { isBattle = true; curBattleScope = scopeDepth + 1; /*break;*/ }
else if(currentSection == history) { /*currentSection = history;*/ /*break;*/ }
else if(currentSection == original_wargoal) { /*currentSection = original_wargoal;*/ /*break;*/ }
else if(currentSection == original_defender) { w.defenders.emplace_back(original_defender); /*break;*/ }
else if(currentSection == original_attacker) { w.attackers.emplace_back(original_attacker); /*break;*/ }
else if(currentSection == casus_belli) { w.wargoal = stringliteral; /*break;*/ }
currentSection.clear();
stringliteral.clear();
break;
}
case '=':
{
isLeftOperand = false;
break;
}
default:
{
break;
}
} //End Switch
}
else
{
if(isBattle)
{
battleStream.emplace_back(token);
continue;
}
if(isLeftOperand)
{
if(token == name) { currentSection = name; continue; }
if(token == battle) { currentSection = battle; continue; }
if(token == history) { currentSection = history; continue; }
if(token == original_wargoal) { currentSection = original_wargoal; continue; }
if(token == original_defender) { currentSection = original_defender; continue; }
if(token == original_attacker) { currentSection = original_attacker; continue; }
if(token == casus_belli) { currentSection = casus_belli; continue; }
if(token == action) { currentSection = action; continue; }
//std::cout << "THIS IS THE UNPARSED TOKEN: |" << token << "| \n";
//currentSection = token;
}
}
}
return w;
}
Battle convertToBattle(const std::vector<std::string>& tokenStream)
{
Battle b;
/*std::cout << "BATTLE TOKEN STREAM:\n";
for(const auto& t : tokenStream)
{
std::cout << t << '|';
}
std::cout << "\nEND BATTLE TOKEN STREAM\n\n";*/
const std::string battle = "battle";
const std::string name = "name";
const std::string location = "location";
const std::string result = "result";
const std::string attacker = "attacker";
const std::string defender = "defender";
const std::string country = "country";
const std::string leader = "leader";
const std::string losses = "losses";
//Scope and Flags
int scopeDepth = 0; //Everytime there is '{', increment, and when '}', decrement
int bracketDepth = 0; //Everytime there is '[', increment, and when ']', decrement
int parenthesisDepth = 0; //Everytime there is '(', increment, and when ')', decrement
bool isLeftOperand = true;
bool isActualBattle = false;
int sideStatus = 0; //0 is none, 1 is atk, 2 is def
std::string currentSection;
std::string stringliteral;
std::string unitname;
currentSection.clear();
stringliteral.clear();
unitname.clear();
for(auto index = 0; index < tokenStream.size(); ++index)
{
const auto& token = tokenStream[index];
if(token.empty())
{
continue;
}
if(isToken(token.at(0)))
{
switch (token.at(0))
{ //Begin Switch
case '"':
{
stringliteral.clear();
index += 1;
while(tokenStream[index].at(0) != '"')
{
//Add the token to the string literal string
stringliteral.append(tokenStream[index]);
index += 1;
}
break;
}
case '(':
{
parenthesisDepth += 1;
break;
}
case ')':
{
parenthesisDepth -= 1;
break;
}
case '[':
{
bracketDepth += 1;
break;
}
case ']':
{
bracketDepth -= 1;
break;
}
case '{':
{
scopeDepth += 1;
break;
}
case '}':
{
scopeDepth -= 1;
break;
}
//Others
case '\n':
{
isLeftOperand = true;
if(stringliteral.empty())
{
//std::cout << "String Literal is empty\n";
break;
}
if(currentSection == name) { b.name = stringliteral; break; }
if(currentSection == battle) { break; }
if(currentSection == attacker) { sideStatus = 1; break; }
if(currentSection == defender) { sideStatus = 2; break; }
if(currentSection == country) { (sideStatus > 1) ? b.countryDEF = stringliteral: b.countryATK = stringliteral; break; }
if(currentSection == leader) { (sideStatus > 1) ? b.leaderDEF = stringliteral: b.leaderATK = stringliteral; break; }
//std::cout << "THE CURRENT SELECTION: |" << currentSection << "|\n";
//std::cout << "THE STRING LITERAL: |" << stringliteral << "|\n";
if(currentSection == result)
{
//std::cout << "Result: StrLiteral: " << stringliteral << "\n";
bool victory = contains(stringliteral, "y");
//std::cout << "Victory: " << victory << "\n";
if(victory)
{
b.doesAttackerWin = true;
}
else
{
b.doesAttackerWin = false;
}
break;
}
if(currentSection == losses) { (sideStatus > 1) ? b.deflosses = std::stoi(stringliteral): b.atklosses = std::stoi(stringliteral); break; }
if(currentSection == location) { b.location = std::stoi(stringliteral); break; }
if(currentSection == "unit")
{
//std::cout << "THE UNIT TYPE: |" << unitname << "|\n";
Unit u;
u.name = unitname;
u.size = std::stoi(stringliteral);
(sideStatus > 1) ? b.defUnits.emplace_back(u): b.atkUnits.emplace_back(u);
}
break;
}
case '=':
{
isLeftOperand = false;
break;
}
default:
{
break;
}
} //End Switch
}
else
{
if(isLeftOperand)
{
if(token == name) { currentSection = name; continue; }
if(token == battle) { currentSection = battle; continue; }
if(token == location) { currentSection = location; continue; }
if(token == result) { currentSection = result; continue; }
if(token == attacker) { currentSection = attacker; continue; }
if(token == defender) { currentSection = defender; continue; }
if(token == country) { currentSection = country; continue; }
if(token == leader) { currentSection = leader; continue; }
if(token == losses) { currentSection = losses; continue; }
currentSection = "unit";
unitname = token;
}
else
{
stringliteral.clear();
stringliteral = token;
}
}
}
return b;
}
//NOT YET IMPLEMENTED!!!
//This should take the history token stream, and make battles, joining, etc from it
void parseWarHistory(War& war, const std::vector<std::string>& tokenStream)
{
Battle b;
const std::string battle = "battle";
const std::string name = "name";
const std::string location = "location";
const std::string result = "result";
const std::string attacker = "attacker";
const std::string defender = "defender";
const std::string country = "country";
const std::string leader = "leader";
const std::string losses = "losses";
const std::string add_attacker = "add_attacker";
const std::string add_defender = "add_defender";
const std::string rem_attacker = "rem_attacker";
const std::string rem_defender = "rem_defender";
//Scope and Flags
int scopeDepth = 0; //Everytime there is '{', increment, and when '}', decrement
int bracketDepth = 0; //Everytime there is '[', increment, and when ']', decrement
int parenthesisDepth = 0; //Everytime there is '(', increment, and when ')', decrement
bool isLeftOperand = true;
bool isActualBattle = false;
int sideStatus = 0; //0 is none, 1 is atk, 2 is def
std::string currentSection;
std::string stringliteral;
std::string unitname;
currentSection.clear();
stringliteral.clear();
unitname.clear();
for(auto index = 0; index < tokenStream.size(); ++index)
{
const auto& token = tokenStream[index];
if(token.empty())
{
continue;
}
if(isToken(token.at(0)))
{
switch (token.at(0))
{ //Begin Switch
case '"':
{
stringliteral.clear();
index += 1;
while(tokenStream[index].at(0) != '"')
{
//Add the token to the string literal string
stringliteral.append(tokenStream[index]);
index += 1;
}
break;
}
case '(':
{
parenthesisDepth += 1;
break;
}
case ')':
{
parenthesisDepth -= 1;
break;
}
case '[':
{
bracketDepth += 1;
break;
}
case ']':
{
bracketDepth -= 1;
break;
}
case '{':
{
scopeDepth += 1;
break;
}
case '}':
{
scopeDepth -= 1;
break;
}
//Others
case '\n':
{
isLeftOperand = true;
if(stringliteral.empty())
{
//std::cout << "String Literal is empty\n";
break;
}
if(currentSection == name) { b.name = stringliteral; break; }
if(currentSection == battle) { break; }
if(currentSection == attacker) { sideStatus = 1; break; }
if(currentSection == defender) { sideStatus = 2; break; }
if(currentSection == country) { (sideStatus > 1) ? b.countryDEF = stringliteral: b.countryATK = stringliteral; break; }
if(currentSection == leader) { (sideStatus > 1) ? b.leaderDEF = stringliteral: b.leaderATK = stringliteral; break; }
//std::cout << "THE CURRENT SELECTION: |" << currentSection << "|\n";
//std::cout << "THE STRING LITERAL: |" << stringliteral << "|\n";
if(currentSection == result) { (stringliteral == "yes") ? b.doesAttackerWin = true : b.doesAttackerWin = false; break; }
if(currentSection == losses) { (sideStatus > 1) ? b.deflosses = std::stoi(stringliteral): b.atklosses = std::stoi(stringliteral); break; }
if(currentSection == location) { b.location = std::stoi(stringliteral); break; }
if(currentSection == "unit")
{
//std::cout << "THE UNIT TYPE: |" << unitname << "|\n";
Unit u;
u.name = unitname;
u.size = std::stoi(stringliteral);
(sideStatus > 1) ? b.defUnits.emplace_back(u): b.atkUnits.emplace_back(u);
}
break;
}
case '=':
{
isLeftOperand = false;
break;
}
default:
{
break;
}
} //End Switch
}
else
{
if(isLeftOperand)
{
if(token == name) { currentSection = name; continue; }
if(token == battle) { currentSection = battle; continue; }
if(token == location) { currentSection = location; continue; }
if(token == result) { currentSection = result; continue; }
if(token == attacker) { currentSection = attacker; continue; }
if(token == defender) { currentSection = defender; continue; }
if(token == country) { currentSection = country; continue; }
if(token == leader) { currentSection = leader; continue; }
if(token == losses) { currentSection = losses; continue; }
currentSection = "unit";
unitname = token;
}
else
{
stringliteral.clear();
stringliteral = token;
}
}
}
} | 22.786996 | 143 | 0.601102 | [
"vector"
] |
2d72f7f0589cc589eae660acfe52450bf8079b7e | 5,026 | cpp | C++ | src/util/json.cpp | andreast271/cbmc | 7877a939ad4221be7ab6e7fb9445dcb53747c2cc | [
"BSD-4-Clause"
] | null | null | null | src/util/json.cpp | andreast271/cbmc | 7877a939ad4221be7ab6e7fb9445dcb53747c2cc | [
"BSD-4-Clause"
] | 2 | 2018-02-14T16:11:37.000Z | 2018-02-23T18:12:27.000Z | src/util/json.cpp | andreast271/cbmc | 7877a939ad4221be7ab6e7fb9445dcb53747c2cc | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module:
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include "json.h"
#include "structured_data.h"
#include <algorithm>
#include <ostream>
const jsont jsont::null_json_object(jsont::kindt::J_NULL);
void jsont::escape_string(const std::string &src, std::ostream &out)
{
for(const auto &ch : src)
{
switch(ch)
{
case '\\':
case '"':
out << '\\';
out << ch;
break;
case '\b':
out << "\\b";
break;
case '\f':
out << "\\f";
break;
case '\n':
out << "\\n";
break;
case '\r':
out << "\\r";
break;
case '\t':
out << "\\t";
break;
default:
out << ch;
}
}
}
/// Recursive printing of the json object.
/// \param out: The stream object to have the json printed to.
/// \param indent: The indentation level.
void jsont::output_rec(std::ostream &out, unsigned indent) const
{
switch(kind)
{
case kindt::J_STRING:
out << '"';
escape_string(value, out);
out << '"';
break;
case kindt::J_NUMBER:
out << value;
break;
case kindt::J_OBJECT:
out << '{';
output_object(out, object, indent);
if(!object.empty())
{
out << '\n';
out << std::string(indent*2, ' ');
}
out << '}';
break;
case kindt::J_ARRAY:
out << '[';
if(array.empty())
out << ' ';
else
{
for(arrayt::const_iterator a_it=array.begin();
a_it!=array.end();
a_it++)
{
if(a_it!=array.begin())
out << ',';
if(a_it->is_object())
{
out << '\n';
out << std::string((indent+1)*2, ' ');
}
else
out << ' ';
a_it->output_rec(out, indent+1);
}
if(array.back().is_object())
out << '\n' << std::string(indent*2, ' ');
else
out << ' ';
}
out << ']';
break;
case kindt::J_TRUE: out << "true"; break;
case kindt::J_FALSE: out << "false"; break;
case kindt::J_NULL: out << "null"; break;
}
}
/// Basic handling of the printing of a JSON object.
/// Dispatches to output_rec for most of the hard work.
/// \param out: The stream that the JSON object is to be
/// printed to.
/// \param object: The JSON object.
/// \param indent: The indentation level.
void jsont::output_object(
std::ostream &out,
const objectt &object,
unsigned indent)
{
for(objectt::const_iterator o_it = object.begin(); o_it != object.end();
o_it++)
{
if(o_it != object.begin())
out << ',';
// A JSON object always starts with an opening brace,
// after which we put a newline.
out << '\n';
out << std::string((indent + 1) * 2, ' ');
jsont::output_key(out, o_it->first);
o_it->second.output_rec(out, indent + 1);
}
}
void jsont::output_key(std::ostream &out, const std::string &key)
{
out << '"';
jsont::escape_string(key, out);
out << "\": ";
}
void jsont::swap(jsont &other)
{
std::swap(other.kind, kind);
other.array.swap(array);
other.object.swap(object);
other.value.swap(value);
}
bool operator==(const jsont &left, const jsont &right)
{
if(left.kind != right.kind)
return false;
switch(left.kind)
{
case jsont::kindt::J_NULL:
return true;
case jsont::kindt::J_TRUE:
return true;
case jsont::kindt::J_FALSE:
return true;
case jsont::kindt::J_NUMBER:
return left.value == right.value;
case jsont::kindt::J_STRING:
return left.value == right.value;
case jsont::kindt::J_ARRAY:
{
const auto &left_array = static_cast<const json_arrayt &>(left);
const auto &right_array = static_cast<const json_arrayt &>(right);
return left_array.size() == right_array.size() &&
std::equal(
left_array.begin(), left_array.end(), right_array.begin());
}
case jsont::kindt::J_OBJECT:
{
const auto &left_object = static_cast<const json_objectt &>(left);
const auto &right_object = static_cast<const json_objectt &>(right);
if(left_object.size() != left_object.size())
return false;
return std::all_of(
left_object.begin(),
left_object.end(),
[&](const std::pair<std::string, jsont> &pair) {
return right_object[pair.first] == pair.second;
});
}
}
UNREACHABLE;
}
jsont json_node(const structured_data_entryt &entry)
{
if(entry.is_leaf())
return entry.leaf_object();
else
{
json_objectt result;
for(const auto sub_entry : entry.children())
{
result[sub_entry.first.camel_case()] = json_node(sub_entry.second);
}
return std::move(result);
}
}
jsont to_json(const structured_datat &data)
{
if(data.data().size() == 0)
return jsont{};
json_objectt result;
for(const auto sub_entry : data.data())
{
result[sub_entry.first.camel_case()] = json_node(sub_entry.second);
}
return std::move(result);
}
| 21.206751 | 74 | 0.560088 | [
"object"
] |
2d73c0486a91202c240d9ecbc94db4ef4eddacd4 | 1,216 | cpp | C++ | libs/numeric/mtl/experimental/block_matrix_2x2.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 24 | 2019-03-26T15:25:45.000Z | 2022-03-26T10:00:45.000Z | libs/numeric/mtl/experimental/block_matrix_2x2.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 2 | 2020-04-17T12:35:32.000Z | 2021-03-03T15:46:25.000Z | libs/numeric/mtl/experimental/block_matrix_2x2.cpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 10 | 2019-12-01T13:40:30.000Z | 2022-01-14T08:39:54.000Z | // Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
// 2008 Dresden University of Technology and the Trustees of Indiana University.
// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.
#include <iostream>
#include <boost/numeric/mtl/mtl.hpp>
using namespace std;
int main(int argc, char** argv)
{
using namespace mtl;
using mblock= matrix<double, dim<2, 2> >;
using vblock= mtl::vector<double, dim<2> >;
using mtype= matrix<mblock, sparse>;
using vtype= mtl::vector<vblock>;
mtype A(2, 3);
{
mat::inserter<mtype> ins(A);
mblock mb;
mb[0][0]= 1; mb[0][1]= 2;
mb[1][0]= 3; mb[1][1]= 4;
ins[0][0] << mb;
mb[1][1]= 5;
ins[1][1] << mb;
// ins(0, 0) << mblock{{1, 2}, {3, 4}};
// ins[1][1] << mblock{{3, 4}, {5, 6}};
}
// cout << "A = " << A;
vtype x{vblock{1, 3}, vblock{1, 2}, vblock{9, 3}};
cout << "x = " << x << endl;
vtype y( A * x );
cout << "y= " << y << endl;
return 0;
}
| 22.109091 | 94 | 0.574013 | [
"vector"
] |
2d7473e1636614269b5069f2f4a8f22cc37240e8 | 1,997 | cpp | C++ | src/Base/GLWindow.cpp | sadads1337/fit-gl | 88d9ae1f1935301d71ae6e090aff24e6829a7580 | [
"MIT"
] | 2 | 2021-04-25T15:18:40.000Z | 2022-02-27T15:44:04.000Z | src/Base/GLWindow.cpp | sadads1337/fit-gl | 88d9ae1f1935301d71ae6e090aff24e6829a7580 | [
"MIT"
] | 31 | 2021-02-17T21:12:59.000Z | 2021-05-26T07:06:59.000Z | src/Base/GLWindow.cpp | sadads1337/fit-gl | 88d9ae1f1935301d71ae6e090aff24e6829a7580 | [
"MIT"
] | 9 | 2021-02-08T08:52:51.000Z | 2022-02-27T15:43:55.000Z | #include "GLWindow.hpp"
#include <QPainter>
namespace fgl {
GLWindow::GLWindow(QWindow *parent) : QWindow{parent} {
// This one inits OpenGL functions.
setSurfaceType(QWindow::OpenGLSurface);
}
void GLWindow::init() {}
void GLWindow::render() {
// Lazy init render device.
if (!device_) {
device_ = std::make_unique<QOpenGLPaintDevice>(size());
}
// Clear all buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// Init sizes.
const auto pixelRatio = devicePixelRatio();
device_->setSize(size() * pixelRatio);
device_->setDevicePixelRatio(pixelRatio);
// Paint now.
const QPainter painter{device_.get()};
render(painter);
}
void GLWindow::render(const QPainter &) {}
void GLWindow::renderLater() {
// Post message to request window surface redraw.
requestUpdate();
}
void GLWindow::setAnimated(const bool animating) { animating_ = animating; }
void GLWindow::renderNow() {
// If not exposed yet then skip render.
if (!isExposed()) {
return;
}
auto needsInitialize = false;
// Lazy init gl context.
if (!context_) {
context_ = std::make_unique<QOpenGLContext>(this);
context_->setFormat(requestedFormat());
context_->create();
needsInitialize = true;
}
const auto contextBindSuccess = context_->makeCurrent(this);
if (!contextBindSuccess) {
return;
}
if (needsInitialize) {
initializeOpenGLFunctions();
init();
}
// Render now then swap buffers.
render();
context_->swapBuffers(this);
// Post message to redraw later if animating.
if (animating_) {
renderLater();
}
}
bool GLWindow::event(QEvent *event) {
Q_ASSERT(event);
switch (event->type()) {
case QEvent::UpdateRequest:
// In case someone requested update we render inplace.
renderNow();
return true;
default:
return QWindow::event(event);
}
}
void GLWindow::exposeEvent(QExposeEvent *) {
if (isExposed()) {
renderNow();
}
}
} // namespace fgl
| 20.171717 | 77 | 0.678017 | [
"render"
] |
2d77a063bd69140cc3f0265af392f7e5c875b50e | 7,636 | cpp | C++ | Code/VulkanBackend/Source/VulkanResourcePackager.cpp | DhirajWishal/Flint | 0750bd515de0b5cc3d23f7c2282c50ca483dff24 | [
"Apache-2.0"
] | null | null | null | Code/VulkanBackend/Source/VulkanResourcePackager.cpp | DhirajWishal/Flint | 0750bd515de0b5cc3d23f7c2282c50ca483dff24 | [
"Apache-2.0"
] | 1 | 2021-10-30T11:19:53.000Z | 2021-10-30T11:19:54.000Z | Code/VulkanBackend/Source/VulkanResourcePackager.cpp | DhirajWishal/Flint | 0750bd515de0b5cc3d23f7c2282c50ca483dff24 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Dhiraj Wishal
// SPDX-License-Identifier: Apache-2.0
#include "VulkanBackend/VulkanResourcePackager.hpp"
#include "VulkanBackend/VulkanResourcePackage.hpp"
#include "VulkanBackend/VulkanShader.hpp"
namespace Flint
{
namespace VulkanBackend
{
VulkanResourcePackager::VulkanResourcePackager(const uint32 setIndex, const std::shared_ptr<GraphicsPipeline>& pPipeline, const VkDescriptorSetLayout vLayout)
: ResourcePackager(setIndex, pPipeline), vDescriptorSetLayout(vLayout)
{
// Resolve vertex shader data.
{
VulkanShader& vShader = pPipeline->GetVertexShader()->StaticCast<VulkanShader>();
const auto resourceMap = vShader.GetShaderResources();
if (!resourceMap.empty())
{
const auto resources = resourceMap.at(mSetIndex);
mResources.insert(resources.begin(), resources.end());
}
const auto descriptorSetMap = vShader.GetDescriptorSetMap();
if (!descriptorSetMap.empty())
{
const auto poolSizes = descriptorSetMap.at(mSetIndex).mPoolSizes;
vPoolSizes.insert(vPoolSizes.end(), poolSizes.begin(), poolSizes.end());
}
}
// Check and resolve fragment shader data.
if (pPipeline->GetFragmentShader())
{
VulkanShader& vShader = pPipeline->GetFragmentShader()->StaticCast<VulkanShader>();
const auto resourceMap = vShader.GetShaderResources();
if (!resourceMap.empty())
{
const auto resources = resourceMap.at(mSetIndex);
mResources.insert(resources.begin(), resources.end());
}
const auto descriptorSetMap = vShader.GetDescriptorSetMap();
if (!descriptorSetMap.empty())
{
const auto poolSizes = descriptorSetMap.at(mSetIndex).mPoolSizes;
vPoolSizes.insert(vPoolSizes.end(), poolSizes.begin(), poolSizes.end());
}
}
// Check and resolve tessellation control shader data.
if (pPipeline->GetTessellationControlShader())
{
VulkanShader& vShader = pPipeline->GetTessellationControlShader()->StaticCast<VulkanShader>();
const auto resourceMap = vShader.GetShaderResources();
if (!resourceMap.empty())
{
const auto resources = resourceMap.at(mSetIndex);
mResources.insert(resources.begin(), resources.end());
}
const auto descriptorSetMap = vShader.GetDescriptorSetMap();
if (!descriptorSetMap.empty())
{
const auto poolSizes = descriptorSetMap.at(mSetIndex).mPoolSizes;
vPoolSizes.insert(vPoolSizes.end(), poolSizes.begin(), poolSizes.end());
}
}
// Check and resolve tessellation evaluation shader data.
if (pPipeline->GetTessellationEvaluationShader())
{
VulkanShader& vShader = pPipeline->GetTessellationEvaluationShader()->StaticCast<VulkanShader>();
const auto resourceMap = vShader.GetShaderResources();
if (!resourceMap.empty())
{
const auto resources = resourceMap.at(mSetIndex);
mResources.insert(resources.begin(), resources.end());
}
const auto descriptorSetMap = vShader.GetDescriptorSetMap();
if (!descriptorSetMap.empty())
{
const auto poolSizes = descriptorSetMap.at(mSetIndex).mPoolSizes;
vPoolSizes.insert(vPoolSizes.end(), poolSizes.begin(), poolSizes.end());
}
}
// Check and resolve geometry shader data.
if (pPipeline->GetGeometryShader())
{
VulkanShader& vShader = pPipeline->GetGeometryShader()->StaticCast<VulkanShader>();
const auto resourceMap = vShader.GetShaderResources();
if (!resourceMap.empty())
{
const auto resources = resourceMap.at(mSetIndex);
mResources.insert(resources.begin(), resources.end());
}
const auto descriptorSetMap = vShader.GetDescriptorSetMap();
if (!descriptorSetMap.empty())
{
const auto poolSizes = descriptorSetMap.at(mSetIndex).mPoolSizes;
vPoolSizes.insert(vPoolSizes.end(), poolSizes.begin(), poolSizes.end());
}
}
}
VulkanResourcePackager::VulkanResourcePackager(const uint32 setIndex, const std::shared_ptr<ComputePipeline>& pPipeline, const VkDescriptorSetLayout vLayout)
: ResourcePackager(setIndex, pPipeline), vDescriptorSetLayout(vLayout)
{
VulkanShader& vShader = pPipeline->GetShader()->StaticCast<VulkanShader>();
const auto resourceMap = vShader.GetShaderResources();
if (!resourceMap.empty())
{
const auto resources = resourceMap.at(mSetIndex);
mResources.insert(resources.begin(), resources.end());
}
const auto descriptorSetMap = vShader.GetDescriptorSetMap();
if (!descriptorSetMap.empty())
{
const auto poolSizes = descriptorSetMap.at(mSetIndex).mPoolSizes;
vPoolSizes.insert(vPoolSizes.end(), poolSizes.begin(), poolSizes.end());
}
}
std::shared_ptr<ResourcePackage> VulkanResourcePackager::CreatePackage()
{
mDescriptorSetCount++;
CreateDescriptorPool();
return CreateResourcePackage();
}
void VulkanResourcePackager::Terminate()
{
VulkanDevice& vDevice = pPipeline->GetDevice()->StaticCast<VulkanDevice>();
if (vDescriptorPool)
vDevice.GetDeviceTable().vkDestroyDescriptorPool(vDevice.GetLogicalDevice(), vDescriptorPool, nullptr);
bIsTerminated = true;
}
void VulkanResourcePackager::CreateDescriptorPool()
{
VulkanDevice& vDevice = pPipeline->GetDevice()->StaticCast<VulkanDevice>();
if (vDescriptorPool)
vDevice.GetDeviceTable().vkDestroyDescriptorPool(vDevice.GetLogicalDevice(), vDescriptorPool, nullptr);
VkDescriptorPoolCreateInfo vPoolCreateInfo = {};
vPoolCreateInfo.sType = VkStructureType::VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
vPoolCreateInfo.pNext = VK_NULL_HANDLE;
vPoolCreateInfo.flags = 0;
vPoolCreateInfo.maxSets = mDescriptorSetCount;
vPoolCreateInfo.poolSizeCount = static_cast<uint32>(vPoolSizes.size());
vPoolCreateInfo.pPoolSizes = vPoolSizes.data();
FLINT_VK_ASSERT(vDevice.GetDeviceTable().vkCreateDescriptorPool(vDevice.GetLogicalDevice(), &vPoolCreateInfo, nullptr, &vDescriptorPool));
}
std::shared_ptr<VulkanResourcePackage> VulkanResourcePackager::CreateResourcePackage()
{
VulkanDevice& vDevice = pPipeline->GetDevice()->StaticCast<VulkanDevice>();
std::vector<uint32> buffers, images;
for (const auto binding : mResources)
{
if (binding.second == ShaderResourceType::Sampler ||
binding.second == ShaderResourceType::SampledImage ||
binding.second == ShaderResourceType::StorageImage ||
binding.second == ShaderResourceType::CombinedImageSampler)
images.emplace_back(binding.first);
else
buffers.emplace_back(binding.first);
}
std::vector<VkDescriptorSet> vDescriptorSets(mDescriptorSetCount);
// Allocate the descriptor sets.
{
std::vector<VkDescriptorSetLayout> vDescriptorSetLayouts(mDescriptorSetCount, vDescriptorSetLayout);
VkDescriptorSetAllocateInfo vAllocateInfo = {};
vAllocateInfo.sType = VkStructureType::VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
vAllocateInfo.pNext = VK_NULL_HANDLE;
vAllocateInfo.descriptorPool = vDescriptorPool;
vAllocateInfo.descriptorSetCount = mDescriptorSetCount;
vAllocateInfo.pSetLayouts = vDescriptorSetLayouts.data();
FLINT_VK_ASSERT(vDevice.GetDeviceTable().vkAllocateDescriptorSets(vDevice.GetLogicalDevice(), &vAllocateInfo, vDescriptorSets.data()));
}
// Update the existing packages.
for (uint64 i = 0; i < pPackages.size(); i++)
pPackages[i]->StaticCast<VulkanResourcePackage>().SetDescriptorSet(vDescriptorSets[i]);
// Create the new package.
auto pNewPackage = std::make_shared<VulkanResourcePackage>(shared_from_this(), buffers, images, vDescriptorSets.back());
pPackages.emplace_back(pNewPackage);
return pNewPackage;
}
}
} | 35.849765 | 160 | 0.735202 | [
"geometry",
"vector"
] |
2d77cda2ee9f87c434177419ca97eee7125256cb | 2,286 | hpp | C++ | lib/Utils/FileIOUtils.hpp | DanielRother/ROVI | f036148f1ae379bfb319a146eb620ce72a7fec70 | [
"MIT"
] | null | null | null | lib/Utils/FileIOUtils.hpp | DanielRother/ROVI | f036148f1ae379bfb319a146eb620ce72a7fec70 | [
"MIT"
] | null | null | null | lib/Utils/FileIOUtils.hpp | DanielRother/ROVI | f036148f1ae379bfb319a146eb620ce72a7fec70 | [
"MIT"
] | null | null | null | #ifndef __FILEIOUTILS_H__
#define __FILEIOUTILS_H__
#include <Arduino.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
// TODO: Namespace
inline std::string fullfile(const std::string& baseDirectory, const std::string& additionDirectoryOrFile) {
std::string ret = baseDirectory;
// Check if the baseDirectory ends with an slash and add one if not
if (ret.find_last_of("/") != ret.length() - 1) {
ret += "/";
}
return ret + additionDirectoryOrFile;
}
inline std::vector<std::string> splitString(const std::string& s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
template<typename T>
inline std::string to_string(T value) { //TODO: Andere Methoden haben keine '_'
std::stringstream ss;
ss << value;
return ss.str();
}
inline std::string toLower(const std::string& in) {
std::string lower;
lower.resize(in.size()); // allocate space
std::transform(in.begin(), in.end(), lower.begin(), ::tolower);
return lower;
}
inline bool checkStringForAllowedCharacters(const std::string& inputString, const std::string& allowedChars) {
bool ok = true;
for(auto& character : inputString) {
ok = allowedChars.find(character) != std::string::npos;
if(!ok) {
break;
}
}
return ok;
}
inline std::string trim(const std::string& str, const std::string& whitespace = " \t")
{
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos)
return ""; // no content
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
inline std::string removeCharsFromString(const std::string& str, const std::string& charsToRemove) {
auto retStr = str;
for ( unsigned int i = 0; i < charsToRemove.size(); ++i ) {
retStr.erase( remove(retStr.begin(), retStr.end(), charsToRemove[i]), retStr.end() );
}
return retStr;
}
#endif /* __FILEIOUTILS_H__ */ | 26.894118 | 110 | 0.652231 | [
"vector",
"transform"
] |
2d7a80d8ef3fa1d887eeee53830723a4793a2e93 | 2,064 | cpp | C++ | Engine/Engine/graphicsclass.cpp | aytona/GAME3111_Assignment1 | 783cb7b6611f0e7a580ce6227edb46d539cecc68 | [
"MIT"
] | null | null | null | Engine/Engine/graphicsclass.cpp | aytona/GAME3111_Assignment1 | 783cb7b6611f0e7a580ce6227edb46d539cecc68 | [
"MIT"
] | null | null | null | Engine/Engine/graphicsclass.cpp | aytona/GAME3111_Assignment1 | 783cb7b6611f0e7a580ce6227edb46d539cecc68 | [
"MIT"
] | 1 | 2018-08-25T22:12:00.000Z | 2018-08-25T22:12:00.000Z | #include "graphicsclass.h"
#include "cameraclass.h"
GraphicsClass::GraphicsClass() {
m_D3D = 0;
m_Camera = 0;
}
GraphicsClass::GraphicsClass(const GraphicsClass& other) {
}
GraphicsClass::~GraphicsClass() {
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd) {
bool result;
// Create the Direct3D object
m_D3D = new D3DClass;
if (!m_D3D) {
return false;
}
// Init the Direct3D object
result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
if (!result) {
MessageBox(hwnd, L"Could not initialize Direct3D", L"Error", MB_OK);
return false;
}
// Create camera object
m_Camera = new CameraClass;
if (!m_Camera) {
return false;
}
// Set initial position of camera
m_Camera->SetPosition(0.0f, 0.0f, -10.0f);
return true;
}
void GraphicsClass::Shutdown() {
if (m_Camera) {
delete m_Camera;
m_Camera = 0;
}
if (m_D3D) {
m_D3D->Shutdown();
delete m_D3D;
m_D3D = 0;
}
}
bool GraphicsClass::Frame() {
bool result;
static float rotation = 0.0f;
// Update the rotation variable each frame
rotation += (float)D3DX_PI * 0.005f;
if (rotation > 360.0f) {
rotation -= 360;
}
// Render the graphics scene
result = Render(rotation);
if (!result) {
return false;
}
return true;
}
bool GraphicsClass::Render(float rotation) {
D3DXMATRIX viewMatrix, projectionMatrix, worldMatrix;
bool result;
// Clear buffers
m_D3D->BeginScene(0.0f, 0.5f, 0.5f, 1.0f);
// Generate the view matrix based on camera's position
m_Camera->Render();
m_Camera->GetViewMatrix(viewMatrix);
m_D3D->GetWorldMatrix(worldMatrix);
m_D3D->GetProjectionMatrix(projectionMatrix);
// Rotate the world matrix by the rotation value
D3DXMatrixRotationY(&worldMatrix, rotation);
// Present rendered scene
m_D3D->EndScene();
return true;
} | 21.278351 | 119 | 0.636628 | [
"render",
"object"
] |
2d7abd31913218f281a3b941c945e0438525c9be | 2,194 | cpp | C++ | libs/dev/Math/MathEngine/VectApp.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | libs/dev/Math/MathEngine/VectApp.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | libs/dev/Math/MathEngine/VectApp.cpp | Norseman055/immaterial-engine | 6aca0fad64f5b2b9fe6eb351528a79a39dc94625 | [
"MIT"
] | null | null | null | /*****************************************************************************/
/* */
/* File: VectApp.cpp */
/* */
/* Vector Application Class */
/* */
/*****************************************************************************/
#include "MathEngine.h"
#include "MathApp.h"
/*****************************************************************************
* LERP - linear interpolation
*
* This function returns a point on a line segment given in parametric form.
* Where the inputs are point a (starting point), point b (ending point) of
* the line segment and the parametric variable t. If t is in the range of
* ranging from t=0.0 to 1.0, this function returns a point on the line
* segment. If t=0.0 this function returns point a, if t=1.0 this returns
* point b. Values of t<0.0 return points on the infinite line defined
* before point a. Values of t>1.0 returns points on the infinite line
* defined after point b.
*
* inputs:
* a - point A
* b - point B
* t - parametric t
*
* @return Vector (point) linearly interpolated based on parametric t
*
* Example:
*
* Vect v1(1.0f, 2.0f, 3.0f); // create v1=[1,2,3,1]
* Vect v2(-5.0f, 2.0f, 7.0f); // create v2=[-5,2,7,1]
* Vect out; // create out vector
*
* out = lineParametric (v1, v2, 0.4f ); // t = 0.4f
******************************************************************************/
// do magic
void VectApp::Lerp( Vect &out, const Vect &a, const Vect &b, const float t )
{
out = a + t * (b - a);
};
void VectApp::LerpArray(Vect *out, const Vect *a, const Vect *b, const float t, const int numVects )
{
for (int i = 0; i < numVects; i++)
{
out[i] = a[i] + t * (b[i] - a[i]);
}
};
/***** END of File VectApp.cpp ***********************************************/
| 36.566667 | 102 | 0.400638 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.