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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b83a230dd77a6f6f2382d4cb8e50316136738593 | 4,758 | cpp | C++ | SurfaceReconstruction/SurfaceReconstruction/Scene/CapturedScene.cpp | pavelsevecek/TSR | ca411dedf178e5830f0536e361136f1e16751bc8 | [
"BSD-3-Clause"
] | 102 | 2017-10-17T10:10:59.000Z | 2022-01-19T02:10:29.000Z | SurfaceReconstruction/SurfaceReconstruction/Scene/CapturedScene.cpp | pavelsevecek/TSR | ca411dedf178e5830f0536e361136f1e16751bc8 | [
"BSD-3-Clause"
] | 2 | 2019-12-21T11:59:15.000Z | 2020-09-08T11:38:36.000Z | SurfaceReconstruction/SurfaceReconstruction/Scene/CapturedScene.cpp | pavelsevecek/TSR | ca411dedf178e5830f0536e361136f1e16751bc8 | [
"BSD-3-Clause"
] | 27 | 2017-10-18T09:37:34.000Z | 2022-03-22T01:30:51.000Z | /*
* Copyright (C) 2018 by Author: Aroudj, Samir
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#ifdef _DEBUG
#include <iostream>
#endif // _DEBUG
#include "Platform/FailureHandling/FileCorruptionException.h"
#include "Platform/Utilities/HelperFunctions.h"
#include "Platform/Utilities/ParametersManager.h"
#include "Platform/Utilities/PlyFile.h"
#include "SurfaceReconstruction/Image/ColorImage.h"
#include "SurfaceReconstruction/Image/DepthImage.h"
#include "SurfaceReconstruction/Scene/Camera/Cameras.h"
#include "SurfaceReconstruction/Scene/Camera/MVECameraIO.h"
#include "SurfaceReconstruction/Scene/CapturedScene.h"
#include "SurfaceReconstruction/Scene/FileNaming.h"
using namespace Math;
using namespace FailureHandling;
using namespace std;
using namespace Storage;
using namespace SurfaceReconstruction;
using namespace Utilities;
const char *CapturedScene::PARAMETER_NAME_IMAGE_SCALE = "imageScale";
const char *CapturedScene::PARAMETER_NAME_INPUT_ORIENTATION = "inputOrientation";
const char *CapturedScene::PARAMETER_NAME_INPUT_ORIGIN = "inputOrigin";
const char *CapturedScene::PARAMETER_NAME_PLY_FILE = "plyFile";
CapturedScene::CapturedScene(const Path &metaFileName, const vector<IReconstructorObserver *> &observers) :
Scene(observers)
{
// load what scene / what data to be loaded & cameras
vector<Path> plyCloudFileNames;
vector<uint32> imageScales;
loadMetaData(plyCloudFileNames, imageScales, metaFileName);
loadCameras();
// load image-based data
{
vector<vector<uint32> *> cameraIndices;
vector<uint32> camerasPerSamples;
loadDepthMeshes(cameraIndices, camerasPerSamples, imageScales);
mSamples.addSamplesViaMeshes(mDepthMeshes, cameraIndices, camerasPerSamples);
// free camera indices
for (uint32 i = 0; i < cameraIndices.size(); ++i)
delete cameraIndices[i];
}
// load samples via ply files
mSamples.addSamplesViaClouds(plyCloudFileNames, mViewToCameraIndices, mInputOrientation, mInputOrigin);
}
void CapturedScene::loadMetaData(vector<Path> &plyCloudFileNames, vector<uint32> &imageScales,
const Path &fileName)
{
// get parameters
if (!getParameters(fileName))
return;
// load ply file names and scales of images to determine what images are loaded
File file(fileName, File::OPEN_READING, false);
string textLine;
vector<string> parts;
while (file.readTextLine(textLine))
{
// get & check parameter parts: type name = value;
Utilities::split(parts, textLine, " \t");
if (parts.size() < 4)
continue;
if (parts[2] != "=")
continue;
// some ply file or image tag?
const string value = parts[3].substr(0, parts[3].find_last_of(";"));
if (parts[0] == "string" && parts[1] == PARAMETER_NAME_PLY_FILE)
{
const Path path(value);
plyCloudFileNames.push_back(path);
}
else if (parts[0] == "uint32" && parts[1] == PARAMETER_NAME_IMAGE_SCALE)
{
const uint32 scale = Converter::to<uint32>(value);
imageScales.push_back(scale);
}
else
{
continue;
}
}
}
bool CapturedScene::getParameters(const Path &fileName)
{
// load base parameters
if (!Scene::getParameters(fileName))
return false;
// get parameters for captured scene
ParametersManager &manager = ParametersManager::getSingleton();
// load inverse rotation matrix for input data
Vector3 angles(0.0f, 0.0f, 0.0f);
if (manager.get(angles, PARAMETER_NAME_INPUT_ORIENTATION))
mInputOrientation = Matrix3x3::createRotationFromExtrinsicAngles(angles.x, angles.y, angles.z);
else
mInputOrientation.setToIdentity();
// load inverse translation for input data
mInputOrigin.set(0.0f, 0.0f, 0.0f);
manager.get(mInputOrigin, PARAMETER_NAME_INPUT_ORIGIN);
return true;
}
void CapturedScene::loadCameras()
{
// input transformation
Matrix3x3 inverseRotation(mInputOrientation);
inverseRotation.transpose();
const Vector3 translation = -mInputOrigin * inverseRotation;
try
{
// load cameras from single MVE cameras file?
if (!mRelativeCamerasFile.getString().empty())
{
// load views from some cameras file containing all cameras
const Path camFile = Path::appendChild(mFolder, mRelativeCamerasFile);
MVECameraIO loader(camFile);
loader.loadFromCamerasFile(mCameras, mViewToCameraIndices, inverseRotation, translation);
return;
}
}
catch (Exception &exception)
{
cerr << "Could not open cameras file!" << endl;
exception;
}
// load views from folders within MVE views folder?
MVECameraIO loader(getViewsFolder());
loader.loadFromMetaIniFiles(mCameras, mViewToCameraIndices, inverseRotation, translation);
}
CapturedScene::~CapturedScene()
{
}
| 30.305732 | 107 | 0.758932 | [
"vector"
] |
b83ea8e11daa14f78728275ad65e44c031c1b612 | 275 | cpp | C++ | leetcode/algorithm/338.cpp | juseongkr/BOJ | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 7 | 2020-02-03T10:00:19.000Z | 2021-11-16T11:03:57.000Z | leetcode/algorithm/338.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2021-01-03T06:58:24.000Z | 2021-01-03T06:58:24.000Z | leetcode/algorithm/338.cpp | juseongkr/Algorithm-training | 8f10a2bf9a7d695455493fbe7423347a8b648416 | [
"Apache-2.0"
] | 1 | 2020-01-22T14:34:03.000Z | 2020-01-22T14:34:03.000Z | class Solution {
public:
vector<int> countBits(int num) {
vector<int> dp(num+1, 0);
if (num >= 1)
dp[1] = 1;
if (num >= 2)
dp[2] = 1;
for (int i=3; i<=num; ++i) {
if (i & 1)
dp[i] = dp[i-1] + 1;
else
dp[i] = dp[i/2];
}
return dp;
}
};
| 13.095238 | 33 | 0.447273 | [
"vector"
] |
cdc8b90efe41a103475ae56dae08e6ce04aa763c | 633 | cpp | C++ | Temporary/ParallelMerge.cpp | vishalbelsare/CombBLAS | 426f6be0b29831025cdcacc1f8f69e3520bfb0ff | [
"BSD-3-Clause-LBNL"
] | 22 | 2020-08-14T19:14:13.000Z | 2022-02-05T20:14:59.000Z | Temporary/ParallelMerge.cpp | vishalbelsare/CombBLAS | 426f6be0b29831025cdcacc1f8f69e3520bfb0ff | [
"BSD-3-Clause-LBNL"
] | 8 | 2020-10-09T23:23:36.000Z | 2021-08-05T20:35:18.000Z | Temporary/ParallelMerge.cpp | vishalbelsare/CombBLAS | 426f6be0b29831025cdcacc1f8f69e3520bfb0ff | [
"BSD-3-Clause-LBNL"
] | 8 | 2020-12-04T09:10:06.000Z | 2022-01-04T15:37:59.000Z | #include <vector>
#include <utility>
#include <parallel/algorithm>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int sequences[10][10];
for (int i = 0; i < 10; ++i)
for (int j = 0; j < 10; ++j)
sequences[i][j] = i*j;
int out[100];
std::vector<std::pair<int*, int*> > seqs;
for (int i = 0; i < 10; ++i)
{ seqs.push_back(std::make_pair(sequences[i], sequences[i] + 10)); }
int * final = __gnu_parallel::multiway_merge(seqs.begin(), seqs.end(), out, 100, std::less<int>());
copy(out, final, ostream_iterator<int>(cout, " "));
return 0;
}
| 22.607143 | 103 | 0.597156 | [
"vector"
] |
cdc8be84fa2dbdb037f59cfcd977122b9249a3f5 | 1,662 | hpp | C++ | lumino/LuminoEngine/include/LuminoEngine/Tilemap/TilemapModel.hpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 30 | 2016-01-24T05:35:45.000Z | 2020-03-03T09:54:27.000Z | lumino/LuminoEngine/include/LuminoEngine/Tilemap/TilemapModel.hpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/LuminoEngine/include/LuminoEngine/Tilemap/TilemapModel.hpp | GameDevery/Lumino | abce2ddca4b7678b04dbfd0ae5348e196c3c9379 | [
"MIT"
] | 5 | 2016-04-03T02:52:05.000Z | 2018-01-02T16:53:06.000Z |
#pragma once
#include "Common.hpp"
#include "Tileset.hpp"
namespace ln {
class RenderingContext;
class TilemapLayer;
// 基本タイルは、横8タイル、縦最大 8191 タイルまで。最大 ID は 65535.
// ただし、現実的には 4096px 程度に抑えてほしいので、16x16 タイルを使ったとしても、最大は 8 * 256 = 2048 個。
// AutoTile は展開すると32, 余裕見て 64、坂道分も作ると考えると + 20。128 個をワンセットにしてみる。
// それにアニメーションを考慮して、AutoTile ひとつ分の最大オフセットは 1024.
// Tileset span 65536 でも十分足りそう。
// 0~163843 を通常タイル、16384~32767 をAutoTile, 32768~65535 はReserved にしてみる。
// - タイルグリッドの座標系は UE4 にならって、左上を 0,0 とする。
class TilemapModel
: public Object
{
LN_OBJECT;
public:
static Ref<TilemapModel> create();
/** 指定したサイズとレイヤー数で、すべてのタイルを 0 で初期化する。 */
void reset(int width, int height, int layers);
Tileset* tileset() const;
void setTileset(Tileset* tileset);
void addLayer(TilemapLayer* layer);
TilemapLayer* layer(int index) const;
const Size& tileSize() const;
int width() const;
int height() const;
bool isValidTilePosition(int x, int y) const;
uint8_t tilePassageFlags(int x, int y) const;
TilemapLayer* getValidFrontLayer(int x, int y) const;
public: // TODO: internal
void render(RenderingContext* context, const Matrix& transform, const detail::TilemapBounds& bounds);
bool fetchTileset(int tileGlobalId, Tileset** outTileset, int* outTileLocalId);
protected:
LN_CONSTRUCT_ACCESS:
TilemapModel();
virtual ~TilemapModel();
void init();
void init(const StringView& filePath);
private:
//struct TilesetSlot
//{
// Ref<Tileset> tileset;
// int startId;
//};
Ref<Tileset> m_tileset;
List<Ref<TilemapLayer>> m_layers; // インデックスの低い方が奥。
int m_tilesetIdSpan;
};
} // namespace ln
| 24.441176 | 105 | 0.711793 | [
"render",
"object",
"transform"
] |
cdcd8501d229920e714f3bd5f73f4fbe512b313f | 12,196 | cc | C++ | components/query_tiles/internal/tile_manager.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/query_tiles/internal/tile_manager.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/query_tiles/internal/tile_manager.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-03-07T14:20:02.000Z | 2021-03-07T14:20:02.000Z | // Copyright 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 <map>
#include <string>
#include <unordered_set>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "components/query_tiles/internal/stats.h"
#include "components/query_tiles/internal/tile_config.h"
#include "components/query_tiles/internal/tile_iterator.h"
#include "components/query_tiles/internal/tile_manager.h"
#include "components/query_tiles/internal/tile_utils.h"
#include "components/query_tiles/internal/trending_tile_handler.h"
#include "components/query_tiles/switches.h"
namespace query_tiles {
namespace {
// A special tile group for tile stats.
constexpr char kTileStatsGroup[] = "tile_stats";
class TileManagerImpl : public TileManager {
public:
TileManagerImpl(std::unique_ptr<TileStore> store,
base::Clock* clock,
const std::string& accept_languages)
: initialized_(false),
store_(std::move(store)),
clock_(clock),
accept_languages_(accept_languages) {}
private:
// TileManager implementation.
void Init(TileGroupStatusCallback callback) override {
store_->InitAndLoad(base::BindOnce(&TileManagerImpl::OnTileStoreInitialized,
weak_ptr_factory_.GetWeakPtr(),
std::move(callback)));
}
void SaveTiles(std::unique_ptr<TileGroup> group,
TileGroupStatusCallback callback) override {
if (!initialized_) {
std::move(callback).Run(TileGroupStatus::kUninitialized);
return;
}
auto group_copy = *group;
store_->Update(group_copy.id, group_copy,
base::BindOnce(&TileManagerImpl::OnGroupSaved,
weak_ptr_factory_.GetWeakPtr(),
std::move(group), std::move(callback)));
}
void GetTiles(GetTilesCallback callback) override {
if (!tile_group_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), std::vector<Tile>()));
return;
}
// First remove the inactive trending tiles.
RemoveIdleTrendingTiles();
// Now build the tiles to return. Don't filter the subtiles, as they are
// only used for UMA purpose now.
// TODO(qinmin): remove all subtiles before returning the result, as they
// are not used.
std::vector<Tile> tiles =
trending_tile_handler_.FilterExtraTrendingTiles(tile_group_->tiles);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), std::move(tiles)));
}
void GetTile(const std::string& tile_id, TileCallback callback) override {
// First remove the inactive trending tiles.
RemoveIdleTrendingTiles();
// Find the tile.
const Tile* result = nullptr;
if (tile_group_) {
TileIterator it(*tile_group_, TileIterator::kAllTiles);
while (it.HasNext()) {
const auto* tile = it.Next();
DCHECK(tile);
if (tile->id == tile_id) {
result = tile;
break;
}
}
}
auto result_tile = result ? base::make_optional(*result) : base::nullopt;
if (result_tile.has_value()) {
// Get the tiles to display, and convert the result vector.
// TODO(qinmin): make GetTile() return a vector of sub tiles, rather than
// the parent tile so we don't need the conversion below.
std::vector<Tile> sub_tiles =
trending_tile_handler_.FilterExtraTrendingTiles(
result_tile->sub_tiles);
if (!sub_tiles.empty()) {
std::vector<std::unique_ptr<Tile>> sub_tile_ptrs;
for (auto& tile : sub_tiles)
sub_tile_ptrs.emplace_back(std::make_unique<Tile>(std::move(tile)));
result_tile->sub_tiles = std::move(sub_tile_ptrs);
}
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), std::move(result_tile)));
}
TileGroupStatus PurgeDb() override {
if (!initialized_)
return TileGroupStatus::kUninitialized;
if (!tile_group_)
return TileGroupStatus::kNoTiles;
store_->Delete(tile_group_->id,
base::BindOnce(&TileManagerImpl::OnGroupDeleted,
weak_ptr_factory_.GetWeakPtr()));
tile_group_.reset();
return TileGroupStatus::kNoTiles;
}
void SetAcceptLanguagesForTesting(
const std::string& accept_languages) override {
accept_languages_ = accept_languages;
}
TileGroup* GetTileGroup() override {
return tile_group_ ? tile_group_.get() : nullptr;
}
void OnTileStoreInitialized(
TileGroupStatusCallback callback,
bool success,
std::map<std::string, std::unique_ptr<TileGroup>> loaded_groups) {
if (!success) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback),
TileGroupStatus::kFailureDbOperation));
return;
}
initialized_ = true;
PruneAndSelectGroup(std::move(callback), std::move(loaded_groups));
}
// Select the most recent unexpired group from |loaded_groups| with the
// correct locale, and delete other groups.
void PruneAndSelectGroup(
TileGroupStatusCallback callback,
std::map<std::string, std::unique_ptr<TileGroup>> loaded_groups) {
TileGroupStatus status = TileGroupStatus::kSuccess;
base::Time last_updated_time;
std::string selected_group_id;
for (const auto& pair : loaded_groups) {
DCHECK(!pair.first.empty()) << "Should not have empty tile group key.";
auto* group = pair.second.get();
if (!group)
continue;
if (pair.first == kTileStatsGroup)
continue;
if (ValidateLocale(group) && !IsGroupExpired(group) &&
(group->last_updated_ts > last_updated_time)) {
last_updated_time = group->last_updated_ts;
selected_group_id = pair.first;
}
}
// Moves the selected group into in memory holder.
if (!selected_group_id.empty()) {
tile_group_ = std::move(loaded_groups[selected_group_id]);
loaded_groups.erase(selected_group_id);
} else {
status = TileGroupStatus::kNoTiles;
}
// Keep the stats group in memory for tile score calculation.
if (loaded_groups.find(kTileStatsGroup) != loaded_groups.end() &&
base::FeatureList::IsEnabled(features::kQueryTilesLocalOrdering)) {
tile_stats_group_ = std::move(loaded_groups[kTileStatsGroup]);
// prevent the stats group from being deleted.
loaded_groups.erase(kTileStatsGroup);
if (tile_group_) {
SortTilesAndClearUnusedStats(&tile_group_->tiles,
&tile_stats_group_->tile_stats);
}
}
trending_tile_handler_.Reset();
// Deletes other groups.
for (const auto& group_to_delete : loaded_groups)
DeleteGroup(group_to_delete.first);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), status));
}
// Returns true if the group is expired.
bool IsGroupExpired(const TileGroup* group) const {
if (clock_->Now() >=
group->last_updated_ts + TileConfig::GetExpireDuration()) {
stats::RecordGroupPruned(stats::PrunedGroupReason::kExpired);
return true;
}
return false;
}
// Check whether |locale_| matches with that of the |group|.
bool ValidateLocale(const TileGroup* group) const {
if (!accept_languages_.empty() && !group->locale.empty()) {
// In case the primary language matches (en-GB vs en-IN), consider
// those are matching.
std::string group_primary =
group->locale.substr(0, group->locale.find("-"));
for (auto& lang :
base::SplitString(accept_languages_, ",", base::TRIM_WHITESPACE,
base::SPLIT_WANT_NONEMPTY)) {
if (lang.substr(0, lang.find("-")) == group_primary)
return true;
}
}
stats::RecordGroupPruned(stats::PrunedGroupReason::kInvalidLocale);
return false;
}
void OnGroupSaved(std::unique_ptr<TileGroup> group,
TileGroupStatusCallback callback,
bool success) {
if (!success) {
std::move(callback).Run(TileGroupStatus::kFailureDbOperation);
return;
}
// Only swap the in memory tile group when there is no existing tile group.
if (!tile_group_) {
tile_group_ = std::move(group);
trending_tile_handler_.Reset();
}
std::move(callback).Run(TileGroupStatus::kSuccess);
}
void DeleteGroup(const std::string& key) {
store_->Delete(key, base::BindOnce(&TileManagerImpl::OnGroupDeleted,
weak_ptr_factory_.GetWeakPtr()));
}
void OnGroupDeleted(bool success) {
// TODO(hesen): Record db operation metrics.
NOTIMPLEMENTED();
}
void OnTileClicked(const std::string& tile_id) override {
// If the tile stats haven't been created, create it here.
if (!tile_stats_group_) {
tile_stats_group_ = std::make_unique<TileGroup>();
tile_stats_group_->id = kTileStatsGroup;
}
tile_stats_group_->OnTileClicked(tile_id);
// It's fine if |tile_stats_group_| is not saved, so no callback needs to
// be passed to Update().
store_->Update(kTileStatsGroup, *tile_stats_group_, base::DoNothing());
trending_tile_handler_.OnTileClicked(tile_id);
}
void OnQuerySelected(const base::Optional<std::string>& parent_tile_id,
const base::string16& query_text) override {
if (!tile_group_)
return;
// Find the parent tile first. If it cannot be found, that's fine as the
// old tile score will be used.
std::vector<std::unique_ptr<Tile>>* tiles = &tile_group_->tiles;
if (parent_tile_id) {
for (const auto& tile : tile_group_->tiles) {
if (tile->id == parent_tile_id.value()) {
tiles = &tile->sub_tiles;
break;
}
}
}
// Now check if a sub tile has the same query text.
for (const auto& tile : *tiles) {
if (query_text == base::UTF8ToUTF16(tile->query_text)) {
OnTileClicked(tile->id);
break;
}
}
}
void RemoveIdleTrendingTiles() {
if (!tile_group_)
return;
std::vector<std::string> tiles_to_remove =
trending_tile_handler_.GetInactiveTrendingTiles();
if (tiles_to_remove.empty())
return;
tile_group_->RemoveTiles(tiles_to_remove);
store_->Update(tile_group_->id, *tile_group_, base::DoNothing());
}
// Indicates if the db is fully initialized, rejects calls if not.
bool initialized_;
// Storage layer of query tiles.
std::unique_ptr<TileStore> store_;
// The tile group in-memory holder.
std::unique_ptr<TileGroup> tile_group_;
// The tile group that contains stats for ranking all tiles.
// TODO(qinmin): Having a separate TileGroup just for ranking the tiles
// seems weird, probably do it through a separate store or use PrefService.
std::unique_ptr<TileGroup> tile_stats_group_;
// Clock object.
base::Clock* clock_;
// Accept languages from the PrefService. Used to check if tiles stored are of
// the same language.
std::string accept_languages_;
// Object for managing trending tiles.
TrendingTileHandler trending_tile_handler_;
base::WeakPtrFactory<TileManagerImpl> weak_ptr_factory_{this};
};
} // namespace
TileManager::TileManager() = default;
std::unique_ptr<TileManager> TileManager::Create(
std::unique_ptr<TileStore> tile_store,
base::Clock* clock,
const std::string& locale) {
return std::make_unique<TileManagerImpl>(std::move(tile_store), clock,
locale);
}
} // namespace query_tiles
| 34.451977 | 80 | 0.659397 | [
"object",
"vector"
] |
cdd00aa970cd4540ad0c5ec74025b7efbfd1c451 | 3,988 | hh | C++ | elements/tcp/tcpencap.hh | leeopop/ClickNF | 5bca7586195d1b24d3a899fa084feafa93f81790 | [
"MIT"
] | 32 | 2017-11-02T12:33:21.000Z | 2022-02-07T22:25:58.000Z | elements/tcp/tcpencap.hh | leeopop/ClickNF | 5bca7586195d1b24d3a899fa084feafa93f81790 | [
"MIT"
] | 2 | 2019-02-18T08:47:16.000Z | 2019-05-24T14:41:23.000Z | elements/tcp/tcpencap.hh | leeopop/ClickNF | 5bca7586195d1b24d3a899fa084feafa93f81790 | [
"MIT"
] | 10 | 2018-06-13T11:54:53.000Z | 2020-09-08T06:52:43.000Z | /*
* tcpencap.{cc,hh} -- encapsulates packet with a TCP header
* Rafael Laufer, Massimo Gallo
*
* Copyright (c) 2017 Nokia Bell Labs
*
* 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.
*
*
*/
#ifndef CLICK_TCPENCAP_HH
#define CLICK_TCPENCAP_HH
#include <click/element.hh>
CLICK_DECLS
/*
=c
TCPEncap(SRC, DST, I<KEYWORDS>)
=s ip
encapsulates packets with a TCP header
=d
Encapsulates each incoming packet with a TCP header with source port SRC and
destination port DST.
Keyword arguments are:
=over 8
=item SEQNO
Number between 0 and 63. The IP header's DSCP value. Default is 0.
=item ACKNO
Number between 0 and 3. The IP header's ECN value. Default is 0.
=item SYN
Boolean. If true, sets the TCP header's SYN bit to 1. Default is false.
=item ACK
Boolean. If true, sets the TCP header's ACK bit to 1. Default is false.
=item RST
Boolean. If true, sets the TCP header's RST bit to 1. Default is false.
=item FIN
Boolean. If true, sets the TCP header's FIN bit to 1. Default is false.
=item URG
Boolean. If true, sets the TCP header's URG bit to 1. Default is false.
=item PSH
Boolean. If true, sets the TCP header's PSH bit to 1. Default is false.
=item WINDOW
Number between 0 and 65535. The TCP header's window size. Default is 0.
=item URGENT
Number between 0 and 65535. The TCP header's urgent pointer. Default is 0.
=item TSVAL
Number between 0 and 2^32 - 1. TCP timestamp value. Default is 0. If
this is nonzero, the TCP timestamp option will be included in the header.
=item TSECR
Number between 0 and 2^32 - 1. TCP timestamp echo reply. Default is 0. If
this is nonzero, the TCP timestamp option will be included in the header.
=back
The StripTCPHeader element can be used by the receiver to get rid of the
encapsulation header.
=e
Wraps data packets with an TCP header.
... -> TCPEncap
-> IPEncap
-> ...
=a UDPIPEncap, StripIPHeader, StripTCPHeader */
class TCPEncap final : public Element { public:
TCPEncap() CLICK_COLD;
const char *class_name() const { return "TCPEncap"; }
const char *port_count() const { return PORTS_1_1; }
const char *processing() const { return AGNOSTIC; }
int configure(Vector<String> &, ErrorHandler *) CLICK_COLD;
bool can_live_reconfigure() const { return true; }
Packet *smaction(Packet *);
void push(int, Packet *) final;
Packet *pull(int);
private:
uint16_t _src;
uint16_t _dst;
uint32_t _seqno;
uint32_t _ackno;
uint8_t _flags;
uint16_t _window;
uint16_t _urgent;
uint32_t _tsval;
uint32_t _tsecr;
};
CLICK_ENDDECLS
#endif
| 27.315068 | 148 | 0.748495 | [
"vector"
] |
cdd915fc9f4cf7c3a0d0824bf961cb221ab01370 | 759 | hpp | C++ | src/Domain/InitialElementIds.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/Domain/InitialElementIds.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | 1 | 2022-03-25T18:26:16.000Z | 2022-03-25T19:30:39.000Z | src/Domain/InitialElementIds.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | 1 | 2019-01-03T21:47:04.000Z | 2019-01-03T21:47:04.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <array>
#include <cstddef>
#include <vector>
/// \cond
template <size_t VolumeDim>
class ElementId;
/// \endcond
/// \ingroup ComputationalDomainGroup
/// \brief Create the `ElementId`s of the a single Block
template <size_t VolumeDim>
std::vector<ElementId<VolumeDim>> initial_element_ids(
size_t block_id, std::array<size_t, VolumeDim> initial_ref_levs) noexcept;
/// \ingroup ComputationalDomainGroup
/// \brief Create the `ElementId`s of the initial computational domain.
template <size_t VolumeDim>
std::vector<ElementId<VolumeDim>> initial_element_ids(
const std::vector<std::array<size_t, VolumeDim>>&
initial_refinement_levels) noexcept;
| 28.111111 | 78 | 0.758893 | [
"vector"
] |
cddbbd892fdd178a125b2f280dfc336ac1a13c2b | 4,370 | hpp | C++ | Player.hpp | FocuzJS/Cyth | 8e0b1a2e24481d4344915f88b490901b9278b074 | [
"MIT"
] | 18 | 2018-06-07T10:52:00.000Z | 2021-12-13T09:09:28.000Z | Player.hpp | FocuzJS/Cyth | 8e0b1a2e24481d4344915f88b490901b9278b074 | [
"MIT"
] | 18 | 2018-04-16T03:08:47.000Z | 2019-01-22T19:05:44.000Z | Player.hpp | FocuzJS/Cyth | 8e0b1a2e24481d4344915f88b490901b9278b074 | [
"MIT"
] | 7 | 2018-04-16T14:42:24.000Z | 2021-09-21T02:47:03.000Z | #pragma once
#include "lua.hpp"
#include "Netvars.hpp"
#include <optional>
constexpr auto entity = hash::fnv1a("DT_BaseEntity");
class Player
{
public:
inline const char* get_classname()
{
void* networkable = this + 8;
using get_client_class_t = const char**(__thiscall*)(void*);
return *(method<get_client_class_t>(2, networkable)(networkable) + 2);
}
inline bool is_dormant()
{
void* networkable = this + 8;
using is_dormant_t = bool(__thiscall*)(void*);
return method<is_dormant_t>(8, networkable)(networkable);
}
inline size_t get_index()
{
void* networkable = this + 8;
using get_entity_index_t = size_t(__thiscall*)(void*);
return method<get_entity_index_t>(9, networkable)(networkable);
}
inline bool is_npc()
{
return !!std::memcmp(this->get_classname(), "npc", 3);
}
inline bool is_player()
{
return !!std::strstr(this->get_classname(), "player");
}
inline const Angle& get_angles()
{
using namespace hash::literals;
auto offset = globals::netvars["DT_GMOD_Player"_fnv1a]["m_angEyeAngles[0]"_fnv1a];
return *reinterpret_cast<Angle*>(reinterpret_cast<uintptr_t>(this) + offset);
}
inline const int32_t get_health()
{
using namespace hash::literals;
auto offset = globals::netvars[entity]["m_iHealth"_fnv1a];
return *reinterpret_cast<int32_t*>(reinterpret_cast<uintptr_t>(this) + offset);
}
inline const int32_t get_max_health()
{
using namespace hash::literals;
auto offset = globals::netvars[entity]["m_iMaxHealth"_fnv1a];
return *reinterpret_cast<int32_t*>(reinterpret_cast<uintptr_t>(this) + offset);
}
inline const Vector& get_pos()
{
using namespace hash::literals;
auto offset = globals::netvars[entity]["m_vecOrigin"_fnv1a];
return *reinterpret_cast<Vector*>(reinterpret_cast<uintptr_t>(this) + offset);
}
inline const uint32_t get_team()
{
using namespace hash::literals;
auto offset = globals::netvars[entity]["m_iTeamNum"_fnv1a];
return *reinterpret_cast<int32_t*>(reinterpret_cast<uintptr_t>(this) + offset);
}
inline std::optional<uint32_t> get_team_color()
{
auto glua = globals::lua->create_interface(lua::type::client);
if (!glua)
return {};
glua->PushSpecial(lua::special::glob);
glua->GetField(-1, "team");
glua->GetField(-1, "GetColor");
glua->PushNumber(this->get_team());
glua->Call(1, 1);
glua->PushString("r");
glua->GetTable(-2);
auto r = glua->GetNumber(-1);
glua->Pop();
glua->PushString("g");
glua->GetTable(-2);
auto g = glua->GetNumber(-1);
glua->Pop();
glua->PushString("b");
glua->GetTable(-2);
auto b = glua->GetNumber(-1);
glua->Pop(4);
return 0xFF000000 + (static_cast<uint32_t>(r)) + (static_cast<uint32_t>(g) << 8) + (static_cast<uint32_t>(b) << 16);
}
inline std::optional<bool> is_admin()
{
auto glua = globals::lua->create_interface(lua::type::client);
if (!glua)
return {};
glua->PushSpecial(lua::special::glob);
glua->GetField(-1, "Entity");
glua->PushNumber(this->get_index());
glua->Call(1, 1);
glua->GetField(-1, "IsAdmin");
glua->Push(-2);
glua->Call(1, 1);
bool admin = glua->GetBool();
glua->Pop(3);
return admin;
}
inline const Vector& get_oob_min()
{
using namespace hash::literals;
auto offset = globals::netvars[entity]["m_vecMins"_fnv1a];
return *reinterpret_cast<Vector*>(reinterpret_cast<uintptr_t>(this) + offset);
}
inline const Vector& get_oob_max()
{
using namespace hash::literals;
auto offset = globals::netvars[entity]["m_vecMaxs"_fnv1a];
return *reinterpret_cast<Vector*>(reinterpret_cast<uintptr_t>(this) + offset);
}
inline std::string get_team_name()
{
auto glua = globals::lua->create_interface(lua::type::client);
if (!glua)
return {};
glua->PushSpecial(lua::special::glob);
glua->GetField(-1, "team");
glua->GetField(-1, "GetName");
glua->PushNumber(this->get_team());
glua->Call(1, 1);
std::string team = glua->GetString();
glua->Pop(3);
return team;
}
inline std::string get_name()
{
auto glua = globals::lua->create_interface(lua::type::client);
if (!glua)
return {};
glua->PushSpecial(lua::special::glob);
glua->GetField(-1, "Entity");
glua->PushNumber(this->get_index());
glua->Call(1, 1);
glua->GetField(-1, "Name");
glua->Push(-2);
glua->Call(1, 1);
std::string name = glua->GetString();
glua->Pop(3);
return name;
}
}; | 23.75 | 118 | 0.677803 | [
"vector"
] |
cde0b8957a92efddce23b6ddf7eee8f199366b90 | 40,050 | cpp | C++ | src/lib/client/NetworkControllerBasis.cpp | gerickson/openhlx | f23a825ca56ee226db393da14d81a7d4e9ae0b33 | [
"Apache-2.0"
] | 1 | 2021-05-21T21:10:09.000Z | 2021-05-21T21:10:09.000Z | src/lib/client/NetworkControllerBasis.cpp | gerickson/openhlx | f23a825ca56ee226db393da14d81a7d4e9ae0b33 | [
"Apache-2.0"
] | 12 | 2021-06-12T16:42:30.000Z | 2022-02-01T18:44:42.000Z | src/lib/client/NetworkControllerBasis.cpp | gerickson/openhlx | f23a825ca56ee226db393da14d81a7d4e9ae0b33 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2021 Grant Erickson
* 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.
*
*/
/**
* @file
* This file implements a derivable object for realizing a HLX
* Ethernet network interface controller, in a client.
*
*/
#include "NetworkControllerBasis.hpp"
#include <memory>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <LogUtilities/LogUtilities.hpp>
#include <OpenHLX/Client/CommandManager.hpp>
#include <OpenHLX/Client/NetworkControllerCommands.hpp>
#include <OpenHLX/Client/NetworkStateChangeNotifications.hpp>
#include <OpenHLX/Model/NetworkModel.hpp>
#include <OpenHLX/Utilities/Assert.hpp>
#include <OpenHLX/Utilities/ElementsOf.hpp>
using namespace HLX::Common;
using namespace HLX::Model;
using namespace HLX::Utilities;
using namespace Nuovations;
namespace HLX
{
namespace Client
{
// Class-scoped Notification Regular Expression Data
/**
* Class-scoped server network interface DHCPv4 enabled notification
* regular expression.
*
*/
Command::Network::DHCPv4EnabledResponse NetworkControllerBasis::kDHCPv4EnabledResponse;
/**
* Class-scoped server network interface EUI-48 address notification
* regular expression.
*
*/
Command::Network::EthernetEUI48Response NetworkControllerBasis::kEthernetEUI48Response;
/**
* Class-scoped server network interface default router IP address
* notification regular expression.
*
*/
Command::Network::IPDefaultRouterAddressResponse NetworkControllerBasis::kIPDefaultRouterAddressResponse;
/**
* Class-scoped server network interface host IP address notification
* regular expression.
*
*/
Command::Network::IPHostAddressResponse NetworkControllerBasis::kIPHostAddressResponse;
/**
* Class-scoped server network interface IP netmask notification
* regular expression.
*
*/
Command::Network::IPNetmaskResponse NetworkControllerBasis::kIPNetmaskResponse;
/**
* Class-scoped server network interface Control4 SDDP enabled
* notification regular expression.
*
*/
Command::Network::SDDPEnabledResponse NetworkControllerBasis::kSDDPEnabledResponse;
/**
* Class-scoped server network interface query notification regular
* expression.
*
*/
Command::Network::QueryResponse NetworkControllerBasis::kQueryResponse;
/**
* @brief
* This is a class constructor.
*
* This constructs the network interface controller with the
* specified network interface model.
*
* @param[in] aNetworkModel A mutable reference to the network
* interface model to construct the
* controller with. This is retained by a
* weak pointer reference and,
* consequently, must remain in scope for
* the lifetime of the controller.
*
*/
NetworkControllerBasis :: NetworkControllerBasis(Model::NetworkModel &aNetworkModel) :
Client::ObjectControllerBasis(),
mNetworkModel(aNetworkModel)
{
return;
}
/**
* @brief
* This is the class destructor.
*
*/
NetworkControllerBasis :: ~NetworkControllerBasis(void)
{
return;
}
// MARK: Initializer(s)
/**
* @brief
* This is the class initializer.
*
* This initializes the class with the specified command manager and
* timeout.
*
* @param[in] aCommandManager A reference to the command manager
* instance to initialize the controller
* with.
* @param[in] aTimeout The timeout to initialize the controller
* with that will serve as the timeout for
* future operations with the peer server.
*
* @retval kStatus_Success If successful.
* @retval -EINVAL If an internal parameter was
* invalid.
* @retval -ENOMEM If memory could not be allocated.
* @retval kError_NotInitialized The base class was not properly
* initialized.
* @retval kError_InitializationFailed If initialization otherwise failed.
*
*/
Status
NetworkControllerBasis :: Init(CommandManager &aCommandManager, const Timeout &aTimeout)
{
DeclareScopedFunctionTracer(lTracer);
Status lRetval = kStatus_Success;
lRetval = ResponseInit();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = ObjectControllerBasis::Init(aCommandManager, aTimeout);
nlREQUIRE_SUCCESS(lRetval, done);
done:
return (lRetval);
}
/**
* @brief
* Refresh or obtain an up-to-date view of the server peer state.
*
* This attempts to refresh or obtain an up-to-date view of the
* server peer state with the specified timeout.
*
* Presently, this controller does so by executing a "query network
* [QE]" command with the peer server.
*
* @param[in] aTimeout The timeout to use for the refresh operation
* with the peer server.
*
* @retval kStatus_Success If successful.
* @retval -ENOMEM If memory could not be allocated
* for the command exchange or
* exchange state.
* @retval kError_InitializationFailed If initialization otherwise failed.
*
*/
Status
NetworkControllerBasis :: Refresh(const Timeout &aTimeout)
{
Status lRetval = kStatus_Success;
(void)aTimeout;
// Notify the base controller that we have begun a refresh
// operation.
SetRefreshRequested(true);
// Issue a query network request.
lRetval = Query();
nlREQUIRE_SUCCESS(lRetval, done);
done:
return (lRetval);
}
// MARK: Implementation
/**
* @brief
* Register or unregister notification handlers.
*
* This registers or unregisters the solicited and unsolicited client
* command response notification handlers that this controller is
* interested in and will handle on behalf of the client.
*
* @param[in] aRegister Indicates whether to register (true) or
* unregister (false) the handlers.
*
* @retval kStatus_Success If successful.
* @retval -EINVAL If either of the handler iterators
* was null.
* @retval -EEXIST If a registration already exists.
* @retval -ENOENT If there was no such handler
* registration to unregister.
* @retval kError_NotInitialized The base class was not properly
* initialized.
* @retval kError_InitializationFailed If initialization otherwise failed.
*
*/
Status
NetworkControllerBasis :: DoNotificationHandlers(const bool &aRegister)
{
static const NotificationHandlerBasis lNotificationHandlers[] = {
{
kDHCPv4EnabledResponse,
NetworkControllerBasis::DHCPv4EnabledNotificationReceivedHandler
},
{
kEthernetEUI48Response,
NetworkControllerBasis::EthernetEUI48NotificationReceivedHandler
},
{
kIPDefaultRouterAddressResponse,
NetworkControllerBasis::IPDefaultRouterAddressNotificationReceivedHandler
},
{
kIPHostAddressResponse,
NetworkControllerBasis::IPHostAddressNotificationReceivedHandler
},
{
kIPNetmaskResponse,
NetworkControllerBasis::IPNetmaskNotificationReceivedHandler
},
{
kSDDPEnabledResponse,
NetworkControllerBasis::SDDPEnabledNotificationReceivedHandler
}
};
static constexpr size_t lNotificationHandlerCount = ElementsOf(lNotificationHandlers);
Status lRetval = kStatus_Success;
lRetval = Client::ObjectControllerBasis::DoNotificationHandlers(&lNotificationHandlers[0],
&lNotificationHandlers[lNotificationHandlerCount],
this,
aRegister);
nlREQUIRE_SUCCESS(lRetval, done);
done:
return (lRetval);
}
/**
* @brief
* Initialize client command response regular expression patterns.
*
* This initializes solicited and unsolicited client command
* responses that this controller would like to register to handle.
*
* @retval kStatus_Success If successful.
* @retval -EINVAL If an internal parameter was
* invalid.
* @retval -ENOMEM If memory could not be allocated.
* @retval kError_InitializationFailed If initialization otherwise failed.
*
*/
Status
NetworkControllerBasis :: ResponseInit(void)
{
Status lRetval = kStatus_Success;
// Initialize static notification response regular expression pattern data.
lRetval = kDHCPv4EnabledResponse.Init();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = kEthernetEUI48Response.Init();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = kIPDefaultRouterAddressResponse.Init();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = kIPHostAddressResponse.Init();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = kIPNetmaskResponse.Init();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = kSDDPEnabledResponse.Init();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = kQueryResponse.Init();
nlREQUIRE_SUCCESS(lRetval, done);
done:
return (lRetval);
}
// MARK: Observer Methods
/**
* @brief
* Query the Ethernet network interface state.
*
* This queries the current HLX server Ethernet network interface state.
*
* @retval kStatus_Success If successful.
* @retval -ENOMEM If memory could not be allocated
* for the command exchange or
* exchange state.
* @retval kError_InitializationFailed If initialization otherwise failed.
*
*/
Status
NetworkControllerBasis :: Query(void)
{
Command::ExchangeBasis::MutableCountedPointer lCommand;
Status lRetval = kStatus_Success;
lCommand.reset(new Command::Network::Query());
nlREQUIRE_ACTION(lCommand, done, lRetval = -ENOMEM);
lRetval = std::static_pointer_cast<Command::Network::Query>(lCommand)->Init();
nlREQUIRE_SUCCESS(lRetval, done);
lRetval = SendCommand(lCommand,
NetworkControllerBasis::QueryCompleteHandler,
NetworkControllerBasis::CommandErrorHandler,
this);
nlREQUIRE_SUCCESS(lRetval, done);
done:
return (lRetval);
}
// MARK: Command Completion Handlers
/**
* @brief
* Asynchronous query Ethernet network interface client command
* response completion handler.
*
* This handles an asynchronous client command response for the query
* Ethernet network interface command request.
*
* @param[in] aExchange A mutable shared pointer to the exchange
* associated with the client command response
* and its original request.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
*
*/
void
NetworkControllerBasis :: QueryCompleteHandler(Command::ExchangeBasis::MutableCountedPointer &aExchange,
const RegularExpression::Matches &aMatches)
{
const Command::ResponseBasis * lResponse = aExchange->GetResponse();
const size_t lExpectedMatchCount = lResponse->GetRegularExpression().GetExpectedMatchCount();
nlREQUIRE(aMatches.size() == lExpectedMatchCount, done);
MaybeUpdateRefreshIfRefreshWasRequested();
done:
return;
}
/**
* @brief
* Asynchronous network controller client command request
* error handler.
*
* This handles any asynchronous client network controller
* command request that results in an error response from the HLX
* peer server.
*
* @param[in] aExchange A mutable shared pointer to the exchange
* associated with the client command error
* and its original request.
* @param[in] aError An immutable reference to the error
* associated with the failed client command
* request.
*
*/
void
NetworkControllerBasis :: CommandErrorHandler(Command::ExchangeBasis::MutableCountedPointer &aExchange, const Common::Error &aError)
{
const Command::RequestBasis * lRequest = aExchange->GetRequest();
const uint8_t * lBuffer = lRequest->GetBuffer();
const size_t lBufferSize = lRequest->GetSize();
OnCommandError(lBuffer, lBufferSize, "Network Command", aError);
}
// MARK: Command Completion Handler Trampolines
/**
* @brief
* Asynchronous query Ethernet network interface client command
* response completion handler trampoline.
*
* This invokes the handler for an asynchronous client command
* response for the query Ethernet network interface command request.
*
* @param[in] aExchange A mutable shared pointer to the exchange
* associated with the client command
* response and its original request.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: QueryCompleteHandler(Command::ExchangeBasis::MutableCountedPointer &aExchange, const RegularExpression::Matches &aMatches, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->QueryCompleteHandler(aExchange, aMatches);
}
}
/**
* @brief
* Asynchronous network controller client command request error
* handler trampoline.
*
* This invokes the handler for any asynchronous client network
* controller command request that results in an error response from
* the HLX peer server.
*
* @param[in] aExchange A mutable shared pointer to the exchange
* associated with the client command
* error response and its original
* request.
* @param[in] aError An immutable reference to the error
* associated with the failed command
* request.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: CommandErrorHandler(Command::ExchangeBasis::MutableCountedPointer &aExchange, const Common::Error &aError, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->CommandErrorHandler(aExchange, aError);
}
}
// MARK: Unsolicited Notification Handlers
/**
* @brief
* Ethernet network interface DHCPv4 enabled changed client
* unsolicited notification handler.
*
* This handles an asynchronous, unsolicited client notification for
* the Ethernet network interface DHCPv4 enabled changed
* notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
*
*/
void
NetworkControllerBasis :: DHCPv4EnabledNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const Common::RegularExpression::Matches &aMatches)
{
NetworkModel::EnabledType lEnabled;
StateChange::NetworkDHCPv4EnabledNotification lStateChangeNotification;
Status lStatus;
(void)aSize;
nlREQUIRE(aMatches.size() == Command::Network::DHCPv4EnabledResponse::kExpectedMatches, done);
// Match 2/2: Enabled
lStatus = Utilities::Parse(aBuffer + aMatches.at(1).rm_so,
Common::Utilities::Distance(aMatches.at(1)),
lEnabled);
nlREQUIRE_SUCCESS(lStatus, done);
// If the DHCPv4 enabled state is unchanged, SetDHCPv4Enabled will
// return kStatus_ValueAlreadySet and there will be no need to
// send a state change notification. If we receive
// kStatus_Success, it is the first time set or a change and state
// change notification needs to be sent.
lStatus = mNetworkModel.SetDHCPv4Enabled(lEnabled);
nlEXPECT_SUCCESS(lStatus, done);
lStatus = lStateChangeNotification.Init(lEnabled);
nlREQUIRE_SUCCESS(lStatus, done);
OnStateDidChange(lStateChangeNotification);
done:
return;
}
static Common::Status
Parse(const uint8_t *aBuffer, const size_t &aBufferLength, NetworkModel::EthernetEUI48Type &aEthernetEUI48)
{
int lConversions;
Status lRetval = kStatus_Success;
(void)aBufferLength;
lConversions = sscanf(reinterpret_cast<const char *>(aBuffer),
"%02hhx-%02hhx-%02hhx-%02hhx-%02hhx-%02hhx",
&aEthernetEUI48[0],
&aEthernetEUI48[1],
&aEthernetEUI48[2],
&aEthernetEUI48[3],
&aEthernetEUI48[4],
&aEthernetEUI48[5]);
nlREQUIRE_ACTION(lConversions == sizeof(NetworkModel::EthernetEUI48Type), done, lRetval = -EINVAL);
done:
return (lRetval);
}
static Common::Status
Parse(const uint8_t *aBuffer, const size_t &aBufferLength, Common::IPAddress &aIPAddress)
{
const size_t lLength = std::min(aBufferLength,
static_cast<size_t>(INET6_ADDRSTRLEN));
char lBuffer[INET6_ADDRSTRLEN];
Status lRetval = kStatus_Success;
memset(lBuffer, 0, INET6_ADDRSTRLEN);
memcpy(lBuffer, aBuffer, lLength);
lRetval = aIPAddress.FromString(lBuffer, lLength);
nlREQUIRE_SUCCESS(lRetval, done);
done:
return (lRetval);
}
/**
* @brief
* Ethernet network interface EUI-48 address changed client
* unsolicited notification handler.
*
* This handles an asynchronous, unsolicited client notification for
* the Ethernet network interface EUI-48 address changed
* notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
*
*/
void
NetworkControllerBasis :: EthernetEUI48NotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const Common::RegularExpression::Matches &aMatches)
{
NetworkModel::EthernetEUI48Type lEthernetEUI48;
StateChange::NetworkEthernetEUI48Notification lStateChangeNotification;
Status lStatus;
(void)aSize;
nlREQUIRE(aMatches.size() == Command::Network::EthernetEUI48Response::kExpectedMatches, done);
// Match 2/2: Ethernet Address
lStatus = Parse(aBuffer + aMatches.at(1).rm_so,
Common::Utilities::Distance(aMatches.at(1)),
lEthernetEUI48);
nlREQUIRE_SUCCESS(lStatus, done);
// If the Ethernet EUI-48 address is unchanged, SetEthernetEUI48
// will return kStatus_ValueAlreadySet and there will be no need
// to send a state change notification. If we receive
// kStatus_Success, it is the first time set or a change and state
// change notification needs to be sent.
lStatus = mNetworkModel.SetEthernetEUI48(lEthernetEUI48);
nlEXPECT_SUCCESS(lStatus, done);
lStatus = lStateChangeNotification.Init(lEthernetEUI48);
nlREQUIRE_SUCCESS(lStatus, done);
OnStateDidChange(lStateChangeNotification);
done:
return;
}
/**
* @brief
* Ethernet network interface default router IP address changed
* client unsolicited notification handler.
*
* This handles an asynchronous, unsolicited client notification for
* the Ethernet network interface default router IP address changed
* notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
*
*/
void
NetworkControllerBasis :: IPDefaultRouterAddressNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const RegularExpression::Matches &aMatches)
{
Common::IPAddress lDefaultRouterIPAddress;
StateChange::NetworkIPDefaultRouterAddressNotification lStateChangeNotification;
Status lStatus;
(void)aSize;
nlREQUIRE(aMatches.size() == Command::Network::IPDefaultRouterAddressResponse::kExpectedMatches, done);
// Match 2/2: IP Address
lStatus = Parse(aBuffer + aMatches.at(1).rm_so,
Common::Utilities::Distance(aMatches.at(1)),
lDefaultRouterIPAddress);
nlREQUIRE_SUCCESS(lStatus, done);
// If the IP address is unchanged, SetDefaultRouterAddress
// will return kStatus_ValueAlreadySet and there will be no need
// to send a state change notification. If we receive
// kStatus_Success, it is the first time set or a change and state
// change notification needs to be sent.
lStatus = mNetworkModel.SetDefaultRouterAddress(lDefaultRouterIPAddress);
nlEXPECT_SUCCESS(lStatus, done);
lStatus = lStateChangeNotification.Init(lDefaultRouterIPAddress);
nlREQUIRE_SUCCESS(lStatus, done);
OnStateDidChange(lStateChangeNotification);
done:
return;
}
/**
* @brief
* Ethernet network interface host IP address changed client
* unsolicited notification handler.
*
* This handles an asynchronous, unsolicited client notification for
* the Ethernet network interface host IP address changed
* notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
*
*/
void
NetworkControllerBasis :: IPHostAddressNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const RegularExpression::Matches &aMatches)
{
Common::IPAddress lHostIPAddress;
StateChange::NetworkIPHostAddressNotification lStateChangeNotification;
Status lStatus;
(void)aSize;
nlREQUIRE(aMatches.size() == Command::Network::IPHostAddressResponse::kExpectedMatches, done);
// Match 2/2: IP Address
lStatus = Parse(aBuffer + aMatches.at(1).rm_so,
Common::Utilities::Distance(aMatches.at(1)),
lHostIPAddress);
nlREQUIRE_SUCCESS(lStatus, done);
// If the IP address is unchanged, SetHostAddress
// will return kStatus_ValueAlreadySet and there will be no need
// to send a state change notification. If we receive
// kStatus_Success, it is the first time set or a change and state
// change notification needs to be sent.
lStatus = mNetworkModel.SetHostAddress(lHostIPAddress);
nlEXPECT_SUCCESS(lStatus, done);
lStatus = lStateChangeNotification.Init(lHostIPAddress);
nlREQUIRE_SUCCESS(lStatus, done);
OnStateDidChange(lStateChangeNotification);
done:
return;
}
/**
* @brief
* Ethernet network interface IP netmask changed client
* unsolicited notification handler.
*
* This handles an asynchronous, unsolicited client notification for
* the Ethernet network interface IP netmask changed
* notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
*
*/
void
NetworkControllerBasis :: IPNetmaskNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const RegularExpression::Matches &aMatches)
{
Common::IPAddress lIPNetmask;
StateChange::NetworkIPNetmaskNotification lStateChangeNotification;
Status lStatus;
(void)aSize;
nlREQUIRE(aMatches.size() == Command::Network::IPNetmaskResponse::kExpectedMatches, done);
// Match 2/2: IP Address
lStatus = Parse(aBuffer + aMatches.at(1).rm_so,
Common::Utilities::Distance(aMatches.at(1)),
lIPNetmask);
nlREQUIRE_SUCCESS(lStatus, done);
// If the IP address is unchanged, SetNetmask
// will return kStatus_ValueAlreadySet and there will be no need
// to send a state change notification. If we receive
// kStatus_Success, it is the first time set or a change and state
// change notification needs to be sent.
lStatus = mNetworkModel.SetNetmask(lIPNetmask);
nlEXPECT_SUCCESS(lStatus, done);
lStatus = lStateChangeNotification.Init(lIPNetmask);
nlREQUIRE_SUCCESS(lStatus, done);
OnStateDidChange(lStateChangeNotification);
done:
return;
}
/**
* @brief
* Ethernet network interface Control4 SDDP enabled changed client
* unsolicited notification handler.
*
* This handles an asynchronous, unsolicited client notification for
* the Ethernet network interface Control4 SDDP enabled changed
* notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
*
*/
void
NetworkControllerBasis :: SDDPEnabledNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const Common::RegularExpression::Matches &aMatches)
{
NetworkModel::EnabledType lEnabled;
StateChange::NetworkSDDPEnabledNotification lStateChangeNotification;
Status lStatus;
(void)aSize;
nlREQUIRE(aMatches.size() == Command::Network::SDDPEnabledResponse::kExpectedMatches, done);
// Match 2/2: Enabled
lStatus = Utilities::Parse(aBuffer + aMatches.at(1).rm_so,
Common::Utilities::Distance(aMatches.at(1)),
lEnabled);
nlREQUIRE_SUCCESS(lStatus, done);
// If the Control4 SDDP enabled state is unchanged, SetSDDPEnabled
// will return kStatus_ValueAlreadySet and there will be no need
// to send a state change notification. If we receive
// kStatus_Success, it is the first time set or a change and state
// change notification needs to be sent.
lStatus = mNetworkModel.SetSDDPEnabled(lEnabled);
nlEXPECT_SUCCESS(lStatus, done);
lStatus = lStateChangeNotification.Init(lEnabled);
nlREQUIRE_SUCCESS(lStatus, done);
OnStateDidChange(lStateChangeNotification);
done:
return;
}
// MARK: Unsolicited Notification Handler Trampolines
/**
* @brief
* Ethernet network interface DHCPv4 enabled state changed client
* unsolicited notification handler trampoline.
*
* This invokes the handler for an unsolicited, asynchronous client
* notification for the Ethernet network interface DHCPv4 enabled
* state changed notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the
* notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the
* notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: DHCPv4EnabledNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const Common::RegularExpression::Matches &aMatches, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->DHCPv4EnabledNotificationReceivedHandler(aBuffer, aSize, aMatches);
}
}
/**
* @brief
* Ethernet network interface EUI-48 address changed client
* unsolicited notification handler trampoline.
*
* This invokes the handler for an unsolicited, asynchronous client
* notification for the Ethernet network interface EUI-48 address
* changed notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the
* notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the
* notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: EthernetEUI48NotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const Common::RegularExpression::Matches &aMatches, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->EthernetEUI48NotificationReceivedHandler(aBuffer, aSize, aMatches);
}
}
/**
* @brief
* Ethernet network interface default router IP address changed
* client unsolicited notification handler trampoline.
*
* This invokes the handler for an unsolicited, asynchronous client
* notification for the Ethernet network interface default router IP
* address changed notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the
* notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the
* notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: IPDefaultRouterAddressNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const RegularExpression::Matches &aMatches, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->IPDefaultRouterAddressNotificationReceivedHandler(aBuffer, aSize, aMatches);
}
}
/**
* @brief
* Ethernet network interface host IP address changed client
* unsolicited notification handler trampoline.
*
* This invokes the handler for an unsolicited, asynchronous client
* notification for the Ethernet network interface host IP address
* changed notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the
* notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the
* notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: IPHostAddressNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const RegularExpression::Matches &aMatches, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->IPHostAddressNotificationReceivedHandler(aBuffer, aSize, aMatches);
}
}
/**
* @brief
* Ethernet network interface IP netmask changed client unsolicited
* notification handler trampoline.
*
* This invokes the handler for an unsolicited, asynchronous client
* notification for the Ethernet network interface IP netmask changed
* notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the
* notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the
* notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: IPNetmaskNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const RegularExpression::Matches &aMatches, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->IPNetmaskNotificationReceivedHandler(aBuffer, aSize, aMatches);
}
}
/**
* @brief
* Ethernet network interface Control4 SDDP enabled state changed
* client unsolicited notification handler trampoline.
*
* This invokes the handler for an unsolicited, asynchronous client
* notification for the Ethernet network interface Control4 SDDP
* enabled state changed notification.
*
* @param[in] aBuffer An immutable pointer to the start of the
* buffer extent containing the
* notification.
* @param[in] aSize An immutable reference to the size of the
* buffer extent containing the
* notification.
* @param[in] aMatches An immutable reference to the regular
* expression substring matches associated
* with the client command response that
* triggered this handler.
* @param[in,out] aContext A pointer to the controller class
* instance that registered this
* trampoline to call back into from
* the trampoline.
*
*/
void
NetworkControllerBasis :: SDDPEnabledNotificationReceivedHandler(const uint8_t *aBuffer, const size_t &aSize, const Common::RegularExpression::Matches &aMatches, void *aContext)
{
NetworkControllerBasis *lController = static_cast<NetworkControllerBasis *>(aContext);
if (lController != nullptr)
{
lController->SDDPEnabledNotificationReceivedHandler(aBuffer, aSize, aMatches);
}
}
}; // namespace Client
}; // namespace HLX
| 36.113616 | 180 | 0.639625 | [
"object",
"model"
] |
cde0fe0946c79a3d054169061978cb2b7a234be2 | 15,199 | cpp | C++ | MUSEN/Modules/Simulator/GPUSimulator.cpp | msolids/musen | 67d9a70d03d771ccda649c21b78d165684e31171 | [
"BSD-3-Clause"
] | 19 | 2020-09-28T07:22:50.000Z | 2022-03-07T09:52:20.000Z | MUSEN/Modules/Simulator/GPUSimulator.cpp | msolids/musen | 67d9a70d03d771ccda649c21b78d165684e31171 | [
"BSD-3-Clause"
] | 5 | 2020-12-26T18:18:27.000Z | 2022-02-23T22:56:43.000Z | MUSEN/Modules/Simulator/GPUSimulator.cpp | msolids/musen | 67d9a70d03d771ccda649c21b78d165684e31171 | [
"BSD-3-Clause"
] | 11 | 2020-11-02T11:32:03.000Z | 2022-01-27T08:22:04.000Z | /* Copyright (c) 2013-2020, MUSEN Development Team. All rights reserved.
This file is part of MUSEN framework http://msolids.net/musen.
See LICENSE file for license and warranty information. */
#include "GPUSimulator.h"
CGPUSimulator::CGPUSimulator()
{
Construct();
}
CGPUSimulator::CGPUSimulator(const CBaseSimulator& _other) :
CBaseSimulator{ _other }
{
Construct();
}
CGPUSimulator::~CGPUSimulator()
{
if (m_pInteractProps)
CUDA_FREE_D(m_pInteractProps);
CUDA_FREE_D(m_pDispatchedResults_d);
CUDA_FREE_H(m_pDispatchedResults_h);
}
void CGPUSimulator::Construct()
{
CGPU::SetExternalAccel(m_externalAcceleration);
m_gpu.SetAnisotropyFlag(m_considerAnisotropy);
m_gpu.SetPBC(m_scene.m_PBC);
CUDA_MALLOC_D(&m_pDispatchedResults_d, sizeof(SDispatchedResults));
CUDA_MALLOC_H(&m_pDispatchedResults_h, sizeof(SDispatchedResults));
}
void CGPUSimulator::SetExternalAccel(const CVector3& _accel)
{
CBaseSimulator::SetExternalAccel(_accel);
CGPU::SetExternalAccel(m_externalAcceleration);
}
void CGPUSimulator::Initialize()
{
CBaseSimulator::Initialize();
CGPU::SetSimulationDomain(m_pSystemStructure->GetSimulationDomain());
// get flag of anisotropy
CGPU::SetAnisotropyFlag(m_considerAnisotropy);
// Initialize scene, PBC, models on GPU
m_sceneGPU.InitializeScene(m_scene, m_pSystemStructure);
// store particle coordinates
m_sceneGPU.CUDASaveVerletCoords();
m_gpu.SetPBC(m_scene.m_PBC);
CUDAInitializeWalls();
m_gpu.InitializeCollisions();
CUDAInitializeMaterials();
}
void CGPUSimulator::InitializeModelParameters()
{
CBaseSimulator::InitializeModelParameters();
for (auto& model : m_models)
model->InitializeGPU(m_cudaDefines);
}
void CGPUSimulator::UpdateCollisionsStep(double _dTimeStep)
{
// clear all forces and moment on GPU
m_sceneGPU.ClearAllForcesAndMoments();
// if there is no contact model, then there is no necessity to calculate contacts
if (m_pPPModel || m_pPWModel)
{
UpdateVerletLists(_dTimeStep); // between PP and PW
CUDAUpdateActiveCollisions();
}
}
void CGPUSimulator::CalculateForcesStep(double _dTimeStep)
{
if (m_pPPModel) CalculateForcesPP(_dTimeStep);
if (m_pPWModel) CalculateForcesPW(_dTimeStep);
if (m_pSBModel) CalculateForcesSB(_dTimeStep);
if (m_pLBModel) CalculateForcesLB(_dTimeStep);
if (m_pEFModel) CalculateForcesEF(_dTimeStep);
cudaStreamQuery(0);
}
void CGPUSimulator::CalculateForcesPP(double _dTimeStep)
{
if (!m_gpu.m_CollisionsPP.collisions.nElements) return;
m_pPPModel->CalculatePPForceGPU(m_currentTime, _dTimeStep, m_pInteractProps, m_sceneGPU.GetPointerToParticles(), m_gpu.m_CollisionsPP.collisions);
}
void CGPUSimulator::CalculateForcesPW(double _dTimeStep)
{
if (!m_gpu.m_CollisionsPW.collisions.nElements) return;
m_pPWModel->CalculatePWForceGPU(m_currentTime, _dTimeStep, m_pInteractProps,
m_sceneGPU.GetPointerToParticles(), m_sceneGPU.GetPointerToWalls(), m_gpu.m_CollisionsPW.collisions);
m_gpu.GatherForcesFromPWCollisions(m_sceneGPU.GetPointerToParticles(), m_sceneGPU.GetPointerToWalls());
}
void CGPUSimulator::CalculateForcesSB(double _dTimeStep)
{
if (m_scene.GetBondsNumber() == 0) return;
m_pSBModel->CalculateSBForceGPU(m_currentTime, _dTimeStep, m_sceneGPU.GetPointerToParticles(), m_sceneGPU.GetPointerToSolidBonds());
}
void CGPUSimulator::CalculateForcesEF(double _dTimeStep)
{
m_pEFModel->CalculateEFForceGPU(m_currentTime, _dTimeStep, m_sceneGPU.GetPointerToParticles());
}
void CGPUSimulator::MoveParticles(bool _bPredictionStep)
{
if (!m_externalAcceleration.IsZero())
m_gpu.ApplyExternalAcceleration(m_sceneGPU.GetPointerToParticles());
if (!_bPredictionStep)
{
if (m_variableTimeStep)
m_currSimulationStep = m_gpu.CalculateNewTimeStep(m_currSimulationStep, m_initSimulationStep, m_partMoveLimit, m_timeStepFactor, m_sceneGPU.GetPointerToParticles());
m_gpu.MoveParticles(m_currSimulationStep, m_initSimulationStep, m_sceneGPU.GetPointerToParticles(), m_variableTimeStep);
}
else
m_gpu.MoveParticlesPrediction(m_currSimulationStep / 2., m_sceneGPU.GetPointerToParticles());
MoveParticlesOverPBC(); // move virtual particles and check boundaries
}
void CGPUSimulator::MoveWalls(double _dTimeStep)
{
m_wallsVelocityChanged = false;
// analysis of transition to new interval
for (unsigned iGeom = 0; iGeom < m_pSystemStructure->GeometriesNumber(); ++iGeom)
{
CRealGeometry* pGeom = m_pSystemStructure->Geometry(iGeom);
if (pGeom->Planes().empty()) continue;
if ((pGeom->Motion()->MotionType() == CGeometryMotion::EMotionType::FORCE_DEPENDENT) ||
(pGeom->Motion()->MotionType() == CGeometryMotion::EMotionType::CONSTANT_FORCE)) // force
{
const CVector3 vTotalForce = m_gpu.CalculateTotalForceOnWall(iGeom, m_sceneGPU.GetPointerToWalls());
pGeom->UpdateMotionInfo(vTotalForce.z);
}
else
pGeom->UpdateMotionInfo(m_currentTime); // time
CVector3 vVel = pGeom->GetCurrentVelocity();
CVector3 vRotVel = pGeom->GetCurrentRotVelocity();
CVector3 vRotCenter = pGeom->GetCurrentRotCenter();
if (m_currentTime == 0 || vVel != pGeom->GetCurrentVelocity() || vRotVel != pGeom->GetCurrentRotVelocity() || vRotCenter != pGeom->GetCurrentRotCenter())
m_wallsVelocityChanged = true;
if ( !pGeom->FreeMotion().IsZero() )
m_wallsVelocityChanged = true;
if (vRotVel.IsZero() && pGeom->FreeMotion().IsZero() && vVel.IsZero()) continue;
CMatrix3 RotMatrix;
if (!vRotVel.IsZero())
RotMatrix = CQuaternion(vRotVel*_dTimeStep).ToRotmat();
m_gpu.MoveWalls(_dTimeStep, iGeom, vVel, vRotVel, vRotCenter, RotMatrix, pGeom->FreeMotion(),
pGeom->Motion()->MotionType() == CGeometryMotion::EMotionType::FORCE_DEPENDENT, pGeom->RotateAroundCenter(), pGeom->Mass(), m_sceneGPU.GetPointerToWalls(), m_externalAcceleration);
}
}
size_t CGPUSimulator::GenerateNewObjects()
{
// TODO: find why contacts are not being detected. Check generation of agglomerates.
//if (!m_generationManager->IsNeedToBeGenerated(m_currentTime)) return; // no need to generate new objects
//// get actual data from device
//m_sceneGPU.CUDAParticlesGPU2CPU(&m_scene);
//m_sceneGPU.CUDABondsGPU2CPU(&m_scene);
//m_sceneGPU.CUDAWallsGPU2CPU(&m_scene);
//
//const size_t newObjects = CBaseSimulator::GenerateNewObjects();
//if (newObjects) // new objects have been generated
//{
// // update data on device
// m_sceneGPU.CUDAParticlesCPU2GPU(&m_scene);
// m_sceneGPU.CUDABondsCPU2GPU(&m_scene);
// CUDAInitializeMaterials();
//}
return 0;
}
void CGPUSimulator::UpdatePBC()
{
m_scene.m_PBC.UpdatePBC(m_currentTime);
if (!m_scene.m_PBC.vVel.IsZero()) // if velocity is not zero
{
InitializeModelParameters(); // set new PBC to all models
m_gpu.SetPBC(m_scene.m_PBC); // set new PBC to GPU scene
}
}
void CGPUSimulator::PrepareAdditionalSavingData()
{
SParticleStruct& particles = m_scene.GetRefToParticles();
SSolidBondStruct& bonds = m_scene.GetRefToSolidBonds();
static SGPUCollisions PPCollisions(SBasicGPUStruct::EMemType::HOST), PWCollisions(SBasicGPUStruct::EMemType::HOST);
m_gpu.CopyCollisionsGPU2CPU(PPCollisions, PWCollisions);
// reset previously calculated stresses
for (auto& data : m_additionalSavingData)
data.stressTensor.Init(0);
// save stresses caused by solid bonds
for (size_t i = 0; i < bonds.Size(); ++i)
{
if (!bonds.Active(i) && !m_pSystemStructure->GetObjectByIndex(bonds.InitIndex(i))->IsActive(m_currentTime)) continue;
const size_t leftID = bonds.LeftID(i);
const size_t rightID = bonds.RightID(i);
CVector3 connVec = (particles.Coord(leftID) - particles.Coord(rightID)).Normalized();
m_additionalSavingData[bonds.LeftID(i) ].AddStress(-1 * connVec * particles.Radius(leftID ), bonds.TotalForce(i), PI * pow(2 * particles.Radius(leftID ), 3) / 6);
m_additionalSavingData[bonds.RightID(i)].AddStress( connVec * particles.Radius(rightID), -1 * bonds.TotalForce(i), PI * pow(2 * particles.Radius(rightID), 3) / 6);
}
// save stresses caused by particle-particle contact
for (size_t i = 0; i < PPCollisions.nElements; ++i)
{
if (!PPCollisions.ActivityFlags[i]) continue;
const size_t srcID = PPCollisions.SrcIDs[i];
const size_t dstID = PPCollisions.DstIDs[i];
CVector3 connVec = (particles.Coord(srcID) - particles.Coord(dstID)).Normalized();
m_additionalSavingData[PPCollisions.SrcIDs[i]].AddStress(-1 * connVec * particles.Radius(srcID), PPCollisions.TotalForces[i], PI * pow(2 * particles.Radius(srcID), 3) / 6);
m_additionalSavingData[PPCollisions.DstIDs[i]].AddStress( connVec * particles.Radius(dstID), -1 * PPCollisions.TotalForces[i], PI * pow(2 * particles.Radius(dstID), 3) / 6);
}
// save stresses caused by particle-wall contacts
for (size_t i = 0; i < PWCollisions.nElements; ++i)
{
if (!PWCollisions.ActivityFlags[i]) continue;
CVector3 connVec = (PWCollisions.ContactVectors[i] - particles.Coord(PWCollisions.DstIDs[i])).Normalized();
m_additionalSavingData[PWCollisions.DstIDs[i]].AddStress(connVec * particles.Radius(PWCollisions.DstIDs[i]), PWCollisions.TotalForces[i], PI * pow(2 * particles.Radius(PWCollisions.DstIDs[i]), 3) / 6);
}
}
void CGPUSimulator::SaveData()
{
clock_t t = clock();
cudaDeviceSynchronize();
m_sceneGPU.CUDABondsGPU2CPU( m_scene );
m_sceneGPU.CUDAParticlesGPU2CPUAllData(m_scene);
m_sceneGPU.CUDAWallsGPU2CPUAllData(m_scene);
m_nBrockenBonds = m_sceneGPU.GetBrokenBondsNumber();
m_maxParticleVelocity = m_sceneGPU.GetMaxPartVelocity();
p_SaveData();
m_verletList.AddDisregardingTimeInterval(clock() - t);
}
void CGPUSimulator::UpdateVerletLists(double _dTimeStep)
{
CUDAUpdateGlobalCPUData();
if (m_verletList.IsNeedToBeUpdated(_dTimeStep, sqrt(m_pDispatchedResults_h->dMaxSquaredPartDist) , m_maxWallVelocity))
{
m_sceneGPU.CUDAParticlesGPU2CPUVerletData(m_scene);
m_sceneGPU.CUDAWallsGPU2CPUVerletData(m_scene);
m_verletList.UpdateList(m_currentTime);
static STempStorage storePP, storePW; // to reuse memory
CUDAUpdateVerletLists(m_verletList.m_PPList, m_verletList.m_PPVirtShift, m_gpu.m_CollisionsPP, storePP, true);
CUDAUpdateVerletLists(m_verletList.m_PWList, m_verletList.m_PWVirtShift, m_gpu.m_CollisionsPW, storePW, false);
m_sceneGPU.CUDASaveVerletCoords();
}
}
void CGPUSimulator::CUDAUpdateGlobalCPUData()
{
// check that all particles are remains in simulation domain
m_gpu.CheckParticlesInDomain(m_currentTime, m_sceneGPU.GetPointerToParticles(), &m_pDispatchedResults_d->nActivePartNum);
// update max velocities
m_sceneGPU.GetMaxSquaredPartDist(&m_pDispatchedResults_d->dMaxSquaredPartDist);
if (m_wallsVelocityChanged)
m_sceneGPU.GetMaxWallVelocity(&m_pDispatchedResults_d->dMaxWallVel);
CUDA_MEMCPY_D2H(m_pDispatchedResults_h, m_pDispatchedResults_d, sizeof(SDispatchedResults));
const bool bNewInactiveParticles = (m_nInactiveParticles != m_sceneGPU.GetParticlesNumber() - m_pDispatchedResults_h->nActivePartNum);
if (bNewInactiveParticles && m_sceneGPU.GetBondsNumber())
{
m_gpu.CheckBondsActivity(m_currentTime, m_sceneGPU.GetPointerToParticles(), m_sceneGPU.GetPointerToSolidBonds());
m_sceneGPU.CUDABondsActivityGPU2CPU(m_scene);
m_scene.UpdateParticlesToBonds();
}
m_nInactiveParticles = m_sceneGPU.GetParticlesNumber() - m_pDispatchedResults_h->nActivePartNum;
if (m_wallsVelocityChanged)
m_maxWallVelocity = m_pDispatchedResults_h->dMaxWallVel;
}
void CGPUSimulator::CUDAUpdateActiveCollisions()
{
m_gpu.UpdateActiveCollisionsPP(m_sceneGPU.GetPointerToParticles());
m_gpu.UpdateActiveCollisionsPW(m_sceneGPU.GetPointerToParticles(), m_sceneGPU.GetPointerToWalls());
}
void CGPUSimulator::CUDAUpdateVerletLists(const std_matr_u& _verletListCPU, const std_matr_u8& _verletListShiftsCPU,
CGPU::SCollisionsHolder& _collisions, STempStorage& _store, bool _bPPVerlet)
{
const size_t nParticles = m_scene.GetTotalParticlesNumber();
// calculate total number of possible contacts
size_t nCollsions = 0;
for (const auto& colls : _verletListCPU)
nCollsions += colls.size();
// create verlet lists for GPU
_store.hvVerletPartInd.resize(nParticles + 1);
_store.hvVerletDst.resize(nCollsions);
_store.hvVerletSrc.resize(nCollsions);
_store.hvVirtShifts.resize(nCollsions);
if (!_store.hvVerletPartInd.empty()) _store.hvVerletPartInd.front() = 0; // for easier access
for (size_t i = 1; i < nParticles; ++i)
_store.hvVerletPartInd[i] = _store.hvVerletPartInd[i - 1] + _verletListCPU[i-1].size();
if (!_store.hvVerletPartInd.empty()) _store.hvVerletPartInd.back() = nCollsions; // for easier access
ParallelFor(nParticles, [&](size_t i)
{
std::copy(_verletListCPU[i].begin(), _verletListCPU[i].end(), _store.hvVerletDst.begin() + _store.hvVerletPartInd[i]);
std::fill(_store.hvVerletSrc.begin() + _store.hvVerletPartInd[i], _store.hvVerletSrc.begin() + _store.hvVerletPartInd[i] + _verletListCPU[i].size(), static_cast<unsigned>(i));
if (m_scene.m_PBC.bEnabled)
std::copy(_verletListShiftsCPU[i].begin(), _verletListShiftsCPU[i].end(), _store.hvVirtShifts.begin() + _store.hvVerletPartInd[i]);
});
// update verlet lists on device
m_gpu.UpdateVerletLists(_bPPVerlet, m_sceneGPU.GetPointerToParticles(), m_sceneGPU.GetPointerToWalls(), _store.hvVerletSrc, _store.hvVerletDst, _store.hvVerletPartInd,
_store.hvVirtShifts, _collisions.vVerletSrc, _collisions.vVerletDst, _collisions.vVerletPartInd, _collisions.collisions);
m_gpu.SortByDst(_bPPVerlet ? m_scene.GetTotalParticlesNumber() : m_scene.GetWallsNumber(),
_collisions.vVerletSrc, _collisions.vVerletDst, _collisions.vVerletCollInd_DstSorted, _collisions.vVerletPartInd_DstSorted);
}
void CGPUSimulator::CUDAInitializeMaterials()
{
if (m_pInteractProps)
{
CUDA_FREE_D(m_pInteractProps);
m_pInteractProps = NULL;
}
size_t nCompounds = m_scene.GetCompoundsNumber();
m_gpu.SetCompoundsNumber( nCompounds );
if (!nCompounds) return;
SInteractProps* pInteractPropsHost;
CUDA_MALLOC_H(&pInteractPropsHost, sizeof(SInteractProps)*nCompounds*nCompounds);
CUDA_MALLOC_D(&m_pInteractProps, sizeof(SInteractProps)*nCompounds*nCompounds);
for (unsigned i = 0; i < nCompounds; ++i)
for (unsigned j = 0; j < nCompounds; ++j)
pInteractPropsHost[i*nCompounds + j] = m_scene.GetInteractProp(i*nCompounds + j);
CUDA_MEMCPY_H2D(m_pInteractProps, pInteractPropsHost, sizeof(SInteractProps)*nCompounds*nCompounds);
CUDA_FREE_H(pInteractPropsHost);
}
void CGPUSimulator::CUDAInitializeWalls()
{
std::vector<std::vector<unsigned>> vvWallsInGeom(m_pSystemStructure->GeometriesNumber());
for (size_t i = 0; i < m_pSystemStructure->GeometriesNumber(); ++i)
{
const CRealGeometry* pGeom = m_pSystemStructure->Geometry(i);
const auto& planes = pGeom->Planes();
vvWallsInGeom[i].resize(planes.size());
for (size_t j = 0; j < planes.size(); ++j)
vvWallsInGeom[i][j] = static_cast<unsigned>(m_scene.m_vNewIndexes[planes[j]]);
}
m_gpu.InitializeWalls(vvWallsInGeom, m_scene.m_adjacentWalls);
}
void CGPUSimulator::MoveParticlesOverPBC()
{
if (!m_scene.m_PBC.bEnabled) return;
m_gpu.MoveParticlesOverPBC(m_sceneGPU.GetPointerToParticles());
}
void CGPUSimulator::GetOverlapsInfo(double& _dMaxOverlap, double& _dAverageOverlap, size_t _nMaxParticleID)
{
m_gpu.GetOverlapsInfo(m_sceneGPU.GetPointerToParticles(), _nMaxParticleID, _dMaxOverlap, _dAverageOverlap);
}
| 38.772959 | 203 | 0.780117 | [
"geometry",
"vector",
"model",
"solid"
] |
cde2a6f1b4c142dcf71cfe6840190329e27b428e | 203 | cpp | C++ | cmake/external/eigen/doc/snippets/Tutorial_std_sort.cpp | fushwLZU/onnxruntime_test | 7ee82dde9150dc0d3014c06a82eabdecb989f2f3 | [
"MIT"
] | 310 | 2020-04-06T17:01:21.000Z | 2022-03-27T17:52:35.000Z | cmake/external/eigen/doc/snippets/Tutorial_std_sort.cpp | fushwLZU/onnxruntime_test | 7ee82dde9150dc0d3014c06a82eabdecb989f2f3 | [
"MIT"
] | 74 | 2020-03-30T08:02:35.000Z | 2021-01-07T18:00:49.000Z | external/eigen/doc/snippets/Tutorial_std_sort.cpp | lucaparisi91/qmc3 | f76178896ecf7b79af863f8d4fc3653326bea5c3 | [
"MIT"
] | 29 | 2020-04-10T07:16:23.000Z | 2022-01-31T20:54:30.000Z | Array4i v = Array4i::Random().abs();
cout << "Here is the initial vector v:\n" << v.transpose() << "\n";
std::sort(v.begin(), v.end());
cout << "Here is the sorted vector v:\n" << v.transpose() << "\n";
| 40.6 | 67 | 0.581281 | [
"vector"
] |
cde53f504c6a2542cf3289b1efdbf5c241a76e69 | 16,775 | cpp | C++ | admin/wmi/wbem/winmgmt/adap/adapthrd.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/wmi/wbem/winmgmt/adap/adapthrd.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/wmi/wbem/winmgmt/adap/adapthrd.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (C) 1999-2001 Microsoft Corporation
Module Name:
ADAPTHRD.CPP
Abstract:
History:
--*/
#include "precomp.h"
#include <stdio.h>
#include <process.h>
#include <wbemcli.h>
#include <cominit.h>
#include "ntreg.h"
#include "adapthrd.h"
// IMPORTANT!!!!
// This code MUST be revisited to do the following:
// A>>>>> Exception Handling around the outside calls
// B>>>>> Use a named mutex around the calls
// C>>>>> Make the calls on another thread
// D>>>>> Place and handle registry entries that indicate a bad DLL!
////////////////////////////////////////////////////////////////////////////////////////////
//
// CAdapThreadRequest
//
////////////////////////////////////////////////////////////////////////////////////////////
CAdapThreadRequest::CAdapThreadRequest( void )
: m_hWhenDone( NULL ),
m_hrReturn( WBEM_S_NO_ERROR )
////////////////////////////////////////////////////////////////////////////////////////////
//
// Constructor
//
////////////////////////////////////////////////////////////////////////////////////////////
{
}
CAdapThreadRequest::~CAdapThreadRequest( void )
////////////////////////////////////////////////////////////////////////////////////////////
//
// Destructor
//
////////////////////////////////////////////////////////////////////////////////////////////
{
if (m_hWhenDone ) CloseHandle( m_hWhenDone );
}
HRESULT CAdapThreadRequest::EventLogError( void )
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////
//
// CAdapThread
//
////////////////////////////////////////////////////////////////////////////////////////////
CAdapThread::CAdapThread( CAdapPerfLib* pPerfLib )
: m_pPerfLib( pPerfLib ),
m_hEventQuit( NULL ),
m_hSemReqPending( NULL ),
m_hThread( NULL ),
m_fOk( FALSE )
////////////////////////////////////////////////////////////////////////////////////////////
//
// Constructor
//
////////////////////////////////////////////////////////////////////////////////////////////
{
// Initialize the control members
// ==============================
Init();
}
CAdapThread::~CAdapThread()
////////////////////////////////////////////////////////////////////////////////////////////
//
// Destructor
//
////////////////////////////////////////////////////////////////////////////////////////////
{
if ( NULL != m_hThread )
{
Shutdown();
}
Clear();
// Clean up the queue
// ==================
while ( m_RequestQueue.Size() > 0 )
{
CAdapThreadRequest* pRequest = (CAdapThreadRequest*) m_RequestQueue.GetAt( 0 );
if ( NULL != pRequest )
{
pRequest->Release();
}
m_RequestQueue.RemoveAt( 0 );
}
}
BOOL CAdapThread::Init( void )
////////////////////////////////////////////////////////////////////////////////////////////
//
// Initializes the control variables
//
////////////////////////////////////////////////////////////////////////////////////////////
{
if ( !m_fOk )
{
if ( ( m_hEventQuit = CreateEvent( NULL, TRUE, FALSE, NULL ) ) != NULL )
{
if ( ( m_hSemReqPending = CreateSemaphore( NULL, 0, 0x7FFFFFFF, NULL ) ) != NULL )
{
if ( ( m_hThreadReady = CreateEvent( NULL, TRUE, FALSE, NULL ) ) != NULL )
{
m_fOk = TRUE;
}
}
}
}
if ( !m_fOk )
{
ERRORTRACE( ( LOG_WMIADAP, "CAdapThread::Init() failed.\n" ) );
}
return m_fOk;
}
BOOL CAdapThread::Clear( BOOL fClose )
////////////////////////////////////////////////////////////////////////////////////////////
//
// Clears the control variables and thread variables
//
////////////////////////////////////////////////////////////////////////////////////////////
{
CInCritSec ics(&m_cs);
// Don't close the handles unless we've been told to.
m_fOk = FALSE;
if ( NULL != m_hEventQuit )
{
if ( fClose )
{
CloseHandle( m_hEventQuit );
}
m_hEventQuit = NULL;
}
if ( NULL != m_hSemReqPending )
{
if ( fClose )
{
CloseHandle( m_hSemReqPending );
}
m_hSemReqPending = NULL;
}
if ( NULL != m_hThread )
{
if ( fClose )
{
CloseHandle( m_hThread );
}
m_hThread = NULL;
}
m_dwThreadId = 0;
return TRUE;
}
HRESULT CAdapThread::Enqueue( CAdapThreadRequest* pRequest )
////////////////////////////////////////////////////////////////////////////////////////////
//
// Add a request to the request queue
//
////////////////////////////////////////////////////////////////////////////////////////////
{
HRESULT hr = WBEM_NO_ERROR;
// Ensure that the thread has started
// ==================================
hr = Begin();
if ( SUCCEEDED( hr ) )
{
// We will use a new one for EVERY operation
HANDLE hEventDone = CreateEvent( NULL, TRUE, FALSE, NULL );
if ( NULL != hEventDone )
{
// Let the request know about the new event handle
// ===========================================
pRequest->SetWhenDoneHandle( hEventDone );
// Auto-lock the queue
// ===================
CInCritSec ics( &m_cs );
try
{
// Add the request to the queue
// ============================
if (CFlexArray::no_error == m_RequestQueue.Add( (void*) pRequest ))
pRequest->AddRef();
else
hr = WBEM_E_OUT_OF_MEMORY;
ReleaseSemaphore( m_hSemReqPending, 1, NULL );
}
catch(...)
{
hr = WBEM_E_OUT_OF_MEMORY;
}
}
else
{
hr = WBEM_E_OUT_OF_MEMORY;
}
}
return hr;
}
HRESULT CAdapThread::Begin( void )
////////////////////////////////////////////////////////////////////////////////////////////
//
// If the thread has not already started, then intializes the control variables, and starts
// the thread.
//
////////////////////////////////////////////////////////////////////////////////////////////
{
HRESULT hr = WBEM_S_NO_ERROR;
// Verify that the thread does not already exist
// =============================================
if ( NULL == m_hThread )
{
// Coping will enter and exit the critical section
CInCritSec ics( &m_cs );
// Double check the thread handle here in case somebody fixed us up while we were
// waiting on the critical section.
if ( NULL == m_hThread )
{
// Initialize the control variables
// ================================
if ( Init() )
{
// Makes sure the pending event semaphore is signalled once for each entry in the queue
// ====================================================================================
if ( m_RequestQueue.Size() > 0 )
{
ReleaseSemaphore( m_hSemReqPending, m_RequestQueue.Size(), NULL );
}
// Start the thread
// ================
m_hThread = (HANDLE) _beginthreadex( NULL, 0, CAdapThread::ThreadProc, (void*) this,
0, (unsigned int *) &m_dwThreadId );
if ( NULL == m_hThread )
{
hr = WBEM_E_FAILED;
}
else
{
if ( WAIT_OBJECT_0 != WaitForSingleObject( m_hThreadReady, 60000 ) )
{
hr = WBEM_E_FAILED;
ERRORTRACE( ( LOG_WMIADAP, "Worker thread for %S could not be verified.\n", (LPCWSTR)m_pPerfLib->GetServiceName() ) );
SetEvent( m_hEventQuit );
}
else
{
DEBUGTRACE( ( LOG_WMIADAP, "Worker thread for %S is 0x%x\n", (LPCWSTR)m_pPerfLib->GetServiceName(), m_dwThreadId ) );
}
}
}
else
{
hr = WBEM_E_FAILED;
}
} // IF NULL == m_hThread
}
if ( FAILED( hr ) )
{
ERRORTRACE( ( LOG_WMIADAP, "CAdapThread::Begin() failed: %X.\n", hr ) );
}
return hr;
}
unsigned CAdapThread::ThreadProc( void * pVoid )
////////////////////////////////////////////////////////////////////////////////////////////
//
// This is the static entry point fo the worker thread. It addref's the thread's perflib
// (see comment below) and then calls the objects processing method.
//
////////////////////////////////////////////////////////////////////////////////////////////
{
unsigned uRet;
try
{
// The calling object
// ==================
CAdapThread* pThis = (CAdapThread*) pVoid;
// The perflib to be processed
// ===========================
CAdapPerfLib* pPerfLib = pThis->m_pPerfLib;
// In an attempt to avoid circular references, we are addrefing the performance library wrapper
// instead of the thread object. The thread object will be destructed by the perflib wrapper
// only after the final reference is released. This thread is dependent on the perflib, but is
// by the thread wrapper. As a result, when the thread has completed processing, if we indicate
// that we are finished with the perflib by releasing the perflib wrapper, then the thread wrapper
// may destroyed at the same time. Note the use of auto-release.
if ( NULL != pPerfLib )
pPerfLib->AddRef();
CAdapReleaseMe arm( pPerfLib );
// Call the processing method
// ==========================
uRet = pThis->RealEntry();
}
catch(...)
{
// <Gasp> We have been betrayed... try to write something to the error log
// =======================================================================
CriticalFailADAPTrace( "An unhandled exception has been thrown in a worker thread." );
uRet = ERROR_OUTOFMEMORY;
}
return uRet;
}
unsigned CAdapThread::RealEntry( void )
////////////////////////////////////////////////////////////////////////////////////////////
//
// This is the method that contains the loop that processes the requests. While there
// are requests in the queue and the thread has not been instructed to terminate, then
// grab a request and execute it. When the request has completed, then signal the completion
// event to tell the originating thread that the request has been satisfied.
//
////////////////////////////////////////////////////////////////////////////////////////////
{
HANDLE ahEvents[2];
// Use local copies of these in case we have some timing issue in which we get destructed
// on another thread, but for some reason this guy keeps going.
HANDLE hPending = m_hSemReqPending,
hQuit = m_hEventQuit;
ahEvents[0] = hPending;
ahEvents[1] = hQuit;
DWORD dwWait = 0;
DWORD dwReturn = 0;
// Signal that everything is OK and we are ready to rock!
// ======================================================
if ( SetEvent( m_hThreadReady ) )
{
// If the m_hEventQuit event is signaled, or if it runs into a bizarre error,
// exit loop, otherwise continue as long as there is requests in the queue
// ==========================================================================
while ( ( dwWait = WaitForMultipleObjects( 2, ahEvents, FALSE, INFINITE ) ) == WAIT_OBJECT_0 )
{
// Check for the quit event, since if both events are signalled, we'll let this
// guy take precedence
if ( WaitForSingleObject( hQuit, 0 ) == WAIT_OBJECT_0 )
{
break;
}
// Get the next request from of the FIFO queue
// ===========================================
m_cs.Enter();
CAdapThreadRequest* pRequest = (CAdapThreadRequest*) m_RequestQueue.GetAt( 0 );
CAdapReleaseMe armRequest( pRequest );
m_RequestQueue.RemoveAt( 0 );
m_cs.Leave();
// Execute it
// ==========
dwReturn = pRequest->Execute( m_pPerfLib );
// Fire the completion event
// ==========================
if ( NULL != pRequest->GetWhenDoneHandle() )
{
SetEvent( pRequest->GetWhenDoneHandle() );
}
}
DEBUGTRACE( ( LOG_WMIADAP, "Thread 0x%x for %S is terminating\n", m_dwThreadId, (LPCWSTR)m_pPerfLib->GetServiceName() ) );
// If the exit condition is not due to a signaled m_hEventQuit, then evaluate error
// ================================================================================
if ( WAIT_FAILED == dwWait )
{
dwReturn = GetLastError();
}
}
if ( ERROR_SUCCESS != dwReturn )
{
ERRORTRACE( ( LOG_WMIADAP, "CAdapThread::RealEntry() for %S failed: %X.\n", (LPCWSTR)m_pPerfLib->GetServiceName(), dwReturn ) );
}
return dwReturn;
}
HRESULT CAdapThread::Shutdown( DWORD dwTimeout )
////////////////////////////////////////////////////////////////////////////////////////////
//
// Performs a gentle shutdown of the thread by signaling the exit event.
//
////////////////////////////////////////////////////////////////////////////////////////////
{
HRESULT hr = WBEM_NO_ERROR;
// Make sure that we are not killing ourself
// =========================================
if ( ( NULL != m_hThread ) && ( GetCurrentThreadId() != m_dwThreadId ) )
{
SetEvent( m_hEventQuit );
DWORD dwWait = WaitForSingleObject( m_hThread, dwTimeout );
switch ( dwWait )
{
case WAIT_OBJECT_0:
{
m_hThread = NULL;
hr = WBEM_S_NO_ERROR;
}break;
case WAIT_TIMEOUT:
{
hr = WBEM_E_FAILED;
}break;
default:
{
hr = WBEM_E_FAILED;
}
}
if ( FAILED( hr ) )
{
ERRORTRACE( ( LOG_WMIADAP, "CAdapThread::Shutdown() failed.\n" ) );
}
}
else
{
hr = WBEM_S_FALSE;
}
return hr;
}
HRESULT CAdapThread::Reset( void )
////////////////////////////////////////////////////////////////////////////////////////////
//
// This function will be called if a thread apparently got eaten, in which case, we're
// not sure if it will come back or not. So, we will clear our member data (not close anything)
// and kick off a new processing thread. Please note that this could leak handles, but then again,
// it looks like somebody ate a thread, so there are other potential problems afoot here.
//
////////////////////////////////////////////////////////////////////////////////////////////
{
HRESULT hr = WBEM_S_NO_ERROR;
// Signal the quit event so if the thread that is executing ever returns it will know to drop
// out. Clear can then rid us of the appropriate handles so we can start all over again.
SetEvent( m_hEventQuit );
// Scoping will enter and exit the critical section, so if anyone tries to enqueue any requests
// while we are executing, we don't step all over each other.
CInCritSec ics( &m_cs );
// Clear shouldn't close the handles
Clear( FALSE );
if ( Init() )
{
hr = Begin();
}
else
{
hr = WBEM_E_FAILED;
}
if ( FAILED( hr ) )
{
ERRORTRACE( ( LOG_WMIADAP, "CAdapThread::Reset() failed: %X.\n", hr ) );
}
return hr;
}
| 30.225225 | 153 | 0.415201 | [
"object"
] |
cde74090e2bcb92f9354f359401b46e394956619 | 14,680 | cpp | C++ | dev/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetUtils.cpp | pawandayma/lumberyard | e178f173f9c21369efd8c60adda3914e502f006a | [
"AML"
] | 6 | 2018-01-21T14:07:01.000Z | 2020-03-13T17:57:26.000Z | dev/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetUtils.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | null | null | null | dev/Code/Framework/AzToolsFramework/AzToolsFramework/Asset/AssetUtils.cpp | olivier-be/lumberyard | 3d688932f919dbf5821f0cb8a210ce24abe39e9e | [
"AML"
] | 6 | 2020-06-04T04:21:02.000Z | 2021-06-22T17:09:27.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/Debug/Trace.h>
#include <AzCore/Module/ModuleManagerBus.h>
#include <AzCore/Module/DynamicModuleHandle.h>
#include <AzFramework/API/ApplicationAPI.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/API/EditorAssetSystemAPI.h>
#include <AzToolsFramework/Asset/AssetUtils.h>
#include <GemRegistry/IGemRegistry.h>
AZ_PUSH_DISABLE_WARNING(4127 4251 4800, "-Wunknown-warning-option")
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QDirIterator>
AZ_POP_DISABLE_WARNING
namespace AzToolsFramework
{
namespace AssetUtils
{
namespace Internal
{
const char AssetConfigPlatfomrDir[] = "AssetProcessorConfig";
QStringList FindWildcardMatches(const QString& sourceFolder, QString relativeName)
{
if (relativeName.isEmpty())
{
return QStringList();
}
const int pathLen = sourceFolder.length() + 1;
relativeName.replace('\\', '/');
QStringList returnList;
QRegExp nameMatch{ relativeName, Qt::CaseInsensitive, QRegExp::Wildcard };
QDirIterator diretoryIterator(sourceFolder, QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
QStringList files;
while (diretoryIterator.hasNext())
{
diretoryIterator.next();
if (!diretoryIterator.fileInfo().isFile())
{
continue;
}
QString pathMatch{ diretoryIterator.filePath().mid(pathLen) };
if (nameMatch.exactMatch(pathMatch))
{
returnList.append(diretoryIterator.filePath());
}
}
return returnList;
}
void ReadPlatformInfosFromConfigFile(QString configFile, QStringList& enabledPlatforms)
{
// in the inifile the platform can be missing (commented out)
// in which case it is disabled implicitly by not being there
// or it can be 'disabled' which means that it is explicitly disabled.
// or it can be 'enabled' which means that it is explicitly enabled.
if (!QFile::exists(configFile))
{
return;
}
QSettings loader(configFile, QSettings::IniFormat);
// Read in enabled platforms
loader.beginGroup("Platforms");
QStringList keys = loader.allKeys();
for (int idx = 0; idx < keys.count(); idx++)
{
QString val = loader.value(keys[idx]).toString();
QString platform = keys[idx].toLower().trimmed();
val = val.toLower().trimmed();
if (val == "enabled")
{
if (!enabledPlatforms.contains(val))
{
enabledPlatforms.push_back(platform);
}
}
else if (val == "disabled")
{
// disable platform explicitly.
int index = enabledPlatforms.indexOf(platform);
if (index != -1)
{
enabledPlatforms.removeAt(index);
}
}
}
loader.endGroup();
}
void AddGemConfigFiles(const AZStd::vector<AzToolsFramework::AssetUtils::GemInfo>& gemInfoList, QStringList& configFiles)
{
// there can only be one gam gem per project, so if we find one, we cache the name of it so that
// later we can add it to the very end of the list, giving it the ability to override all other config files.
QString gameConfigPath;
for (const GemInfo& gemElement : gemInfoList)
{
QString gemAbsolutePath(gemElement.m_absoluteFilePath.c_str());
QDir gemDir(gemAbsolutePath);
QString absPathToConfigFile = gemDir.absoluteFilePath("AssetProcessorGemConfig.ini");
if (gemElement.m_isGameGem)
{
gameConfigPath = absPathToConfigFile;
}
else
{
configFiles.push_back(absPathToConfigFile);
}
}
// if a 'game gem' was discovered during the above loop, we want to append it to the END of the list
if (!gameConfigPath.isEmpty())
{
configFiles.push_back(gameConfigPath);
}
}
bool AddPlatformConfigFilePaths(const char* root, QStringList& configFilePaths)
{
QString configWildcardName{ "*" };
configWildcardName.append(AssetProcessorPlatformConfigFileName);
QDir sourceRoot(root);
QStringList platformList = FindWildcardMatches(sourceRoot.filePath(AssetConfigPlatfomrDir), configWildcardName);
for (const auto& thisConfig : platformList)
{
configFilePaths.append(thisConfig);
}
return (platformList.size() > 0);
}
}
const char* AssetProcessorPlatformConfigFileName = "AssetProcessorPlatformConfig.ini";
const char* AssetProcessorGamePlatformConfigFileName = "AssetProcessorGamePlatformConfig.ini";
const char GemsDirectoryName[] = "Gems";
GemInfo::GemInfo(AZStd::string name, AZStd::string relativeFilePath, AZStd::string absoluteFilePath, AZStd::string identifier, bool isGameGem, bool assetOnlyGem)
: m_gemName(name)
, m_relativeFilePath(relativeFilePath)
, m_absoluteFilePath(absoluteFilePath)
, m_identifier(identifier)
, m_isGameGem(isGameGem)
, m_assetOnly(assetOnlyGem)
{
}
QStringList GetEnabledPlatforms(QStringList configFiles)
{
QStringList enabledPlatforms;
// note that the current host platform is enabled by default.
enabledPlatforms.push_back(AzToolsFramework::AssetSystem::GetHostAssetPlatform());
for (const QString& configFile : configFiles)
{
Internal::ReadPlatformInfosFromConfigFile(configFile, enabledPlatforms);
}
return enabledPlatforms;
}
QStringList GetConfigFiles(const char* root, const char* assetRoot, const char* gameName, bool addPlatformConfigs, bool addGemsConfigs)
{
QStringList configFiles;
QDir configRoot(root);
QString rootConfigFile = configRoot.filePath(AssetProcessorPlatformConfigFileName);
configFiles.push_back(rootConfigFile);
if (addPlatformConfigs)
{
Internal::AddPlatformConfigFilePaths(root, configFiles);
}
if (addGemsConfigs)
{
AZStd::vector<AzToolsFramework::AssetUtils::GemInfo> gemInfoList;
if (!GetGemsInfo(root, assetRoot, gameName, gemInfoList))
{
AZ_Error("AzToolsFramework::AssetUtils", false, "Failed to read gems for game project (%s).\n", gameName);
return {};
}
Internal::AddGemConfigFiles(gemInfoList, configFiles);
}
QDir assetRootDir(assetRoot);
assetRootDir.cd(gameName);
QString projectConfigFile = assetRootDir.filePath(AssetProcessorGamePlatformConfigFileName);
configFiles.push_back(projectConfigFile);
return configFiles;
}
bool GetGemsInfo(const char* root, const char* assetRoot, const char* gameName, AZStd::vector<GemInfo>& gemInfoList)
{
Gems::IGemRegistry* registry = nullptr;
Gems::IProjectSettings* projectSettings = nullptr;
AZ::ModuleManagerRequests::LoadModuleOutcome result = AZ::Failure(AZStd::string("Failed to connect to ModuleManagerRequestBus.\n"));
AZ::ModuleManagerRequestBus::BroadcastResult(result, &AZ::ModuleManagerRequestBus::Events::LoadDynamicModule, "GemRegistry", AZ::ModuleInitializationSteps::Load, false);
if (!result.IsSuccess())
{
AZ_Error("AzToolsFramework::AssetUtils", false, "Could not load the GemRegistry module - %s.\n", result.GetError().c_str());
return false;
}
// Use shared_ptr aliasing ctor to use the refcount/deleter from the moduledata pointer, but we only need to store the dynamic module handle.
auto registryModule = AZStd::shared_ptr<AZ::DynamicModuleHandle>(result.GetValue(), result.GetValue()->GetDynamicModuleHandle());
auto CreateGemRegistry = registryModule->GetFunction<Gems::RegistryCreatorFunction>(GEMS_REGISTRY_CREATOR_FUNCTION_NAME);
Gems::RegistryDestroyerFunction registryDestroyerFunc = registryModule->GetFunction<Gems::RegistryDestroyerFunction>(GEMS_REGISTRY_DESTROYER_FUNCTION_NAME);
if (!CreateGemRegistry || !registryDestroyerFunc)
{
AZ_Error("AzToolsFramework::AssetUtils", false, "Failed to load GemRegistry functions.\n");
return false;
}
registry = CreateGemRegistry();
if (!registry)
{
AZ_Error("AzToolsFramework::AssetUtils", false, "Failed to create Gems::GemRegistry.\n");
return false;
}
registry->AddSearchPath({ root, GemsDirectoryName }, false);
registry->AddSearchPath({ assetRoot, GemsDirectoryName }, false);
const char* engineRootPath = nullptr;
AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(engineRootPath, &AzToolsFramework::ToolsApplicationRequestBus::Events::GetEngineRootPath);
if (engineRootPath && azstricmp(engineRootPath, root))
{
registry->AddSearchPath({ engineRootPath, GemsDirectoryName }, false);
}
projectSettings = registry->CreateProjectSettings();
if (!projectSettings)
{
registryDestroyerFunc(registry);
AZ_Error("AzToolsFramework::AssetUtils", false, "Failed to create Gems::ProjectSettings.\n");
return false;
}
if (!projectSettings->Initialize(assetRoot, gameName))
{
registry->DestroyProjectSettings(projectSettings);
registryDestroyerFunc(registry);
AZ_Error("AzToolsFramework::AssetUtils", false, "Failed to initialize Gems::ProjectSettings.\n");
return false;
}
auto loadProjectOutcome = registry->LoadProject(*projectSettings, true);
if (!loadProjectOutcome.IsSuccess())
{
registry->DestroyProjectSettings(projectSettings);
registryDestroyerFunc(registry);
AZ_Error("AzToolsFramework::AssetUtils", false, "Failed to load Gems project: %s.\n", loadProjectOutcome.GetError().c_str());
return false;
}
// Populating the gem info list
for (const auto& pair : projectSettings->GetGems())
{
Gems::IGemDescriptionConstPtr desc = registry->GetGemDescription(pair.second);
if (!desc)
{
Gems::ProjectGemSpecifier gemSpecifier = pair.second;
AZStd::string errorStr = AZStd::string::format("Failed to load Gem with ID %s and Version %s (from path %s).\n",
gemSpecifier.m_id.ToString<AZStd::string>().c_str(), gemSpecifier.m_version.ToString().c_str(), gemSpecifier.m_path.c_str());
if (Gems::IGemDescriptionConstPtr latestVersion = registry->GetLatestGem(pair.first))
{
errorStr += AZStd::string::format(" Found version %s, you may want to use that instead.\n", latestVersion->GetVersion().ToString().c_str());
}
AZ_Error("AzToolsFramework::AssetUtils", false, errorStr.c_str());
return false;
}
// Note: the two 'false' parameters in the ToString call below ToString(false, false)
// eliminates brackets and dashes in the formatting of the UUID.
// this keeps it compatible with legacy formatting which also omitted the curly braces and the dashes in the UUID.
AZStd::string gemId = desc->GetID().ToString<AZStd::string>(false, false).c_str();
AZStd::to_lower(gemId.begin(), gemId.end());
bool assetOnlyGem = true;
Gems::ModuleDefinitionVector moduleList = desc->GetModules();
for (Gems::ModuleDefinitionConstPtr moduleDef : moduleList)
{
if (moduleDef->m_linkType != Gems::LinkType::NoCode)
{
assetOnlyGem = false;
break;
}
}
gemInfoList.emplace_back(GemInfo(desc->GetName(), desc->GetPath(), desc->GetAbsolutePath(), gemId, desc->IsGameGem(), assetOnlyGem));
}
registry->DestroyProjectSettings(projectSettings);
registryDestroyerFunc(registry);
return true;
}
} //namespace AssetUtils
} //namespace AzToolsFramework
| 43.431953 | 181 | 0.581471 | [
"vector"
] |
cde976fa516a36e611b42a74900e6f07f38c7c52 | 2,815 | cc | C++ | chrome/browser/vr/elements/text.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/vr/elements/text.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/vr/elements/text.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/vr/elements/text.h"
#include "base/memory/ptr_util.h"
#include "cc/paint/skia_paint_canvas.h"
#include "chrome/browser/vr/elements/ui_texture.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/render_text.h"
namespace vr {
class TextTexture : public UiTexture {
public:
TextTexture(int resource_id, float font_height, float text_width)
: resource_id_(resource_id),
font_height_(font_height),
text_width_(text_width) {}
~TextTexture() override {}
void OnSetMode() override { set_dirty(); }
private:
gfx::Size GetPreferredTextureSize(int width) const override {
return gfx::Size(width, width);
}
gfx::SizeF GetDrawnSize() const override { return size_; }
void Draw(SkCanvas* sk_canvas, const gfx::Size& texture_size) override;
gfx::SizeF size_;
int resource_id_;
// These widths are in meters.
float font_height_;
float text_width_;
DISALLOW_COPY_AND_ASSIGN(TextTexture);
};
Text::Text(int maximum_width_pixels,
float font_height_meters,
float text_width_meters,
int resource_id)
: TexturedElement(maximum_width_pixels),
texture_(base::MakeUnique<TextTexture>(resource_id,
font_height_meters,
text_width_meters)) {}
Text::~Text() {}
UiTexture* Text::GetTexture() const {
return texture_.get();
}
void TextTexture::Draw(SkCanvas* sk_canvas, const gfx::Size& texture_size) {
cc::SkiaPaintCanvas paint_canvas(sk_canvas);
gfx::Canvas gfx_canvas(&paint_canvas, 1.0f);
gfx::Canvas* canvas = &gfx_canvas;
gfx::FontList fonts;
auto text = l10n_util::GetStringUTF16(resource_id_);
float pixels_per_meter = texture_size.width() / text_width_;
int pixel_font_height = static_cast<int>(font_height_ * pixels_per_meter);
GetFontList(pixel_font_height, text, &fonts);
gfx::Rect text_bounds(texture_size.width(), 0);
std::vector<std::unique_ptr<gfx::RenderText>> lines =
// TODO(vollick): if this subsumes all text, then we should probably move
// this function into this class.
PrepareDrawStringRect(text, fonts, color_scheme().world_background_text,
&text_bounds, kTextAlignmentCenter,
kWrappingBehaviorWrap);
// Draw the text.
for (auto& render_text : lines)
render_text->Draw(canvas);
// Note, there is no padding here whatsoever.
size_ = gfx::SizeF(text_bounds.size());
}
} // namespace vr
| 31.988636 | 79 | 0.691297 | [
"geometry",
"vector"
] |
cdeb75afb4cd35819634b0cc7ec2c3059eb85c39 | 48,523 | cpp | C++ | src/cpp/filter_old.cpp | lanl/tardigrade-overlap-coupling | a79c8c31b89bc1448ce4a3d438c3f3771f860042 | [
"BSD-3-Clause"
] | null | null | null | src/cpp/filter_old.cpp | lanl/tardigrade-overlap-coupling | a79c8c31b89bc1448ce4a3d438c3f3771f860042 | [
"BSD-3-Clause"
] | null | null | null | src/cpp/filter_old.cpp | lanl/tardigrade-overlap-coupling | a79c8c31b89bc1448ce4a3d438c3f3771f860042 | [
"BSD-3-Clause"
] | null | null | null | /*!
===============================================================================
| filter.cpp |
===============================================================================
| An implementation of the micromorphic filter using the overlap coupling |
| library. |
===============================================================================
*/
#include "filter.h"
namespace filter{
int open_format1_file(const std::string &fn, std::ifstream &file){
/*!
Open a file in format 1
:param std::string fn: The filename
*/
file = std::ifstream(fn);
if(file.is_open()){
return 0;
}
else{
std::cout << "Error: cannot open file: " << fn << "\n";
return 1;
}
}
int open_input_file(const std::string &fn, const int format, std::ifstream &file){
/*!
Open an input file of the provided format.
:param const std::string &fn: The input filename
:param const int format: The file format
:param std::ifstream &file: The opened file.
*/
if (format == 1){
return open_format1_file(fn, file);
}
return 1;
}
int read_past_header(std::ifstream &file, input_format &mp_format, input_format &dof_format, const int format){
/*!
* Read past the file header for the given format
*
* :param const std::ifstream &file: The input file
* :param input_format &mp_format: The format of a material point line
* :param input_format &dof_format: The format of a dof point line
* :param int format: The format of the file
*/
if (format==1){
return read_past_header_format1(file, mp_format, dof_format);
}
return 1;
}
// FOLLOWING LINES FROM https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
// trim from start (in place)
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
static inline void trim(std::string &s) {
ltrim(s);
rtrim(s);
}
// END LINES FROM https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
int set_format(std::string &line, input_format &format){
/*!
* Set the format from the input line
*
* :param std::string &line: A line from the input file
* :param input_format &format: The format to be specified
*/
std::vector< std::string > sline;
split_string(line, ",", sline);
std::vector< unsigned int > vals(2, 0);
for (unsigned int i=1; i<sline.size(); i+=3){
vals[0] = std::stol(sline[i+1]);
vals[1] = std::stol(sline[i+2]);
format.emplace(sline[i], vals);
}
return 0;
}
int read_past_header_format1(std::ifstream &file, input_format &mp_format, input_format &dof_format){
/*!
* Read past the header information for format 1
*
* :param std::ifstream file: The input file
* :param input_format &mp_format: The format of a material point line
* :param input_format &dof_format: The format of a dof point line
*/
std::string line;
std::cout << "File header:\n\n";
while (std::getline(file, line)){
if (line.find("*MPFORMAT") != std::string::npos){
set_format(line, mp_format);
}
else if (line.find("*DOFFORMAT") != std::string::npos){
set_format(line, dof_format);
}
else if (std::strcmp(line.c_str(), "BEGIN DATA") == 0){
std::cout << "\n";
return 0;
}
else{
std::cout << line << "\n";
}
}
return 1;
}
int read_timestep(std::ifstream &file, const int format, std::ofstream &output_file, elib::vecOfvec &data){
/*!
Read in the information for a single timestep in the provided format.
:param std::ifstream &file: The input file to read
:param const int format: The input file format
:param std::ofstream &output_file: The output file
:param elib::vecOfvec &data: The parsed data. Note: All data is converted to double
*/
double time;
int result;
if (format == 1){
result = read_timestep_format1(file, time, data);
}
else{
result = 1;
}
output_file << "*TIMESTEP, " << time << "\n";
return result;
}
int find_current_time_format1(std::ifstream &file, elib::vecOfvec &data, double &time){
/*!
Read in the current time from the input file.
:param std::ifstream &file: The input file to read
:param elib::vecOfvec &data: The parsed data. Note: All data is converted to double.
*/
std::string line;
std::size_t found;
std::string time_indicator = "t = ";
while (std::getline(file, line)){
//Search for a line that begins with 't = '
found = line.find(time_indicator);
if (found!=std::string::npos){
time = std::stod(line.substr(found+4, line.size()-(found+4)));
std::cout << "Retrieving data from timestep: " << time << "\n";
return 0;
}
}
return 1;
}
int split_string(const std::string &line, const std::string &delimiter, std::vector< std::string > &parsed_line){
/*!
Split the provided string at the given delimiter
*/
size_t last, next;
last = next = 0;
parsed_line.resize(0);
std::string substr;
while ((next = line.find(delimiter, last)) != std::string::npos){
substr = line.substr(last, next - last);
trim(substr);
parsed_line.push_back(substr);//line.substr(last, next - last));
last = next + 1;
}
parsed_line.push_back(line.substr(last));
return 0;
}
int parsed_line_to_data(const std::vector< std::string > &parsed_line, elib::vec &line_data){
/*!
Convert a parsed line into data
:param const std::vector< std::string > &parsed_line: A parsed line from the input file
:param elib::vec &line_data: The double representation of the data line
*/
//Convert the string to data
line_data.resize(parsed_line.size());
if (std::strcmp(parsed_line[0].c_str(), "MP")==0){
//Assign a material point a value of 1
line_data[0] = 1;
}
else if (std::strcmp(parsed_line[0].c_str(), "DOFP")==0){
//Assign a data point a value of 2
line_data[0] = 2;
}
for (unsigned int i=1; i<parsed_line.size(); i++){
line_data[i] = std::stod(parsed_line[i]);
}
return 0;
}
int read_timestep_data_format1(std::ifstream &file, elib::vecOfvec &data){
/*!
Read in the data for the current timestep using format 1
:param std::ifstream &file: The input file to read
:param elib::vecOfvec &data: The parsed data. Note: All data is converted to double.
*/
std::string line;
std::string time_indicator = "t = ";
std::string delimiter = ",";
std::streampos oldpos = file.tellg();
std::vector< std::string > parsed_line;
size_t found;
elib::vec line_data;
while (std::getline(file, line)){
if (line.size() > 0){
//Check if a new timestep has been found
found = line.find(time_indicator);
if (found!=std::string::npos){
file.seekg(oldpos);
return 0;
}
//Split the line at the commas
split_string(line, delimiter, parsed_line);
//Convert the parsed line to a vector
parsed_line_to_data(parsed_line, line_data);
data.push_back(line_data);
}
}
return 0;
}
int read_timestep_format1(std::ifstream &file, double &time, elib::vecOfvec &data){
/*!
Read in the information for a single timestep.
:param std::ifstream &file: The input file to read
:param elib::vecOfvec &data: The parsed data. Note: All data is converted to double.
*/
//Get the current time
int get_time_result = find_current_time_format1(file, data, time);
if (get_time_result>0){
std::cout << "Error reading in new timestep\n";
return 1;
}
//Read in the data
return read_timestep_data_format1(file, data);
}
int build_filters(const assembly::node_map &nodes, const assembly::element_map elements,
const assembly::qrule_map &qrules, const unsigned int num_macro_dof, filter_map &filters,
const bool shared_dof_material){
/*!
* Build the filters for processing data.
*
* :param const assembly::node_map &nodes: The nodes of the micromorphic filter.
* :param const assembly::element_map &elements: The elements of the micromorphic filter.
* :param const assembly::qrule_map &qrules: The quadrature rules for the elements.
* :param const unsigned int num_macro_dof: The number of macro-scale degrees of freedom.
* :param filter_map &filters: Return map of the element ids to their corresponding sub-filters.
* :param const bool shared_dof_material: Flag indicating if the dof is co-located with the stress
* even when it isn't it is sometimes advantageous to pretend like it is for pure filtering operations.
*/
//Clear the filters
filters.clear();
//Iterate over the element types.
for (auto _element_types = elements.begin(); _element_types!=elements.end(); _element_types++){
//Find the quadrature rule
auto qrule = qrules.find(_element_types->first);
if (qrule == qrules.end()){
std::cout << "Error: quadrature rule for " << _element_types->first << " not found.\n";
return 1;
}
//Loop over the elements. This could be parallelized but it probably won't make a difference.
for (auto _element = _element_types->second.begin(); _element!=_element_types->second.end(); _element++){
auto elid = filters.find(_element->first);
if (elid != filters.end()){
std::cout << "Error: filters must be made of elements with unique ids.\n"
<< " " << _element->first << " is already used.\n";
return 1;
}
//Create a vector of the filter's nodes
elib::vecOfvec element_nodes(_element->second.size());
for (unsigned int i=0; i<element_nodes.size(); i++){
auto point = nodes.find(_element->second[i]);
if (point == nodes.end()){
std::cout << "Error: node " << _element->second[i] << " not found.\n";
return 1;
}
element_nodes[i] = point->second;
}
//Initialize the filter
filters.emplace(_element->first, overlap::MicromorphicFilter(_element->first, _element_types->first,
_element->second, element_nodes, qrule->second,
num_macro_dof, shared_dof_material));
}
}
return 0;
}
int populate_filters(const elib::vecOfvec &data, const input_format &mp_format, const input_format &dof_format,
const assembly::node_map &nodes,
const assembly::element_map &elements, const assembly::qrule_map &qrules,
const bool update_shapefunction, const bool shared_dof_material,
const unsigned int num_macro_dof,
std::map<unsigned int, unsigned int > µ_node_to_row,
std::map< unsigned int, unsigned int > µ_node_elcount, filter_map &filters){
/*!
* Populate the micromorphic sub-filters using the provided data.
*
* :param const elib::vecOfvec &data: The DNS data at the current timestep.
* :param const input_format &mp_format: The format of a material point dataline
* :param const input_format &dof_format: The format of a degree of freedom dataline
* :param const assembly::node_map &nodes: The nodes of the micromorphic filter.
* :param const assembly::element_map &elements: The elements of the micromorphic filter.
* :param const assembly::qrule_map &qrules: The quadrature rules for the elements.
* :param const bool update_shapefunction: Flag indicating of the shapefunction matrix is to be updated.
* :param const bool shared_dof_material: Flag indicating if the degrees of freedom and material quantities are known at
* the same points.
* :param const unsigned int num_macro_dof: The number of degrees of freedom to macro-scale has.
* :param std::map< unsigned int, unsigned int > µ_node_to_row: The mapping from the micro node number to the
* row of the shape function matrix.
* :param std::map< unsigned int, unsigned int > µ_node_elcount: The number of filters a node is contained within.
* :param filter_map &filters: Return map of the element ids to their corresponding sub-filters.
*/
//Construct the filters if they haven't been formed yet
if (filters.size() == 0){
std::cout << " Filter list unpopulated. Initial construction of filters occuring\n";
int bf_result = build_filters(nodes, elements, qrules, num_macro_dof, filters, shared_dof_material);
if (bf_result>0){
return 1;
}
}
else{
for (auto filter=filters.begin(); filter!=filters.end(); filter++){
filter->second.clear_microscale();
}
}
//Erase micro_node_to_row
if (update_shapefunction){
micro_node_to_row.clear();
micro_node_elcount.clear();
}
//This probably could/should be parallelized
unsigned int index = 0;
std::vector< double > position;
unsigned int nodeid;
for (auto datapoint=data.begin(); datapoint!=data.end(); datapoint++){
unsigned int containing_filters = 0;
//Determine whether the point is a material point or dof point
int pointtype = (int)((*datapoint)[0]+0.5);
//Iterate over the macro-scale filters
for (auto filter = filters.begin(); filter!=filters.end(); filter++){
bool iscontained = false;
if (pointtype==1){
get_position(*datapoint, mp_format, nodeid, position);
iscontained = filter->second.add_micro_material_point(nodeid, position);
}
else if (pointtype==2){
get_position(*datapoint, dof_format, nodeid, position);
iscontained = filter->second.add_micro_dof_point(nodeid, position);
}
if (iscontained){
containing_filters += 1;
}
}
//Giving the current point a mapping to the shape-function matrix if required.
if ((update_shapefunction) && (shared_dof_material) && (containing_filters>0) && (pointtype==1)){
//Update in the case of a material point and shared dof-material points (i.e. MPM)
micro_node_to_row.emplace((*datapoint)[1], index);
//Adjust the weighting on the point if it is contained in elements.
//Note that this should only happen if a point is on the boundary between
//multiple filter domains.
if (containing_filters > 1){
micro_node_elcount.emplace((unsigned int)((*datapoint)[1]+0.5), containing_filters);
}
}
else if ((update_shapefunction) && (!shared_dof_material) && (containing_filters>0) && (pointtype==2)){
//Update in the case of a dof point and non-shared dof-material points (i.e. FEA)
micro_node_to_row.emplace((*datapoint)[1], index);
//Adjust the weighting on the point if it is contained in elements.
//Note that this should only happen if a point is on the boundary between
//multiple filter domains.
if (containing_filters > 1){
micro_node_elcount.emplace((unsigned int)((*datapoint)[1]+0.5), containing_filters);
}
}
//Increment index if it was contained
if (containing_filters>0){
index++;
}
}
return 0;
}
int construct_micro_displacement_vector_from_positions(const elib::vecOfvec &data, const input_format &mp_format,
const input_format &dof_format, const uint_to_vec &reference_coordinates,
const bool shared_dof_material,
const unsigned int num_micro_dof, const uint_map µ_node_to_row,
elib::vec µ_displacement_vector){
/*!
* Construct the micro displacement vector by computing the difference between the current position and some
* reference position.
*
* :param const elib::vecOfvec &data: A collection of micro-scale data
* :param const input_format &mp_format: The format of a material point dataline
* :param const input_format &dof_format: The format of a degree of freedom dataline
* :param const uint_to_vec &reference_coordinates: The reference coordinates for the data
* :param const bool shared_dof_material: Whether the degrees of freedom are located at the material points or not.
* :param const unsigned int num_micro_dof: The number of micro-scale degrees of freedom per node
* :param const uint_map µ_node_to_row: The map from the micro node to the row of the shape-function matrix
* :param elib::vec µ_displacement_vector: The returned micro-scale displacement vector
*/
micro_displacement_vector.resize(micro_node_to_row.size()*num_micro_dof);
// std::cout << "reference coordinates:\n"; print(reference_coordinates);
std::vector< double > pi;
bool dof_point;
int nodetype;
unsigned int nodeid;
int gp_result;
for (auto dataline=data.begin(); dataline!=data.end(); dataline++){
//Compute the difference between the current coordinates and the
//reference
dof_point = false;
nodetype = (int)((*dataline)[0]+0.5);
gp_result = 0;
//Extract the point information if required
if ((nodetype==1) && (shared_dof_material)){
dof_point = true;
gp_result = get_position(*dataline, mp_format, nodeid, pi);
}
else if ((nodetype==2) && (!shared_dof_material)){
dof_point = true;
gp_result = get_position(*dataline, dof_format, nodeid, pi);
}
if (gp_result > 0){
return gp_result;
}
//Check if the current node is located in the referencecoordinates map (it better be!)
if (dof_point){
auto ref = reference_coordinates.find(nodeid);
if (ref == reference_coordinates.end()){
std::cerr << "Error: node " << nodeid << " not found in reference coordinates.\n";
std::cerr << " it is currently required that nodes cannot be deleted.\n";
return 1;
}
//Assign the value to the micro-displacement (dof) vector
auto it = micro_node_to_row.find(nodeid);
if (it != micro_node_to_row.end()){
for (unsigned int i=0; i<pi.size(); i++){
micro_displacement_vector[num_micro_dof*it->second+i] = pi[i] - ref->second[i];
}
}
}
}
return 0;
}
int assign_dof_information_to_filters(const assembly::node_map &nodes, const assembly::element_map &elements,
const uint_map ¯o_node_to_col, const unsigned int num_macro_dof,
const std::vector< double > ¯o_displacement, filter_map &filters){
/*!
* Assign the computed macro-scale degree of freedom values to the nodes
*
*/
//Assign the dof information to the filter and update their current nodal positions.
for (auto filter=filters.begin(); filter!=filters.end(); filter++){
//Get the elements of the given type
auto elementtype=elements.find(filter->second.element_type());
if (elementtype == elements.end()){
std::cout << "Error: cant find filter element type in elements\n";
return 1;
}
//Get the element nodal definition
auto element = elementtype->second.find(filter->second.id());
if (element == elementtype->second.end()){
std::cout << "Error: filter not found in element list\n";
return 1;
}
//Iterate through the element's nodes
unsigned int index=0;
// std::cout << "macro_node_to_col:\n";
// print(macro_node_to_col);
// std::cout << "macro_displacement:\n";
// for (unsigned int i=0; i<8; i++){
// for (unsigned int j=0; j<num_macro_dof; j++){
// std::cout << macro_displacement[num_macro_dof*i + j] << ", ";
// }
// std::cout << "\n";
// }
// std::cout << "element nodes:\n";
for (auto n=element->second.begin(); n!=element->second.end(); n++){
auto dofptr = macro_node_to_col.find(*n);
if (dofptr == macro_node_to_col.end()){
std::cerr << "Error: filter node " << *n << "not found in macro_node_to_col map\n";
return 1;
}
filter->second.update_dof_values(index,
std::vector< double >(macro_displacement.begin() + num_macro_dof*dofptr->second,
macro_displacement.begin() + num_macro_dof*dofptr->second + num_macro_dof));
//We assume that the first dof values are the macro displacements
unsigned int uenp_result = filter->second.update_element_node_position(index);
// unsigned int uenp_result = filter->second.update_element_node_positions(index,
// std::vector< double > (¯o_displacement[num_macro_dof*dofptr->second],
// ¯o_displacement[num_macro_dof*dofptr->second+filter->second.dim()])
// );
if (uenp_result > 0){
return 1;
}
index++;
}
//filter->second.print();
}
return 0;
}
int assemble_micro_density(const elib::vecOfvec &data, const input_format &mp_format, std::map< unsigned int, double > µ_density){
/*!
* Assemble the micro-density map for use in homogenizing the density
*
* :const elib::vecOfvec &data: The data array read from the DNS file
* :const input_format &mp_format: The format of the material point lines
* :std::map< unsigned int, double > µ_density: The extracted data
*/
auto idit = mp_format.find("ID");
auto densityit = mp_format.find("DENSITY");
if ((idit == mp_format.end()) || (densityit == mp_format.end())){
std::cout << "MPFORMAT:\n"; print(mp_format);
std::cout << "Error: density or id not defined in *MPFORMAT\n";
return 1;
}
for (auto dataline = data.begin(); dataline!=data.end(); dataline++){
if ((unsigned int)((*dataline)[0]+0.5) == 1){
micro_density.emplace((*dataline)[ idit->second[0] ], (*dataline)[ densityit->second[0] ]);
}
}
return 0;
}
int assemble_micro_stress(const elib::vecOfvec &data, const input_format &mp_format,
std::map< unsigned int, std::vector< double > > µ_stress){
/*!
* Assemble the micro-stress map for use in computing the micromorphic stress measures
*
* :const elib::vecOfvec &data: The data array read from the DNS file
* :const input_format &mp_format: The format of the material point lines
* :std::map< unsigned int, std::vector< double > > µ_stress: The extracted data
*/
auto idit = mp_format.find("ID");
auto stressit = mp_format.find("STRESS");
if ((idit == mp_format.end()) || (stressit == mp_format.end())){
std::cout << "MPFORMAT:\n"; print(mp_format);
std::cerr << "Error: stress or id not defined in *MPFORMAT\n";
return 1;
}
for (auto dataline = data.begin(); dataline!=data.end(); dataline++){
if ((unsigned int)((*dataline)[0]+0.5) == 1){
std::vector< double > stress(stressit->second[1]);
for (unsigned int i=0; i<stressit->second[1]; i++){
stress[i] = (*dataline)[stressit->second[0]+i];
}
micro_stress.emplace((*dataline)[ idit->second[0] ], stress);
}
}
return 0;
}
int get_position(const elib::vec &dataline, const input_format &format, unsigned int &node_id, elib::vec &position){
/*!
* Get the position from the provided dataline given the format
*
* :param const elib::vec &dataline: The line of data as read from the input file
* :param const input_format &format: The formatting of the line
* :param unsigned int &node_id: The id associated with the position.
* :param elib::vec &position: The returned position vector
*/
auto idit = format.find("ID");
auto pit = format.find("POSITION");
if ((idit == format.end()) || (pit == format.end())){
std::cerr << "Error: ID or POSITION not found in format\n";
return 1;
}
node_id = dataline[idit->second[0]];
position.resize(pit->second[1]);
for (unsigned int i=0; i<pit->second[1]; i++){
position[i] = dataline[pit->second[0]+i];
}
return 0;
}
int populate_reference_coordinates(const elib::vecOfvec &data, const bool shared_dof_material, const input_format &mp_format,
const input_format &dof_format, uint_to_vec &reference_coordinates){
/*!
* Populate the reference coordinates map
*
* :param const elib::vecOfvec &data: The dns data to be parsed.
* :param const input_format &mp_format: The format of material points.
* :param const input_format &dof_format: The format of degree of freedom points
* :param uint_to_vec &reference_coordinates: The reference coordinates map
*/
//Populate the reference coordinate map
reference_coordinates.clear();
std::vector< double > pi;
bool dof_point;
int nodetype;
unsigned int nodeid;
int gp_result;
for (auto dataline=data.begin(); dataline!=data.end(); dataline++){
// std::vector< double > pi(num_micro_dof);
dof_point = false;
gp_result = 0;
nodetype = (int)((*dataline)[0]+0.5);
//Extract the point information if required
if ((nodetype==1) && (shared_dof_material)){
dof_point = true;
gp_result = get_position(*dataline, mp_format, nodeid, pi);
}
else if ((nodetype==2) && (!shared_dof_material)){
dof_point = true;
gp_result = get_position(*dataline, dof_format, nodeid, pi);
}
if (gp_result > 0){
return gp_result;
}
//Store the reference coordinates of the point if it is a DOF point
if (dof_point){
reference_coordinates.emplace(nodeid, pi);
}
}
return 0;
}
int process_timestep_totalLagrangian(const elib::vecOfvec &data, const input_format &mp_format, const input_format &dof_format,
const assembly::node_map &nodes,
const assembly::element_map &elements, const assembly::qrule_map &qrules,
const bool shared_dof_material,
std::map< unsigned int, unsigned int > ¯o_node_to_col,
std::map< unsigned int, unsigned int > µ_node_to_row,
std::map< unsigned int, unsigned int > µ_node_elcount,
std::map< unsigned int, elib::vec > &reference_coordinates,
overlap::SpMat &shapefunctions, overlap::QRsolver &dof_solver, filter_map &filters,
std::ofstream &output_file,
const unsigned int num_macro_dof, const unsigned int num_micro_dof){
/*!
* Process the current timestep using a Total-Lagrangian approach.
* If filters is empty, it is assumed that this is the first increment and they will be
* populated along with the shape-function matrix.
*
* Note that, even in a total-Lagrangian framework, we still must re-populate the material
* point integrators every timestep but we can leave the shape-function matrix in tact. This
* is because we do not, generally, know how the micro-volumes volumetrically deform but we
* can choose to use the points originally contained within the filter as the points that
* determine the filter's motion. This is what is meant by Total-Lagrangian.
*
* :param const elib::vecOfvec &data: The DNS data at the current timestep.
* :param const input_format &mp_format: The format of a material point dataline
* :param const input_format &dof_format: The format of a degree of freedom dataline
* :param const assembly::node_map &nodes: The nodes of the micromorphic filter.
* :param const assembly::element_map &elements: The elements of the micromorphic filter.
* :param const assembly::qrule_map &qrules: The quadrature rules for the elements.
* :param const bool shared_dof_material: Whether the dof and material information is co-located.
* :param std::map< unsigned int, unsigned int > ¯o_node_to_col: The map from macro nodes to the corresponding
* column of the matrix (normalized by the num_macro_dof)
* :param std::map< unsigned int, unsigned int > µ_node_to_row: The map from micro nodes to the corresponding
* row of the matrix (normalized by the num_micro_dof)
* :param std::map< unsigned int, unsigned int > µ_node_elcount: The number of macro elements (filters)
* containing the given micro node. Only occurs for micro nodes on the boundaries between two filters and
* is only populated for nodes greater than 1.
* :param std::map< unsigned int, elib::vec > &reference_coordinates: The reference coordinates used to compute
* the change in position of the dof points.
* :param overlap::SpMat &shapefunctions: The shapefunction matrix.
* :param overlap::QRsolver &dof_solver: The degree of freedom solver object.
* :param filter_map &filters: Return map of the element ids to their corresponding sub-filters.
* :param std::ofstream &output_file: The output file to write the filter results to
* :param const unsigned int num_macro_dof: The number of macro-scale degrees of freedom (default 12)
* :param const unsigned int num_micro_dof: The number of micro-scale degrees of freedom (default 3)
*/
//Check if the filters have been populated yet. If not, we will re-compute the shape-function matrix.
bool populated_filters = false;
// std::vector< unsigned int > macro_node_ids(nodes.size());
// std::vector< double > u_450(3);
if (filters.size() == 0){
populated_filters = true;
macro_node_to_col.clear();
unsigned int index = 0;
for (auto it=nodes.begin(); it!=nodes.end(); it++){
macro_node_to_col.emplace(it->first, index);
// macro_node_ids[index] = it->first;
index++;
}
}
else{
//Compute the macro displacement
std::cout << " Computing the macro-displacement\n";
std::vector< double > macro_displacement(shapefunctions.cols());
std::vector< double > micro_displacement(shapefunctions.rows());
int cmdvfp_result = construct_micro_displacement_vector_from_positions(data, mp_format, dof_format, reference_coordinates,
shared_dof_material, num_micro_dof,
micro_node_to_row,
micro_displacement);
if (cmdvfp_result > 0){
return 1;
}
//Solve for the macro dof
Eigen::Map< overlap::EigVec > b(micro_displacement.data(), micro_displacement.size(), 1);
Eigen::Map< overlap::EigVec > x(macro_displacement.data(), macro_displacement.size(), 1);
x = dof_solver.solve(b);
std::cout << " Assigning macro-dof values to the filter\n";
assign_dof_information_to_filters(nodes, elements, macro_node_to_col, num_macro_dof,
macro_displacement, filters);
}
//Populate the filters
int pf_result = populate_filters(data, mp_format, dof_format, nodes, elements, qrules,
populated_filters, shared_dof_material, num_macro_dof,
micro_node_to_row, micro_node_elcount, filters);
if (pf_result > 0){
std::cout << "Error in population of filters.\n";
return 1;
}
//Perform the voronoi cell decomposition (maybe should be parallelized)
std::cout << "Constructing Integrators\n";
for (auto filter = filters.begin(); filter!=filters.end(); filter++){
filter->second.construct_integrators();
}
//Compute the mass and volume properties of the filters
std::cout << "Computing Mass Properties\n";
std::map< unsigned int, double > micro_density;
assemble_micro_density(data, mp_format, micro_density);
for (auto filter = filters.begin(); filter!=filters.end(); filter++){
std::cout << "filter: " << filter->first << "\n";
filter->second.compute_mass_properties(micro_density);
}
//Compute the stress properties of the filters
std::cout << "Computing Stress Properties\n";
std::map< unsigned int, std::vector< double > > micro_stress;
assemble_micro_stress(data, mp_format, micro_stress);
for (auto filter=filters.begin(); filter!=filters.end(); filter++){
filter->second.compute_stress_properties(micro_stress);
}
//Construct the shapefunction matrix if required
if (populated_filters){
std::cout << "Computing the Shape-Function matrix\n";
std::cout << " Formulating the shape-function matrix terms\n";
std::vector< overlap::T > tripletList;
for (auto filter = filters.begin(); filter!=filters.end(); filter++){
//Compute the contribution of the current filter to the shape-function matrix
const std::vector< unsigned int > *macro_node_ids = filter->second.get_element_global_node_ids();
// std::cout << "macro_node_ids:\n";
// for (unsigned int i=0; i<macro_node_ids->size(); i++){
// std::cout << (*macro_node_ids)[i] << "\n";
// }
filter->second.add_shapefunction_matrix_contribution(macro_node_to_col, micro_node_to_row, *macro_node_ids,
micro_node_elcount, num_macro_dof, num_micro_dof,
data.size(), tripletList, shared_dof_material);
}
//Construct the shapefunction matrix
std::cout << " Constructing the shape-function matrix from " << tripletList.size() << " terms.\n";
std::cout << " rows, cols: " << num_micro_dof*micro_node_to_row.size() << ", " << num_macro_dof*macro_node_to_col.size() << "\n";
shapefunctions = overlap::SpMat(num_micro_dof*micro_node_to_row.size(), num_macro_dof*macro_node_to_col.size());
shapefunctions.setFromTriplets(tripletList.begin(), tripletList.end());
//Construct the DOF solver
std::cout << " Performing QR decomposition\n";
dof_solver.compute(shapefunctions);
if (dof_solver.info()!=Eigen::Success){
std::cout << "Error: Failure in QR decomposition.\n";
return 1;
}
//Populate the reference coordinate map
populate_reference_coordinates(data, shared_dof_material, mp_format, dof_format, reference_coordinates);
}
std::cout << "Compute deformation properties\n";
for (auto filter=filters.begin(); filter!=filters.end(); filter++){
filter->second.compute_deformation_properties();
}
for (auto filter = filters.begin(); filter!=filters.end(); filter++){
filter->second.write_to_file(output_file);
}
return 0;
}
int process_timestep(const elib::vecOfvec &data, const input_format &mp_format,
const input_format &dof_format, const assembly::node_map &nodes,
const assembly::element_map &elements, const assembly::qrule_map &qrules,
const unsigned int mode, const bool shared_dof_material,
std::map< unsigned int, unsigned int > ¯o_node_to_col,
std::map< unsigned int, unsigned int > µ_node_to_row,
std::map< unsigned int, unsigned int > µ_node_elcount,
std::map< unsigned int, elib::vec > &reference_coordinates,
overlap::SpMat &shapefunctions, overlap::QRsolver &dof_solver, filter_map &filters,
std::ofstream &output_file){
/*!
* Process the current timestep and compute the macro-scale stress and deformation quantities
*
* :param const elib::vecOfvec &data: The DNS data at the current timestep.
* :param const input_format &mp_format: The format of a material point dataline
* :param const input_format &dof_format: The format of a degree of freedom dataline
* :param const assembly::node_map &nodes: The nodes of the micromorphic filter.
* :param const assembly::element_map &elements: The elements of the micromorphic filter.
* :param const assembly::qrule_map &qrules: The quadrature rules for the elements.
* :param const unsigned int mode: The mode that the filter is operating in.
* Options:
* 0 Total Lagrangian. If filters is empty, it will be assumed that
* the current timestep is the reference configuration.
* :param bool shared_dof_material: Flag which indicates if the dof and material information are
* co-located.
* :param std::map< unsigned int, unsigned int > ¯o_node_to_col: The map from macro nodes to the corresponding
* column of the matrix (normalized by the num_macro_dof)
* :param std::map< unsigned int, unsigned int > µ_node_to_row: The map from micro nodes to the corresponding
* row of the matrix (normalized by the num_micro_dof)
* :param std::map< unsigned int, unsigned int > µ_node_elcount: The number of macro elements (filters)
* containing the given micro node. Only occurs for micro nodes on the boundaries between two filters and
* is only populated for nodes greater than 1.
* :param std::map< unsigned int, elib::vec > &reference_coordinates: The reference coordinates used to compute
* the change in position of the dof points.
* :param overlap::SpMat &shapefunctions: The shapefunction matrix.
* :param overlap::QRsolver &dof_solver: The solver for the degrees of freedom.
* :param filter_map &filters: Return map of the element ids to their corresponding sub-filters.
* :param std::ofstream &output_file: The file to write the output data to
*/
if (mode == 0){
return process_timestep_totalLagrangian(data, mp_format, dof_format, nodes, elements, qrules,
shared_dof_material, macro_node_to_col, micro_node_to_row,
micro_node_elcount, reference_coordinates,
shapefunctions, dof_solver, filters, output_file);
}
return 1;
}
int print(const std::map< unsigned int, unsigned int > &map){
/*!
* print the map to the terminal
*/
for (auto it=map.begin(); it!=map.end(); it++){
std::cerr << it->first << ": " << it->second << "\n";
}
return 0;
}
int print(const uint_to_vec &map){
/*!
* print the map to the terminal
*/
for (auto it=map.begin(); it!=map.end(); it++){
std::cerr << it->first << ": "; elib::print(it->second);
}
return 0;
}
int print(const input_format &format){
/*!
* print the format to the terminal
*/
for (auto it=format.begin(); it!=format.end(); it++){
std::cerr << it->first << ": " << it->second[0] << ", " << it->second[1] << "\n";
}
return 0;
}
}
int main(int argc, char **argv){
/*!
* Main
*
* Read in an input file and write out the filtered values.
*
* format should be:
* ./filter input_filename filter_filename output_filename
*/
std::string input_fn;
std::string filter_fn;
std::string output_fn;
std::ifstream input_file;
std::ofstream output_file;
elib::vecOfvec data;
std::cout << "\n\n";
std::cout << "###########################\n";
std::cout << "### MICROMORPHIC FILTER ###\n";
std::cout << "###########################\n";
std::cout << "\n";
std::cout << " author: Nathan Miller\n";
std::cout << " email: nathanm@lanl.gov\n\n";
int format=1; //Hard-coded to format 1
int mode=0; //Hard-coded to total Lagrangian
bool shared_dof_material = 1; //Hard-coded to co-located information
//TODO: There are errors when non-colocated information is used.
if (argc != 4){
std::cout << "argc: " << argc << "\n";
std::cout << "Error: require three filenames. A dns data filename to read, a filter definition, and a filename to write.\n";
}
else{
input_fn = argv[1];
filter_fn = argv[2];
output_fn = argv[3];
std::cout << "Opening filter definition file.\n";
//Open the filter definition file
assembly::node_map nodes;
assembly::element_map elements;
assembly::qrule_map qrules;
overlap::SpMat shapefunctions;
overlap::QRsolver dof_solver;
filter::input_format mp_format;
filter::input_format dof_format;
filter::filter_map filters;
filter::uint_map macro_node_to_col;
filter::uint_map micro_node_to_row;
filter::uint_map micro_node_elcount;
std::map< unsigned int, elib::vec > reference_coordinates;
int connresult = assembly::read_connectivity_data(filter_fn, nodes, elements, qrules);
if (connresult > 1){
std::cout << "Error in constructing filter\n";
return 1;
}
output_file.open(output_fn);
output_file << "*INPUT_FILE, " << input_fn << "\n";
output_file << "*FILTER_CONFIGURATION_FILE, " << filter_fn << "\n";
//Open the dns file
std::cout << "Opening micro-scale data file.\n";
int openresult = filter::open_input_file(input_fn, format, input_file);
if (openresult>0){
std::cout << "Error in opening the DNS input file\n";
return 1;
}
//Read past the header
int headerresult = filter::read_past_header(input_file, mp_format, dof_format, format);
if (headerresult>0){
std::cout << "Error in skipping the header.\n Check the input file format.\n";
return 1;
}
//Read the timeseries
while (!input_file.eof()){
data.resize(0);
int filterresult = filter::read_timestep(input_file, format, output_file, data);
if (filterresult>0){
std::cout << "Error reading timestep.\n";
return 1;
}
std::cout << "Initializing filters\n";
int pt_result = filter::process_timestep(data, mp_format, dof_format, nodes, elements, qrules,
mode, shared_dof_material,
macro_node_to_col, micro_node_to_row, micro_node_elcount,
reference_coordinates,
shapefunctions, dof_solver, filters, output_file);
if (pt_result > 0){
std::cout << "Error in processing timestep\n";
return 1;
}
else{
std::cout << "Timestep processing successful\n\n";
}
}
output_file.close();
}
std::cout << "Processing of input file " << input_fn << " completed.\n";
std::cout << "Output written to " << output_fn << "\n";
return 0;
}
| 43.951993 | 142 | 0.56332 | [
"object",
"shape",
"vector"
] |
cdf1f45159e98fbc8b69b282a5b5d69904c8aa31 | 2,148 | cpp | C++ | 0399-Evaluate Division/0399-Evaluate Division.cpp | zhuangli1987/LeetCode-1 | e81788abf9e95e575140f32a58fe983abc97fa4a | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 0301-0400/0399-Evaluate Division/0399-Evaluate Division.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 0301-0400/0399-Evaluate Division/0399-Evaluate Division.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class Solution {
public:
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
int n = equations.size();
for (int i = 0; i < n; ++i) {
string eq1 = equations[i].first;
string eq2 = equations[i].second;
Node *node1, *node2;
if (table.find(equations[i].first) != table.end()) {
node1 = table[eq1];
}
else {
node1 = new Node(values[i]);
table[eq1] = node1;
}
if (table.find(equations[i].second) != table.end()) {
node2 = table[eq2];
}
else {
node2 = new Node(1);
table[eq2] = node2;
}
Node* parent1 = findParent(node1);
Node* parent2 = findParent(node2);
if (parent1 != parent2) {
double ratio = node2->val * values[i] / node1->val;
for (auto it = table.begin(); it != table.end(); ++it) {
if (findParent(it->second) == parent1) {
it->second->val *= ratio;
}
}
parent2->parent = parent1;
}
}
vector<double> result;
for (auto& p : queries) {
if (table.find(p.first) == table.end() || table.find(p.second) == table.end() || findParent(table[p.first]) != findParent(table[p.second])) {
result.push_back(-1);
}
else {
result.push_back(table[p.first]->val / table[p.second]->val);
}
}
return result;
}
private:
struct Node {
Node* parent;
double val;
Node(double v) : val(v) {parent = this;}
};
unordered_map<string, Node*> table;
Node* findParent(Node* node) {
while (node->parent != node) {
node->parent = node->parent->parent;
node = node->parent;
}
return node;
}
};
| 31.588235 | 153 | 0.442272 | [
"vector"
] |
cdf2dd3609e56c471a6f5c2f6617c6efa9af924a | 3,385 | hpp | C++ | src/include/functional/functional.hpp | boazsade/machine_learinig_models | eb1f9eda0e4e25a6d028b25682dfb20628a20624 | [
"MIT"
] | null | null | null | src/include/functional/functional.hpp | boazsade/machine_learinig_models | eb1f9eda0e4e25a6d028b25682dfb20628a20624 | [
"MIT"
] | null | null | null | src/include/functional/functional.hpp | boazsade/machine_learinig_models | eb1f9eda0e4e25a6d028b25682dfb20628a20624 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <iostream>
#include <cassert>
// type erasure holder that can hide the actual implementation
// and allow using different actions that exposes the same interface
// note that these actions are not related, but only need to be supported
// with the global functions "preform_action" they all
// defined with input and output types, but the actual action is hidden
// note that for generic invokation (not when we need to store something),
// there is an invake and apply in the standard C++ 17 and onward, that togheter
// with lambda can achive the same things, only problem with these is that you
// cannot build a sort of pipeline of operations that doing different things internally
// but look uniform from the outside
template<typename Arg, typename Res>
struct poli_function
{
using arg_type = Arg;
using result_type = Res;
poli_function() = default;
template<typename T>
poli_function(T underlay_data) :
impl(std::make_shared<object<T>>(std::move(underlay_data)))
{
}
template<typename T>
poli_function& operator = (T fi)
{
impl = std::make_shared<object<T>>(std::move(fi));
return *this;
}
static result_type preform(const poli_function& self,
const arg_type& args)
{
return self.impl->preform(args);
}
static std::ostream& print(const poli_function& self,
std::ostream& os)
{
assert(self.impl);
return self.impl->print(os);
}
template<typename A, typename R>
poli_function<A, R>
rebind() const
{
poli_function<A, R> result{impl};
return result;
}
static std::string as_string(const poli_function& me)
{
return me.impl->as_string();
}
private:
struct interface
{
virtual ~interface() = default;
virtual std::ostream& print(std::ostream& os) const = 0;
virtual result_type preform(const arg_type& args) const = 0;
virtual std::string as_string() const = 0;
};
template<typename Underlay>
struct object : interface
{
object(Underlay td) :
action(std::move(td))
{
}
std::ostream& print(std::ostream& os) const
{
return os<<action;
}
result_type preform(const arg_type& args) const
{
return preform_action(action, args);
}
std::string as_string() const
{
return to_string(action);
}
Underlay action;
};
using impl_type = std::shared_ptr<interface>;
poli_function(impl_type ip) :
impl{ip}
{
}
impl_type impl;
};
template<typename A, typename R> inline
R preform_action(const poli_function<A, R>& with, const A& args)
{
return poli_function<A, R>::preform(with, args);
}
template<typename A, typename R> inline
std::ostream& operator << (std::ostream& os, const poli_function<A, R>& action)
{
return poli_function<A, R>::print(action, os);
}
template<typename A1, typename R1, typename A2, typename R2>
inline poli_function<A1, R1> rebind(poli_function<A2, R2> from)
{
return from.template rebind<A1, R1>();
}
template<typename A, typename R> inline
std::string to_string(const poli_function<A, R>& action) {
return poli_function<A, R>::as_string(action);
}
| 25.451128 | 87 | 0.64195 | [
"object"
] |
cdf7d11bab8c2c2a7d36352511cb80d5c71bed6d | 1,177 | cpp | C++ | IOPi/tests/set_bus_pullups.cpp | Sephiroth1402/ABElectronics_CPP_Libraries | e1b5f2c2ac691bb096aa2a2bf9af1cf2d26251b4 | [
"MIT"
] | null | null | null | IOPi/tests/set_bus_pullups.cpp | Sephiroth1402/ABElectronics_CPP_Libraries | e1b5f2c2ac691bb096aa2a2bf9af1cf2d26251b4 | [
"MIT"
] | null | null | null | IOPi/tests/set_bus_pullups.cpp | Sephiroth1402/ABElectronics_CPP_Libraries | e1b5f2c2ac691bb096aa2a2bf9af1cf2d26251b4 | [
"MIT"
] | null | null | null | /*
set_bus_pullups.cpp
Version 1.0 Created 01/07/2020
compile with "g++ set_bus_pullups.cpp ../ABE_IoPi.cpp -Wall -Wextra -Wpedantic -Woverflow -o set_bus_pullups"
run with "./set_bus_pullups"
This test validates the set_bus_pullups method in the IOPi class.
Hardware Required: Logic Analyser on I2C Pins
=== Expected Result ============================
> Console Output:
Logic output Started
Logic output Ended
> Logic Analyser Output:
W 0x20 0xA0 0x02
W 0x20 0x0C 0x00 0x00
looping to
W 0x20 0x0C 0xFE 0xFF
"""
*/
#include <stdio.h>
#include <stdexcept>
#include <unistd.h>
#include <iostream>
#include "../ABE_IoPi.h"
using namespace std;
void clearscreen()
{
printf("\033[2J\033[1;1H");
}
int main(int argc, char **argv)
{
setvbuf(stdout, NULL, _IONBF, 0); // needed to print to the command line
using namespace ABElectronics_CPP_Libraries;
IoPi bus(0x20, false); // new iopi object without initialisation
// Logic Analyser Check
cout << "Logic output Started\n";
for (uint16_t a = 0; a < 65535; a++){
bus.set_bus_pullups(a);
}
cout << "Logic output Ended\n";
(void)argc;
(void)argv;
return (0);
}
| 17.308824 | 115 | 0.672048 | [
"object"
] |
cdfcc56329d0c9bc23049f92a7b8a540448f66f7 | 13,231 | cpp | C++ | raideng/scsi_con.cpp | barak/raidutils | 8eed7a577ac4565da324cd742e8f1afe7ae101e0 | [
"BSD-3-Clause"
] | null | null | null | raideng/scsi_con.cpp | barak/raidutils | 8eed7a577ac4565da324cd742e8f1afe7ae101e0 | [
"BSD-3-Clause"
] | null | null | null | raideng/scsi_con.cpp | barak/raidutils | 8eed7a577ac4565da324cd742e8f1afe7ae101e0 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 1996-2004, Adaptec Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of 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 Adaptec 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.
*/
//File - SCSI_CON.CPP
//***************************************************************************
//
//Description:
//
// This file contains the function definitions for the dptSCSIcon_C
//class.
//
//Author: Doug Anderson
//Date: 3/9/93
//
//Editors:
//
//Remarks:
//
//
//***************************************************************************
//Include Files -------------------------------------------------------------
#include "allfiles.hpp"
//Function - dptSCSIcon_C::dptSCSIcon_C() - start
//===========================================================================
//
//Description:
//
// This function is the constructor for the dptSCSIcon_C class.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
dptSCSIcon_C::dptSCSIcon_C()
{
// Clear all flags
flags = 0;
// Default = Return the first 6 bytes as the ID
idSize = 6;
// Default = 15 I/O slots supported
maxSlots = 15;
}
//dptSCSIcon_C::dptSCSIcon_C() - end
//Function - dptSCSIcon_C::preAddSuppress() - start
//===========================================================================
//
//Description:
//
// This function positions the suppress device list to add devices
//in SCSI address order.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
void dptSCSIcon_C::preAddSuppress(dptCoreDev_C *dev_P)
{
// Position the list to add the device in SCSI addr order
positionSCSI(suppressList,((dptSCSIdev_C *)dev_P)->getAddr());
}
//dptSCSIcon_C::preAddSuppress() - end
//Function - dptSCSIcon_C::isDupName() - start
//===========================================================================
//
//Description:
//
// This function checks for a duplicate DPT name.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
uSHORT dptSCSIcon_C::isDupName(uCHAR *inStr_P,uSHORT inLimit)
{
uSHORT duplicate = 0;
dptDevice_C *dev_P;
dptObject_C *obj_P = (dptObject_C *) objectList.reset();
while ((obj_P!=NULL) && !duplicate) {
if (obj_P->isDevice()) {
// Cast the object as a device
dev_P = (dptDevice_C *) obj_P;
// If the DPT name exists...
if (findSubString(inStr_P,dev_P->dptName,inLimit,DPT_NAME_SIZE,0))
duplicate = 1;
}
obj_P = (dptObject_C *) objectList.next();
}
return (duplicate);
}
//dptSCSIcon_C::isDupName() - end
//Function - dptSCSIcon_C::rtnIDfromData() - start
//===========================================================================
//
//Description:
//
// This function traverses the master object list returning the IDs
//of the objects with data that matches the specified input data.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
DPT_RTN_T dptSCSIcon_C::rtnIDfromData(dptBuffer_S *fromEng_P,
dptBuffer_S *toEng_P,
uSHORT action
)
{
DPT_RTN_T retVal = MSG_RTN_COMPLETED;
uCHAR mask = 0;
uCHAR rtnFlags = 0;
uCHAR level = 0xff;
uCHAR dataMatch;
access_U inData;
access_U objData;
inData.u32 = 0;
// If no data was specified...
if (!toEng_P->extract(inData.u8,4))
inData.u32 = 0;
if (toEng_P->extract(mask)) {
rtnFlags = (mask & 0xc0);
mask = (~mask) & 0xf;
}
if (action!=1)
toEng_P->extract(level);
dptSCSIobj_C *obj_P = (dptSCSIobj_C *) objectList.reset();
while (obj_P!=NULL) {
if (action==1)
// Get the object's status
objData.u32 = obj_P->status.getLong();
else {
// Update the object's HBA #
obj_P->updateHBAnum();
// Get the object's SCSI address
objData.u32 = obj_P->getAddrL();
#ifdef _DPT_BIG_ENDIAN
trueSwap4(&objData.u32);
#endif
}
dataMatch = 0;
if (objData.u8[3]==inData.u8[0])
dataMatch |= 0x8;
if (objData.u8[2]==inData.u8[1])
dataMatch |= 0x4;
if (objData.u8[1]==inData.u8[2])
dataMatch |= 0x2;
if (objData.u8[0]==inData.u8[3])
dataMatch |= 0x1;
// If a data match was found...
if ((dataMatch&mask)==mask) {
dataMatch = 0;
if (rtnFlags & 0x80) {
if (obj_P->isDevice()) {
if (rtnFlags==0x80)
dataMatch = 1;
}
else if (rtnFlags==0xc0)
dataMatch = 1;
}
else
dataMatch = 1;
}
else
dataMatch = 0;
if (dataMatch) {
// If all levels are to be returned...
if (level==0xff)
// Return the object's ID structure
retVal = obj_P->returnID(fromEng_P);
// If a specific level is to be returned...
else if (obj_P->getLevel()==level)
// Return the object's ID structure
retVal = obj_P->returnID(fromEng_P);
}
// Get the next object in the list
obj_P = (dptSCSIobj_C *) objectList.next();
}
return (retVal);
}
//dptSCSIcon_C::rtnIDfromData() - end
//Function - dptSCSIcon_C::rtnIDfromASCII() - start
//===========================================================================
//
//Description:
//
// This function traverses the master object list returning the IDs
//of the objects with matching ASCII data.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
DPT_RTN_T dptSCSIcon_C::rtnIDfromASCII(dptBuffer_S *fromEng_P,
dptBuffer_S *toEng_P,
uSHORT action
)
{
DPT_RTN_T retVal = MSG_RTN_COMPLETED;
uSHORT inLimit = 0;
uSHORT searchLimit = 0;
uCHAR *in_P;
uCHAR *search_P;
uCHAR searchType = 0;
// Determine the # of data bytes input
while (toEng_P->extract(searchType))
inLimit++;
if (searchType>2)
searchType = 0;
if (inLimit>0)
in_P = (uCHAR *) toEng_P->data;
dptSCSIobj_C *obj_P = (dptSCSIobj_C *) objectList.reset();
while (obj_P!=NULL) {
search_P = NULL;
// Get a pointer to the ASCII field to search
switch (action) {
case 0: search_P = (uCHAR *) obj_P->descr.vendorID;
searchLimit = 8;
break;
case 1: search_P = (uCHAR *) obj_P->descr.productID;
searchLimit = 16;
break;
case 2: search_P = (uCHAR *) obj_P->descr.revision;
searchLimit = 4;
break;
case 3: search_P = (uCHAR *) obj_P->descr.vendorExtra;
searchLimit = 20;
break;
case 4: if (obj_P->isDevice())
search_P = ((dptSCSIdev_C *)obj_P)->dptName;
searchLimit = 16;
break;
}
if (search_P!=NULL) {
if (findSubString(in_P,search_P,inLimit,searchLimit,searchType))
retVal = obj_P->returnID(fromEng_P);
}
// Get the next object in the list
obj_P = (dptSCSIobj_C *) objectList.next();
}
return (retVal);
}
//dptSCSIcon_C::rtnIDfromASCII() - end
//Function - dptSCSIcon_C::rtnHidden() - start
//===========================================================================
//
//Description:
//
// This function returns the IDs of all suppressed devices with no
//RAID parent.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
DPT_RTN_T dptSCSIcon_C::rtnHidden(dptBuffer_S *fromEng_P,uSHORT rtnAll)
{
DPT_RTN_T retVal = MSG_RTN_COMPLETED;
dptRAIDdev_C *raid_P;
raid_P = (dptRAIDdev_C *) suppressList.reset();
while (raid_P!=NULL) {
// If the suppressed device has no RAID parent...
if (!raid_P->isComponent()) {
retVal = raid_P->returnID(fromEng_P);
if (rtnAll)
retVal = rtnFromList(raid_P->compList,fromEng_P,DPT_ANY_OBJECT,OPT_TRAVERSE_COMP,0,0xffff);
}
// Get the next suppressed device
raid_P = (dptRAIDdev_C *) suppressList.next();
}
return (retVal);
}
//dptSCSIcon_C::rtnHidden() - end
//Function - dptSCSIcon_C::rtnSysConfig() - start
//===========================================================================
//
//Description:
//
// This function returns the system configuration to the specified
//output buffer.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
DPT_RTN_T dptSCSIcon_C::rtnSysConfig(dptBuffer_S *fromEng_P)
{
DPT_RTN_T retVal;
// Return the information structure for all level 1 managers (HBAs)
rtnConfigLevel(DPT_ANY_MANAGER,1,fromEng_P);
// Return the information structure for all level 2 managers (BCDs)
rtnConfigLevel(DPT_ANY_MANAGER,2,fromEng_P);
// Return the information structure for all level 3 devices
rtnConfigLevel(DPT_ANY_DEVICE,3,fromEng_P);
// Return the information structure for all level 2 devices
rtnConfigLevel(DPT_ANY_DEVICE,2,fromEng_P);
// Return the information structure for all level 1 devices
rtnConfigLevel(DPT_ANY_DEVICE,1,fromEng_P);
// Return the information structure for all level 0 devices
retVal = rtnConfigLevel(DPT_ANY_DEVICE,0,fromEng_P);
return (retVal);
}
//dptSCSIcon_C::rtnSysConfig() - end
//Function - dptSCSIcon_C::rtnConfigLevel() - start
//===========================================================================
//
//Description:
//
// This function returns objects of the specified level to the
//specified output buffer.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
DPT_RTN_T dptSCSIcon_C::rtnConfigLevel(uSHORT inType,
uSHORT inLevel,
dptBuffer_S *fromEng_P
)
{
DEBUG_BEGIN(6, dptSCSIcon_C::rtnConfigLevel());
DPT_RTN_T retVal = MSG_RTN_COMPLETED;
dptObject_C *obj_P = (dptObject_C *) objectList.reset();
while (obj_P!=NULL) {
if (obj_P->getLevel()==inLevel) {
if (obj_P->isManager() && (inType==DPT_ANY_MANAGER))
// Return the manager info
retVal = obj_P->rtnConfigInfo(fromEng_P);
else if ( obj_P->isDevice() && (inType==DPT_ANY_DEVICE))
// Return the device info
retVal = obj_P->rtnConfigInfo(fromEng_P);
DEBUG(5, PRT_DADDR(obj_P) << "Returning Level " << (int)inLevel << " Info successful");
}
obj_P = (dptObject_C *) objectList.next();
}
return (retVal);
}
//dptSCSIcon_C::rtnConfigLevel() - end
//Function - dptSCSIcon_C::findConfigMgr() - start
//===========================================================================
//
//Description:
//
// This function attempts to find the specified manager when loading
//a configuration file.
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------
dptManager_C * dptSCSIcon_C::findConfigMgr(uSHORT inLevel,
dptAddr_S inAddr
)
{
uSHORT done = 0;
dptManager_C *mgr_P = (dptManager_C *) objectList.reset();
while ((mgr_P!=NULL) && !done) {
if (mgr_P->isManager()) {
if (inLevel==1) {
if (inAddr.hba==mgr_P->getHBA())
done = 1;
}
else if (inAddr==mgr_P->getAddr())
done = 1;
}
if (!done)
mgr_P = (dptManager_C *) objectList.next();
}
return (mgr_P);
}
//dptSCSIcon_C::findConfigMgr() - end
| 25.395393 | 93 | 0.592699 | [
"object"
] |
cdfdf6448e757601fa5bd74db7fd36d56b660a30 | 12,117 | cpp | C++ | darkness-engine/include/shaders/core/ibl/Irradiance.ps.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 6 | 2019-10-17T11:31:55.000Z | 2022-02-11T08:51:20.000Z | darkness-engine/include/shaders/core/ibl/Irradiance.ps.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-08-11T09:01:29.000Z | 2020-08-11T09:01:29.000Z | darkness-engine/include/shaders/core/ibl/Irradiance.ps.cpp | Karmiska/Darkness | c87eaf067a2707a0141909125ff461f69a3812e0 | [
"MIT"
] | 1 | 2020-06-02T15:48:20.000Z | 2020-06-02T15:48:20.000Z | #include "Irradiance.ps.h"
#include "engine/graphics/ShaderStorage.h"
#include "engine/graphics/Sampler.h"
#include "tools/ByteRange.h"
#include "tools/Debug.h"
#include <memory>
namespace engine
{
namespace shaders
{
#pragma warning( push )
#pragma warning( disable : 4702 )
std::shared_ptr<const ShaderBinary> IrradiancePS::load(const Device& device, ShaderStorage& storage) const
{
return storage.loadShader(device, "C:/work/darkness/darkness-engine/data/shaders/vulkan/core/ibl/Irradiance.ps.spv", "C:/work/darkness/darkness-engine/data/shaders/vulkan/core/ibl/Irradiance.ps.support", -1, {});
ASSERT(false, "Could not load the permutation necessary. This is a bug.");
return {};
}
#pragma warning( pop )
IrradiancePS::IrradiancePS()
: m_constantRange{
}
, m_inputParameters
{
ShaderInputParameter{"position", "SV_Position0", "float4"}
,
ShaderInputParameter{"pos", "NORMAL", "float4"}
}
{}
#pragma warning( push )
#pragma warning( disable : 4100 )
IrradiancePS::IrradiancePS(const IrradiancePS& cl)
: m_constantRange{
}
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = cl.m_constantRange[i].buffer;
}
environmentMap = cl.environmentMap;
environmentSampler = cl.environmentSampler;
}
#pragma warning( pop )
#pragma warning( push )
#pragma warning( disable : 4100 )
IrradiancePS::IrradiancePS(IrradiancePS&& cl)
: m_constantRange{
}
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = std::move(cl.m_constantRange[i].buffer);
}
environmentMap = std::move(cl.environmentMap);
environmentSampler = std::move(cl.environmentSampler);
}
#pragma warning( pop )
#pragma warning( push )
#pragma warning( disable : 4100 )
IrradiancePS& IrradiancePS::operator=(const IrradiancePS& cl)
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = cl.m_constantRange[i].buffer;
}
environmentMap = cl.environmentMap;
environmentSampler = cl.environmentSampler;
return *this;
}
#pragma warning( pop )
#pragma warning( push )
#pragma warning( disable : 4100 )
IrradiancePS& IrradiancePS::operator=(IrradiancePS&& cl)
{
for (int i = 0; i < m_constantRange.size(); ++i)
{
m_constantRange[i].buffer = std::move(cl.m_constantRange[i].buffer);
}
environmentMap = std::move(cl.environmentMap);
environmentSampler = std::move(cl.environmentSampler);
return *this;
}
#pragma warning( pop )
std::vector<std::string> IrradiancePS::textureSrvNames() const
{
return {
"environmentMap"
};
}
std::vector<std::string> IrradiancePS::textureUavNames() const
{
return {
};
}
std::vector<std::string> IrradiancePS::bufferSrvNames() const
{
return {
};
}
std::vector<std::string> IrradiancePS::bufferUavNames() const
{
return {
};
}
std::vector<std::string> IrradiancePS::samplerNames() const
{
return {
"environmentSampler"
};
}
std::vector<std::string> IrradiancePS::srvNames() const
{
return {
"environmentMap"
};
}
std::vector<std::string> IrradiancePS::uavNames() const
{
return {
};
}
#pragma warning( push )
#pragma warning( disable : 4100 )
engine::ResourceDimension IrradiancePS::textureDimension(const std::string& name) const
{
if("environmentMap" == name) return engine::ResourceDimension::TextureCubemap;
return engine::ResourceDimension::Unknown;
}
#pragma warning( pop )
std::vector<TextureSRV> IrradiancePS::texture_srvs() const
{
std::vector<TextureSRV> result;
result.emplace_back(environmentMap);
return result;
}
std::vector<TextureUAV> IrradiancePS::texture_uavs() const
{
std::vector<TextureUAV> result;
return result;
}
std::vector<BufferSRV> IrradiancePS::buffer_srvs() const
{
std::vector<BufferSRV> result;
return result;
}
std::vector<BufferUAV> IrradiancePS::buffer_uavs() const
{
std::vector<BufferUAV> result;
return result;
}
std::vector<TextureBindlessSRV> IrradiancePS::bindless_texture_srvs() const
{
std::vector<TextureBindlessSRV> result;
return result;
}
std::vector<TextureBindlessUAV> IrradiancePS::bindless_texture_uavs() const
{
std::vector<TextureBindlessUAV> result;
return result;
}
std::vector<BufferBindlessSRV> IrradiancePS::bindless_buffer_srvs() const
{
std::vector<BufferBindlessSRV> result;
return result;
}
std::vector<BufferBindlessUAV> IrradiancePS::bindless_buffer_uavs() const
{
std::vector<BufferBindlessUAV> result;
return result;
}
std::vector<Shader::ConstantRange>& IrradiancePS::constants()
{
return m_constantRange;
}
std::vector<Sampler> IrradiancePS::samplers() const
{
std::vector<Sampler> result;
result.emplace_back(environmentSampler);
return result;
}
const std::vector<ShaderInputParameter>& IrradiancePS::inputParameters() const
{
return m_inputParameters;
}
// warning C4172: returning address of local variable or temporary
// this will never happen as the name will always match the correct resource
#pragma warning( push )
#pragma warning( disable : 4172 )
#pragma warning( disable : 4100 )
bool IrradiancePS::hasTextureSrv(const std::string& name) const
{
if(name == std::string("environmentMap")) return true;
return false;
}
bool IrradiancePS::hasTextureUav(const std::string& name) const
{
return false;
}
bool IrradiancePS::hasBufferSrv(const std::string& name) const
{
return false;
}
bool IrradiancePS::hasBufferUav(const std::string& name) const
{
return false;
}
bool IrradiancePS::hasBindlessTextureSrv(const std::string& name) const
{
return false;
}
bool IrradiancePS::hasBindlessTextureUav(const std::string& name) const
{
return false;
}
bool IrradiancePS::hasBindlessBufferSrv(const std::string& name) const
{
return false;
}
bool IrradiancePS::hasBindlessBufferUav(const std::string& name) const
{
return false;
}
const TextureSRV& IrradiancePS::textureSrv(const std::string& name) const
{
if(name == std::string("environmentMap")) return environmentMap;
ASSERT(false, "Tried to look for non-existing resource");
return TextureSRV();
}
const TextureUAV& IrradiancePS::textureUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return TextureUAV();
}
const BufferSRV& IrradiancePS::bufferSrv(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferSRV();
}
const BufferUAV& IrradiancePS::bufferUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferUAV();
}
void IrradiancePS::textureSrv(const std::string& name, TextureSRV& texture)
{
if(name == std::string("environmentMap")) { environmentMap = texture; return; }
ASSERT(false, "Tried to set non-existing resource");
}
void IrradiancePS::textureUav(const std::string& name, TextureUAV& texture)
{
ASSERT(false, "Tried to set non-existing resource");
}
void IrradiancePS::bufferSrv(const std::string& name, BufferSRV& buffer)
{
ASSERT(false, "Tried to set non-existing resource");
}
void IrradiancePS::bufferUav(const std::string& name, BufferUAV& buffer)
{
ASSERT(false, "Tried to set non-existing resource");
}
const Sampler& IrradiancePS::sampler(const std::string& name) const
{
if(name == std::string("environmentSampler")) return environmentSampler;
ASSERT(false, "Tried to look for non-existing resource");
return Sampler();
}
const TextureBindlessSRV& IrradiancePS::bindlessTextureSrv(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return TextureBindlessSRV();
}
const TextureBindlessUAV& IrradiancePS::bindlessTextureUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return TextureBindlessUAV();
}
const BufferBindlessSRV& IrradiancePS::bindlessBufferSrv(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferBindlessSRV();
}
const BufferBindlessUAV& IrradiancePS::bindlessBufferUav(const std::string& name) const
{
ASSERT(false, "Tried to look for non-existing resource");
return BufferBindlessUAV();
}
#pragma warning( pop )
uint32_t IrradiancePS::descriptorCount() const
{
return 1;
}
}
} | 24.041667 | 224 | 0.494842 | [
"vector"
] |
a80497acf68e2f409a5e6a6802ef79b78d5eb4e0 | 11,297 | cc | C++ | xls/jit/proc_builder_visitor.cc | AdrianaDJ/xls | c6672aec22a13a5761a8cd29968bf317177b95b7 | [
"Apache-2.0"
] | null | null | null | xls/jit/proc_builder_visitor.cc | AdrianaDJ/xls | c6672aec22a13a5761a8cd29968bf317177b95b7 | [
"Apache-2.0"
] | null | null | null | xls/jit/proc_builder_visitor.cc | AdrianaDJ/xls | c6672aec22a13a5761a8cd29968bf317177b95b7 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xls/jit/proc_builder_visitor.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
namespace xls {
absl::Status ProcBuilderVisitor::Visit(
llvm::Module* module, llvm::Function* llvm_fn, FunctionBase* xls_fn,
LlvmTypeConverter* type_converter, bool is_top, bool generate_packed,
JitChannelQueueManager* queue_mgr, RecvFnT recv_fn, SendFnT send_fn) {
ProcBuilderVisitor visitor(module, llvm_fn, xls_fn, type_converter, is_top,
generate_packed, queue_mgr, recv_fn, send_fn);
return visitor.BuildInternal();
}
ProcBuilderVisitor::ProcBuilderVisitor(
llvm::Module* module, llvm::Function* llvm_fn, FunctionBase* xls_fn,
LlvmTypeConverter* type_converter, bool is_top, bool generate_packed,
JitChannelQueueManager* queue_mgr, RecvFnT recv_fn, SendFnT send_fn)
: FunctionBuilderVisitor(module, llvm_fn, xls_fn, type_converter, is_top,
generate_packed),
queue_mgr_(queue_mgr),
recv_fn_(recv_fn),
send_fn_(send_fn) {}
absl::StatusOr<llvm::Value*> ProcBuilderVisitor::InvokeRecvCallback(
llvm::IRBuilder<>* builder, JitChannelQueue* queue, Node* node) {
llvm::Type* void_type = llvm::Type::getVoidTy(ctx());
llvm::Type* int64_type = llvm::Type::getInt64Ty(ctx());
llvm::Type* int8_ptr_type = llvm::Type::getInt8PtrTy(ctx(), 0);
// To actually receive a message, we'll be pulling it from some queue (that
// will be known at JIT compilation time). Rather than trying to code that
// up as LLVM IR, we provide the dequeue operation as an external function
// (currently "DequeueMessage"). To call such a function - being defined
// outside LLVM - we need to:
// 1) conceptually add it to our module under construction, which requires
// defining its signature to LLVM,
// LLVM doesn't like void* types, so we use int64s instead.
std::vector<llvm::Type*> params(
{int64_type, int64_type, int8_ptr_type, int64_type, int64_type});
llvm::FunctionType* fn_type =
llvm::FunctionType::get(void_type, params, /*isVarArg=*/false);
llvm::Type* recv_type = type_converter()->ConvertToLlvmType(node->GetType());
int64 recv_bytes = type_converter()->GetTypeByteSize(node->GetType());
llvm::AllocaInst* alloca = builder->CreateAlloca(recv_type);
// 2) create the argument list to pass to the function. We use opaque
// pointers to our data elements, to avoid recursively defining every
// type used by every type and so on.
static_assert(sizeof(Receive) == sizeof(ReceiveIf));
std::vector<llvm::Value*> args({
llvm::ConstantInt::get(int64_type, reinterpret_cast<uint64>(queue)),
// This is sinful, I know, but ReceiveIf and Receive are
// layout-compatible..._for now_ (hence the static_assert above).
// TODO(meheff) : Make Receive & ReceiveIf share a common base
// class (also Send & SendIf).
llvm::ConstantInt::get(int64_type, reinterpret_cast<uint64>(node)),
builder->CreatePointerCast(alloca, int8_ptr_type),
llvm::ConstantInt::get(int64_type, recv_bytes),
llvm_fn()->getArg(llvm_fn()->arg_size() - 1),
});
// 3) finally emit the function call,
llvm::ConstantInt* fn_addr = llvm::ConstantInt::get(
llvm::Type::getInt64Ty(ctx()), reinterpret_cast<uint64>(recv_fn_));
llvm::Value* fn_ptr =
builder->CreateIntToPtr(fn_addr, llvm::PointerType::get(fn_type, 0));
builder->CreateCall(fn_type, fn_ptr, args);
// 4) then load its result from the bounce buffer.
return builder->CreateLoad(alloca);
}
absl::Status ProcBuilderVisitor::HandleReceive(Receive* recv) {
XLS_ASSIGN_OR_RETURN(JitChannelQueue * queue,
queue_mgr_->GetQueueById(recv->channel_id()));
XLS_ASSIGN_OR_RETURN(llvm::Value * invoke,
InvokeRecvCallback(builder(), queue, recv));
llvm::Value* result =
builder()->CreateInsertValue(invoke, type_converter()->GetToken(), {0});
return StoreResult(recv, result);
}
absl::Status ProcBuilderVisitor::HandleReceiveIf(ReceiveIf* recv_if) {
// First, declare the join block (so the case blocks can refer to it).
llvm::BasicBlock* join_block = llvm::BasicBlock::Create(
ctx(), absl::StrCat(recv_if->GetName(), "_join"), llvm_fn());
// Create a block/branch for the true predicate case.
llvm::BasicBlock* true_block = llvm::BasicBlock::Create(
ctx(), absl::StrCat(recv_if->GetName(), "_true"), llvm_fn(), join_block);
llvm::IRBuilder<> true_builder(true_block);
XLS_ASSIGN_OR_RETURN(JitChannelQueue * queue,
queue_mgr_->GetQueueById(recv_if->channel_id()));
XLS_ASSIGN_OR_RETURN(llvm::Value * true_result,
InvokeRecvCallback(&true_builder, queue, recv_if));
llvm::Value* true_token = type_converter()->GetToken();
true_builder.CreateBr(join_block);
// And the same for a false predicate - this will return an empty/zero value.
// Creating an empty struct emits ops, so it needs a builder.
llvm::BasicBlock* false_block = llvm::BasicBlock::Create(
ctx(), absl::StrCat(recv_if->GetName(), "_false"), llvm_fn(), join_block);
llvm::IRBuilder<> false_builder(false_block);
llvm::Type* result_type =
type_converter()->ConvertToLlvmType(recv_if->GetType());
llvm::Value* false_result = CreateTypedZeroValue(result_type);
llvm::Value* false_token = node_map().at(recv_if->operand(0));
false_builder.CreateBr(join_block);
// Next, create a branch op w/the original builder,
builder()->CreateCondBr(node_map().at(recv_if->predicate()), true_block,
false_block);
// then join the two branches back together.
auto join_builder = std::make_unique<llvm::IRBuilder<>>(join_block);
llvm::PHINode* phi =
join_builder->CreatePHI(result_type, /*NumReservedValues=*/2);
phi->addIncoming(true_result, true_block);
phi->addIncoming(false_result, false_block);
llvm::PHINode* token_phi = join_builder->CreatePHI(
type_converter()->GetTokenType(), /*NumReservedValues=*/2);
token_phi->addIncoming(true_token, true_block);
token_phi->addIncoming(false_token, false_block);
llvm::Value* result = join_builder->CreateInsertValue(phi, token_phi, {0});
// Finally, set this's IRBuilder to be the output block's (since that's where
// the Function continues).
set_builder(std::move(join_builder));
return StoreResult(recv_if, result);
}
absl::Status ProcBuilderVisitor::InvokeSendCallback(
llvm::IRBuilder<>* builder, JitChannelQueue* queue, Node* node,
absl::Span<Node* const> operands) {
llvm::Type* void_type = llvm::Type::getVoidTy(ctx());
llvm::Type* int64_type = llvm::Type::getInt64Ty(ctx());
llvm::Type* int8_ptr_type = llvm::Type::getInt8PtrTy(ctx(), 0);
// We do the same for sending/enqueuing as we do for receiving/dequeueing
// above (set up and call an external function).
std::vector<llvm::Type*> params({
int64_type,
int64_type,
int8_ptr_type,
int64_type,
int64_type,
});
llvm::FunctionType* fn_type =
llvm::FunctionType::get(void_type, params, /*isVarArg=*/false);
// Pack all the data to be sent into a contiguous tuple (we'll need to pack
// the data anyway, since llvm::Values don't automatically correspond to
// pointer-referencable storage; that's what allocas are for).
std::vector<Type*> tuple_elems;
for (const Node* operand : operands) {
tuple_elems.push_back(operand->GetType());
}
TupleType tuple_type(tuple_elems);
llvm::Type* send_op_types = type_converter()->ConvertToLlvmType(&tuple_type);
int64 send_type_size = type_converter()->GetTypeByteSize(&tuple_type);
llvm::Value* tuple = CreateTypedZeroValue(send_op_types);
for (int i = 0; i < operands.size(); i++) {
tuple = builder->CreateInsertValue(tuple, node_map().at(operands[i]),
{static_cast<uint>(i)});
}
llvm::AllocaInst* alloca = builder->CreateAlloca(send_op_types);
builder->CreateStore(tuple, alloca);
std::vector<llvm::Value*> args({
llvm::ConstantInt::get(int64_type, reinterpret_cast<uint64>(queue)),
llvm::ConstantInt::get(int64_type, reinterpret_cast<uint64>(node)),
builder->CreatePointerCast(alloca, int8_ptr_type),
llvm::ConstantInt::get(int64_type, send_type_size),
llvm_fn()->getArg(llvm_fn()->arg_size() - 1),
});
llvm::ConstantInt* fn_addr = llvm::ConstantInt::get(
llvm::Type::getInt64Ty(ctx()), reinterpret_cast<uint64>(send_fn_));
llvm::Value* fn_ptr =
builder->CreateIntToPtr(fn_addr, llvm::PointerType::get(fn_type, 0));
builder->CreateCall(fn_type, fn_ptr, args);
return absl::OkStatus();
}
absl::Status ProcBuilderVisitor::HandleSend(Send* send) {
XLS_ASSIGN_OR_RETURN(JitChannelQueue * queue,
queue_mgr_->GetQueueById(send->channel_id()));
XLS_RETURN_IF_ERROR(
InvokeSendCallback(builder(), queue, send, send->data_operands()));
return StoreResult(send, type_converter()->GetToken());
}
absl::Status ProcBuilderVisitor::HandleSendIf(SendIf* send_if) {
// First, declare the join block (so the case blocks can refer to it).
llvm::BasicBlock* join_block = llvm::BasicBlock::Create(
ctx(), absl::StrCat(send_if->GetName(), "_join"), llvm_fn());
llvm::BasicBlock* true_block = llvm::BasicBlock::Create(
ctx(), absl::StrCat(send_if->GetName(), "_true"), llvm_fn(), join_block);
llvm::IRBuilder<> true_builder(true_block);
XLS_ASSIGN_OR_RETURN(JitChannelQueue * queue,
queue_mgr_->GetQueueById(send_if->channel_id()));
XLS_RETURN_IF_ERROR(InvokeSendCallback(&true_builder, queue, send_if,
send_if->data_operands()));
llvm::Value* true_token = type_converter()->GetToken();
true_builder.CreateBr(join_block);
llvm::BasicBlock* false_block = llvm::BasicBlock::Create(
ctx(), absl::StrCat(send_if->GetName(), "_false"), llvm_fn(), join_block);
llvm::IRBuilder<> false_builder(false_block);
llvm::Value* false_token = node_map().at(send_if->operand(0));
false_builder.CreateBr(join_block);
builder()->CreateCondBr(node_map().at(send_if->predicate()), true_block,
false_block);
auto join_builder = std::make_unique<llvm::IRBuilder<>>(join_block);
llvm::PHINode* phi = join_builder->CreatePHI(type_converter()->GetTokenType(),
/*NumReservedValues=*/2);
phi->addIncoming(true_token, true_block);
phi->addIncoming(false_token, false_block);
set_builder(std::move(join_builder));
return StoreResult(send_if, phi);
}
} // namespace xls
| 45.552419 | 80 | 0.698947 | [
"vector"
] |
a805e77500f1894a277ecfc6e80536dc4c61820d | 401 | cpp | C++ | AtCoder/ABC177/c2.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | AtCoder/ABC177/c2.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | AtCoder/ABC177/c2.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
const int mod = 1000000007;
int main() {
int n;
cin >> n;
vector<int> a(n);
rep(i, n) cin >> a[i];
int ans = 0;
int x = 0;
rep(i, n) {
ans = (ans + (ll)a[i] * x) % mod;
x = (x + a[i]) % mod;
}
cout << ans << endl;
return 0;
}
| 16.708333 | 47 | 0.496259 | [
"vector"
] |
a80b4b2be269fae32ed28d8e0a665b199639069f | 32,600 | cc | C++ | src/core/ensemble_scheduler.cc | LittleReal/tensorrt-inference-server | f2010b1277af93a032df6979e8086bec486ed5dd | [
"BSD-3-Clause"
] | null | null | null | src/core/ensemble_scheduler.cc | LittleReal/tensorrt-inference-server | f2010b1277af93a032df6979e8086bec486ed5dd | [
"BSD-3-Clause"
] | null | null | null | src/core/ensemble_scheduler.cc | LittleReal/tensorrt-inference-server | f2010b1277af93a032df6979e8086bec486ed5dd | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of 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 NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "src/core/ensemble_scheduler.h"
#include <mutex>
#include "src/core/api.pb.h"
#include "src/core/backend.h"
#include "src/core/cuda_utils.h"
#include "src/core/logging.h"
#include "src/core/provider_utils.h"
#include "src/core/server.h"
#include "src/core/server_status.h"
#include "src/core/trtserver.h"
namespace nvidia { namespace inferenceserver {
namespace {
// Step specifies the backend, providers and status objects used for
// the internal infer request
struct Step {
Step(size_t step_idx) : step_idx_(step_idx) {}
std::shared_ptr<InferenceBackend> backend_;
std::shared_ptr<InferRequestProvider> request_provider_;
std::shared_ptr<InferResponseProvider> response_provider_;
std::unordered_map<std::string, std::shared_ptr<AllocatedMemory>> output_map_;
Status infer_status_;
size_t step_idx_;
};
// EnsembleContext maintains the state of the ensemble request
//
// Using static functions to take advantage of shared_ptr, a copy of the
// shared_ptr will be made when a step is scheduled and it will go out of
// scope after the step's callback is finished. The step's callback will
// schedule new steps if available and the last step will finish the ensemble
// request.
// So we don't have to maintian the context in scheduler as the shared_ptr
// will destroy the context for us if there are no "in-flight" steps.
class EnsembleContext {
public:
EnsembleContext(
InferenceServer* is, EnsembleInfo* info,
const std::shared_ptr<ModelInferStats>& stats,
const std::shared_ptr<InferRequestProvider>& request_provider,
const std::shared_ptr<InferResponseProvider>& response_provider,
std::function<void(const Status&)> OnComplete, cudaStream_t stream);
// Perform transition on 'context' state given the information of
// 'completed_step'
static void Proceed(
const std::shared_ptr<EnsembleContext>& context,
const std::shared_ptr<Step>& completed_step = nullptr);
private:
static TRTSERVER_Error* ResponseAlloc(
TRTSERVER_ResponseAllocator* allocator, const char* tensor_name,
size_t byte_size, TRTSERVER_Memory_Type preferred_memory_type,
int64_t preferred_memory_type_id, void* userp, void** buffer,
void** buffer_userp, TRTSERVER_Memory_Type* allocated_memory_type,
int64_t* allocated_memory_type_id);
static TRTSERVER_Error* ResponseRelease(
TRTSERVER_ResponseAllocator* allocator, void* buffer, void* buffer_userp,
size_t byte_size, TRTSERVER_Memory_Type memory_type,
int64_t memory_type_id);
using StepList = std::vector<std::shared_ptr<Step>>;
using VersionMap =
std::unordered_map<int64_t, std::shared_ptr<InferenceBackend>>;
// Storing each tensor's meta data in 1st element, batch size in 2nd
// (0 for non-batchable), and the raw data in 3rd.
using TensorData =
std::tuple<InferRequestHeader::Input, size_t, std::shared_ptr<Memory>>;
// Return the list of step that becomes ready due to tensor update
// from 'completed_step'
Status PrepareSteps(
const std::shared_ptr<Step>& completed_step, StepList& steps);
// Prepare infer stats and call the inference server's function to process
// the infer requests specified in 'steps'
static void ScheduleSteps(
const std::shared_ptr<EnsembleContext>& context, const StepList& steps);
// Helper function that updates ensemble state given 'completed_step' and
// returns the list of updated tensors in 'updated_tensors'
Status UpdateEnsembleState(
const std::shared_ptr<Step>& completed_step,
std::vector<std::string>& updated_tensors);
// Helper function that returns a list of 'steps' that should be run under
// current ensemble state. 'updated_tensors' is used so that we don't need to
// iterate all the tensors to determine which step can be run.
Status GetNextSteps(
const std::vector<std::string>& updated_tensors, StepList& steps);
// Helper function that completes the response of the ensemble request
Status FinishEnsemble();
// Helper function that initialize the 'step' given the info at 'step_idx'.
// The 'step' will have proper request / response provider for the model
Status InitStep(size_t step_idx, std::shared_ptr<Step>* step);
// Helper function that set the output of the ensemble request if it is ready
// and valid.
// Return error if some of the required outputs are not set (deadlock)
Status CheckAndSetEnsembleOutput();
// Helper function to reshape the given tensor according to the
// config shape and batching info and its actual shape and batching info.
// Returns the batch size to be used after the reshape.
size_t ReshapeTensorDims(
const DimsList& config_dims, const bool allow_batching,
const size_t tensor_batch_size, DimsList* mutable_dims);
InferenceServer* is_;
EnsembleInfo* info_;
// All EnsembleContext will use the same CUDA stream managed by
// the ensemble scheduler
cudaStream_t stream_;
// Mutex to avoid concurrent call on 'PrepareSteps' where ensemble state
// are being modified
std::mutex mutex_;
size_t inflight_step_counter_;
// pointer that either points to 'pruned_tensor_to_step_' or to
// 'info_->tensor_to_step_' if all ensemble outputs are requested
std::unordered_map<std::string, std::set<size_t>>* tensor_to_step_;
std::unordered_map<std::string, std::set<size_t>> pruned_tensor_to_step_;
std::unordered_map<std::string, TensorData> tensor_data_;
// Handle to all backend that may be used in the ensemble
std::unordered_map<std::string, VersionMap> handles_;
// Request specific information that obtained from ensemble request and
// should be applied to all internal requests
uint32_t flags_;
uint64_t correlation_id_;
uint32_t batch_size_;
// Objects related to the ensemble infer request
Status ensemble_status_;
std::shared_ptr<ModelInferStats> stats_;
std::shared_ptr<InferRequestProvider> request_provider_;
std::shared_ptr<InferResponseProvider> response_provider_;
std::function<void(const Status&)> OnComplete_;
// Output tensors whose labels are not provided by the ensemble
std::set<std::string> no_label_tensors_;
// The allocator that will be used to allocate buffers for the
// inference result tensors.
std::unique_ptr<
TRTSERVER_ResponseAllocator, decltype(&TRTSERVER_ResponseAllocatorDelete)>
allocator_;
};
EnsembleContext::EnsembleContext(
InferenceServer* is, EnsembleInfo* info,
const std::shared_ptr<ModelInferStats>& stats,
const std::shared_ptr<InferRequestProvider>& request_provider,
const std::shared_ptr<InferResponseProvider>& response_provider,
std::function<void(const Status&)> OnComplete, cudaStream_t stream)
: is_(is), info_(info), stream_(stream), inflight_step_counter_(0),
stats_(stats), request_provider_(request_provider),
response_provider_(response_provider), OnComplete_(OnComplete),
allocator_(nullptr, TRTSERVER_ResponseAllocatorDelete)
{
// Obtain backend handles of all models in ensemble request such that
// they have the same lifetime as the ensemble request to avoid unloading
// while the ensemble is executing.
for (const auto& step_info : info_->steps_) {
auto it = handles_.find(step_info.model_name_);
if (it == handles_.end()) {
it = handles_.emplace(std::make_pair(step_info.model_name_, VersionMap()))
.first;
}
auto ver_it = it->second.find(step_info.model_version_);
if (ver_it == it->second.end()) {
std::shared_ptr<InferenceBackend> backend = nullptr;
ensemble_status_ = is_->GetInferenceBackend(
step_info.model_name_, step_info.model_version_, &backend);
if (!ensemble_status_.IsOk()) {
break;
}
it->second.emplace(std::make_pair(step_info.model_version_, backend));
}
}
// Prune ensemble first if not all outputs are requested
std::set<std::string> ignored_tensor;
for (const auto& ensemble_output : info_->ensemble_output_shape_) {
ignored_tensor.insert(ensemble_output.first);
}
for (const auto& output : request_provider_->RequestHeader().output()) {
ignored_tensor.erase(output.name());
}
if (ignored_tensor.empty()) {
tensor_to_step_ = &(info_->tensor_to_step_);
} else {
pruned_tensor_to_step_ = info_->tensor_to_step_;
tensor_to_step_ = &pruned_tensor_to_step_;
// Backward traversal
std::unordered_map<size_t, size_t> step_requested_output_count;
while (!ignored_tensor.empty()) {
std::set<std::string> new_ignored_tensor;
for (const auto& output : ignored_tensor) {
auto step_idx = info_->tensor_to_prev_step_[output];
auto& step = info_->steps_[step_idx];
auto it = step_requested_output_count.find(step_idx);
if (it == step_requested_output_count.end()) {
auto output_count = step.output_to_tensor_.size();
it =
step_requested_output_count.emplace(step_idx, output_count).first;
}
// If none of the outputs of the step is requested,
// then the step can be pruned
if (--it->second == 0) {
for (const auto& input : step.input_to_tensor_) {
auto& step_set = pruned_tensor_to_step_[input.second];
step_set.erase(step_idx);
// If all steps depend on a tensor are pruned,
// then the tensor can be ignored.
if (step_set.empty()) {
new_ignored_tensor.insert(input.second);
}
}
}
}
ignored_tensor.swap(new_ignored_tensor);
}
}
for (const auto& pair : *tensor_to_step_) {
tensor_data_.emplace(pair.first, TensorData());
}
if (ensemble_status_.IsOk()) {
const auto& request_header = request_provider_->RequestHeader();
batch_size_ = request_header.batch_size();
correlation_id_ = request_header.correlation_id();
flags_ = request_header.flags();
for (const auto& input : request_header.input()) {
auto it = tensor_data_.find(input.name());
if (it != tensor_data_.end()) {
auto& tensor_data = it->second;
std::get<0>(tensor_data) = input;
std::get<1>(tensor_data) = (info_->allow_batching_ ? batch_size_ : 0);
request_provider_->GetMemory(it->first, &(std::get<2>(tensor_data)));
} else {
ensemble_status_ = Status(
RequestStatusCode::INVALID_ARG,
"unexpected input '" + input.name() +
"' in request header that does not map to any ensemble inputs");
}
}
}
if (ensemble_status_.IsOk()) {
const std::shared_ptr<LabelProvider>& label_provider =
response_provider_->GetLabelProvider();
for (const auto& pair : info_->ensemble_output_shape_) {
const auto& label = label_provider->GetLabel(pair.first, 0);
if (label == "") {
no_label_tensors_.emplace(pair.first);
}
}
}
TRTSERVER_ResponseAllocator* allocator;
TRTSERVER_Error* err = TRTSERVER_ResponseAllocatorNew(
&allocator, ResponseAlloc, ResponseRelease);
if (err != nullptr) {
ensemble_status_ = Status(
TrtServerCodeToRequestStatus(TRTSERVER_ErrorCode(err)),
TRTSERVER_ErrorMessage(err));
TRTSERVER_ErrorDelete(err);
} else {
allocator_.reset(allocator);
}
}
TRTSERVER_Error*
EnsembleContext::ResponseAlloc(
TRTSERVER_ResponseAllocator* allocator, const char* tensor_name,
size_t byte_size, TRTSERVER_Memory_Type preferred_memory_type,
int64_t preferred_memory_type_id, void* userp, void** buffer,
void** buffer_userp, TRTSERVER_Memory_Type* allocated_memory_type,
int64_t* allocated_memory_type_id)
{
auto tensor_data_map = reinterpret_cast<
std::unordered_map<std::string, std::shared_ptr<AllocatedMemory>>*>(
userp);
*buffer = nullptr;
*buffer_userp = nullptr;
auto allocated_buffer = std::make_shared<AllocatedMemory>(
byte_size, preferred_memory_type, preferred_memory_type_id);
auto mutable_buffer = allocated_buffer->MutableBuffer(
allocated_memory_type, allocated_memory_type_id);
if ((mutable_buffer != nullptr) || (byte_size == 0)) {
if (byte_size != 0) {
*buffer = static_cast<void*>(mutable_buffer);
}
tensor_data_map->emplace(tensor_name, std::move(allocated_buffer));
LOG_VERBOSE(1) << "Internal response allocation: " << tensor_name
<< ", size " << byte_size << ", addr " << *buffer
<< ", memory type " << *allocated_memory_type << ", type id "
<< *allocated_memory_type_id;
}
return nullptr; // Success
}
TRTSERVER_Error*
EnsembleContext::ResponseRelease(
TRTSERVER_ResponseAllocator* allocator, void* buffer, void* buffer_userp,
size_t byte_size, TRTSERVER_Memory_Type memory_type, int64_t memory_type_id)
{
LOG_VERBOSE(1) << "Internal response release: "
<< "size " << byte_size << ", addr " << buffer;
// Don't do anything when releasing a buffer since ResponseAlloc
// passes the ownership of the data to ensemble context.
return nullptr; // Success
}
void
EnsembleContext::Proceed(
const std::shared_ptr<EnsembleContext>& context,
const std::shared_ptr<Step>& completed_step)
{
StepList ready_steps;
Status status = context->PrepareSteps(completed_step, ready_steps);
if (status.IsOk()) {
ScheduleSteps(context, ready_steps);
}
}
Status
EnsembleContext::PrepareSteps(
const std::shared_ptr<Step>& completed_step, StepList& ready_steps)
{
{
std::lock_guard<std::mutex> lock(mutex_);
// Initialization error, ensemble status will be not ok since the beginning
if (completed_step == nullptr && !ensemble_status_.IsOk()) {
ensemble_status_ = FinishEnsemble();
}
if (ensemble_status_.IsOk()) {
StepList res;
std::vector<std::string> updated_tensors;
ensemble_status_ = UpdateEnsembleState(completed_step, updated_tensors);
if (ensemble_status_.IsOk()) {
ensemble_status_ = GetNextSteps(updated_tensors, res);
}
// Error or no more progress (completed or deadlock)
// in either case, FinishEnsemble() won't be called again
if ((!ensemble_status_.IsOk()) || (inflight_step_counter_ == 0)) {
ensemble_status_ = FinishEnsemble();
} else {
ready_steps.swap(res);
}
}
return ensemble_status_;
}
}
Status
EnsembleContext::UpdateEnsembleState(
const std::shared_ptr<Step>& completed_step,
std::vector<std::string>& updated_tensors)
{
updated_tensors.clear();
if (completed_step == nullptr) {
for (const auto& pair : tensor_data_) {
if (std::get<2>(pair.second) != nullptr) {
updated_tensors.push_back(pair.first);
}
}
} else {
inflight_step_counter_--;
RETURN_IF_ERROR(completed_step->infer_status_);
auto step_idx = completed_step->step_idx_;
RETURN_IF_ERROR(completed_step->response_provider_->FinalizeResponse(
*(completed_step->backend_)));
const auto& response_header =
completed_step->response_provider_->ResponseHeader();
const bool allow_batching =
(completed_step->backend_->Config().max_batch_size() > 0);
const size_t batch_size =
(allow_batching ? response_header.batch_size() : 0);
for (const auto& output : response_header.output()) {
if (output.has_raw()) {
auto it = info_->steps_[step_idx].output_to_tensor_.find(output.name());
if (it != info_->steps_[step_idx].output_to_tensor_.end()) {
auto& tensor_data = tensor_data_[it->second];
auto& meta_data = std::get<0>(tensor_data);
*(meta_data.mutable_dims()) = output.raw().dims();
meta_data.set_batch_byte_size(output.raw().batch_byte_size());
std::get<1>(tensor_data) = batch_size;
std::get<2>(tensor_data) =
std::move(completed_step->output_map_[it->first]);
updated_tensors.push_back(it->second);
auto tensor_it = no_label_tensors_.find(it->second);
if (tensor_it != no_label_tensors_.end()) {
// Check the inner model's lookup map first in case it is also an
// ensemble model. In that case, the label of the inner model may
// come from another model.
InferResponseProvider::SecondaryLabelProvider provider;
if (completed_step->response_provider_->GetSecondaryLabelProvider(
it->first, &provider)) {
response_provider_->SetSecondaryLabelProvider(
*tensor_it, provider);
} else {
const std::shared_ptr<LabelProvider>& label_provider =
completed_step->response_provider_->GetLabelProvider();
response_provider_->SetSecondaryLabelProvider(
*tensor_it, std::make_pair(it->first, label_provider));
}
no_label_tensors_.erase(tensor_it);
}
} else {
return Status(
RequestStatusCode::INTERNAL,
"internal response header specified output '" + output.name() +
"' that does not map to any ensemble tensors");
}
} else {
return Status(
RequestStatusCode::INTERNAL,
"internal response header should return output '" + output.name() +
"' as raw data instead of classification result");
}
}
}
return Status::Success;
}
Status
EnsembleContext::GetNextSteps(
const std::vector<std::string>& updated_tensors, StepList& steps)
{
steps.clear();
std::set<size_t> next_step_idx;
// Get steps whose tensors used for input are set
for (const auto tensor_name : updated_tensors) {
const auto& step_idx = (*tensor_to_step_)[tensor_name];
for (const auto& idx : step_idx) {
bool ready = true;
for (const auto& input_pair : info_->steps_[idx].input_to_tensor_) {
if (std::get<2>(tensor_data_[input_pair.second]) == nullptr) {
ready = false;
break;
}
}
if (ready) {
next_step_idx.insert(idx);
}
}
}
for (const auto& idx : next_step_idx) {
steps.emplace_back();
RETURN_IF_ERROR(InitStep(idx, &(steps.back())));
}
inflight_step_counter_ += steps.size();
return Status::Success;
}
Status
EnsembleContext::InitStep(size_t step_idx, std::shared_ptr<Step>* step)
{
std::unordered_map<std::string, std::shared_ptr<Memory>> input_map;
InferRequestHeader request_header;
auto& version_map = handles_[info_->steps_[step_idx].model_name_];
auto& backend = version_map[info_->steps_[step_idx].model_version_];
const bool allow_batching = (backend->Config().max_batch_size() > 0);
size_t batch_size = (allow_batching ? batch_size_ : 0);
// Set inputs in request header and prepare input map
for (const auto& pair : info_->steps_[step_idx].input_to_tensor_) {
auto input = request_header.add_input();
*input = std::get<0>(tensor_data_[pair.second]);
input->set_name(pair.first);
// If the actual shape and config shape agree with each other without
// considering batch size, non-batch / batch conversion are not required
const ModelInput* input_config;
backend->GetInput(pair.first, &input_config);
batch_size = ReshapeTensorDims(
input_config->dims(), allow_batching,
std::get<1>(tensor_data_[pair.second]), input->mutable_dims());
input_map[pair.first] = std::get<2>(tensor_data_[pair.second]);
}
// Set requested outputs in request header
for (const auto& pair : info_->steps_[step_idx].output_to_tensor_) {
request_header.add_output()->set_name(pair.first);
}
request_header.set_correlation_id(correlation_id_);
request_header.set_flags(flags_);
request_header.set_batch_size((batch_size == 0 ? 1 : batch_size));
RETURN_IF_ERROR(NormalizeRequestHeader(*backend, request_header));
step->reset(new Step(step_idx));
(*step)->backend_ = backend;
RETURN_IF_ERROR(InferRequestProvider::Create(
info_->steps_[step_idx].model_name_,
info_->steps_[step_idx].model_version_, request_header, input_map,
&((*step)->request_provider_)));
// Request header is stored in response provider as reference, so use
// header from request provider as the providers have same lifetime
RETURN_IF_ERROR(InferResponseProvider::Create(
(*step)->request_provider_->RequestHeader(),
(*step)->backend_->GetLabelProvider(), allocator_.get(), ResponseAlloc,
&((*step)->output_map_), ResponseRelease,
&((*step)->response_provider_)));
return Status::Success;
}
size_t
EnsembleContext::ReshapeTensorDims(
const DimsList& config_dims, const bool allow_batching,
const size_t tensor_batch_size, DimsList* mutable_dims)
{
size_t batch_size = tensor_batch_size;
// If the actual shape and config shape agree with each other without
// considering batch size, non-batch / batch conversion are not required.
if (!CompareDimsWithWildcard(*mutable_dims, config_dims)) {
// Only reshape if one setting is batchable while the other is not,
// otherwise the shape mismatch can not be recovered with reshape
// and should have caused error during validation.
if (allow_batching != (tensor_batch_size != 0)) {
if (allow_batching) {
// assume first dim is batch dim and extract it.
auto bit = mutable_dims->begin();
batch_size = *bit;
mutable_dims->erase(bit);
} else {
// insert batch size as first dim. Protobuf only allows appending to the
// back, so have to move batch size forward one by one
mutable_dims->Add(tensor_batch_size);
for (size_t bidx = mutable_dims->size() - 1; bidx >= 1; bidx--) {
mutable_dims->SwapElements(bidx - 1, bidx);
}
batch_size = 0;
}
}
}
return batch_size;
}
Status
EnsembleContext::FinishEnsemble()
{
#ifdef TRTIS_ENABLE_STATS
stats_->SetModelExecutionCount(1);
#endif // TRTIS_ENABLE_STATS
if (ensemble_status_.IsOk()) {
ensemble_status_ = CheckAndSetEnsembleOutput();
}
// Add ensemble name to make error message more trackable
if (!ensemble_status_.IsOk()) {
ensemble_status_ = Status(
ensemble_status_.Code(), "in ensemble '" + info_->ensemble_name_ +
"', " + ensemble_status_.Message());
}
OnComplete_(ensemble_status_);
return ensemble_status_;
}
Status
EnsembleContext::CheckAndSetEnsembleOutput()
{
bool cuda_async_copy = false;
for (const auto& output_pair : info_->ensemble_output_shape_) {
if (!response_provider_->RequiresOutput(output_pair.first)) {
continue;
}
// Check if output is ready
const auto& tensor_data = tensor_data_[output_pair.first];
const auto& meta_data = std::get<0>(tensor_data);
const auto& memory_block = std::get<2>(tensor_data);
if (memory_block == nullptr) {
return Status(
RequestStatusCode::INVALID_ARG,
"unexpected deadlock, output '" + output_pair.first +
"' is not set while no more ensemble steps can be made");
} else if (meta_data.batch_byte_size() != memory_block->TotalByteSize()) {
return Status(
RequestStatusCode::INTERNAL,
"unexpected size for output '" + output_pair.first + "', byte-size " +
std::to_string(meta_data.batch_byte_size()) + " does not equal " +
std::to_string(memory_block->TotalByteSize()));
}
// copy data to ensemble response provider
size_t expected_byte_size = meta_data.batch_byte_size();
DimsList output_dims = meta_data.dims();
ReshapeTensorDims(
output_pair.second, info_->allow_batching_, std::get<1>(tensor_data),
&output_dims);
std::vector<int64_t> shape;
if (info_->allow_batching_) {
shape.push_back(batch_size_);
}
for (const auto& dim : output_dims) {
shape.push_back(dim);
}
// Use the memory type of the memory block as preferred memory type
TRTSERVER_Memory_Type dst_memory_type, allocated_memory_type;
int64_t dst_memory_type_id;
size_t content_size;
memory_block->BufferAt(
0, &content_size, &dst_memory_type, &dst_memory_type_id);
void* buffer;
int64_t allocated_memory_type_id;
RETURN_IF_ERROR(response_provider_->AllocateOutputBuffer(
output_pair.first, &buffer, expected_byte_size, shape, dst_memory_type,
dst_memory_type_id, &allocated_memory_type, &allocated_memory_type_id));
// Done with this output if 'expected_byte_size' is 0
if (expected_byte_size == 0) {
continue;
} else if (buffer == nullptr) {
return Status(
RequestStatusCode::INTERNAL,
"failed to allocate buffer for output '" + output_pair.first + "'");
}
size_t content_offset = 0;
size_t content_idx = 0;
TRTSERVER_Memory_Type src_memory_type;
int64_t src_memory_type_id;
const char* content = memory_block->BufferAt(
content_idx, &content_size, &src_memory_type, &src_memory_type_id);
bool cuda_used = false;
while (content != nullptr) {
RETURN_IF_ERROR(CopyBuffer(
output_pair.first, src_memory_type, src_memory_type_id,
allocated_memory_type, allocated_memory_type_id, content_size,
content, ((char*)buffer) + content_offset, stream_, &cuda_used));
cuda_async_copy |= cuda_used;
content_offset += content_size;
content_idx++;
content = memory_block->BufferAt(
content_idx, &content_size, &src_memory_type, &src_memory_type_id);
}
}
if (cuda_async_copy) {
#ifdef TRTIS_ENABLE_GPU
cudaStreamSynchronize(stream_);
#else
return Status(
RequestStatusCode::INTERNAL,
"unexpected CUDA copy flag set while GPU is not supported");
#endif // TRTIS_ENABLE_GPU
}
return Status::Success;
}
void
EnsembleContext::ScheduleSteps(
const std::shared_ptr<EnsembleContext>& context, const StepList& steps)
{
for (const auto& step : steps) {
#ifdef TRTIS_ENABLE_STATS
auto infer_stats = std::make_shared<ModelInferStats>(
context->is_->StatusManager(), step->backend_->Name());
infer_stats->CaptureTimestamp(
ModelInferStats::TimestampKind::kRequestStart);
infer_stats->SetRequestedVersion(step->backend_->Version());
infer_stats->SetMetricReporter(step->backend_->MetricReporter());
infer_stats->SetBatchSize(
step->request_provider_->RequestHeader().batch_size());
infer_stats->SetFailed(true);
// Passing trace-related objects down
infer_stats->SetTraceManager(context->stats_->GetTraceManager());
infer_stats->NewTrace(context->stats_->GetTrace());
#else
auto infer_stats = std::make_shared<ModelInferStats>();
#endif // TRTIS_ENABLE_STATS
context->is_->InferAsync(
step->backend_, step->request_provider_, step->response_provider_,
infer_stats,
[context, step, infer_stats](const Status& status) mutable {
if (!status.IsOk()) {
LOG_VERBOSE(1) << "Ensemble infer failed: " << status.Message();
}
#ifdef TRTIS_ENABLE_STATS
infer_stats->SetFailed(!status.IsOk());
infer_stats->CaptureTimestamp(
ModelInferStats::TimestampKind::kRequestEnd);
infer_stats->Report();
#endif // TRTIS_ENABLE_STATS
step->infer_status_ = status;
#ifdef TRTIS_ENABLE_STATS
{
std::lock_guard<std::mutex> lk(context->mutex_);
// Accumulate the queue and compute durations from this
// composing model
context->stats_->IncrementQueueDuration(*infer_stats);
context->stats_->IncrementComputeDuration(*infer_stats);
}
#endif // TRTIS_ENABLE_STATS
Proceed(context, step);
});
}
}
} // namespace
Status
EnsembleScheduler::Create(
InferenceServer* const server, const ModelConfig& config,
std::unique_ptr<Scheduler>* scheduler)
{
scheduler->reset(new EnsembleScheduler(server, config));
return Status::Success;
}
void
EnsembleScheduler::Enqueue(
const std::shared_ptr<ModelInferStats>& stats,
const std::shared_ptr<InferRequestProvider>& request_provider,
const std::shared_ptr<InferResponseProvider>& response_provider,
std::function<void(const Status&)> OnComplete)
{
std::shared_ptr<EnsembleContext> context(new EnsembleContext(
is_, info_.get(), stats, request_provider, response_provider, OnComplete,
stream_));
EnsembleContext::Proceed(context);
}
EnsembleScheduler::EnsembleScheduler(
InferenceServer* const server, const ModelConfig& config)
: is_(server), stream_(nullptr)
{
#ifdef TRTIS_ENABLE_GPU
// create CUDA stream
auto cuerr = cudaStreamCreate(&stream_);
if (cuerr != cudaSuccess) {
stream_ = nullptr;
LOG_ERROR << "unable to create stream for " << config.name() << ": "
<< cudaGetErrorString(cuerr);
}
#endif // TRTIS_ENABLE_GPU
// Set 'info_' based on 'config'
info_.reset(new EnsembleInfo());
info_->ensemble_name_ = config.name();
info_->allow_batching_ = (config.max_batch_size() != 0);
for (const auto& input : config.input()) {
info_->tensor_to_step_.emplace(input.name(), std::set<size_t>());
}
for (const auto& output : config.output()) {
info_->tensor_to_step_.emplace(output.name(), std::set<size_t>());
if (output.has_reshape()) {
info_->ensemble_output_shape_[output.name()] = output.reshape().shape();
} else {
info_->ensemble_output_shape_[output.name()] = output.dims();
}
}
for (const auto& element : config.ensemble_scheduling().step()) {
size_t step_idx = info_->steps_.size();
info_->steps_.emplace_back(element.model_name(), element.model_version());
for (const auto& pair : element.input_map()) {
auto it = info_->tensor_to_step_.find(pair.second);
if (it == info_->tensor_to_step_.end()) {
it = info_->tensor_to_step_.emplace(pair.second, std::set<size_t>())
.first;
}
it->second.insert(step_idx);
info_->steps_[step_idx].input_to_tensor_.emplace(
std::make_pair(pair.first, pair.second));
}
for (const auto& pair : element.output_map()) {
auto it = info_->tensor_to_step_.find(pair.second);
if (it == info_->tensor_to_step_.end()) {
it = info_->tensor_to_step_.emplace(pair.second, std::set<size_t>())
.first;
}
info_->steps_[step_idx].output_to_tensor_.emplace(
std::make_pair(pair.first, pair.second));
info_->tensor_to_prev_step_.emplace(pair.second, step_idx);
}
}
}
EnsembleScheduler::~EnsembleScheduler()
{
#ifdef TRTIS_ENABLE_GPU
if (stream_ != nullptr) {
cudaError_t err = cudaStreamDestroy(stream_);
if (err != cudaSuccess) {
LOG_ERROR << "Failed to destroy cuda stream: " << cudaGetErrorString(err);
}
}
#endif // TRTIS_ENABLE_GPU
}
}} // namespace nvidia::inferenceserver
| 37.342497 | 80 | 0.69181 | [
"shape",
"vector",
"model"
] |
a812bc875bba4efa8740f06ebd552ad3f0ce5ff4 | 9,299 | cpp | C++ | src/lib/storage/index/group_key/composite_group_key_index.cpp | bengelhaupt/hyrise | dc2b6d9f205b9f31f989dc8821b6167ad7202fab | [
"MIT"
] | 1 | 2021-07-02T09:51:19.000Z | 2021-07-02T09:51:19.000Z | src/lib/storage/index/group_key/composite_group_key_index.cpp | bengelhaupt/hyrise | dc2b6d9f205b9f31f989dc8821b6167ad7202fab | [
"MIT"
] | null | null | null | src/lib/storage/index/group_key/composite_group_key_index.cpp | bengelhaupt/hyrise | dc2b6d9f205b9f31f989dc8821b6167ad7202fab | [
"MIT"
] | null | null | null | #include "composite_group_key_index.hpp"
#include <algorithm>
#include <climits>
#include <cstdint>
#include <iterator>
#include <memory>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include "storage/base_dictionary_segment.hpp"
#include "storage/vector_compression/base_compressed_vector.hpp"
#include "storage/vector_compression/base_vector_decompressor.hpp"
#include "storage/vector_compression/fixed_width_integer/fixed_width_integer_utils.hpp"
#include "utils/assert.hpp"
#include "variable_length_key_proxy.hpp"
namespace opossum {
size_t CompositeGroupKeyIndex::estimate_memory_consumption(ChunkOffset row_count, ChunkOffset distinct_count,
uint32_t value_bytes) {
return ((row_count + distinct_count) * sizeof(ChunkOffset) + distinct_count * value_bytes);
}
CompositeGroupKeyIndex::CompositeGroupKeyIndex(
const std::vector<std::shared_ptr<const AbstractSegment>>& segments_to_index)
: AbstractChunkIndex{get_chunk_index_type_of<CompositeGroupKeyIndex>()} {
Assert(!segments_to_index.empty(), "CompositeGroupKeyIndex requires at least one segment to be indexed.");
if constexpr (HYRISE_DEBUG) {
auto first_size = segments_to_index.front()->size();
auto all_segments_have_same_size =
std::all_of(segments_to_index.cbegin(), segments_to_index.cend(),
[first_size](const auto& segment) { return segment->size() == first_size; });
Assert(all_segments_have_same_size,
"CompositeGroupKey requires same length of all segments that should be indexed.");
}
// cast and check segments
_indexed_segments.reserve(segments_to_index.size());
for (const auto& segment : segments_to_index) {
auto dict_segment = std::dynamic_pointer_cast<const BaseDictionarySegment>(segment);
Assert(static_cast<bool>(dict_segment), "CompositeGroupKeyIndex only works with dictionary segments.");
Assert(dict_segment->compressed_vector_type(),
"Expected DictionarySegment to use vector compression for attribute vector");
Assert(is_fixed_width_integer(*dict_segment->compressed_vector_type()),
"CompositeGroupKeyIndex only works with Fixed-width integer compressed attribute vectors.");
_indexed_segments.emplace_back(dict_segment);
}
// retrieve memory consumption by each concatenated key
auto bytes_per_key =
std::accumulate(_indexed_segments.begin(), _indexed_segments.end(), CompositeKeyLength{0u},
[](auto key_length, const auto& segment) {
return key_length + byte_width_for_fixed_width_integer_type(*segment->compressed_vector_type());
});
// create concatenated keys and save their positions
// at this point duplicated keys may be created, they will be handled later
auto segment_size = _indexed_segments.front()->size();
auto keys = std::vector<VariableLengthKey>(segment_size);
_position_list.resize(segment_size);
auto attribute_vector_widths_and_decompressors = [&]() {
auto decompressors =
std::vector<std::pair<size_t, std::unique_ptr<BaseVectorDecompressor>>>(_indexed_segments.size());
std::transform(
_indexed_segments.cbegin(), _indexed_segments.cend(), decompressors.begin(), [](const auto& segment) {
const auto byte_width = byte_width_for_fixed_width_integer_type(*segment->compressed_vector_type());
auto decompressor = segment->attribute_vector()->create_base_decompressor();
return std::make_pair(byte_width, std::move(decompressor));
});
return decompressors;
}();
for (ChunkOffset chunk_offset = 0; chunk_offset < static_cast<ChunkOffset>(segment_size); ++chunk_offset) {
auto concatenated_key = VariableLengthKey(bytes_per_key);
for (const auto& [byte_width, decompressor] : attribute_vector_widths_and_decompressors) {
concatenated_key.shift_and_set(decompressor->get(chunk_offset), static_cast<uint8_t>(byte_width * CHAR_BIT));
}
keys[chunk_offset] = std::move(concatenated_key);
_position_list[chunk_offset] = chunk_offset;
}
// sort keys and their positions
std::sort(_position_list.begin(), _position_list.end(),
[&keys](auto left, auto right) { return keys[left] < keys[right]; });
_keys = VariableLengthKeyStore(static_cast<ChunkOffset>(segment_size), bytes_per_key);
for (ChunkOffset chunk_offset = 0; chunk_offset < static_cast<ChunkOffset>(segment_size); ++chunk_offset) {
_keys[chunk_offset] = keys[_position_list[chunk_offset]];
}
// create offsets to unique keys
_key_offsets.reserve(segment_size);
_key_offsets.emplace_back(0);
for (ChunkOffset chunk_offset = 1; chunk_offset < static_cast<ChunkOffset>(segment_size); ++chunk_offset) {
if (_keys[chunk_offset] != _keys[chunk_offset - 1]) _key_offsets.emplace_back(chunk_offset);
}
_key_offsets.shrink_to_fit();
// remove duplicated keys
auto unique_keys_end = std::unique(_keys.begin(), _keys.end());
_keys.erase(unique_keys_end, _keys.end());
_keys.shrink_to_fit();
}
AbstractChunkIndex::Iterator CompositeGroupKeyIndex::_cbegin() const { return _position_list.cbegin(); }
AbstractChunkIndex::Iterator CompositeGroupKeyIndex::_cend() const { return _position_list.cend(); }
AbstractChunkIndex::Iterator CompositeGroupKeyIndex::_lower_bound(const std::vector<AllTypeVariant>& values) const {
auto composite_key = _create_composite_key(values, false);
return _get_position_iterator_for_key(composite_key);
}
AbstractChunkIndex::Iterator CompositeGroupKeyIndex::_upper_bound(const std::vector<AllTypeVariant>& values) const {
auto composite_key = _create_composite_key(values, true);
return _get_position_iterator_for_key(composite_key);
}
VariableLengthKey CompositeGroupKeyIndex::_create_composite_key(const std::vector<AllTypeVariant>& values,
bool is_upper_bound) const {
auto result = VariableLengthKey(_keys.key_size());
// retrieve the partial keys for every value except for the last one and append them into one partial-key
for (auto column_id = ColumnID{0}; column_id < values.size() - 1; ++column_id) {
Assert(!variant_is_null(values[column_id]), "CompositeGroupKeyIndex doesn't support NULL handling yet.");
auto partial_key = _indexed_segments[column_id]->lower_bound(values[column_id]);
auto bits_of_partial_key =
byte_width_for_fixed_width_integer_type(*_indexed_segments[column_id]->compressed_vector_type()) * CHAR_BIT;
result.shift_and_set(partial_key, static_cast<uint8_t>(bits_of_partial_key));
}
// retrieve the partial key for the last value (depending on whether we have a lower- or upper-bound-query)
// and append it to the previously created partial key to obtain the key containing all provided values
const auto& segment_for_last_value = _indexed_segments[values.size() - 1];
auto&& partial_key = is_upper_bound ? segment_for_last_value->upper_bound(values.back())
: segment_for_last_value->lower_bound(values.back());
auto bits_of_partial_key =
byte_width_for_fixed_width_integer_type(*segment_for_last_value->compressed_vector_type()) * CHAR_BIT;
result.shift_and_set(partial_key, static_cast<uint8_t>(bits_of_partial_key));
// fill empty space of key with zeros if less values than segments were provided
auto empty_bits = std::accumulate(
_indexed_segments.cbegin() + values.size(), _indexed_segments.cend(), static_cast<uint8_t>(0u),
[](auto value, auto segment) {
return value + byte_width_for_fixed_width_integer_type(*segment->compressed_vector_type()) * CHAR_BIT;
});
result <<= empty_bits;
return result;
}
AbstractChunkIndex::Iterator CompositeGroupKeyIndex::_get_position_iterator_for_key(
const VariableLengthKey& key) const {
// get an iterator pointing to the search-key in the keystore
// (use always lower_bound() since the search method is already handled within creation of composite key)
auto key_it = std::lower_bound(_keys.cbegin(), _keys.cend(), key);
if (key_it == _keys.cend()) return _position_list.cend();
// get the start position in the position-vector, ie the offset, by getting the offset_iterator for the key
// (which is at the same position as the iterator for the key in the keystore)
auto offset_it = _key_offsets.cbegin();
std::advance(offset_it, std::distance(_keys.cbegin(), key_it));
// get an iterator pointing to that start position
auto position_it = _position_list.cbegin();
std::advance(position_it, *offset_it);
return position_it;
}
std::vector<std::shared_ptr<const AbstractSegment>> CompositeGroupKeyIndex::_get_indexed_segments() const {
auto result = std::vector<std::shared_ptr<const AbstractSegment>>();
result.reserve(_indexed_segments.size());
for (auto&& indexed_segment : _indexed_segments) {
result.emplace_back(indexed_segment);
}
return result;
}
size_t CompositeGroupKeyIndex::_memory_consumption() const {
size_t byte_count = _keys.size() * _keys.key_size();
byte_count += _key_offsets.size() * sizeof(ChunkOffset);
byte_count += _position_list.size() * sizeof(ChunkOffset);
return byte_count;
}
} // namespace opossum
| 47.443878 | 120 | 0.743736 | [
"vector",
"transform"
] |
a81317d50bf9ecce3826e209ebbaaac96df6a0ca | 2,299 | cpp | C++ | Clowns' F8/GUILabel.cpp | cherry-glasses/Project-2-Game | 9fcd27c4a0b56718be5fe6bc365299286cbf947b | [
"MIT"
] | 1 | 2021-02-04T13:37:00.000Z | 2021-02-04T13:37:00.000Z | Clowns' F8/GUILabel.cpp | cherry-glasses/Project-2-Game | 9fcd27c4a0b56718be5fe6bc365299286cbf947b | [
"MIT"
] | 23 | 2019-04-03T08:49:08.000Z | 2019-05-25T14:04:44.000Z | Clowns' F8/GUILabel.cpp | cherry-glasses/Clowns-F8 | 9fcd27c4a0b56718be5fe6bc365299286cbf947b | [
"MIT"
] | 1 | 2019-02-25T22:49:46.000Z | 2019-02-25T22:49:46.000Z | #include "Application.h"
#include "ModuleGUIManager.h"
#include "GUIElement.h"
#include "GUILabel.h"
#include "ModuleRender.h"
#include "SDL_ttf/include/SDL_ttf.h"
GUILabel::GUILabel(int x, int y, std::string text, SDL_Color color, _TTF_Font* font, int curr, int def, GUIElement* son, bool centrated) : GUIElement(type, x, y, area, son)
{
type = GUI_ELEMENT_TYPE::GUI_LABEL;
this->color = color;
this->font = font;
if (curr == -1000 && def == -1000)
{
this->text = text;
}
else
{
this->text = std::to_string(curr);
this->text.push_back('/');
this->text += std::to_string(def);
}
tex = App->fonts->Print(this->text.data(), this->color, this->font);
// Create rect
int width = 0, height = 0;
App->fonts->CalcSize(this->text.data(), width, height, App->gui_manager->default_font_used);
area.w = width;
area.h = height;
area.x = 0;
area.y = 0;
if (centrated)
{
position.first = x - (area.w / 2);
position.second = y - (area.h / 2);
}
else
{
position.first = x;
position.second = y;
}
}
void GUILabel::Update(float dt)
{
Move();
}
void GUILabel::DrawLabel()
{
App->render->Blit(tex, position.first, position.second, &area, 0.0f);
}
// Note: see SDL_RenderSetClip() for clipping
void GUILabel::SetText(std::string text)
{
this->text = text;
tex = App->fonts->Print(this->text.data(), this->color, this->font);
// Create new rect
int width = 0, height = 0;
App->fonts->CalcSize(this->text.data(), width, height, App->gui_manager->default_font_used);
area.w = width;
area.h = height;
area.x = 0;
area.y = 0;
}
void GUILabel::AddChar(std::string c)
{
this->text += c;
tex = App->fonts->Print(this->text.data(), this->color, this->font);
// Create new rect
int width = 0, height = 0;
App->fonts->CalcSize(this->text.data(), width, height, App->gui_manager->default_font_used);
area.w = width;
area.h = height;
area.x = 0;
area.y = 0;
}
void GUILabel::DeleteLastChar()
{
if (this->text.length() > 0)
{
char* temp_text = (char*)(this->text.data());
temp_text[this->text.length() - 1] = '\0';
this->text = temp_text;
}
// Create new rect
int width = 0, height = 0;
App->fonts->CalcSize(this->text.data(), width, height, App->gui_manager->default_font_used);
area.w = width;
area.h = height;
area.x = 0;
area.y = 0;
} | 21.091743 | 172 | 0.643758 | [
"render"
] |
a816f3773334e209a1f1ad052dfeaa0c42161e3e | 2,171 | hpp | C++ | OREData/ored/model/marketobserver.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 335 | 2016-10-07T16:31:10.000Z | 2022-03-02T07:12:03.000Z | OREData/ored/model/marketobserver.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 59 | 2016-10-31T04:20:24.000Z | 2022-01-03T16:39:57.000Z | OREData/ored/model/marketobserver.hpp | mrslezak/Engine | c46ff278a2c5f4162db91a7ab500a0bb8cef7657 | [
"BSD-3-Clause"
] | 180 | 2016-10-08T14:23:50.000Z | 2022-03-28T10:43:05.000Z | /*
Copyright (C) 2019 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file ored/model/marketobserver.hpp
\brief helper class for model builders that observes market ts
\ingroup models
*/
#pragma once
#include <ql/patterns/observable.hpp>
namespace ore {
namespace data {
using namespace QuantLib;
//! Observer class for Model Builders
/*!
This class holds all observables of a builder, except special ones like vol surfaces
that should be handled separately in the builders to determine whether
a recalibration of the model is required.
\ingroup models
*/
class MarketObserver : public Observer, public Observable {
public:
MarketObserver() : updated_(true){};
//! Add an observable
void addObservable(boost::shared_ptr<Observable> observable);
//! Observer interface
void update();
//! Returns true if has been updated, reset updated flag if required
bool hasUpdated(const bool reset);
private:
//! Flag to indicate if updated
bool updated_;
};
// implementation
inline void MarketObserver::addObservable(boost::shared_ptr<Observable> observable) {
registerWith(observable);
updated_ = true;
}
inline void MarketObserver::update() {
updated_ = true;
notifyObservers();
};
inline bool MarketObserver::hasUpdated(const bool reset) {
if (!reset)
return updated_;
else {
bool upd = updated_;
updated_ = false;
return upd;
}
}
} // namespace data
} // namespace ore
| 27.1375 | 86 | 0.731921 | [
"model"
] |
a818cecc08dd54714ffc8cf52b0d4eb087b69051 | 9,038 | cpp | C++ | Utilities/LearnLambda.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 39 | 2015-01-01T07:59:51.000Z | 2021-10-01T18:11:46.000Z | Utilities/LearnLambda.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 1 | 2019-04-24T09:56:15.000Z | 2019-04-24T14:45:46.000Z | Utilities/LearnLambda.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 18 | 2015-01-11T15:10:23.000Z | 2022-02-24T20:02:10.000Z | /*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* 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.txt
*
* 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 "CriminisiInpainting.h"
// Custom
#include "PatchPair.h"
#include "PixelDifference.h"
#include "SelfPatchCompare.h"
// ITK
#include "itkAddImageFilter.h"
#include "itkImageFileReader.h"
#include "itkXorImageFilter.h"
// Boost
#include <boost/bind.hpp>
void ModifyMask(const Mask::Pointer inputMask, const unsigned int radius, Mask::Pointer outputMask);
int main(int argc, char *argv[])
{
// Verify arguments
if(argc != 5)
{
std::cerr << "Required arguments: image imageMask patchRadius outputPrefix" << std::endl;
return EXIT_FAILURE;
}
// Parse arguments
std::string imageFilename = argv[1];
std::string maskFilename = argv[2];
std::stringstream ssPatchRadius;
ssPatchRadius << argv[3];
int patchRadius = 0;
ssPatchRadius >> patchRadius;
std::string outputPrefix = argv[4];
// Output arguments
std::cout << "Reading image: " << imageFilename << std::endl;
std::cout << "Reading mask: " << maskFilename << std::endl;
std::cout << "Patch radius: " << patchRadius << std::endl;
//std::cout << "Output: " << outputFilename << std::endl;
typedef itk::ImageFileReader< FloatVectorImageType > ImageReaderType;
ImageReaderType::Pointer imageReader = ImageReaderType::New();
imageReader->SetFileName(imageFilename.c_str());
imageReader->Update();
FloatVectorImageType::Pointer scaledImage = FloatVectorImageType::New();
// Initialize
Helpers::DeepCopy<FloatVectorImageType>(imageReader->GetOutput(), scaledImage);
std::vector<float> maxValues = Helpers::MaxValuesVectorImage<float>(imageReader->GetOutput());
// Scale all channels the same
// for(unsigned int channel = 0; channel < imageReader->GetOutput()->GetNumberOfComponentsPerPixel(); ++channel)
// {
// Helpers::ScaleChannel<float>(imageReader->GetOutput(), channel, 1.0f, scaledImage);
// }
// Scale color channels
for(unsigned int channel = 0; channel < 3; ++channel)
{
Helpers::ScaleChannel<float>(scaledImage, channel, 0.33f, scaledImage);
}
// Scale depth channel
Helpers::ScaleChannel<float>(scaledImage, 3, 1.0f, scaledImage);
Helpers::WriteImage<FloatVectorImageType>(scaledImage, "scaled.mha");
typedef itk::ImageFileReader< Mask > MaskReaderType;
MaskReaderType::Pointer maskReader = MaskReaderType::New();
maskReader->SetFileName(maskFilename.c_str());
maskReader->Update();
Mask::Pointer finalMask = Mask::New();
ModifyMask(maskReader->GetOutput(), patchRadius, finalMask);
cout.setf(ios::showpoint);
std::vector<float> lambdas;
for(unsigned int i = 0; i <= 10; ++i)
{
lambdas.push_back(0.1f * static_cast<float>(i));
std::cout << "Using lambda " << lambdas[i] << std::endl;
}
std::shared_ptr<SelfPatchCompare> patchCompare(new SelfPatchCompare);
patchCompare->SetNumberOfComponentsPerPixel(imageReader->GetOutput()->GetNumberOfComponentsPerPixel());
//patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchAverageAbsoluteSourceDifference,patchCompare,_1));
patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchColorDifference,patchCompare,_1));
patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchDepthDifference,patchCompare,_1));
std::ofstream fout("scores.txt");
fout.setf(ios::showpoint);
for(unsigned int lambdaId = 0; lambdaId < lambdas.size(); ++lambdaId)
{
// Inpaint
std::cout << "Inpainting with lambda = " << lambdas[lambdaId] << std::endl;
PatchPair::DepthColorLambda = lambdas[lambdaId];
CriminisiInpainting inpainting;
//inpainting.SetDebugFunctionEnterLeave(true);
inpainting.SetPatchRadius(patchRadius);
inpainting.SetImage(scaledImage);
inpainting.SetMask(finalMask);
inpainting.SetMaxForwardLookPatches(3);
inpainting.SetPatchCompare(patchCompare);
inpainting.PatchSortFunction = &SortByDepthAndColor;
//inpainting.PatchSortFunction = &SortByAverageAbsoluteDifference;
//DepthAndColorDifference = ColorDifference * Lambda + (1.0 - Lambda) * DepthDifference;
// When lambda = 0, only the depth is used
// When lambda = 1, only the color is used
inpainting.Initialize();
inpainting.Inpaint();
// Compute error
itk::ImageRegionIterator<Mask> iterator(finalMask, finalMask->GetLargestPossibleRegion());
float depthError = 0.0f;
float colorError = 0.0f;
while(!iterator.IsAtEnd())
{
if(finalMask->IsHole(iterator.GetIndex()))
{
colorError += ColorPixelDifference::Difference(scaledImage->GetPixel(iterator.GetIndex()), inpainting.GetCurrentOutputImage()->GetPixel(iterator.GetIndex()));
depthError += DepthPixelDifference::Difference(scaledImage->GetPixel(iterator.GetIndex()), inpainting.GetCurrentOutputImage()->GetPixel(iterator.GetIndex()));
}
++iterator;
}
std::cout << "colorError: " << colorError << std::endl;
std::cout << "depthError: " << depthError << std::endl;
fout << colorError << " " << depthError << std::endl;
// Unscale all channels
for(unsigned int channel = 0; channel < imageReader->GetOutput()->GetNumberOfComponentsPerPixel(); ++channel)
{
Helpers::ScaleChannel<float>(inpainting.GetCurrentOutputImage(), channel, maxValues[channel], inpainting.GetCurrentOutputImage());
}
std::stringstream ssFloat;
ssFloat.setf(ios::showpoint);
ssFloat << outputPrefix << "_float_lambda_" << lambdas[lambdaId] << ".mha";
Helpers::WriteImage<FloatVectorImageType>(inpainting.GetCurrentOutputImage(), ssFloat.str());
std::stringstream ssRGB;
ssRGB.setf(ios::showpoint);
ssRGB << outputPrefix << "_RGB_lambda_" << lambdas[lambdaId] << ".mha";
Helpers::WriteVectorImageAsRGB(inpainting.GetCurrentOutputImage(), ssRGB.str());
//Helpers::WriteVectorImageAsRGB(inpainting.GetCurrentOutputImage(), Helpers::ReplaceFileExtension(ss.str(), "png"));
}
fout.close();
return EXIT_SUCCESS;
}
void ModifyMask(const Mask::Pointer inputMask, const unsigned int patchRadius, Mask::Pointer outputMask)
{
Mask::Pointer originalHole = Mask::New();
Helpers::DeepCopy<Mask>(inputMask, originalHole);
Helpers::ChangeValue<Mask>(originalHole, 255, 122);
// Expand (dilate) the hole and subtract the old hole. This leaves a region where we know what the solution of the inpainting should be.
// Dilate the hole.
Mask::Pointer dilatedImage = Mask::New();
Helpers::DilateImage<Mask>(inputMask, dilatedImage, patchRadius);
Helpers::WriteImage<Mask>(dilatedImage, "Debug/DilatedImage.mha");
// Subtract the old hole
typedef itk::XorImageFilter <Mask> XorImageFilterType;
XorImageFilterType::Pointer xorFilter = XorImageFilterType::New();
xorFilter->SetInput1(inputMask);
xorFilter->SetInput2(dilatedImage);
xorFilter->Update();
Helpers::WriteImage<Mask>(xorFilter->GetOutput(), "Debug/DilatedAndSubtractedImage.mha");
Mask::Pointer thinMask = Mask::New();
Helpers::DeepCopy<Mask>(xorFilter->GetOutput(), thinMask);
// At this point we have a thin region around the original hole. We do not need to use this entire region to learn lambda.
// To reduce the region, we copy large black blocks over random pixels in the thin region.
std::vector<itk::Index<2> > nonZeroPixels = Helpers::GetNonZeroPixels<Mask>(thinMask);
unsigned int originalNumberOfNonZeroPixels = nonZeroPixels.size();
// Copy zero blocks
float ratioToKeep = .3;
while(static_cast<float>(Helpers::CountNonZeroPixels<Mask>(thinMask))/static_cast<float>(originalNumberOfNonZeroPixels) > ratioToKeep)
{
unsigned int pixelId = rand() % nonZeroPixels.size();
itk::ImageRegion<2> region = Helpers::GetRegionInRadiusAroundPixel(nonZeroPixels[pixelId], patchRadius*2);
Helpers::SetRegionToConstant<Mask>(thinMask, region, 0);
nonZeroPixels = Helpers::GetNonZeroPixels<Mask>(thinMask);
}
// Combine
typedef itk::AddImageFilter <Mask, Mask> AddImageFilterType;
AddImageFilterType::Pointer addFilter = AddImageFilterType::New ();
addFilter->SetInput1(originalHole);
addFilter->SetInput2(thinMask);
addFilter->Update();
Helpers::WriteImage<Mask>(addFilter->GetOutput(), "Debug/FinalHole.mha");
Helpers::DeepCopy<Mask>(addFilter->GetOutput(), outputMask);
}
| 38.29661 | 159 | 0.712326 | [
"vector"
] |
a8193eecf316076c1e4b1b4c255e4917c2e1ae48 | 4,670 | cpp | C++ | src/proto/http/header.cpp | jimi36/librabbit | 32a44f0ebeef6c54f248505073772895e4ebb9c9 | [
"Apache-2.0"
] | 1 | 2019-12-22T06:03:01.000Z | 2019-12-22T06:03:01.000Z | src/proto/http/header.cpp | jimi36/librabbit | 32a44f0ebeef6c54f248505073772895e4ebb9c9 | [
"Apache-2.0"
] | null | null | null | src/proto/http/header.cpp | jimi36/librabbit | 32a44f0ebeef6c54f248505073772895e4ebb9c9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2015-2018 ZhengHaiTao <ming8ren@163.com>
*
* 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 "pump/debug.h"
#include "pump/proto/http/header.h"
namespace pump {
namespace proto {
namespace http {
#define head_value_sep "; "
header::header() noexcept :
header_parsed_(false) {}
void header::set_head(const std::string &name, int32_t value) {
char strval[64] = {0};
pump_snprintf(strval, sizeof(strval) - 1, "%d", value);
headers_[name].push_back(strval);
}
void header::set_head(const std::string &name, const std::string &value) {
auto vals = split_string(value, "[,;] *");
auto it = headers_.find(name);
if (it == headers_.end()) {
headers_[name] = vals;
} else {
it->second.insert(it->second.end(), vals.begin(), vals.end());
}
}
void header::set_unique_head(const std::string &name, int32_t value) {
char strval[64] = {0};
pump_snprintf(strval, sizeof(strval) - 1, "%d", value);
headers_[name] = std::vector<std::string>(1, strval);
}
void header::set_unique_head(
const std::string &name,
const std::string &value) {
headers_[name] = split_string(value, "[,;] *");
}
bool header::get_head(const std::string &name, int32_t &value) const {
auto it = headers_.find(name);
if (it == headers_.end() || it->second.empty()) {
return false;
}
value = atol(it->second[0].c_str());
return true;
}
bool header::get_head(const std::string &name, std::string &value) const {
auto it = headers_.find(name);
if (it == headers_.end() || it->second.empty()) {
return false;
}
value = join_strings(it->second, head_value_sep);
return true;
}
bool header::get_head(
const std::string &name,
std::vector<std::string> &values) const {
auto it = headers_.find(name);
if (it == headers_.end() || it->second.empty()) {
return false;
}
values = it->second;
return true;
}
bool header::has_head(const std::string &name) const {
if (headers_.find(name) == headers_.end()) {
return false;
}
return true;
}
int32_t header::__parse_header(const char *b, int32_t size) {
if (header_parsed_) {
return 0;
}
std::string name;
std::string value;
const char *beg = b;
const char *end = b;
const char *line_end = nullptr;
while ((line_end = find_http_line_end(beg, uint32_t(size - (end - b))))) {
// Check parsed complete
if (beg + http_crlf_length == line_end) {
beg += http_crlf_length;
header_parsed_ = true;
break;
}
// Parse header name
while (end < line_end && *end != ':') {
++end;
}
if (end >= line_end || end == beg) {
return -1;
}
name.assign(beg, end);
// Skip to header vaule position
while (end < line_end && (*end == ' ' || *end == ':')) {
++end;
}
pump_assert(end <= line_end - http_crlf_length);
// Parse header value
beg = end;
end = line_end - http_crlf_length;
if (end > beg) {
value.assign(beg, end);
}
// Store header
set_head(name, value);
beg = end = line_end;
}
return int32_t(beg - b);
}
int32_t header::__serialize_header(std::string &buffer) const {
int32_t size = 0;
std::string value;
char header_line[http_line_max_length + 1] = {0};
for (auto beg = headers_.begin(); beg != headers_.end(); beg++) {
auto cnt = beg->second.size();
if (cnt == 0) {
continue;
} else if (cnt == 1) {
value = beg->second[0];
} else {
value = join_strings(beg->second, head_value_sep);
}
size += pump_snprintf(
header_line,
sizeof(header_line) - 1,
"%s: %s\r\n",
beg->first.c_str(),
value.c_str());
buffer.append(header_line);
}
size += http_crlf_length;
buffer.append(http_crlf);
return size;
}
} // namespace http
} // namespace proto
} // namespace pump | 27.151163 | 78 | 0.583512 | [
"vector"
] |
a825619714b0330ed1f0d8f4f4f2d2293b0429c1 | 3,510 | cpp | C++ | test/source/example.cpp | TheLartians/Glue | 721cbb74771be98e78c2eaf2de4751cf9de7cc9f | [
"MIT"
] | 51 | 2019-08-07T08:34:51.000Z | 2021-10-04T08:32:32.000Z | test/source/example.cpp | TheLartians/Glue | 721cbb74771be98e78c2eaf2de4751cf9de7cc9f | [
"MIT"
] | 54 | 2019-05-03T12:17:27.000Z | 2020-05-25T15:45:26.000Z | test/source/example.cpp | TheLartians/Glue | 721cbb74771be98e78c2eaf2de4751cf9de7cc9f | [
"MIT"
] | 2 | 2020-05-20T12:51:25.000Z | 2021-02-25T19:54:15.000Z | #include <doctest/doctest.h>
#include <vector>
// clang-format off
#include <glue/value.h>
#include <iostream>
void valueExample() {
// `glue::Value`s hold an `revisited::Any` type that can store any type of value
glue::Value value = "Hello glue!";
// access the any type through the `->` or `*` operator
// `as<T>()` returns an `std::optional<T>` that is defined if the cast is possible
std::cout << *value->as<std::string>() << std::endl;
// `glue::MapValue` is a wrapper for a container that maps strings to values
// `glue::createAnyMap()` creates a map based on `std::unordered_set`
// Values also accept lambda functions
glue::MapValue map = glue::createAnyMap();
map["myNumber"] = 42;
map["myString"] = value;
map["myCallback"] = [](bool a, float b){ return a ? b : -b; };
map["myMap"] = glue::createAnyMap();
// use helper functions to cast to maps or callbacks.
// the result will evaluate to `false` if no cast is possible.
if (auto f = map["myCallback"].asFunction()) {
// callbacks are stored as a `revisited::AnyFunction` and can accept both values or `Any` arguments
// (here `map["myNumber"]` is casted to an `Any` through the `*` operator)
// `get<T>` returns casts the value to `T` or throws an exception if not possible
std::cout << f(false, *map["myNumber"]).get<int>() << std::endl;
}
// inner maps are also `glue::MapValue`s.
map["myMap"]["inner"] = "inner value";
}
// clang-format on
// clang-format off
#include <glue/class.h>
#include <glue/context.h>
#include <iostream>
#include <glue/declarations.h>
struct A {
std::string member;
};
struct B: public A {
B(std::string value) : A{value} {}
int method(int v) { return int(member.size()) + v; }
};
void classExample() {
auto map = glue::createAnyMap();
// `glue::createClass<T>` is a convience function for declaring maps for class APIs
// `addConstructor<Args...>()` adds a function that constructs `A` given the argument types `Args...`
// `.addMember("name", &T::member)` adds a setter (`member`) and getter (`setMember`) function
map["A"] = glue::createClass<A>()
.addConstructor<>()
.addMember("member", &A::member)
;
// classes can be made inheritance aware
// `setExtends(map)` uses the argument map or callback to retrieve undefined keys
// `glue::WithBases<A>()` adds implicit conversions to the listed base classes
// `addMethod("name", &T::method)` adds a method that calls a member function or lambda
map["B"] = glue::createClass<B>(glue::WithBases<A>())
.setExtends(map["A"])
.addConstructor<std::string>()
.addMethod("method", &B::method)
.addMethod("lambda", [](const B &b, int x){ return b.member.size() + x; })
;
// contexts collect map class data and can be used to test instance creation
glue::Context context;
context.addRootMap(map);
// `glue::Instance` captures a value and behaves as a class instance
auto b = context.createInstance(map["B"][glue::keys::constructorKey]("arg"));
// calls will be treated as member functions
std::cout << b["member"]().get<std::string>() << std::endl;
b["setMember"]("new value");
std::cout << b["lambda"](10).get<int>() << std::endl;
glue::DeclarationPrinter printer;
printer.init();
printer.print(std::cout, map, &context);
}
// clang-format on
TEST_CASE("Example") {
auto orig_buf = std::cout.rdbuf();
std::cout.rdbuf(NULL);
CHECK_NOTHROW(valueExample());
CHECK_NOTHROW(classExample());
std::cout.rdbuf(orig_buf);
}
| 34.411765 | 103 | 0.659544 | [
"vector"
] |
a839c297167a1fdf1ad56284bb7b4871ccb66496 | 9,828 | hpp | C++ | open/Inspur/code/harness/harness_dlrm/batch_maker.hpp | fenz-org/mlperf_inference_results_v0.7 | 2e38bec7f8df806283802a69db3d0038a37d026e | [
"Apache-2.0"
] | 19 | 2020-10-26T17:37:22.000Z | 2022-01-20T09:32:38.000Z | open/Inspur/code/harness/harness_dlrm/batch_maker.hpp | fenz-org/mlperf_inference_results_v0.7 | 2e38bec7f8df806283802a69db3d0038a37d026e | [
"Apache-2.0"
] | 11 | 2020-10-21T19:18:48.000Z | 2021-03-11T18:50:36.000Z | open/Inspur/code/harness/harness_dlrm/batch_maker.hpp | fenz-org/mlperf_inference_results_v0.7 | 2e38bec7f8df806283802a69db3d0038a37d026e | [
"Apache-2.0"
] | 19 | 2020-10-21T19:15:17.000Z | 2022-01-04T08:32:08.000Z | /*
* Copyright (c) 2020, NVIDIA CORPORATION. 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.
*/
#pragma once
#include <condition_variable>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#include <string>
#include <nvToolsExt.h>
#include "qsl.hpp"
#include "dlrm_qsl.hpp"
#include "lwis_buffers.h"
using DLRMNumericInputType = int8_t;
using DLRMCategoricalInputType = int32_t;
using DLRMOutputType = float;
using DLRMInferCallback = std::function<void(std::vector<mlperf::QuerySampleResponse>&)>;
#define NVTX 0
#if NVTX
#define NVTX_MARK(message) nvtxMarkA(message);
#define NVTX_NAME_THIS_THREAD(name) nvtxNameOsThreadA(pthread_self(), name)
#define NVTX_RANGE_PUSH(message) nvtxRangePushA(message);
#define NVTX_RANGE_POP() nvtxRangePop();
#else
#define NVTX_MARK(message)
#define NVTX_NAME_THIS_THREAD(name)
#define NVTX_RANGE_PUSH(message)
#define NVTX_RANGE_POP()
#endif
constexpr size_t kMIN_NUM_PAIRS = 100;
struct DLRMTask
{
mlperf::QuerySample querySample;
size_t numIndividualPairs;
};
/* DLRMDataBuffer abstracts a host and device buffer and provides H2DAsync and D2HAsync. However, it does not assume
* that `host` refers to its own internal buffer to allow passing in arbitrary host memory addresses. To use its
* internal buffer, use `GetHostPtr()`.
*/
template<typename T>
class DLRMDataBuffer
{
public:
DLRMDataBuffer(size_t length, size_t maxBatchSize, bool allocHost=true, bool allocDevice=true) :
mLength(length),
mMaxBatchSize(maxBatchSize),
mMaxBytes(maxBatchSize * sizeof(T) * mLength),
mHostBuffer(allocHost ? mMaxBytes : 0),
mDeviceBuffer(allocDevice ? mMaxBytes : 0),
mHostPtr(static_cast<T*>(mHostBuffer.data())),
mDevicePtr(static_cast<T*>(mDeviceBuffer.data()))
{
CHECK_EQ(mMaxBatchSize > 0, true);
CHECK_EQ(mMaxBytes > 0, true);
CHECK_EQ(!allocHost || (mHostPtr != nullptr), true);
CHECK_EQ(!allocDevice || (mDevicePtr != nullptr), true);
}
void H2H(const T* hostPtr, size_t size, size_t offset = 0)
{
CHECK_EQ(mHostPtr != nullptr, true);
memcpy(GetHostPtr() + offset * mLength, hostPtr, ElemByteSize() * size);
}
void H2DAsync(const T* hostPtr, size_t size, cudaStream_t stream, bool oddBatch = false)
{
// if oddBatch, only the first (size - 1) inputs on host have valid data
// the last one will not be copied
auto unpaddedBatchSize = oddBatch ? size - 1 : size;
CHECK_EQ(mDevicePtr != nullptr, true);
CHECK_EQ(cudaMemcpyAsync(
mDevicePtr,
hostPtr,
ElemByteSize() * unpaddedBatchSize,
cudaMemcpyHostToDevice,
stream
),
cudaSuccess);
if (oddBatch)
{
CHECK_EQ(cudaMemcpyAsync(
mDevicePtr + unpaddedBatchSize * mLength,
hostPtr,
ElemByteSize() * 1,
cudaMemcpyHostToDevice,
stream
),
cudaSuccess);
}
}
void D2HAsync(T* hostPtr, size_t size, cudaStream_t stream)
{
CHECK_EQ(mDevicePtr != nullptr, true);
CHECK_EQ(cudaMemcpyAsync(
hostPtr,
mDevicePtr,
ElemByteSize() * size,
cudaMemcpyDeviceToHost,
stream
),
cudaSuccess);
}
size_t ElemByteSize() { return mLength * sizeof(T); }
T* const GetDevicePtr() { return mDevicePtr; }
T* const GetHostPtr() { return mHostPtr; }
void SetHostPtr(T* ptr) { mHostPtr = ptr; }
void ResetHostPtr() { mHostPtr = static_cast<T*>(mHostBuffer.data()); }
bool isDefaultHostPtr() { return mHostPtr == static_cast<T*>(mHostBuffer.data()); }
private:
size_t mLength;
size_t mMaxBatchSize;
size_t mMaxBytes;
lwis::HostBuffer mHostBuffer;
lwis::DeviceBuffer mDeviceBuffer;
T* const mDevicePtr;
T* mHostPtr;
};
// Aliases for convenience
using DLRMNumericBuffer = DLRMDataBuffer<DLRMNumericInputType>;
using DLRMCategoricalBuffer = DLRMDataBuffer<DLRMCategoricalInputType>;
using DLRMOutputBuffer = DLRMDataBuffer<DLRMOutputType>;
class BatchMaker;
class Batch
{
public:
Batch(std::string id, size_t maxBatchSize, size_t minBatchSize, size_t numericVolume, size_t categoricalVolume, BatchMaker* batchMaker);
// Copy task data from QSL memory to this Batch's host buffers
void doCopy(size_t tasksOffset, size_t pairsOffset, size_t pairsToCopy);
// Reset batch state after consumption in inference
void reset();
// pad batch size to be even if needed, and set a flag to indicate this
void padToEvenSize();
void pushTask(DLRMTask task) { mTasks.push_back(task); }
std::vector<DLRMTask> const getTasks() const { return mTasks; }
void commitCopies(size_t numCopies) { mCommittedCopies += numCopies; }
size_t getCommittedCopies() const { return mCommittedCopies; }
void completeCopies(size_t numCopies) { mCompletedCopies += numCopies; }
size_t getCompletedCopies() const { return mCompletedCopies; }
void markReadyWhenComplete() { mReadyWhenComplete = true; }
bool isReadyWhenComplete() const { return mReadyWhenComplete; }
bool isComplete() const { return mCompletedCopies == mCommittedCopies && mReadyWhenComplete; }
bool isOddBatch() const { return mOddBatch; }
size_t getFreeSpace() const { return mMaxBatchSize - mCommittedCopies; }
std::string mDebugId;
BatchMaker* mBatchMaker;
DLRMNumericInputType* const getNumericHostPtr() { return mNumericInputBuf.GetHostPtr(); }
DLRMCategoricalInputType* const getCategoricalHostPtr() { return mCategoricalInputBuf.GetHostPtr(); }
private:
void ContiguityAwareH2H(size_t tasksOffset, size_t pairsOffset, size_t pairsToCopy);
void IndividualH2H(size_t tasksOffset, size_t pairsOffset, size_t pairsToCopy);
std::vector<DLRMTask> mTasks;
DLRMNumericBuffer mNumericInputBuf;
DLRMCategoricalBuffer mCategoricalInputBuf;
size_t mCommittedCopies;
size_t mCompletedCopies;
size_t mMinBatchSize;
size_t mMaxBatchSize;
bool mReadyWhenComplete;
bool mOddBatch;
};
class BatchMaker
{
public:
BatchMaker(size_t numStagingThreads,
size_t numStagingBatches,
size_t maxBatchSize,
size_t maxPairsPerThread,
size_t numericVolume,
size_t categoricalVolume,
bool checkContiguity,
std::shared_ptr<DLRMSampleLibrary> qsl,
std::vector<int> cpus);
~BatchMaker();
void IssueQuery(const std::vector<mlperf::QuerySample>& samples);
void FlushQueries();
void StopWork();
// Interface to fetch the earliest Batch from the queue of Batches ready for inference,
// blocking if no batch is ready
Batch* GetBatch();
// Interface to notify that the inference thread has completed H2D transfer
// of a `batch` and it can be returned to the pool of idle batches
void NotifyH2D(Batch *batch);
std::shared_ptr<DLRMSampleLibrary> mQsl;
bool mCheckContiguity;
private:
// Greedily fetches tasks, and copies them to the active staging batch
void StageBatch(int threadIdx);
// Pushes a staged batch to the queue of batches ready for inference
// NOTE: Should be called under mutex lock
void HandleReadyBatch(Batch *batch);
// Close this batch for new copies, and handle related bookkeeping
void CloseBatch(Batch* batch);
// Check if batch satisfies conditions to be marked as ready
void ReadyBatchIfComplete(Batch* batch);
// All Batches owned by this BatchMaker
std::vector<Batch> mInputBatches;
// Pointers to idle empty Batches, which are not ready, not staging, and not being used for inference
std::vector<Batch*> mIdleBatches;
// Queue of staged Batches that are ready to be sent for inference
std::deque<Batch*> mReadyBatches;
// Pointer to Batch currently being used for inference by all StageBatch threads
Batch* mStagingBatch;
// Queue of task IDs coming from LoadGen which are to be staged
std::deque<DLRMTask> mTasksQ;
// Threads running StageBatch
std::vector<std::thread> mStagingThreads;
// Mutex to serialize access mStagingBatch & mIdleBatches
std::mutex mMutex;
// Condition variable on which StageBatch will wait to produce batches
std::condition_variable mProducerCV;
// Condition variable on which GetBatch will wait to consume batches
std::condition_variable mConsumerCV;
// Indicates that there will no new tasks and the worker threads should stop processing samples
bool mStopWork;
// Indicates FlushQueries has been called by LoadGen
bool mFlushQueries;
// Total number of readied pairs sent for inference
size_t mReadiedPairs;
// Total number of pairs issued by LoadGen in IssueQuery
size_t mIssuedPairs;
size_t mMinBatchSize;
size_t mMaxBatchSize;
size_t mMaxPairsPerThread;
size_t mWaitingBatches;
// CPUs on which staging threads should run. Empty implies no constraint.
std::vector<int> mCpus;
bool UseNuma() { return !mCpus.empty(); };
};
| 33.889655 | 140 | 0.69302 | [
"vector"
] |
a83e8f3c1b0217e0f21170282689fcdb32a258c8 | 769 | hpp | C++ | include/engge/Engine/Thread.hpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 127 | 2018-12-09T18:40:02.000Z | 2022-03-06T00:10:07.000Z | include/engge/Engine/Thread.hpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 267 | 2019-02-26T22:16:48.000Z | 2022-02-09T09:49:22.000Z | include/engge/Engine/Thread.hpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 17 | 2019-02-26T20:45:34.000Z | 2021-06-17T15:06:26.000Z | #pragma once
#include <string>
#include <vector>
#include "squirrel.h"
#include "ThreadBase.hpp"
namespace ng {
class Thread final : public ThreadBase {
public:
Thread(std::string name, bool isGlobal,
HSQUIRRELVM v,
HSQOBJECT thread_obj,
HSQOBJECT env_obj,
HSQOBJECT closureObj,
std::vector<HSQOBJECT> args);
~Thread() final;
[[nodiscard]] std::string getName() const final;
[[nodiscard]] HSQUIRRELVM getThread() const final;
[[nodiscard]] bool isGlobal() const final { return m_isGlobal; }
bool call();
private:
std::string m_name;
HSQUIRRELVM m_v;
HSQOBJECT m_threadObj;
HSQOBJECT m_envObj;
HSQOBJECT m_closureObj;
std::vector<HSQOBJECT> m_args;
bool m_isGlobal{false};
};
} // namespace ng
| 22.617647 | 66 | 0.686606 | [
"vector"
] |
a83fe0974b0fb7ea55c53eba79efa327351fb139 | 14,637 | cpp | C++ | include/taichi/math/levelset.cpp | gonnavis/taichi | ba1898643e4548a23ecae340e963614b28b8a103 | [
"MIT"
] | 2 | 2019-06-25T02:12:37.000Z | 2019-06-25T02:12:48.000Z | include/taichi/math/levelset.cpp | gonnavis/taichi | ba1898643e4548a23ecae340e963614b28b8a103 | [
"MIT"
] | 1 | 2019-10-20T08:46:09.000Z | 2019-10-20T08:46:09.000Z | include/taichi/math/levelset.cpp | gonnavis/taichi | ba1898643e4548a23ecae340e963614b28b8a103 | [
"MIT"
] | 1 | 2021-11-29T22:47:24.000Z | 2021-11-29T22:47:24.000Z | /*******************************************************************************
Copyright (c) The Taichi Authors (2016- ). All Rights Reserved.
The use of this software is governed by the LICENSE file.
*******************************************************************************/
#include "levelset.h"
TC_NAMESPACE_BEGIN
template <int DIM>
void LevelSet<DIM>::add_sphere(typename LevelSet<DIM>::Vector center,
real radius,
bool inside_out) {
for (auto &ind : this->get_region()) {
Vector sample = ind.get_pos();
real dist = (inside_out ? -1 : 1) * (length(center - sample) - radius);
this->set(ind, std::min(Array::get(ind), dist));
}
}
template <>
void LevelSet<2>::add_polygon(std::vector<Vector2> polygon, bool inside_out) {
for (auto &ind : this->get_region()) {
Vector2 p = ind.get_pos();
real dist = ((inside_polygon(p, polygon) ^ inside_out) ? -1 : 1) *
(nearest_distance(p, polygon));
this->set(ind, std::min(Array::get(ind), dist));
}
}
template <>
Vector2 LevelSet<2>::get_gradient(const Vector2 &pos) const {
assert_info(inside(pos),
"LevelSet Gradient Query out of Bound! (" +
std::to_string(pos.x) + ", " + std::to_string(pos.y) + ")");
real x = pos.x, y = pos.y;
x = clamp(x - storage_offset.x, 0.0_f, this->res[0] - 1.0_f - eps);
y = clamp(y - storage_offset.y, 0.0_f, this->res[1] - 1.0_f - eps);
const int x_i = clamp(int(x), 0, this->res[0] - 2);
const int y_i = clamp(int(y), 0, this->res[1] - 2);
const real x_r = x - x_i;
const real y_r = y - y_i;
const real gx = lerp(y_r, Array::get(x_i + 1, y_i) - Array::get(x_i, y_i),
Array::get(x_i + 1, y_i + 1) - Array::get(x_i, y_i + 1));
const real gy = lerp(x_r, Array::get(x_i, y_i + 1) - Array::get(x_i, y_i),
Array::get(x_i + 1, y_i + 1) - Array::get(x_i + 1, y_i));
return Vector2(gx, gy);
}
template <int DIM>
typename LevelSet<DIM>::Vector LevelSet<DIM>::get_normalized_gradient(
const typename LevelSet<DIM>::Vector &pos) const {
Vector gradient = get_gradient(pos);
if (length(gradient) < 1e-10f)
gradient[0] = 1.0_f;
return normalize(gradient);
}
template <>
real LevelSet<2>::get(const Vector2 &pos) const {
assert_info(inside(pos),
"LevelSet Query out of Bound! (" + std::to_string(pos.x) + ", " +
std::to_string(pos.y) + ")");
real x = pos.x, y = pos.y;
x = clamp(x - this->storage_offset.x, 0.0_f, this->res[0] - 1.0_f - eps);
y = clamp(y - this->storage_offset.y, 0.0_f, this->res[1] - 1.0_f - eps);
const int x_i = clamp(int(x), 0, this->res[0] - 2);
const int y_i = clamp(int(y), 0, this->res[1] - 2);
const real x_r = x - x_i;
const real y_r = y - y_i;
const real ly0 = lerp(x_r, Array::get(x_i, y_i), Array::get(x_i + 1, y_i));
const real ly1 =
lerp(x_r, Array::get(x_i, y_i + 1), Array::get(x_i + 1, y_i + 1));
return lerp(y_r, ly0, ly1);
}
template <>
real LevelSet<3>::get(const Vector3 &pos) const {
assert_info(inside(pos),
"LevelSet Query out of Bound! (" + std::to_string(pos.x) + ", " +
std::to_string(pos.y) + ", " + std::to_string(pos.z) + ")");
real x = pos.x, y = pos.y, z = pos.z;
x = clamp(x - storage_offset.x, 0.0_f, this->res[0] - 1.0_f - eps);
y = clamp(y - storage_offset.y, 0.0_f, this->res[1] - 1.0_f - eps);
z = clamp(z - storage_offset.z, 0.0_f, this->res[2] - 1.0_f - eps);
const int x_i = clamp(int(x), 0, this->res[0] - 2);
const int y_i = clamp(int(y), 0, this->res[1] - 2);
const int z_i = clamp(int(z), 0, this->res[2] - 2);
const real x_r = x - x_i;
const real y_r = y - y_i;
const real z_r = z - z_i;
return lerp(x_r, lerp(y_r, lerp(z_r, Array3D<real>::get(x_i, y_i, z_i),
Array3D<real>::get(x_i, y_i, z_i + 1)),
lerp(z_r, Array3D<real>::get(x_i, y_i + 1, z_i),
Array3D<real>::get(x_i, y_i + 1, z_i + 1))),
lerp(y_r, lerp(z_r, Array3D<real>::get(x_i + 1, y_i, z_i),
Array3D<real>::get(x_i + 1, y_i, z_i + 1)),
lerp(z_r, Array3D<real>::get(x_i + 1, y_i + 1, z_i),
Array3D<real>::get(x_i + 1, y_i + 1, z_i + 1))));
}
template <>
typename LevelSet<2>::Array LevelSet<2>::rasterize(
LevelSet<2>::VectorI output_res) {
for (auto &p : (*this)) {
if (std::isnan(p)) {
printf("Warning: nan in levelset.");
}
}
Array2D<real> out(output_res);
Vector2 actual_size;
if (this->storage_offset == Vector2(0.0_f, 0.0_f)) {
actual_size = Vector2(this->res[0] - 1, this->res[1] - 1);
} else {
actual_size = Vector2(this->res[0], this->res[1]);
}
Vector2 scale_factor = actual_size / output_res.template cast<real>();
for (auto &ind :
Region2D(0, this->res[0], 0, this->res[1], Vector2(0.5f, 0.5f))) {
Vector2 p = scale_factor * ind.get_pos();
out[ind] = this->sample(p);
if (std::isnan(out[ind])) {
out[ind] = std::numeric_limits<real>::infinity();
}
}
return out;
}
template <>
Array3D<real> LevelSet<3>::rasterize(Vector3i output_res) {
for (auto &p : (*this)) {
if (std::isnan(p)) {
printf("Warning: nan in levelset.");
}
}
Array3D<real> out(output_res);
Vector3 actual_size;
if (storage_offset == Vector3(0.0_f, 0.0_f, 0.0_f)) {
actual_size = Vector3(this->res[0] - 1, this->res[1] - 1, this->res[2] - 1);
} else {
actual_size = Vector3(this->res[0], this->res[1], this->res[2]);
}
Vector3 scale_factor = actual_size / output_res.cast<real>();
for (auto &ind :
Region3D(0, res[0], 0, res[1], 0, res[2], Vector3(0.5f, 0.5f, 0.5f))) {
Vector3 p = scale_factor * ind.get_pos();
out[ind] = sample(p);
if (std::isnan(out[ind])) {
out[ind] = std::numeric_limits<real>::infinity();
}
}
return out;
}
template <int DIM>
void LevelSet<DIM>::add_plane(const typename LevelSet<DIM>::Vector &normal_,
real d) {
Vector normal = normalized(normal_);
real coeff = 1.0_f / length(normal);
for (auto &ind : this->get_region()) {
Vector sample = ind.get_pos();
real dist = (taichi::dot(sample, normal) + d) * coeff;
this->set(ind, std::min(Array::get(ind), dist));
}
}
//Box - signed - exact
//
//float sdBox( vec3 p, vec3 b )
//{
// vec3 d = abs(p) - b;
// return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
//}
template <>
void LevelSet<3>::add_cuboid(Vector3 lower_boundry,
Vector3 upper_boundry,
bool inside_out) {
for (auto &ind : this->get_region()) {
Vector3 sample = ind.get_pos();
Vector3 b = (upper_boundry - lower_boundry) * 0.5_f;
Vector3 center = (upper_boundry + lower_boundry) * 0.5_f;
Vector3 p = sample - center;
Vector3 d = p.abs() - b;
Vector3 clamped_d = d;
for (int i = 0; i < 3; ++i)
clamped_d[i] = std::max(clamped_d[i], 0.0_f);
real dist = std::min(std::max(d[0], std::max(d[1], d[2])), 0.0_f) + clamped_d.length();
set(ind, inside_out ? -dist : dist);
}
}
template <int DIM>
void LevelSet<DIM>::add_slope(const Vector ¢er, real radius, real angle) {
TC_ASSERT_INFO(0 <= radius, "Radius should be non-negative");
TC_ASSERT_INFO(0 <= angle && angle <= pi, "Angle should be in [0, PI]");
for (auto &ind : this->get_region()) {
Vector sample = ind.get_pos();
real dist;
if (abs(sample[0]-center[0] <= 1e-6) && abs(sample[1]-center[1])<1e-6) {
dist = radius;
} else {
real ao = std::atan2(sample[0] - center[0], sample[1] - center[1]);
if (ao < 0) ao += pi * 2;
if (angle / 2 <= ao && ao <= pi) {
dist = sample[1] - (center[1] - radius);
} else if (pi <= ao && ao <= pi + angle) {
dist = radius - sqrt(sqr(center[0]-sample[0]) + sqr(center[1]-sample[1]));
} else {
real a = sin(angle);
real b = cos(angle);
real x = center[0] - radius * a;
real y = center[1] - radius * b;
real c = -(a * x + b * y);
dist = (a * sample[0] + b * sample[1] + c) / sqrt(a * a + b * b);
}
}
this->set(ind, std::min(Array::get(ind), dist));
}
}
template <>
void LevelSet<3>::add_cylinder(const Vector ¢er, real radius, bool inside_out) {
for (auto &ind : this->get_region()) {
Vector sample = ind.get_pos();
real dist;
dist = length(Vector(sample[0], 0, sample[2]) - Vector(center[0], 0, center[2])) - radius;
dist = inside_out ? -dist : dist;
this->set(ind, std::min(Array::get(ind), dist));
}
}
template <int DIM>
void LevelSet<DIM>::global_increase(real delta) {
for (auto &ind : this->get_region()) {
this->set(ind, Array::get(ind) + delta);
}
}
template <>
Vector3 LevelSet<3>::get_gradient(const Vector3 &pos) const {
assert_info(inside(pos),
"LevelSet Gradient Query out of Bound! (" +
std::to_string(pos.x) + ", " + std::to_string(pos.y) + ", " +
std::to_string(pos.z) + ")");
real x = pos.x, y = pos.y, z = pos.z;
x = clamp(x - storage_offset.x, 0.0_f, res[0] - 1.0_f - eps);
y = clamp(y - storage_offset.y, 0.0_f, res[1] - 1.0_f - eps);
z = clamp(z - storage_offset.z, 0.0_f, res[2] - 1.0_f - eps);
const int x_i = clamp(int(x), 0, res[0] - 2);
const int y_i = clamp(int(y), 0, res[1] - 2);
const int z_i = clamp(int(z), 0, res[2] - 2);
const real x_r = x - x_i;
const real y_r = y - y_i;
const real z_r = z - z_i;
// TODO: speed this up
const real gx = lerp(y_r, lerp(z_r,
Array3D<real>::get(x_i + 1, y_i, z_i) -
Array3D<real>::get(x_i, y_i, z_i),
Array3D<real>::get(x_i + 1, y_i, z_i + 1) -
Array3D<real>::get(x_i, y_i, z_i + 1)),
lerp(z_r,
Array3D<real>::get(x_i + 1, y_i + 1, z_i) -
Array3D<real>::get(x_i, y_i + 1, z_i),
Array3D<real>::get(x_i + 1, y_i + 1, z_i + 1) -
Array3D<real>::get(x_i, y_i + 1, z_i + 1)));
const real gy = lerp(z_r, lerp(x_r,
Array3D<real>::get(x_i, y_i + 1, z_i) -
Array3D<real>::get(x_i, y_i, z_i),
Array3D<real>::get(x_i + 1, y_i + 1, z_i) -
Array3D<real>::get(x_i + 1, y_i, z_i)),
lerp(x_r,
Array3D<real>::get(x_i, y_i + 1, z_i + 1) -
Array3D<real>::get(x_i, y_i, z_i + 1),
Array3D<real>::get(x_i + 1, y_i + 1, z_i + 1) -
Array3D<real>::get(x_i + 1, y_i, z_i + 1)));
const real gz = lerp(x_r, lerp(y_r,
Array3D<real>::get(x_i, y_i, z_i + 1) -
Array3D<real>::get(x_i, y_i, z_i),
Array3D<real>::get(x_i, y_i + 1, z_i + 1) -
Array3D<real>::get(x_i, y_i + 1, z_i)),
lerp(y_r,
Array3D<real>::get(x_i + 1, y_i, z_i + 1) -
Array3D<real>::get(x_i + 1, y_i, z_i),
Array3D<real>::get(x_i + 1, y_i + 1, z_i + 1) -
Array3D<real>::get(x_i + 1, y_i + 1, z_i)));
return Vector3(gx, gy, gz);
}
template class LevelSet<2>;
template class LevelSet<3>;
template <int DIM>
void DynamicLevelSet<DIM>::initialize(real _t0,
real _t1,
const LevelSet<DIM> &_ls0,
const LevelSet<DIM> &_ls1) {
t0 = _t0;
t1 = _t1;
levelset0 = std::make_shared<LevelSet<DIM>>(_ls0);
levelset1 = std::make_shared<LevelSet<DIM>>(_ls1);
}
template <>
DynamicLevelSet<2>::Vector DynamicLevelSet<2>::get_spatial_gradient(
const DynamicLevelSet<2>::Vector &pos,
real t) const {
Vector2 gxy0 = levelset0->get_gradient(pos);
Vector2 gxy1 = levelset1->get_gradient(pos);
real gx = lerp((t - t0) / (t1 - t0), gxy0.x, gxy1.x);
real gy = lerp((t - t0) / (t1 - t0), gxy0.y, gxy1.y);
Vector2 gradient = Vector2(gx, gy);
if (length(gradient) < 1e-10f)
return Vector2(1, 0);
else
return normalize(gradient);
}
template <>
DynamicLevelSet<3>::Vector DynamicLevelSet<3>::get_spatial_gradient(
const DynamicLevelSet<3>::Vector &pos,
real t) const {
Vector3 gxyz0 = levelset0->get_gradient(pos);
Vector3 gxyz1 = levelset1->get_gradient(pos);
real gx = lerp((t - t0) / (t1 - t0), gxyz0.x, gxyz1.x);
real gy = lerp((t - t0) / (t1 - t0), gxyz0.y, gxyz1.y);
real gz = lerp((t - t0) / (t1 - t0), gxyz0.z, gxyz1.z);
Vector3 gradient = Vector3(gx, gy, gz);
if (length(gradient) < 1e-10f)
return Vector3(1, 0, 0);
else
return normalize(gradient);
}
template <int DIM>
real DynamicLevelSet<DIM>::get_temporal_derivative(
const typename DynamicLevelSet<DIM>::Vector &pos,
real t) const {
real l0 = levelset0->get(pos);
real l1 = levelset1->get(pos);
return (l1 - l0) / (t1 - t0);
}
template <int DIM>
real DynamicLevelSet<DIM>::sample(
const typename DynamicLevelSet<DIM>::Vector &pos,
real t) const {
real l1 = levelset0->get(pos);
real l2 = levelset1->get(pos);
return lerp((t - t0) / (t1 - t0), l1, l2);
}
template <>
Array3D<real> DynamicLevelSet<3>::rasterize(Vector3i res, real t) {
Array3D<real> r0 = levelset0->rasterize(res);
Array3D<real> r1 = levelset1->rasterize(res);
Array3D<real> out(res);
for (auto &ind : Region3D(Vector3i(0), res, Vector3(0.5f, 0.5f, 0.5f))) {
out[ind] = lerp((t - t0) / (t1 - t0), r0[ind], r1[ind]);
if (std::isnan(out[ind])) {
out[ind] = std::numeric_limits<real>::infinity();
}
}
return out;
}
template <>
Array2D<real> DynamicLevelSet<2>::rasterize(Vector2i res, real t) {
Array2D<real> r0 = levelset0->rasterize(res);
Array2D<real> r1 = levelset1->rasterize(res);
Array2D<real> out(res);
for (auto &ind : Region2D(Vector2i(0), res, Vector2(0.5f, 0.5f))) {
out[ind] = lerp((t - t0) / (t1 - t0), r0[ind], r1[ind]);
if (std::isnan(out[ind])) {
out[ind] = std::numeric_limits<real>::infinity();
}
}
return out;
}
template class DynamicLevelSet<2>;
template class DynamicLevelSet<3>;
TC_NAMESPACE_END
| 37.530769 | 94 | 0.539728 | [
"vector"
] |
61b3038e2008d912ee5d6b0464998f1022d68bb1 | 5,541 | cpp | C++ | Hackerrank/3/sol_long.cpp | luchev/uni-data-structures-and-algorithms-assistant-2019 | 3dcb1efc6f65b4736d3761c0bad858cb236bc213 | [
"MIT"
] | 3 | 2019-10-24T08:38:34.000Z | 2019-12-03T10:46:10.000Z | Hackerrank/3/sol_long.cpp | luchev/uni-data-structures-and-algorithms-2019 | 3dcb1efc6f65b4736d3761c0bad858cb236bc213 | [
"MIT"
] | null | null | null | Hackerrank/3/sol_long.cpp | luchev/uni-data-structures-and-algorithms-2019 | 3dcb1efc6f65b4736d3761c0bad858cb236bc213 | [
"MIT"
] | 2 | 2019-10-22T11:51:18.000Z | 2019-11-03T21:51:33.000Z | #include <vector>
#include <random>
#include <iostream>
#include <algorithm>
#include <chrono>
#include <fstream>
using namespace std;
using namespace chrono;
size_t GenerateUnsignedInt(size_t From, size_t To) {
mt19937 rng;
rng.seed(random_device()());
uniform_int_distribution<mt19937::result_type> generate(From, To);
return generate(rng);
}
vector<size_t> GenerateUnsignedInts(size_t Amount, size_t From, size_t To) {
vector<size_t> vect;
mt19937 rng;
rng.seed(random_device()());
uniform_int_distribution<mt19937::result_type> generate(From, To);
for (size_t i = 0; i < Amount; i++) {
vect.push_back(generate(rng));
}
return vect;
}
vector<long long> GenerateInts(size_t Amount, size_t From, size_t To) {
vector<long long> vect;
mt19937 rng;
rng.seed(random_device()());
uniform_int_distribution<mt19937::result_type> generate(From, To);
uniform_int_distribution<mt19937::result_type> sign(0, 1);
for (size_t i = 0; i < Amount; i++) {
vect.push_back((long long)generate(rng) * (sign(rng) == 1 ? -1 : 1));
}
return vect;
}
template<typename T>
void PrintVector(vector<T> Vector) {
for (size_t i = 0; i < Vector.size(); i++) {
cout << Vector[i] << ", ";
}
cout << endl;
}
void PrintDuration(high_resolution_clock::time_point t1, high_resolution_clock::time_point t2) {
long long duration = duration_cast<nanoseconds>(t2 - t1).count();
//cout << "Nanoseconds: " << duration << endl;
//cout << "Microseconds: " << duration / 1000 << endl;
//cout << "Miliseconds: " << duration / 1000000 << endl;
cout << "Seconds: " << duration / 1000000000.0 << endl;
}
//
// End of generators
//
struct Building {
long long height = 0;
long long price = 0;
};
bool CompareHeight(Building& lhs, Building& rhs) {
return (lhs.height < rhs.height); // || (lhs.height == rhs.height && lhs.price < rhs.price));
}
bool ComparePrice(Building& lhs, Building& rhs) {
return (lhs.price < rhs.price); // || (lhs.price == rhs.price && lhs.height < rhs.height));
}
long long Price(Building* buildings, long long arrSize, long long height) {
long long price = 0;
for (long long i = 0; i < arrSize; i++) {
price += abs(buildings[i].height - height) * buildings[i].price;
}
return price;
}
bool BuildingEqual(const Building& a, const Building& b) {
return (a.height == b.height && a.price == b.price);
}
const long long TESTSIZE = 10;
long long Min(long long a, long long b) {
return a < b ? a : b;
}
long long MinPriceTernaryNaive(Building* buildings, long long size, long long left, long long right) {
if (right - left < 3) {
long long currentMin = Price(buildings, size, left);
for (long long i = left + 1; i < right + 1; i++) {
currentMin = Min(currentMin, Price(buildings, size, i));
}
return currentMin;
}
else if (left < right) {
long long leftThird = left + (right - left) / 3;
long long rightThird = right - (right - left) / 3;
long long leftPrice = Price(buildings, size, leftThird);
long long rightPrice = Price(buildings, size, rightThird);
if (leftPrice < rightPrice) {
return MinPriceTernaryNaive(buildings, size, left, rightThird);
}
else if (leftPrice > rightPrice) {
return MinPriceTernaryNaive(buildings, size, leftThird, right);
}
else {
return Min(Min(MinPriceTernaryNaive(buildings, size, left, leftThird), MinPriceTernaryNaive(buildings, size, leftThird, rightThird)),
MinPriceTernaryNaive(buildings, size, rightThird, right));
}
}
return -1;
}
long long MinPriceTernary(Building* buildings, long long size, Building* unique, long long uniqueSize, long long left, long long right) {
if (right - left < 3) {
long long currentMin = Price(buildings, size, buildings[left].height);
for (long long i = left + 1; i < right + 1; i++) {
currentMin = Min(currentMin, Price(buildings, size, buildings[i].height));
}
return currentMin;
} else if (left < right) {
long long leftThird = left + (right - left) / 3;
long long rightThird = right - (right - left) / 3;
long long leftPrice = Price(buildings, size, buildings[leftThird].height);
long long rightPrice = Price(buildings, size, buildings[rightThird].height);
if (leftPrice < rightPrice) {
return MinPriceTernary(buildings, size, unique, uniqueSize, left, rightThird);
}
else if (leftPrice > rightPrice) {
return MinPriceTernary(buildings, size, unique, uniqueSize, leftThird, right);
}
else { // Should never enter this but just in case
return Min(Min(MinPriceTernary(buildings, size, unique, uniqueSize, left, leftThird), MinPriceTernary(buildings, size, unique, uniqueSize, leftThird, rightThird)),
MinPriceTernary(buildings, size, unique, uniqueSize, rightThird, right));
}
}
return -1;
}
int main() {
long long N;
cin >> N;
Building* buildings = new Building[N];
for (size_t i = 0; i < N; i++) {
cin >> buildings[i].height;
cin >> buildings[i].price;
}
sort(buildings, buildings + N, CompareHeight);
if (N > 1) {
cout << MinPriceTernaryNaive(buildings, N, buildings[0].height, buildings[N-1].height);
}
else {
cout << 0;
}
}
| 33.786585 | 175 | 0.623173 | [
"vector"
] |
61b5930404b8c08b067d3453706f81084aa62310 | 8,938 | hpp | C++ | src/core/storage/fileio/s3_api.hpp | cookingcodewithme/turicreate | a89e203d60529d2d72547c03ec9753ea979ee342 | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | src/core/storage/fileio/s3_api.hpp | cookingcodewithme/turicreate | a89e203d60529d2d72547c03ec9753ea979ee342 | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | src/core/storage/fileio/s3_api.hpp | cookingcodewithme/turicreate | a89e203d60529d2d72547c03ec9753ea979ee342 | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /* Copyright © 2020 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at
* https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef TURI_S3_UPLOADER_HPP
#define TURI_S3_UPLOADER_HPP
#ifndef TC_DISABLE_REMOTEFS
#include <aws/s3/S3Client.h>
#include <core/logging/assertions.hpp>
#include <core/storage/fileio/fs_utils.hpp>
#include <fstream>
#include <future>
#include <memory>
#include <string>
#include <vector>
namespace turi {
/**
* \ingroup fileio
* \internal
*
* constructed **only** from user provided url
*
* A complete specification of an S3 bucket and object,
* including all authentication required.
*/
struct s3url {
std::string access_key_id;
std::string secret_key;
std::string bucket;
std::string object_name;
// endpoint that embeded in the url
std::string endpoint;
// endpoint used by sdk, not in the url
boost::optional<std::string> sdk_endpoint;
boost::optional<std::string> sdk_region;
boost::optional<std::string> sdk_proxy;
// this call doesn't compare the optional members
bool operator==(const s3url& other) const {
return access_key_id == other.access_key_id &&
secret_key == other.secret_key && bucket == other.bucket &&
object_name == other.object_name && endpoint == other.endpoint;
}
/*
* @param with_credentials: user should not see this
*
* reconstruct to url format,
* s3://[access_key_id]:[secret_key]:[endpoint/][bucket]/[object_name],
* which turi uses everywhere.
*/
std::string string_from_s3url(bool with_credentials = true) const {
std::string ret("s3://");
ret.reserve(128);
const size_t prot_len = ret.size();
if (with_credentials && !access_key_id.empty()) {
ASSERT_TRUE(!secret_key.empty());
ret.append(access_key_id);
ret.append(1, ':');
ret.append(secret_key);
ret.append(1, ':');
}
// this is embeded form
// something like: s3://s3.amazonaws.com/bucket/object/name
if (!endpoint.empty()) {
ret.append(endpoint);
ret.append(1, '/');
}
ASSERT_TRUE(!bucket.empty());
ret.append(bucket);
if (!object_name.empty()) {
// s3://object_key is a valid case
if (ret.size() > prot_len) ret.append(1, '/');
ret.append(object_name);
}
return ret;
}
friend std::ostream& operator<<(std::ostream& os, const s3url& url) {
if (url.sdk_endpoint)
os << "endpoint used by sdk: " << *url.sdk_endpoint << "; ";
if (url.sdk_region) os << "region used by sdk: " << *url.sdk_region << "; ";
if (url.sdk_proxy) os << "proxy used by sdk: " << *url.sdk_proxy << "; ";
return os << url.string_from_s3url(false);
}
};
/**
* \ingroup fileio
* \internal
*
* initialize the sdk with TRUI constomized environment variable
*
* will set the endpoint/region that used to configure the client
*
* this call will modify optional sdk_* members
*/
Aws::S3::S3Client init_aws_sdk_with_turi_env(s3url& parsed_url);
/**
* \ingroup fileio
* \internal
* Get the last modified time stamp of file.
*
* Throw exception if the url cannot be fetched.
*
* Return empty string if last modified is not available,
* e.g. the url is a directory path or file does not exist.
*/
std::string get_s3_file_last_modified(const std::string& url);
/**
* \ingroup fileio
* \internal
* Return type of list_objects;
*/
struct list_objects_response {
/// Non-empty if there was an error
std::string error;
/// A list of all the "sub-directories" found. Encoded with url, see s3url.
std::vector<std::string> directories;
/// A list of all the objects found. Encoded with url, see s3url.
/// this should be really called object_urls;
std::vector<std::string> objects;
/// A list of all the objects size.
std::vector<size_t> objects_size;
/// Last modified time for the objects.
std::vector<std::string> objects_last_modified;
};
/**
* \ingroup fileio
* \internal
* Lists objects or prefixes prefixed by a give s3 url.
*
* This is a thin wrapper around the S3 API
* http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
* and may not quite do what you think it does.
*
* if s3_url points to a valid prefix, it will return only the prefix
* as a directory. For instance if I have an S3 bucket containing
*
* foo/hello.txt
*
* list_objects("s3://foo") will return simply "foo/" as a directory.
*
* See list_directory() and is_directory() for a more sensible implementation
* which behaves somewhat more file system like.
*
* \returns A list_objects_response object.
* If list_objects_response.error is an empty string, it indicates success.
* Otherwise, it contains an error code. list_objects_response.directories
* indicate all "directories" stored with the requested prefix. And
* list_objects_response.objects indicates all regular objects stored with the
* requested prefix.
*
*/
list_objects_response list_objects(std::string s3_url, std::string proxy = "");
/**
* \ingroup fileio
* \internal
* Lists all objects prefixed by a give s3 url.
*
* if s3_url points to a valid prefix, it return the prefix's contents
* like a directory.
*
* foo/hello.txt
*
* list_objects("s3://foo") will return "foo/hello.txt"
*
* If s3_url points to an object it will just return the object.
*
* \returns A list_objects_response object.
* If list_objects_response.error is an empty string, it indicates success.
* Otherwise, it contains an error code. list_objects_response.directories
* indicate all "directories" stored with the requested prefix. And
* list_objects_response.objects indicates all regular objects stored with the
* requested prefix.
*
*/
list_objects_response list_directory(std::string s3_url,
std::string proxy = "");
/**
* \ingroup fileio
* \internal
* Tests if url is a directory or a regular file.
* Returns a pair of (exists, is_directory). If exists is false,
* is_directory should be ignored
*/
using turi::fileio::file_status;
std::pair<file_status, list_objects_response> is_directory(
std::string s3_url, std::string proxy = "");
/**
* \ingroup fileio
* \internal
* Where url points to a single object, this deletes the object.
* Returns an empty string on success, and an error string on failure.
*/
std::string delete_object(std::string s3_url, std::string proxy = "");
/**
* \ingroup fileio
* \internal
* Where url points to a prefix, this deletes all objects with the
* specified prefix.
* Returns an empty string on success, and an error string on failure.
*/
std::string delete_prefix(std::string s3_url, std::string proxy = "");
/**
* \ingroup fileio
* \internal
* Given an S3 URL of the form expected by parse_s3url,
* this function drops the access_key_id and the secret_key from the string
* returning s3://[bucket]/[object_name]
*
* If the url cannot be parsed, we try the best to remove information associated
* with ':'.
*
* If the url does not begin with s3://, return as is.
*/
std::string sanitize_s3_url(const std::string& url);
/**
* \ingroup fileio
* \internal
* This splits a URL of the form
* s3://[access_key_id]:[secret_key]:[endpoint/][bucket]/[object_name]
* into several pieces.
*
* endpoint and object_name are optional.
*
* Returns true on success, false on failure.
*/
bool parse_s3url(const std::string& url, s3url& ret, std::string& err_msg);
/**
* \ingroup fileio
* \internal
* Set the timeout for S3 upload.
* \param timeout Timeout value in secs.
*/
void set_upload_timeout(long timeout);
/**
* \ingroup fileio
* \internal
* Set the timeout for S3 download.
* \param timeout Timeout value in secs.
*/
void set_download_timeout(long timeout);
struct S3Operation {
enum ops_enum {
Delete,
List,
HEAD,
};
static std::string toString(ops_enum operation) {
return _enum_to_str.at(operation);
}
static const std::vector<std::string> _enum_to_str;
};
template <class Response>
std::ostream& reportS3Error(std::ostream& ss, const s3url& parsed_url,
S3Operation::ops_enum operation,
const Response& outcome) {
auto error = outcome.GetError();
ss << "('" << parsed_url << ", proxy: '" << parsed_url.sdk_proxy
<< "', region: '" << parsed_url.sdk_region << "')"
<< " Error while performing " << S3Operation::toString(operation)
<< ". Error Name: " << error.GetExceptionName()
<< ". Error Message: " << error.GetMessage()
<< ". HTTP Error Code: " << static_cast<int>(error.GetResponseCode());
return ss;
}
#define reportS3ErrorDetailed(ss, parsed_url, operation, outcome) \
reportS3Error(ss, parsed_url, operation, outcome) \
<< " in " << __FILE__ << " at " << __LINE__
} // namespace turi
#endif // End ifndef TC_DISABLE_REMOTEFS
#endif
| 29.114007 | 80 | 0.683151 | [
"object",
"vector"
] |
61b65019796f53c0cc235a852ae652a364eb07e0 | 9,524 | hpp | C++ | src/xpcc/math/geometry/line_segment_2d_impl.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | 161 | 2015-01-13T15:52:06.000Z | 2020-02-13T01:26:04.000Z | src/xpcc/math/geometry/line_segment_2d_impl.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | 281 | 2015-01-06T12:46:40.000Z | 2019-01-06T13:06:57.000Z | src/xpcc/math/geometry/line_segment_2d_impl.hpp | walmis/xpcc | 1d87c4434530c6aeac923f57d379aeaf32e11e1e | [
"BSD-3-Clause"
] | 51 | 2015-03-03T19:56:12.000Z | 2020-03-22T02:13:36.000Z | // coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2009, Roboterclub Aachen e.V.
* 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 Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// ----------------------------------------------------------------------------
#ifndef XPCC__LINE_SEGMENT_2D_HPP
#error "Don't include this file directly, use 'line_segment_2d.hpp' instead!"
#endif
// ----------------------------------------------------------------------------
template<typename T>
xpcc::LineSegment2D<T>::LineSegment2D() :
startPoint(), endPoint()
{
}
template<typename T>
xpcc::LineSegment2D<T>::LineSegment2D(const Vector<T, 2>& start, const Vector<T, 2>& end) :
startPoint(start), endPoint(end)
{
}
// ----------------------------------------------------------------------------
template <typename T>
inline void
xpcc::LineSegment2D<T>::setStartPoint(const Vector<T, 2>& point)
{
this->startPoint = point;
}
template <typename T>
inline const xpcc::Vector<T, 2>&
xpcc::LineSegment2D<T>::getStartPoint() const
{
return this->startPoint;
}
template <typename T>
inline void
xpcc::LineSegment2D<T>::setEndPoint(const Vector<T, 2>& point)
{
this->endPoint = point;
}
template <typename T>
inline const xpcc::Vector<T, 2>&
xpcc::LineSegment2D<T>::getEndPoint() const
{
return this->endPoint;
}
template <typename T>
inline void
xpcc::LineSegment2D<T>::set(const Vector<T, 2>& start, const Vector<T, 2>& end)
{
this->startPoint = start;
this->endPoint = end;
}
// ----------------------------------------------------------------------------
template<typename T>
void
xpcc::LineSegment2D<T>::translate(const Vector<T, 2>& vector)
{
this->startPoint.translate(vector);
this->endPoint.translate(vector);
}
// ----------------------------------------------------------------------------
template<typename T>
T
xpcc::LineSegment2D<T>::getLength() const
{
Vector<T, 2> directionVector = this->endPoint - this->startPoint;
return directionVector.getLength();
}
// ----------------------------------------------------------------------------
template<typename T>
xpcc::Vector<T, 2>
xpcc::LineSegment2D<T>::getDirectionVector() const
{
return endPoint - startPoint;
}
// ----------------------------------------------------------------------------
template<typename T>
const T
xpcc::LineSegment2D<T>::getDistanceTo(const Vector<T, 2>& point) const
{
// vector from the base point of the line to the new point
Vector<T, 2> startToPoint = point - this->startPoint;
Vector<T, 2> directionVector = this->endPoint - this->startPoint;
FloatType c1 = startToPoint.dot(directionVector);
if (c1 <= 0)
{
// point is before the start point => calculate distance to start point
return startToPoint.getLength();
}
FloatType c2 = directionVector.getLengthSquared();
if (c2 <= c1)
{
// point is after the end point => calculate distance to end point
Vector<T, 2> endToPoint = point - this->endPoint;
return endToPoint.getLength();
}
FloatType d = c1 / c2;
// calculate the closest point
Vector<T, 2> closestPoint = this->startPoint + d * directionVector;
// return the length of the vector from the closest point on the line
// to the given point
Vector<T, 2> closestPointToPoint = point - closestPoint;
return closestPointToPoint.getLength();
}
// ----------------------------------------------------------------------------
template<typename T>
const xpcc::Vector<T, 2>
xpcc::LineSegment2D<T>::getClosestPointTo(const Vector<T, 2>& point) const
{
// vector from the base point of the line to the new point
Vector<T, 2> startToPoint = point - this->startPoint;
Vector<T, 2> directionVector = this->endPoint - this->startPoint;
FloatType c1 = startToPoint.dot(directionVector);
if (c1 <= 0)
{
// point is before the start point
return this->startPoint;
}
FloatType c2 = directionVector.getLengthSquared();
if (c2 <= c1)
{
// point is after the end point
return this->endPoint;
}
FloatType d = c1 / c2;
// calculate the closest point
return (this->startPoint + d * directionVector);
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::LineSegment2D<T>::intersects(const LineSegment2D<T>& other) const
{
return (((Vector<T, 2>::ccw(this->startPoint, this->endPoint, other.startPoint) *
Vector<T, 2>::ccw(this->startPoint, this->endPoint, other.endPoint)) <= 0) &&
((Vector<T, 2>::ccw(other.startPoint, other.endPoint, this->startPoint) *
Vector<T, 2>::ccw(other.startPoint, other.endPoint, this->endPoint)) <= 0));
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::LineSegment2D<T>::intersects(const Polygon2D<T>& polygon) const
{
return polygon.intersects(*this);
}
// ----------------------------------------------------------------------------
template <typename T>
bool
xpcc::LineSegment2D<T>::getIntersections(const LineSegment2D& other,
PointSet2D<T>& intersectionPoints) const
{
xpcc::Vector<T, 2> ownDirectionVector = this->endPoint - this->startPoint;
xpcc::Vector<T, 2> otherDirectionVector = other.endPoint - other.startPoint;
xpcc::Vector<T, 2> connectionVector = this->startPoint - other.startPoint;
WideType d = ownDirectionVector.cross(otherDirectionVector);
if (d)
{
FloatType t2 = static_cast<FloatType>(ownDirectionVector.cross(connectionVector)) /
static_cast<FloatType>(d);
if (0.f <= t2 and t2 <= 1.f)
{
FloatType t1 = static_cast<FloatType>(otherDirectionVector.cross(connectionVector)) /
static_cast<FloatType>(d);
if (0.f <= t1 and t1 <= 1.f)
{
intersectionPoints.append(this->startPoint + ownDirectionVector * t1);
return true;
}
}
}
return false;
}
// ----------------------------------------------------------------------------
template <typename T>
bool
xpcc::LineSegment2D<T>::getIntersections(const Circle2D<T>& circle,
PointSet2D<T>& intersectionPoints) const
{
// Direction vector of line, from start to end
xpcc::Vector<T, 2> directionVector = this->endPoint - this->startPoint;
// vector from the center of the circle to line start
xpcc::Vector<T, 2> circleToLine = this->startPoint - circle.center;
WideType a = directionVector.dot(directionVector);
WideType b = 2 * circleToLine.dot(directionVector);
WideType c = circleToLine.dot(circleToLine) -
static_cast<WideType>(circle.radius) * static_cast<WideType>(circle.radius);;
WideType discriminant = (b * b - 4 * a * c);
if (discriminant < 0)
{
// no intersections
return false;
}
else
{
bool result = false;
FloatType e = std::sqrt(discriminant);
FloatType t1 = static_cast<FloatType>(-b - e) / static_cast<FloatType>(2 * a);
if (0.f <= t1 and t1 <= 1.f) {
intersectionPoints.append(this->startPoint + directionVector * t1);
result = true;
}
if (discriminant == 0)
{
// the line is a tangent to the circle intersecting
// it at only one point
return result;
}
FloatType t2 = static_cast<FloatType>(-b + e) / static_cast<FloatType>(2 * a);
if (0.f <= t2 and t2 <= 1.f) {
intersectionPoints.append(this->startPoint + directionVector * t2);
result = true;
}
return result;
}
}
// ----------------------------------------------------------------------------
template <typename T>
bool
xpcc::LineSegment2D<T>::getIntersections(const Polygon2D<T>& polygon,
PointSet2D<T>& intersectionPoints) const
{
// invoke intersection method of the polygon
return polygon.getIntersections(*this, intersectionPoints);
}
// ----------------------------------------------------------------------------
template<typename T>
bool
xpcc::LineSegment2D<T>::operator == (const LineSegment2D &other) const
{
return ((this->startPoint == other.startPoint) &&
(this->endPoint == other.endPoint));
}
template<typename T>
bool
xpcc::LineSegment2D<T>::operator != (const LineSegment2D &other) const
{
return ((this->startPoint != other.startPoint) ||
(this->endPoint != other.endPoint));
}
| 31.432343 | 91 | 0.625052 | [
"vector"
] |
61bf27ead72af823851485ec673820bfc15f9d13 | 138,805 | cpp | C++ | GameBalanceData.cpp | chickenbellyfin/tamods-server | 7db99d298697f3f96bfccfd286b745e25b7ac180 | [
"MIT"
] | 1 | 2021-09-16T15:33:32.000Z | 2021-09-16T15:33:32.000Z | GameBalanceData.cpp | chickenbellyfin/tamods-server | 7db99d298697f3f96bfccfd286b745e25b7ac180 | [
"MIT"
] | 1 | 2022-02-11T09:08:13.000Z | 2022-02-11T09:08:13.000Z | GameBalanceData.cpp | chickenbellyfin/tamods-server | 7db99d298697f3f96bfccfd286b745e25b7ac180 | [
"MIT"
] | 1 | 2021-09-16T15:33:37.000Z | 2021-09-16T15:33:37.000Z | #include "GameBalance.h"
namespace GameBalance {
template <typename ProjType>
static ProjType* getWeaponDefaultProj(AWeapon* dev) {
if (dev->WeaponProjectiles.Count == 0) return NULL;
UClass* projClass = dev->WeaponProjectiles.GetStd(0);
if (!projClass) {
return NULL;
}
if (!projClass->Default) {
return NULL;
}
return (ProjType*)projClass->Default;
}
static UTrDmgType_Base* getWeaponDefaultDamageType(AWeapon* dev) {
UClass* dmgTypeClass = NULL;
ATrProjectile* defProj = getWeaponDefaultProj<ATrProjectile>(dev);
if (defProj) {
// Projectile
dmgTypeClass = defProj->MyDamageType;
}
else {
// Hitscan
dmgTypeClass = dev->InstantHitDamageTypes.GetStd(0);
}
if (!dmgTypeClass) return NULL;
if (!dmgTypeClass->Default || !dmgTypeClass->Default->IsA(UTrDmgType_Base::StaticClass())) {
return NULL;
}
return (UTrDmgType_Base*)dmgTypeClass->Default;
}
template <typename EffectType>
static EffectType* getDefaultEffect(FEffectInfo effi) {
UClass* effClass = effi.effectClass;
if (!effClass || !effClass->Default || !effClass->Default->IsA(EffectType::StaticClass())) return NULL;
return (EffectType*)effClass->Default;
}
template <typename DepType>
static DepType* getDefaultDeployable(ATrDevice* dev) {
if (dev->m_WeaponDeployables.Count == 0) return NULL;
UClass* depClass = dev->m_WeaponDeployables.GetStd(0);
if (!depClass || !depClass->Default || !depClass->Default->IsA(DepType::StaticClass())) return NULL;
return (DepType*)depClass->Default;
}
// Decorators to convert UObject* to some subtype of it
template <typename T>
static std::function<bool(PropValue, UObject*)> applierAdapter(std::function<bool(PropValue, T*)> f, bool performCheck = true) {
return [f, performCheck](PropValue p, UObject* obj) {
if (!obj) return false;
if (performCheck) {
if (!(T::StaticClass())) return false;
if (!obj->IsA(T::StaticClass()) && std::string(T::StaticClass()->Name.GetName()) != std::string(obj->Name.GetName())) {
return false;
}
}
return f(p, (T*)obj);
};
}
template <typename T>
static std::function<bool(UObject*, PropValue&)> getterAdapter(std::function<bool(T*, PropValue&)> f, bool performCheck = true) {
return [f, performCheck](UObject* obj, PropValue& p) {
if (!obj) return false;
if (performCheck) {
if (!(T::StaticClass())) return false;
if (!obj->IsA(T::StaticClass()) && std::string(T::StaticClass()->Name.GetName()) != std::string(obj->Name.GetName())) {
return false;
}
}
return f((T*)obj, p);
};
}
// Decorators to get the default of another arbitrary class in addition to the object for modification
template <typename T, typename ExtraDefault>
static std::function<bool(PropValue, UObject*)> applierAdapterWithAdditionalClass(std::string searchClassName, std::function<bool(PropValue, T*, ExtraDefault*)> f) {
return applierAdapter<T>([f, searchClassName](PropValue p, T* t) {
UObject* obj;
std::string lookupName = searchClassName + " TribesGame.Default__" + searchClassName;
obj = UObject::FindObject<ExtraDefault>(lookupName.c_str());
if (!obj) return false;
return f(p, t, (ExtraDefault*)obj);
});
}
template <typename T, typename ExtraDefault>
static std::function<bool(UObject*, PropValue&)> getterAdapterWithAdditionalClass(std::string searchClassName, std::function<bool(T*, ExtraDefault*, PropValue&)> f) {
return getterAdapter<T>([f, searchClassName](T* t, PropValue& p) {
UObject* obj;
std::string lookupName = searchClassName + " TribesGame.Default__" + searchClassName;
obj = UObject::FindObject<ExtraDefault>(lookupName.c_str());
if (!obj) return false;
return f(t, (ExtraDefault*)obj, p);
});
}
// Decorator functions to handle properties specific to TrDevices which spawn projectiles
template <typename DevType, typename ProjType>
static std::function<bool(PropValue, UObject*)> projDeviceApplierAdapter(std::function<bool(PropValue, DevType*, ProjType*)> f) {
return applierAdapter<DevType>([f](PropValue p, DevType* dev) {
ProjType* defProj = getWeaponDefaultProj<ProjType>(dev);
if (!defProj) return false;
return f(p, dev, defProj);
});
}
template <typename DevType, typename ProjType>
static std::function<bool(UObject*, PropValue&)> projDeviceGetterAdapter(std::function<bool(DevType*, ProjType*, PropValue&)> f) {
return getterAdapter<DevType>([f](DevType* dev, PropValue& ret) {
ProjType* defProj = getWeaponDefaultProj< ProjType>(dev);
if (!defProj) return false;
return f(dev, defProj, ret);
});
}
// Decorator functions to handle properties specific to DamageTypes associated with a TrDevice
static std::function<bool(PropValue, UObject*)> deviceDamageTypeApplierAdapter(std::function<bool(PropValue, ATrDevice*, UTrDmgType_Base*)> f) {
return applierAdapter<ATrDevice>([f](PropValue p, ATrDevice* dev) {
UTrDmgType_Base* dmgType = getWeaponDefaultDamageType(dev);
if (!dmgType) return false;
return f(p, dev, dmgType);
});
}
static std::function<bool(UObject*, PropValue&)> deviceDamageTypeGetterAdapter(std::function<bool(ATrDevice*, UTrDmgType_Base*, PropValue&)> f) {
return getterAdapter<ATrDevice>([f](ATrDevice* dev, PropValue& ret) {
UTrDmgType_Base* dmgType = getWeaponDefaultDamageType(dev);
if (!dmgType) return false;
return f(dev, dmgType, ret);
});
}
// Decorator functions to handle properties specific to an Effect associated with an item
template <typename DevType, typename EffectType>
static std::function<bool(PropValue, UObject*)> effectDeviceApplierAdapter(std::function<bool(PropValue, DevType*, EffectType*)> f) {
return applierAdapter<DevType>([f](PropValue p, DevType* dev) {
if (dev->m_EffectInfo.Count == 0) return false;
EffectType* eff = getDefaultEffect<EffectType>(dev->m_EffectInfo.GetStd(0));
if (!eff) return false;
return f(p, dev, eff);
});
}
template <typename DevType, typename EffectType>
static std::function<bool(UObject*, PropValue&)> effectDeviceGetterAdapter(std::function<bool(DevType*, EffectType*, PropValue&)> f) {
return getterAdapter<DevType>([f](DevType* dev, PropValue& ret) {
if (dev->m_EffectInfo.Count == 0) return false;
EffectType* eff = getDefaultEffect<EffectType>(dev->m_EffectInfo.GetStd(0));
if (!eff) return false;
return f(dev, eff, ret);
});
}
// Decorator functions to handle properties specific to a Deployable associated with an item
template <typename DevType, typename DepType>
static std::function<bool(PropValue, UObject*)> deployableDeviceApplierAdapter(std::function<bool(PropValue, DevType*, DepType*)> f) {
return applierAdapter<DevType>([f](PropValue p, DevType* dev) {
DepType* dep = getDefaultDeployable<DepType>(dev);
if (!dep) return false;
return f(p, dev, dep);
});
}
template <typename DevType, typename DepType>
static std::function<bool(UObject*, PropValue&)> deployableDeviceGetterAdapter(std::function<bool(DevType*, DepType*, PropValue&)> f) {
return getterAdapter<DevType>([f](DevType* dev, PropValue& ret) {
DepType* dep = getDefaultDeployable<DepType>(dev);
if (!dep) return false;
return f(dev, dep, ret);
});
}
// Decorator functions to handle properties specific to DamageTypes associated with a vehicle weapon
static std::function<bool(PropValue, UObject*)> vehDeviceDamageTypeApplierAdapter(std::function<bool(PropValue, ATrVehicleWeapon*, UTrDmgType_Base*)> f) {
return applierAdapter<ATrVehicleWeapon>([f](PropValue p, ATrVehicleWeapon* dev) {
UTrDmgType_Base* dmgType = getWeaponDefaultDamageType(dev);
if (!dmgType) return false;
return f(p, dev, dmgType);
});
}
static std::function<bool(UObject*, PropValue&)> vehDeviceDamageTypeGetterAdapter(std::function<bool(ATrVehicleWeapon*, UTrDmgType_Base*, PropValue&)> f) {
return getterAdapter<ATrVehicleWeapon>([f](ATrVehicleWeapon* dev, PropValue& ret) {
UTrDmgType_Base* dmgType = getWeaponDefaultDamageType(dev);
if (!dmgType) return false;
return f(dev, dmgType, ret);
});
}
namespace Items {
// Ammo
static const Property CLIP_AMMO(
ValueType::INTEGER,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valInt < 0) return false;
dev->MaxAmmoCount = p.valInt;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromInt(dev->MaxAmmoCount);
return true;
})
);
static const Property SPARE_AMMO(
ValueType::INTEGER,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valInt < 0) return false;
dev->m_nMaxCarriedAmmo = p.valInt;
dev->m_nCarriedAmmo = p.valInt;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromInt(dev->m_nMaxCarriedAmmo);
return true;
})
);
static const Property AMMO_PER_SHOT(
ValueType::INTEGER,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valInt < 0) return false;
dev->ShotCost.Set(0, p.valInt);
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromInt(dev->ShotCost.GetStd(0));
return true;
})
);
static const Property LOW_AMMO_CUTOFF(
ValueType::INTEGER,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valInt < 0) return false;
dev->m_nLowAmmoWarning = p.valInt;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromInt(dev->m_nLowAmmoWarning);
return true;
})
);
// Reload / Firing
static const Property RELOAD_TIME(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valFloat < 0) return false;
dev->m_fReloadTime = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fReloadTime);
return true;
})
);
static const Property FIRE_INTERVAL(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valFloat < 0) return false;
dev->FireInterval.Set(0, p.valFloat);
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->FireInterval.GetStd(0));
return true;
})
);
static const Property HOLD_TO_FIRE(
ValueType::BOOLEAN,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_bAllowHoldDownFire = p.valBool;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromBool(dev->m_bAllowHoldDownFire);
return true;
})
);
static const Property CAN_ZOOM(
ValueType::BOOLEAN,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_bCanZoom = p.valBool;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromBool(dev->m_bCanZoom);
return true;
})
);
static const Property RELOAD_SINGLE(
ValueType::BOOLEAN,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_bReloadSingles = p.valBool;
dev->m_bCanEarlyAbortReload = p.valBool;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromBool(dev->m_bReloadSingles);
return true;
})
);
static const Property RELOAD_APPLICATION_PROPORTION(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fPctTimeBeforeReload = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fPctTimeBeforeReload);
return true;
})
);
static const Property BURST_SHOT_COUNT(
ValueType::INTEGER,
applierAdapter<ATrDevice_LightAssaultRifle>([](PropValue p, ATrDevice_LightAssaultRifle* dev) {
dev->m_nShotBurstCount = p.valInt;
return true;
}),
getterAdapter<ATrDevice_LightAssaultRifle>([](ATrDevice_LightAssaultRifle* dev, PropValue& ret) {
ret = PropValue::fromInt(dev->m_nShotBurstCount);
return true;
})
);
static const Property BURST_SHOT_REFIRE_TIME(
ValueType::FLOAT,
applierAdapter<ATrDevice_LightAssaultRifle>([](PropValue p, ATrDevice_LightAssaultRifle* dev) {
dev->m_fBurtShotRefireTime = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_LightAssaultRifle>([](ATrDevice_LightAssaultRifle* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fBurtShotRefireTime);
return true;
})
);
static const Property SPINUP_TIME(
ValueType::FLOAT,
applierAdapter<ATrDevice_ChainGun>([](PropValue p, ATrDevice_ChainGun* dev) {
dev->m_fBuildupTime = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_ChainGun>([](ATrDevice_ChainGun* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fBuildupTime);
return true;
})
);
static const Property SHOTGUN_SHOT_COUNT(
ValueType::INTEGER,
applierAdapter<ATrDevice_Shotgun>([](PropValue p, ATrDevice_Shotgun* dev) {
dev->m_nMinShotCount = p.valInt;
return true;
}),
getterAdapter<ATrDevice_Shotgun>([](ATrDevice_Shotgun* dev, PropValue& ret) {
ret = PropValue::fromInt(dev->m_nMinShotCount);
return true;
})
);
static const Property SHOT_ENERGY_COST(
ValueType::INTEGER,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_PowerPoolCost.Set(0, p.valInt);
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromInt(dev->m_PowerPoolCost.GetStd(0));
return true;
})
);
// Damage
static const Property DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valFloat < 0) return false;
if (dev->IsA(ATrDevice_Deployable::StaticClass())) {
ATrDeployable* dep = getDefaultDeployable<ATrDeployable>(dev);
if (!dep ||!dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
dev = (ATrDevice*)dep->m_DeviceClass->Default;
}
ATrProjectile* defProj = getWeaponDefaultProj<ATrProjectile>(dev);
if (defProj) {
// Projectile
defProj->Damage = p.valFloat;
}
else {
// Hitscan
dev->InstantHitDamage.Set(0, p.valFloat);
}
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
if (dev->IsA(ATrDevice_Deployable::StaticClass())) {
ATrDeployable* dep = getDefaultDeployable<ATrDeployable>(dev);
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
dev = (ATrDevice*)dep->m_DeviceClass->Default;
}
// Is this weapon a projectile or hitscan weapon?
ATrProjectile* defProj = getWeaponDefaultProj<ATrProjectile>(dev);
if (defProj) {
// Projectile
ret = PropValue::fromFloat(defProj->Damage);
}
else {
// Hitscan
ret = PropValue::fromFloat(dev->InstantHitDamage.GetStd(0));
}
return true;
})
);
static const Property EXPLOSIVE_RADIUS(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
if (p.valFloat < 0) return false;
proj->DamageRadius = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->DamageRadius);
return true;
})
);
static const Property DIRECT_HIT_MULTIPLIER(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->m_fDirectHitMultiplier = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fDirectHitMultiplier);
return true;
})
);
static const Property IMPACT_MOMENTUM(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
if (p.valFloat < 0) return false;
ATrProjectile* defProj = getWeaponDefaultProj<ATrProjectile>(dev);
if (defProj) {
// Projectile
defProj->MomentumTransfer = p.valFloat;
}
else {
// Hitscan
dev->InstantHitMomentum.Set(0, p.valFloat);
}
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
// Is this weapon a projectile or hitscan weapon?
ATrProjectile* defProj = getWeaponDefaultProj<ATrProjectile>(dev);
if (defProj) {
// Projectile
ret = PropValue::fromFloat(defProj->MomentumTransfer);
}
else {
// Hitscan
ret = PropValue::fromFloat(dev->InstantHitMomentum.GetStd(0));
}
return true;
})
);
static const Property SELF_IMPACT_MOMENTUM_MULTIPLIER(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->m_fInstigatorMomentumTransferMultiplier = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fInstigatorMomentumTransferMultiplier);
return true;
})
);
static const Property SELF_IMPACT_EXTRA_Z_MOMENTUM(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->m_fInstigatorExtraZMomentum = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fInstigatorExtraZMomentum);
return true;
})
);
static const Property ENERGY_DRAIN(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_EnergyDrainAmount = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_EnergyDrainAmount);
return true;
})
);
static const Property MAX_DAMAGE_RANGE_PROPORTION(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fMaxDamageRangePct = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fMaxDamageRangePct);
return true;
})
);
static const Property MIN_DAMAGE_RANGE_PROPORTION(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fMinDamageRangePct = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fMinDamageRangePct);
return true;
})
);
static const Property MIN_DAMAGE_PROPORTION(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fMinDamagePct = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fMinDamagePct);
return true;
})
);
static const Property BULLET_DAMAGE_RANGE(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fBulletDamageRange = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fBulletDamageRange);
return true;
})
);
static const Property DAMAGE_AGAINST_ARMOR_MULTIPLIER(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstArmor = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstArmor);
return true;
})
);
static const Property DAMAGE_AGAINST_GENERATOR_MULTIPLIER(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstGenerators = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstGenerators);
return true;
})
);
static const Property DAMAGE_AGAINST_BASE_TURRET_MULTIPLIER(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstBaseTurrets = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstBaseTurrets);
return true;
})
);
static const Property DAMAGE_AGAINST_BASE_SENSOR_MULTIPLIER(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstBaseSensors = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstBaseSensors);
return true;
})
);
static const Property DAMAGE_AGAINST_GRAVCYCLE_MULTIPLIER(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstGravCycle = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstGravCycle);
return true;
})
);
static const Property DAMAGE_AGAINST_BEOWULF_MULTIPLIER(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstBeowulf = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstBeowulf);
return true;
})
);
static const Property DAMAGE_AGAINST_SHRIKE_MULTIPLIER(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstShrike = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstShrike);
return true;
})
);
static const Property DOES_GIB_ON_KILL(
ValueType::BOOLEAN,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_bCausesGib = p.valBool;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromBool(dmgType->m_bCausesGib);
return true;
})
);
static const Property GIB_IMPULSE_RADIUS(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fGibRadius = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fGibRadius);
return true;
})
);
static const Property GIB_STRENGTH(
ValueType::FLOAT,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_fGibStrength = p.valFloat;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fGibStrength);
return true;
})
);
static const Property DOES_IMPULSE_FLAG(
ValueType::BOOLEAN,
deviceDamageTypeApplierAdapter([](PropValue p, ATrDevice* dev, UTrDmgType_Base* dmgType) {
dmgType->m_bImpulsesFlags = p.valBool;
return true;
}),
deviceDamageTypeGetterAdapter([](ATrDevice* dev, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromBool(dmgType->m_bImpulsesFlags);
return true;
})
);
static const Property MELEE_DAMAGE_RADIUS(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fDamageRadius = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fDamageRadius);
return true;
})
);
static const Property MELEE_CONE_ANGLE(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fConeAttackAngle = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fConeAttackAngle);
return true;
})
);
static const Property PHASE_DAMAGE_PER_ENERGY(
ValueType::FLOAT,
applierAdapter<ATrDevice_PhaseRifle>([](PropValue p, ATrDevice_PhaseRifle* dev) {
dev->m_DamagePerEnergy = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_PhaseRifle>([](ATrDevice_PhaseRifle* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_DamagePerEnergy);
return true;
})
);
static const Property PHASE_MAX_CONSUMED_ENERGY(
ValueType::FLOAT,
applierAdapter<ATrDevice_PhaseRifle>([](PropValue p, ATrDevice_PhaseRifle* dev) {
dev->m_MaxEnergyConsumed = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_PhaseRifle>([](ATrDevice_PhaseRifle* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_MaxEnergyConsumed);
return true;
})
);
static const Property BXT_CHARGE_MAX_DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrDevice_SniperRifle>([](PropValue p, ATrDevice_SniperRifle* dev) {
dev->m_fMaxAimedDamage = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_SniperRifle>([](ATrDevice_SniperRifle* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fMaxAimedDamage);
return true;
})
);
static const Property BXT_CHARGE_TIME(
ValueType::FLOAT,
applierAdapter<ATrDevice_SniperRifle>([](PropValue p, ATrDevice_SniperRifle* dev) {
dev->r_fAimChargeTime = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_SniperRifle>([](ATrDevice_SniperRifle* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->r_fAimChargeTime);
return true;
})
);
static const Property BXT_CHARGE_MULT_COEFFICIENT(
ValueType::FLOAT,
applierAdapter<ATrDevice_SniperRifle>([](PropValue p, ATrDevice_SniperRifle* dev) {
dev->m_fMultCoeff = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_SniperRifle>([](ATrDevice_SniperRifle* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fMultCoeff);
return true;
})
);
static const Property BXT_CHARGE_DIV_COEFFICIENT(
ValueType::FLOAT,
applierAdapter<ATrDevice_SniperRifle>([](PropValue p, ATrDevice_SniperRifle* dev) {
dev->m_fDivCoeff = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_SniperRifle>([](ATrDevice_SniperRifle* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fDivCoeff);
return true;
})
);
static const Property FRACTAL_DURATION(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_fFractalTime = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fFractalTime);
return true;
})
);
static const Property FRACTAL_SHARD_INTERVAL(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_fFractalInterval = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fFractalInterval);
return true;
})
);
static const Property FRACTAL_ASCENT_TIME(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_fAscentTime = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fAscentTime);
return true;
})
);
static const Property FRACTAL_ASCENT_HEIGHT(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_fAscentHeight = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fAscentHeight);
return true;
})
);
static const Property FRACTAL_SHARD_DISTANCE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_fFractalShotDistance = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fFractalShotDistance);
return true;
})
);
static const Property FRACTAL_SHARD_HEIGHT(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_fZFractalShotDistance = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fZFractalShotDistance);
return true;
})
);
static const Property FRACTAL_SHARD_DAMAGE(
ValueType::INTEGER,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_nFractalDamage = p.valInt;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromInt(proj->m_nFractalDamage);
return true;
})
);
static const Property FRACTAL_SHARD_DAMAGE_RADIUS(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_SpikeGrenade>([](PropValue p, ATrDevice* dev, ATrProj_SpikeGrenade* proj) {
proj->m_fFractalDamageRadius = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_SpikeGrenade>([](ATrDevice* dev, ATrProj_SpikeGrenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fFractalDamageRadius);
return true;
})
);
// Projectile / Tracer
static const Property PROJECTILE_SPEED(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->Speed = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->Speed);
return true;
})
);
static const Property PROJECTILE_MAX_SPEED(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->MaxSpeed = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->MaxSpeed);
return true;
})
);
static const Property COLLISION_SIZE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->CheckRadius = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->CheckRadius);
return true;
})
);
static const Property PROJECTILE_INHERITANCE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->m_fProjInheritVelocityPct = p.valFloat;
proj->m_fProjInheritVelocityPctZ = p.valFloat;
proj->m_fMaxProjInheritPct = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fProjInheritVelocityPct);
return true;
})
);
static const Property PROJECTILE_LIFESPAN(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->LifeSpan = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->LifeSpan);
return true;
})
);
static const Property PROJECTILE_GRAVITY(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->CustomGravityScaling = p.valFloat;
if (proj->CustomGravityScaling == 0.0f) {
proj->Physics = PHYS_Projectile;
}
else {
proj->Physics = PHYS_Falling;
}
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->CustomGravityScaling);
return true;
})
);
static const Property PROJECTILE_TERMINAL_VELOCITY(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->TerminalVelocity = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->TerminalVelocity);
return true;
})
);
static const Property PROJECTILE_BOUNCE_DAMPING(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->m_fBounceDampingPercent = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fBounceDampingPercent);
return true;
})
);
static const Property PROJECTILE_MESH_SCALE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
if (!proj->m_ProjMesh) return false;
proj->m_ProjMesh->SetScale(p.valFloat);
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
if (!proj->m_ProjMesh) return false;
ret = PropValue::fromFloat(proj->m_ProjMesh->Scale);
return true;
})
);
static const Property PROJECTILE_LIGHT_RADIUS(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
if (!proj->m_ProjMesh) return false;
proj->ProjectileLight->Radius = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
if (!proj->m_ProjMesh) return false;
ret = PropValue::fromFloat(proj->ProjectileLight->Radius);
return true;
})
);
static const Property HITSCAN_RANGE(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->WeaponRange = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->WeaponRange);
return true;
})
);
static const Property FIRE_OFFSET_X(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->FireOffset.X = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->FireOffset.X);
return true;
})
);
static const Property FIRE_OFFSET_Y(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->FireOffset.Y = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->FireOffset.Y);
return true;
})
);
static const Property FIRE_OFFSET_Z(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->FireOffset.Z = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->FireOffset.Z);
return true;
})
);
// Accuracy
static const Property ACCURACY(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fDefaultAccuracy = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fDefaultAccuracy);
return true;
})
);
static const Property ACCURACY_LOSS_ON_SHOT(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fAccuracyLossOnShot = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fAccuracyLossOnShot);
return true;
})
);
static const Property ACCURACY_LOSS_ON_JUMP(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fAccuracyLossOnJump = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fAccuracyLossOnJump);
return true;
})
);
static const Property ACCURACY_LOSS_ON_WEAPON_SWITCH(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fAccuracyLossOnWeaponSwitch = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fAccuracyLossOnWeaponSwitch);
return true;
})
);
static const Property ACCURACY_LOSS_MAX(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fAccuracyLossMax = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fAccuracyLossMax);
return true;
})
);
static const Property ACCURACY_CORRECTION_RATE(
ValueType::FLOAT,
applierAdapter<ATrDevice>([](PropValue p, ATrDevice* dev) {
dev->m_fAccuracyCorrectionRate = p.valFloat;
return true;
}),
getterAdapter<ATrDevice>([](ATrDevice* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fAccuracyCorrectionRate);
return true;
})
);
static const Property SHOTGUN_INNER_ACCURACY(
ValueType::FLOAT,
applierAdapter<ATrDevice_Shotgun>([](PropValue p, ATrDevice_Shotgun* dev) {
dev->m_fInnerDefaultAccuracy = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Shotgun>([](ATrDevice_Shotgun* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fInnerDefaultAccuracy);
return true;
})
);
static const Property SHOTGUN_USE_GOTY_SPREAD(
ValueType::BOOLEAN,
applierAdapter<ATrDevice_Shotgun>([](PropValue p, ATrDevice_Shotgun* dev) {
// Doesn't actually modify a real property; this is implemented in clientside TAMods
return true;
}),
getterAdapter<ATrDevice_Shotgun>([](ATrDevice_Shotgun* dev, PropValue& ret) {
// Doesn't proxy to a real underlying value, so don't modify the returned propvalue
return true;
})
);
// Grenade
static const Property THROW_DELAY(
ValueType::FLOAT,
applierAdapter<ATrDevice_AutoFire>([](PropValue p, ATrDevice_AutoFire* dev) {
dev->m_fBuildupTime = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_AutoFire>([](ATrDevice_AutoFire* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fBuildupTime);
return true;
})
);
static const Property THROW_PULL_PIN_TIME(
ValueType::FLOAT,
applierAdapter<ATrDevice_AutoFire>([](PropValue p, ATrDevice_AutoFire* dev) {
dev->m_fPullPinTime = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_AutoFire>([](ATrDevice_AutoFire* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fPullPinTime);
return true;
})
);
static const Property STUCK_DAMAGE_MULTIPLIER(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_Grenade>([](PropValue p, ATrDevice* dev, ATrProj_Grenade* proj) {
proj->m_fStuckDamageMultiplier = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Grenade>([](ATrDevice* dev, ATrProj_Grenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fStuckDamageMultiplier);
return true;
})
);
static const Property STUCK_MOMENTUM_MULTIPLIER(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_Grenade>([](PropValue p, ATrDevice* dev, ATrProj_Grenade* proj) {
proj->m_fStuckMomentumMultiplier = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Grenade>([](ATrDevice* dev, ATrProj_Grenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fStuckMomentumMultiplier);
return true;
})
);
static const Property FUSE_TIMER(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_Grenade>([](PropValue p, ATrDevice* dev, ATrProj_Grenade* proj) {
proj->m_fExplosionTime = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Grenade>([](ATrDevice* dev, ATrProj_Grenade* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fExplosionTime);
return true;
})
);
static const Property EXPLODE_ON_CONTACT(
ValueType::BOOLEAN,
projDeviceApplierAdapter<ATrDevice, ATrProj_Grenade>([](PropValue p, ATrDevice* dev, ATrProj_Grenade* proj) {
proj->m_bExplodeOnTouchEvent = p.valBool;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Grenade>([](ATrDevice* dev, ATrProj_Grenade* proj, PropValue& ret) {
ret = PropValue::fromBool(proj->m_bExplodeOnTouchEvent);
return true;
})
);
static const Property EXPLODE_ON_FUSE(
ValueType::BOOLEAN,
projDeviceApplierAdapter<ATrDevice, ATrProj_Grenade>([](PropValue p, ATrDevice* dev, ATrProj_Grenade* proj) {
proj->m_bTimedExplosion = p.valBool;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Grenade>([](ATrDevice* dev, ATrProj_Grenade* proj, PropValue& ret) {
ret = PropValue::fromBool(proj->m_bTimedExplosion);
return true;
})
);
static const Property MUST_BOUNCE_BEFORE_EXPLODE(
ValueType::BOOLEAN,
projDeviceApplierAdapter<ATrDevice, ATrProj_Grenade>([](PropValue p, ATrDevice* dev, ATrProj_Grenade* proj) {
proj->m_bBounceRequiredForExplode = p.valBool;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Grenade>([](ATrDevice* dev, ATrProj_Grenade* proj, PropValue& ret) {
ret = PropValue::fromBool(proj->m_bBounceRequiredForExplode);
return true;
})
);
// Pack
static const Property PACK_SUSTAINED_ENERGY_COST(
ValueType::FLOAT,
applierAdapter<ATrDevice_Pack>([](PropValue p, ATrDevice_Pack* dev) {
dev->m_fDefaultPowerPoolCostPerSec = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Pack>([](ATrDevice_Pack* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fDefaultPowerPoolCostPerSec);
return true;
})
);
static const Property THRUST_PACK_ENERGY_COST(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_fPowerPoolCost = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fPowerPoolCost);
return true;
})
);
static const Property THRUST_PACK_IMPULSE(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_vBlinkImpulse.X = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_vBlinkImpulse.X);
return true;
})
);
static const Property THRUST_PACK_SIDEWAYS_IMPULSE(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_vBlinkImpulse.Y = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_vBlinkImpulse.Y);
return true;
})
);
static const Property THRUST_PACK_MIN_VERTICAL_IMPULSE(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_fMinZImpulse = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fMinZImpulse);
return true;
})
);
static const Property THRUST_PACK_COOLDOWN_TIME(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_fCooldownTime = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fCooldownTime);
return true;
})
);
static const Property THRUST_PACK_SPEED_RANGE_START(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_fSpeedCapThresholdStart = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fSpeedCapThresholdStart);
return true;
})
);
static const Property THRUST_PACK_SPEED_RANGE_END(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_fSpeedCapThreshold = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fSpeedCapThreshold);
return true;
})
);
static const Property THRUST_PACK_SPEED_CAP_REDUCTION(
ValueType::FLOAT,
applierAdapter<ATrDevice_Blink>([](PropValue p, ATrDevice_Blink* dev) {
dev->m_fSpeedCapPct = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Blink>([](ATrDevice_Blink* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fSpeedCapPct);
return true;
})
);
static const Property SHIELD_PACK_ENERGY_COST_PER_DAMAGE_POINT(
ValueType::FLOAT,
applierAdapterWithAdditionalClass<ATrDevice_ShieldPack, ATrPawn>("TrPawn", [](PropValue p, ATrDevice_ShieldPack* dev, ATrPawn* pawn) {
pawn->m_fShieldMultiple = p.valFloat;
return true;
}),
getterAdapterWithAdditionalClass<ATrDevice_ShieldPack, ATrPawn>("TrPawn", [](ATrDevice_ShieldPack* dev, ATrPawn* pawn, PropValue& ret) {
ret = PropValue::fromFloat(pawn->m_fShieldMultiple);
return true;
})
);
static const Property JAMMER_PACK_RANGE(
ValueType::FLOAT,
applierAdapterWithAdditionalClass<ATrDevice_JammerPack, ATrPawn>("TrPawn", [](PropValue p, ATrDevice_JammerPack* dev, ATrPawn* pawn) {
pawn->m_fJamEffectRadius = p.valFloat;
return true;
}),
getterAdapterWithAdditionalClass<ATrDevice_JammerPack, ATrPawn>("TrPawn", [](ATrDevice_JammerPack* dev, ATrPawn* pawn, PropValue& ret) {
ret = PropValue::fromFloat(pawn->m_fJamEffectRadius);
return true;
})
);
static const Property PACK_BUFF_AMOUNT(
ValueType::FLOAT,
effectDeviceApplierAdapter<ATrDevice_Pack, UTrEffect>([](PropValue p, ATrDevice_Pack* dev, UTrEffect* eff) {
eff->m_fValue = p.valFloat;
return true;
}),
effectDeviceGetterAdapter<ATrDevice_Pack, UTrEffect>([](ATrDevice_Pack* dev, UTrEffect* eff, PropValue& ret) {
ret = PropValue::fromFloat(eff->m_fValue);
return true;
})
);
static const Property STEALTH_PACK_MAX_SPEED(
ValueType::FLOAT,
applierAdapter<ATrDevice_Stealth>([](PropValue p, ATrDevice_Stealth* dev) {
dev->m_fPulseSpeedThreshold = p.valFloat;
return true;
}),
getterAdapter<ATrDevice_Stealth>([](ATrDevice_Stealth* dev, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fPulseSpeedThreshold);
return true;
})
);
// Deployable / Turret
static const Property DEPLOYABLE_RANGE(
ValueType::FLOAT,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable* dep) {
dep->m_fDamageRadius = p.valFloat;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable>([](ATrDevice_Deployable* dev, ATrDeployable* dep, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fDamageRadius);
return true;
})
);
static const Property DEPLOYABLE_MAX_ALLOWED(
ValueType::INTEGER,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable* dep) {
dev->m_nPerPlayerMaxDeployed = p.valInt;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable>([](ATrDevice_Deployable* dev, ATrDeployable* dep, PropValue& ret) {
ret = PropValue::fromInt(dev->m_nPerPlayerMaxDeployed);
return true;
})
);
static const Property DEPLOYABLE_MIN_PROXIMITY(
ValueType::FLOAT,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable* dep) {
dev->m_fOtherDeployableProximityCheck = p.valFloat;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable>([](ATrDevice_Deployable* dev, ATrDeployable* dep, PropValue& ret) {
ret = PropValue::fromFloat(dev->m_fOtherDeployableProximityCheck);
return true;
})
);
static const Property TURRET_TIME_TO_ACQUIRE_TARGET(
ValueType::FLOAT,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable_Turret>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable_Turret* dep) {
dep->m_fTimeToAcquireTarget = p.valFloat;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable_Turret>([](ATrDevice_Deployable* dev, ATrDeployable_Turret* dep, PropValue& ret) {
ret = PropValue::fromFloat(dep->m_fTimeToAcquireTarget);
return true;
})
);
static const Property TURRET_CAN_TARGET_VEHICLES(
ValueType::BOOLEAN,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable_Turret>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable_Turret* dep) {
dep->m_bCanTargetVehicles = p.valBool;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable_Turret>([](ATrDevice_Deployable* dev, ATrDeployable_Turret* dep, PropValue& ret) {
ret = PropValue::fromBool(dep->m_bCanTargetVehicles);
return true;
})
);
// Forcefield
static const Property FORCEFIELD_MIN_DAMAGE(
ValueType::FLOAT,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
subdev->m_MinDamage = p.valFloat;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep, PropValue& ret) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
ret = PropValue::fromFloat(subdev->m_MinDamage);
return true;
})
);
static const Property FORCEFIELD_MAX_DAMAGE(
ValueType::FLOAT,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
subdev->m_MaxDamage = p.valFloat;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep, PropValue& ret) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
ret = PropValue::fromFloat(subdev->m_MaxDamage);
return true;
})
);
static const Property FORCEFIELD_MIN_DAMAGE_SPEED(
ValueType::FLOAT,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
subdev->m_MinSpeed = p.valFloat;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep, PropValue& ret) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
ret = PropValue::fromFloat(subdev->m_MinSpeed);
return true;
})
);
static const Property FORCEFIELD_MAX_DAMAGE_SPEED(
ValueType::FLOAT,
deployableDeviceApplierAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](PropValue p, ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
subdev->m_MaxSpeed = p.valFloat;
return true;
}),
deployableDeviceGetterAdapter<ATrDevice_Deployable, ATrDeployable_ForceField>([](ATrDevice_Deployable* dev, ATrDeployable_ForceField* dep, PropValue& ret) {
if (!dep || !dep->m_DeviceClass || !dep->m_DeviceClass->Default) return false;
ATrSubDevice_ForceField* subdev = (ATrSubDevice_ForceField*)dep->m_DeviceClass->Default;
ret = PropValue::fromFloat(subdev->m_MaxSpeed);
return true;
})
);
// Mines
static const Property MINE_DEPLOY_TIME(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_Mine>([](PropValue p, ATrDevice* dev, ATrProj_Mine* proj) {
proj->m_fDeploySeconds = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Mine>([](ATrDevice* dev, ATrProj_Mine* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fDeploySeconds);
return true;
})
);
static const Property MINE_MAX_ALLOWED(
ValueType::INTEGER,
projDeviceApplierAdapter<ATrDevice, ATrProjectile>([](PropValue p, ATrDevice* dev, ATrProjectile* proj) {
proj->m_nPerPlayerMaxDeployed = p.valInt;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProjectile>([](ATrDevice* dev, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromInt(proj->m_nPerPlayerMaxDeployed);
return true;
})
);
static const Property MINE_COLLISION_CYLINDER_RADIUS(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_Mine>([](PropValue p, ATrDevice* dev, ATrProj_Mine* proj) {
proj->m_fDetonationRadius = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Mine>([](ATrDevice* dev, ATrProj_Mine* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fDetonationRadius);
return true;
})
);
static const Property MINE_COLLISION_CYLINDER_HEIGHT(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_Mine>([](PropValue p, ATrDevice* dev, ATrProj_Mine* proj) {
proj->m_fDetonationHeight = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Mine>([](ATrDevice* dev, ATrProj_Mine* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fDetonationHeight);
return true;
})
);
static const Property CLAYMORE_DETONATION_ANGLE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_Claymore>([](PropValue p, ATrDevice* dev, ATrProj_Claymore* proj) {
proj->m_fDetonationAngle = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_Claymore>([](ATrDevice* dev, ATrProj_Claymore* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fDetonationAngle);
return true;
})
);
static const Property PRISM_MINE_TRIP_DISTANCE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrDevice, ATrProj_PrismMine>([](PropValue p, ATrDevice* dev, ATrProj_PrismMine* proj) {
proj->m_fTripDistance = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrDevice, ATrProj_PrismMine>([](ATrDevice* dev, ATrProj_PrismMine* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fTripDistance);
return true;
})
);
// Main mapping
std::map<PropId, Property> properties = {
// Ammo
{PropId::CLIP_AMMO, CLIP_AMMO},
{PropId::SPARE_AMMO, SPARE_AMMO},
{PropId::AMMO_PER_SHOT, AMMO_PER_SHOT},
{PropId::LOW_AMMO_CUTOFF, LOW_AMMO_CUTOFF},
// Reload / Firing
{PropId::RELOAD_TIME, RELOAD_TIME},
{PropId::FIRE_INTERVAL, FIRE_INTERVAL},
{PropId::HOLD_TO_FIRE, HOLD_TO_FIRE},
{PropId::CAN_ZOOM, CAN_ZOOM},
{PropId::RELOAD_SINGLE, RELOAD_SINGLE},
{PropId::RELOAD_APPLICATION_PROPORTION, RELOAD_APPLICATION_PROPORTION},
{PropId::BURST_SHOT_COUNT, BURST_SHOT_COUNT},
{PropId::BURST_SHOT_REFIRE_TIME, BURST_SHOT_REFIRE_TIME},
{PropId::SPINUP_TIME, SPINUP_TIME},
{PropId::SHOTGUN_SHOT_COUNT, SHOTGUN_SHOT_COUNT},
{PropId::SHOT_ENERGY_COST, SHOT_ENERGY_COST},
// Damage / Impact
{PropId::DAMAGE, DAMAGE},
{PropId::EXPLOSIVE_RADIUS, EXPLOSIVE_RADIUS},
{PropId::DIRECT_HIT_MULTIPLIER, DIRECT_HIT_MULTIPLIER},
{PropId::IMPACT_MOMENTUM, IMPACT_MOMENTUM},
{PropId::SELF_IMPACT_MOMENTUM_MULTIPLIER, SELF_IMPACT_MOMENTUM_MULTIPLIER},
{PropId::SELF_IMPACT_EXTRA_Z_MOMENTUM, SELF_IMPACT_EXTRA_Z_MOMENTUM},
{PropId::ENERGY_DRAIN, ENERGY_DRAIN},
{PropId::MAX_DAMAGE_RANGE_PROPORTION, MAX_DAMAGE_RANGE_PROPORTION},
{PropId::MIN_DAMAGE_RANGE_PROPORTION, MIN_DAMAGE_RANGE_PROPORTION},
{PropId::MIN_DAMAGE_PROPORTION, MIN_DAMAGE_PROPORTION},
{PropId::BULLET_DAMAGE_RANGE, BULLET_DAMAGE_RANGE},
{PropId::DAMAGE_AGAINST_ARMOR_MULTIPLIER, DAMAGE_AGAINST_ARMOR_MULTIPLIER},
{PropId::DAMAGE_AGAINST_GENERATOR_MULTIPLIER, DAMAGE_AGAINST_GENERATOR_MULTIPLIER},
{PropId::DAMAGE_AGAINST_BASE_TURRET_MULTIPLIER, DAMAGE_AGAINST_BASE_TURRET_MULTIPLIER},
{PropId::DAMAGE_AGAINST_BASE_SENSOR_MULTIPLIER, DAMAGE_AGAINST_BASE_SENSOR_MULTIPLIER},
{PropId::DAMAGE_AGAINST_GRAVCYCLE_MULTIPLIER, DAMAGE_AGAINST_GRAVCYCLE_MULTIPLIER},
{PropId::DAMAGE_AGAINST_BEOWULF_MULTIPLIER, DAMAGE_AGAINST_BEOWULF_MULTIPLIER},
{PropId::DAMAGE_AGAINST_SHRIKE_MULTIPLIER, DAMAGE_AGAINST_SHRIKE_MULTIPLIER},
{PropId::DOES_GIB_ON_KILL, DOES_GIB_ON_KILL},
{PropId::GIB_IMPULSE_RADIUS, GIB_IMPULSE_RADIUS},
{PropId::GIB_STRENGTH, GIB_STRENGTH},
{PropId::DOES_IMPULSE_FLAG, DOES_IMPULSE_FLAG},
{PropId::MELEE_DAMAGE_RADIUS, MELEE_DAMAGE_RADIUS},
{PropId::MELEE_CONE_ANGLE, MELEE_CONE_ANGLE},
{PropId::PHASE_DAMAGE_PER_ENERGY, PHASE_DAMAGE_PER_ENERGY},
{PropId::PHASE_MAX_CONSUMED_ENERGY, PHASE_MAX_CONSUMED_ENERGY},
{PropId::BXT_CHARGE_MAX_DAMAGE, BXT_CHARGE_MAX_DAMAGE},
{PropId::BXT_CHARGE_TIME, BXT_CHARGE_TIME},
{PropId::BXT_CHARGE_MULT_COEFFICIENT, BXT_CHARGE_MULT_COEFFICIENT},
{PropId::BXT_CHARGE_DIV_COEFFICIENT, BXT_CHARGE_DIV_COEFFICIENT},
{PropId::FRACTAL_DURATION, FRACTAL_DURATION},
{PropId::FRACTAL_SHARD_INTERVAL, FRACTAL_SHARD_INTERVAL},
{PropId::FRACTAL_ASCENT_TIME, FRACTAL_ASCENT_TIME},
{PropId::FRACTAL_ASCENT_HEIGHT, FRACTAL_ASCENT_HEIGHT},
{PropId::FRACTAL_SHARD_DISTANCE, FRACTAL_SHARD_DISTANCE},
{PropId::FRACTAL_SHARD_HEIGHT, FRACTAL_SHARD_HEIGHT},
{PropId::FRACTAL_SHARD_DAMAGE, FRACTAL_SHARD_DAMAGE},
{PropId::FRACTAL_SHARD_DAMAGE_RADIUS, FRACTAL_SHARD_DAMAGE_RADIUS},
// Projectile / Tracer
{PropId::PROJECTILE_SPEED, PROJECTILE_SPEED},
{PropId::PROJECTILE_MAX_SPEED, PROJECTILE_MAX_SPEED},
{PropId::COLLISION_SIZE, COLLISION_SIZE},
{PropId::PROJECTILE_INHERITANCE, PROJECTILE_INHERITANCE},
{PropId::PROJECTILE_LIFESPAN, PROJECTILE_LIFESPAN},
{PropId::PROJECTILE_GRAVITY, PROJECTILE_GRAVITY},
{PropId::PROJECTILE_TERMINAL_VELOCITY, PROJECTILE_TERMINAL_VELOCITY},
{PropId::PROJECTILE_BOUNCE_DAMPING, PROJECTILE_BOUNCE_DAMPING},
{PropId::PROJECTILE_MESH_SCALE, PROJECTILE_MESH_SCALE},
{PropId::PROJECTILE_LIGHT_RADIUS, PROJECTILE_LIGHT_RADIUS},
{PropId::HITSCAN_RANGE, HITSCAN_RANGE},
{PropId::FIRE_OFFSET_X, FIRE_OFFSET_X},
{PropId::FIRE_OFFSET_Y, FIRE_OFFSET_Y},
{PropId::FIRE_OFFSET_Z, FIRE_OFFSET_Z},
// Accuracy
{PropId::ACCURACY, ACCURACY},
{PropId::ACCURACY_LOSS_ON_SHOT, ACCURACY_LOSS_ON_SHOT},
{PropId::ACCURACY_LOSS_ON_JUMP, ACCURACY_LOSS_ON_JUMP},
{PropId::ACCURACY_LOSS_ON_WEAPON_SWITCH, ACCURACY_LOSS_ON_WEAPON_SWITCH},
{PropId::ACCURACY_LOSS_MAX, ACCURACY_LOSS_MAX},
{PropId::ACCURACY_CORRECTION_RATE, ACCURACY_CORRECTION_RATE},
{PropId::SHOTGUN_INNER_ACCURACY, SHOTGUN_INNER_ACCURACY},
{PropId::SHOTGUN_USE_GOTY_SPREAD, SHOTGUN_USE_GOTY_SPREAD},
// Grenade
{PropId::THROW_DELAY, THROW_DELAY},
{PropId::THROW_PULL_PIN_TIME, THROW_PULL_PIN_TIME},
{PropId::STUCK_DAMAGE_MULTIPLIER, STUCK_DAMAGE_MULTIPLIER},
{PropId::STUCK_MOMENTUM_MULTIPLIER, STUCK_MOMENTUM_MULTIPLIER},
{PropId::FUSE_TIMER, FUSE_TIMER},
{PropId::EXPLODE_ON_CONTACT, EXPLODE_ON_CONTACT},
{PropId::EXPLODE_ON_FUSE, EXPLODE_ON_FUSE},
{PropId::MUST_BOUNCE_BEFORE_EXPLODE, MUST_BOUNCE_BEFORE_EXPLODE},
// Pack
{PropId::PACK_SUSTAINED_ENERGY_COST, PACK_SUSTAINED_ENERGY_COST},
{PropId::THRUST_PACK_ENERGY_COST, THRUST_PACK_ENERGY_COST},
{PropId::THRUST_PACK_IMPULSE, THRUST_PACK_IMPULSE},
{PropId::THRUST_PACK_SIDEWAYS_IMPULSE, THRUST_PACK_SIDEWAYS_IMPULSE},
{PropId::THRUST_PACK_MIN_VERTICAL_IMPULSE, THRUST_PACK_MIN_VERTICAL_IMPULSE},
{PropId::THRUST_PACK_COOLDOWN_TIME, THRUST_PACK_COOLDOWN_TIME},
{PropId::THRUST_PACK_SPEED_RANGE_START, THRUST_PACK_SPEED_RANGE_START},
{PropId::THRUST_PACK_SPEED_RANGE_END, THRUST_PACK_SPEED_RANGE_END},
{PropId::THRUST_PACK_SPEED_CAP_REDUCTION, THRUST_PACK_SPEED_CAP_REDUCTION},
{PropId::SHIELD_PACK_ENERGY_COST_PER_DAMAGE_POINT, SHIELD_PACK_ENERGY_COST_PER_DAMAGE_POINT},
{PropId::JAMMER_PACK_RANGE, JAMMER_PACK_RANGE},
{PropId::PACK_BUFF_AMOUNT, PACK_BUFF_AMOUNT},
{PropId::STEALTH_PACK_MAX_SPEED, STEALTH_PACK_MAX_SPEED},
// Deployable / Turret
{PropId::DEPLOYABLE_RANGE, DEPLOYABLE_RANGE},
{PropId::DEPLOYABLE_MAX_ALLOWED, DEPLOYABLE_MAX_ALLOWED},
{PropId::DEPLOYABLE_MIN_PROXIMITY, DEPLOYABLE_MIN_PROXIMITY},
{PropId::TURRET_TIME_TO_ACQUIRE_TARGET, TURRET_TIME_TO_ACQUIRE_TARGET},
{PropId::TURRET_CAN_TARGET_VEHICLES, TURRET_CAN_TARGET_VEHICLES},
{PropId::FORCEFIELD_MIN_DAMAGE, FORCEFIELD_MIN_DAMAGE },
{PropId::FORCEFIELD_MAX_DAMAGE, FORCEFIELD_MAX_DAMAGE },
{PropId::FORCEFIELD_MIN_DAMAGE_SPEED, FORCEFIELD_MIN_DAMAGE_SPEED },
{PropId::FORCEFIELD_MAX_DAMAGE_SPEED, FORCEFIELD_MAX_DAMAGE_SPEED },
// Mines
{PropId::MINE_DEPLOY_TIME, MINE_DEPLOY_TIME},
{PropId::MINE_MAX_ALLOWED, MINE_MAX_ALLOWED},
{PropId::MINE_COLLISION_CYLINDER_RADIUS, MINE_COLLISION_CYLINDER_RADIUS},
{PropId::MINE_COLLISION_CYLINDER_HEIGHT, MINE_COLLISION_CYLINDER_HEIGHT},
{PropId::CLAYMORE_DETONATION_ANGLE, CLAYMORE_DETONATION_ANGLE},
{PropId::PRISM_MINE_TRIP_DISTANCE, PRISM_MINE_TRIP_DISTANCE},
};
}
namespace Classes {
// Base stats
static const Property HEALTH_POOL(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_nMaxHealthPool = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_nMaxHealthPool);
return true;
})
);
static const Property ENERGY_POOL(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->r_fMaxPowerPool = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->r_fMaxPowerPool);
return true;
})
);
static const Property ENERGY_RECHARGE_RATE(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fPowerPoolRechargeRate = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fPowerPoolRechargeRate);
return true;
})
);
static const Property INITIAL_JET_ENERGY_COST(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fJetpackInitialCost = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fJetpackInitialCost);
return true;
})
);
static const Property JET_ENERGY_COST(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fJetpackPowerPoolCost = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fJetpackPowerPoolCost);
return true;
})
);
static const Property REGEN_TIME(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fSecondsBeforeAutoHeal = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fSecondsBeforeAutoHeal);
return true;
})
);
static const Property REGEN_RATE(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fHealthPoolRechargeRate = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fHealthPoolRechargeRate);
return true;
})
);
static const Property LOW_HEALTH_THRESHOLD(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fLowHealthThreshold = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fLowHealthThreshold);
return true;
})
);
// Movement / Skiing
static const Property MASS(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fMass = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fMass);
return true;
})
);
static const Property GROUND_SPEED(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fMaxGroundSpeed = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fMaxGroundSpeed);
return true;
})
);
static const Property MAX_SKIING_SPEED(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIMaxSkiSpeed = p.valFloat;
fi->m_fFITerminalSkiSpeed = p.valFloat + 500;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIMaxSkiSpeed);
return true;
})
);
static const Property MAX_SKI_CONTROL(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIMaxSkiControlPct = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIMaxSkiControlPct);
return true;
})
);
static const Property SKI_CONTROL_PEAK_SPEED(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIPeakSkiControlSpeed = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIPeakSkiControlSpeed);
return true;
})
);
static const Property SKI_CONTROL_VARIANCE(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFISkiControlSigmaSquare = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFISkiControlSigmaSquare);
return true;
})
);
static const Property SKI_SLOPE_GRAVITY(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFISkiSlopeGravityBoost = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFISkiSlopeGravityBoost);
return true;
})
);
static const Property VEHICLE_SPEED_INHERITANCE(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fVehicleSpeedInheritPercent = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fVehicleSpeedInheritPercent);
return true;
})
);
static const Property MOMENTUM_DAMPENING_ENABLED(
ValueType::BOOLEAN,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_bMomentumDampingEnabled = p.valBool;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromBool(fi->m_bMomentumDampingEnabled);
return true;
})
);
static const Property MOMENTUM_DAMPENING_THRESHOLD(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fMomentumDampingSpeed = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fMomentumDampingSpeed);
return true;
})
);
static const Property MOMENTUM_DAMPENING_PROPORTION(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fMomentumDampingPct = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fMomentumDampingPct);
return true;
})
);
static const Property MAX_HEALTH_REGEN_SPEED(
ValueType::INTEGER,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
TenantedDataStore::ClassSpecificData data = TenantedDataStore::classData.get(fi->ClassId);
data.maxRegenMoveSpeed = p.valInt;
TenantedDataStore::classData.set(fi->ClassId, data);
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
TenantedDataStore::ClassSpecificData data = TenantedDataStore::classData.get(fi->ClassId);
ret = PropValue::fromInt(data.maxRegenMoveSpeed);
return true;
})
);
// Jetting / Air Control
static const Property MAX_JETTING_SPEED(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIMaxJetpackThrustSpeed = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIMaxJetpackThrustSpeed);
return true;
})
);
static const Property JET_ACCELERATION(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFlightAcceleration = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFlightAcceleration);
return true;
})
);
static const Property INITIAL_JET_ACCELERATION_MULTIPLIER(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fJetpackInitAccelMultiplier = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fJetpackInitAccelMultiplier);
return true;
})
);
static const Property INITIAL_JET_LENGTH(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fJetpackInitTotalTime = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fJetpackInitTotalTime);
return true;
})
);
static const Property FORWARD_JET_PROPORTION(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIForwardJettingPct = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIForwardJettingPct);
return true;
})
);
static const Property JET_BOOST_MAX_GROUND_SPEED(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIMaxJetpackBoostGroundspeed = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIMaxJetpackBoostGroundspeed);
return true;
})
);
static const Property AIR_SPEED(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIAirSpeed = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIAirSpeed);
return true;
})
);
static const Property DEFAULT_AIR_CONTROL(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fFIAirControl = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fFIAirControl);
return true;
})
);
static const Property AIR_CONTROL_MAX_MULTIPLIER(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_vAirControlMultiplier.X = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_vAirControlMultiplier.X);
return true;
})
);
static const Property AIR_CONTROL_MIN_MULTIPLIER(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_vAirControlMultiplier.Y = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_vAirControlMultiplier.Y);
return true;
})
);
static const Property AIR_CONTROL_REDUCTION_RANGE_MAX(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_vAirControlReductionRange.X = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_vAirControlReductionRange.X);
return true;
})
);
static const Property AIR_CONTROL_REDUCTION_RANGE_MIN(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_vAirControlReductionRange.Y = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_vAirControlReductionRange.Y);
return true;
})
);
// Collision
static const Property COLLISION_CYLINDER_RADIUS(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fCollisionRadius = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fCollisionRadius);
return true;
})
);
static const Property COLLISION_CYLINDER_HEIGHT(
ValueType::FLOAT,
applierAdapter<UTrFamilyInfo>([](PropValue p, UTrFamilyInfo* fi) {
fi->m_fCollisionHeight = p.valFloat;
return true;
}),
getterAdapter<UTrFamilyInfo>([](UTrFamilyInfo* fi, PropValue& ret) {
ret = PropValue::fromFloat(fi->m_fCollisionHeight);
return true;
})
);
std::map<PropId, Property> properties = {
// Base stats
{PropId::HEALTH_POOL, HEALTH_POOL},
{PropId::ENERGY_POOL, ENERGY_POOL},
{PropId::ENERGY_RECHARGE_RATE, ENERGY_RECHARGE_RATE},
{PropId::INITIAL_JET_ENERGY_COST, INITIAL_JET_ENERGY_COST},
{PropId::JET_ENERGY_COST, JET_ENERGY_COST},
{PropId::REGEN_TIME, REGEN_TIME},
{PropId::REGEN_RATE, REGEN_RATE},
{PropId::LOW_HEALTH_THRESHOLD, LOW_HEALTH_THRESHOLD},
// Movement / Skiing
{PropId::MASS, MASS},
{PropId::GROUND_SPEED, GROUND_SPEED},
{PropId::MAX_SKIING_SPEED, MAX_SKIING_SPEED},
{PropId::MAX_SKI_CONTROL, MAX_SKI_CONTROL},
{PropId::SKI_CONTROL_PEAK_SPEED, SKI_CONTROL_PEAK_SPEED},
{PropId::SKI_CONTROL_VARIANCE, SKI_CONTROL_VARIANCE},
{PropId::SKI_SLOPE_GRAVITY, SKI_SLOPE_GRAVITY},
{PropId::VEHICLE_SPEED_INHERITANCE, VEHICLE_SPEED_INHERITANCE},
{PropId::MOMENTUM_DAMPENING_ENABLED, MOMENTUM_DAMPENING_ENABLED},
{PropId::MOMENTUM_DAMPENING_THRESHOLD, MOMENTUM_DAMPENING_THRESHOLD},
{PropId::MOMENTUM_DAMPENING_PROPORTION, MOMENTUM_DAMPENING_PROPORTION},
{PropId::MAX_HEALTH_REGEN_SPEED, MAX_HEALTH_REGEN_SPEED},
// Jetting / Air Control
{PropId::MAX_JETTING_SPEED, MAX_JETTING_SPEED},
{PropId::JET_ACCELERATION, JET_ACCELERATION},
{PropId::INITIAL_JET_ACCELERATION_MULTIPLIER, INITIAL_JET_ACCELERATION_MULTIPLIER},
{PropId::INITIAL_JET_LENGTH, INITIAL_JET_LENGTH},
{PropId::FORWARD_JET_PROPORTION, FORWARD_JET_PROPORTION},
{PropId::JET_BOOST_MAX_GROUND_SPEED, JET_BOOST_MAX_GROUND_SPEED},
{PropId::AIR_SPEED, AIR_SPEED},
{PropId::DEFAULT_AIR_CONTROL, DEFAULT_AIR_CONTROL},
{PropId::AIR_CONTROL_MAX_MULTIPLIER, AIR_CONTROL_MAX_MULTIPLIER},
{PropId::AIR_CONTROL_MIN_MULTIPLIER, AIR_CONTROL_MIN_MULTIPLIER},
{PropId::AIR_CONTROL_REDUCTION_RANGE_MAX, AIR_CONTROL_REDUCTION_RANGE_MAX},
{PropId::AIR_CONTROL_REDUCTION_RANGE_MIN, AIR_CONTROL_REDUCTION_RANGE_MIN},
// Collision
{PropId::COLLISION_CYLINDER_RADIUS, COLLISION_CYLINDER_RADIUS},
{PropId::COLLISION_CYLINDER_HEIGHT, COLLISION_CYLINDER_HEIGHT},
};
}
namespace Vehicles {
static const Property HEALTH_POOL(
ValueType::INTEGER,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->HealthMax = p.valInt;
veh->Health = veh->HealthMax;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromInt(veh->HealthMax);
return true;
})
);
static const Property ENERGY_POOL(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->r_fMaxPowerPool = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->r_fMaxPowerPool);
return true;
})
);
static const Property ENERGY_RECHARGE_RATE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fPowerPoolRechargeRate = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fPowerPoolRechargeRate);
return true;
})
);
static const Property IS_ARMORED(
ValueType::BOOLEAN,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_bUsesArmoredMultiplier = p.valBool;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromBool(veh->m_bUsesArmoredMultiplier);
return true;
})
);
static const Property IS_HOMING_TARGET(
ValueType::BOOLEAN,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->bHomingTarget = p.valBool;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromBool(veh->bHomingTarget);
return true;
})
);
static const Property CAN_CARRY_FLAG_AS_PILOT(
ValueType::BOOLEAN,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
if (veh->Seats.Count == 0) return false;
veh->Seats.Data[0].ValidFlagSeat = p.valBool;
veh->bCanCarryFlag = veh->Seats.Data[0].ValidFlagSeat || (veh->Seats.Count >= 2 && veh->Seats.Data[1].ValidFlagSeat);
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
if (veh->Seats.Count == 0) return false;
ret = PropValue::fromBool(veh->Seats.Data[0].ValidFlagSeat);
return true;
})
);
static const Property CAN_CARRY_FLAG_AS_PASSENGER(
ValueType::BOOLEAN,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
if (veh->Seats.Count < 2) return false;
veh->Seats.Data[1].ValidFlagSeat = p.valBool;
veh->bCanCarryFlag = veh->Seats.Data[0].ValidFlagSeat || veh->Seats.Data[1].ValidFlagSeat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
if (veh->Seats.Count < 2) return false;
ret = PropValue::fromBool(veh->Seats.Data[1].ValidFlagSeat);
return true;
})
);
static const Property TIME_BEFORE_SELFDESTRUCT(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fTimeToReset = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fTimeToReset);
return true;
})
);
// Movement
static const Property MAX_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->MaxSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->MaxSpeed);
return true;
})
);
static const Property MAX_DIVING_SPEED_MULTIPLIER(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fDivingMaxSpeedMultiplier = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fDivingMaxSpeedMultiplier);
return true;
})
);
static const Property BOOST_MULTIPLIER(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fBoostMultiplier = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fBoostMultiplier);
return true;
})
);
static const Property BOOST_ENERGY_COST(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fBoostEnergyPerSec = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fBoostEnergyPerSec);
return true;
})
);
static const Property BOOST_MIN_USABLE_PROPORTION(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fBoostReactivatePct = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fBoostReactivatePct);
return true;
})
);
static const Property MAX_PLAYER_EXIT_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fMaxPawnLeaveSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fMaxPawnLeaveSpeed);
return true;
})
);
static const Property GRAVITY_SCALE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->CustomGravityScaling = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->CustomGravityScaling);
return true;
})
);
// Self-Damage
static const Property MAX_CRASH_DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fWallMaxDamage = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fWallMaxDamage);
return true;
})
);
static const Property MIN_CRASH_DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fWallMinDamage = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fWallMinDamage);
return true;
})
);
static const Property MAX_CRASH_DAMAGE_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fWallMaxDamageSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fWallMaxDamageSpeed);
return true;
})
);
static const Property MIN_CRASH_DAMAGE_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fWallMinDamageSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fWallMinDamageSpeed);
return true;
})
);
static const Property MAX_VEHICLE_CRASH_DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fVehicleMaxDamage = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fVehicleMaxDamage);
return true;
})
);
static const Property MIN_VEHICLE_CRASH_DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fVehicleMinDamage = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fVehicleMinDamage);
return true;
})
);
static const Property MAX_VEHICLE_CRASH_DAMAGE_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fVehicleMaxDamageSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fVehicleMaxDamageSpeed);
return true;
})
);
static const Property MIN_VEHICLE_CRASH_DAMAGE_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fVehicleMinDamageSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fVehicleMinDamageSpeed);
return true;
})
);
// Ramming
static const Property RAM_MIN_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->MinRunOverSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->MinRunOverSpeed);
return true;
})
);
static const Property RAM_MAX_DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fPawnMaxDamage = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fPawnMaxDamage);
return true;
})
);
static const Property RAM_MIN_DAMAGE(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fPawnMinDamage = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fPawnMinDamage);
return true;
})
);
static const Property RAM_MAX_DAMAGE_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fPawnMaxDamageSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fPawnMaxDamageSpeed);
return true;
})
);
static const Property RAM_PLAYER_PUSH_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fPawnPushSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fPawnPushSpeed);
return true;
})
);
static const Property RAM_FLAG_PUSH_SPEED(
ValueType::FLOAT,
applierAdapter<ATrVehicle>([](PropValue p, ATrVehicle* veh) {
veh->m_fFlagPushSpeed = p.valFloat;
return true;
}),
getterAdapter<ATrVehicle>([](ATrVehicle* veh, PropValue& ret) {
ret = PropValue::fromFloat(veh->m_fFlagPushSpeed);
return true;
})
);
std::map<PropId, Property> properties = {
// Base Stats
{PropId::HEALTH_POOL, HEALTH_POOL},
{PropId::ENERGY_POOL, ENERGY_POOL},
{PropId::ENERGY_RECHARGE_RATE, ENERGY_RECHARGE_RATE},
{PropId::IS_ARMORED, IS_ARMORED},
{PropId::IS_HOMING_TARGET, IS_HOMING_TARGET},
{PropId::CAN_CARRY_FLAG_AS_PILOT, CAN_CARRY_FLAG_AS_PILOT},
{PropId::CAN_CARRY_FLAG_AS_PASSENGER, CAN_CARRY_FLAG_AS_PASSENGER},
{PropId::TIME_BEFORE_SELFDESTRUCT, TIME_BEFORE_SELFDESTRUCT},
// Movement
{PropId::MAX_SPEED, MAX_SPEED},
{PropId::MAX_DIVING_SPEED_MULTIPLIER, MAX_DIVING_SPEED_MULTIPLIER},
{PropId::BOOST_MULTIPLIER, BOOST_MULTIPLIER},
{PropId::BOOST_ENERGY_COST, BOOST_ENERGY_COST},
{PropId::BOOST_MIN_USABLE_PROPORTION, BOOST_MIN_USABLE_PROPORTION},
{PropId::MAX_PLAYER_EXIT_SPEED, MAX_PLAYER_EXIT_SPEED},
{PropId::GRAVITY_SCALE, GRAVITY_SCALE},
// Self-Damage
{PropId::MAX_CRASH_DAMAGE, MAX_CRASH_DAMAGE},
{PropId::MIN_CRASH_DAMAGE, MIN_CRASH_DAMAGE},
{PropId::MAX_CRASH_DAMAGE_SPEED, MAX_CRASH_DAMAGE_SPEED},
{PropId::MIN_CRASH_DAMAGE_SPEED, MIN_CRASH_DAMAGE_SPEED},
{PropId::MAX_VEHICLE_CRASH_DAMAGE, MAX_VEHICLE_CRASH_DAMAGE},
{PropId::MIN_VEHICLE_CRASH_DAMAGE, MIN_VEHICLE_CRASH_DAMAGE},
{PropId::MAX_VEHICLE_CRASH_DAMAGE_SPEED, MAX_VEHICLE_CRASH_DAMAGE_SPEED},
{PropId::MIN_VEHICLE_CRASH_DAMAGE_SPEED, MIN_VEHICLE_CRASH_DAMAGE_SPEED},
// Ramming
{PropId::RAM_MIN_SPEED, RAM_MIN_SPEED},
{PropId::RAM_MAX_DAMAGE, RAM_MAX_DAMAGE},
{PropId::RAM_MIN_DAMAGE, RAM_MIN_DAMAGE},
{PropId::RAM_MAX_DAMAGE_SPEED, RAM_MAX_DAMAGE_SPEED},
{PropId::RAM_PLAYER_PUSH_SPEED, RAM_PLAYER_PUSH_SPEED},
{PropId::RAM_FLAG_PUSH_SPEED, RAM_FLAG_PUSH_SPEED},
};
}
namespace VehicleWeapons {
// Ammo
static const Property CLIP_AMMO(
ValueType::INTEGER,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->MaxAmmoCount = p.valInt;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromInt(wep->MaxAmmoCount);
return true;
})
);
static const Property SPARE_AMMO(
ValueType::INTEGER,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_nCarriedAmmo = p.valInt;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromInt(wep->m_nCarriedAmmo);
return true;
})
);
static const Property AMMO_PER_SHOT(
ValueType::INTEGER,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->ShotCost.Set(0, p.valInt);
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromInt(wep->ShotCost.GetStd(0));
return true;
})
);
// Reload / Firing
static const Property RELOAD_TIME(
ValueType::FLOAT,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_fReloadTime = p.valFloat;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromFloat(wep->m_fReloadTime);
return true;
})
);
static const Property FIRE_INTERVAL(
ValueType::FLOAT,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->FireInterval.Set(0, p.valFloat);
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromFloat(wep->FireInterval.GetStd(0));
return true;
})
);
static const Property RELOAD_SINGLE(
ValueType::BOOLEAN,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_bReloadSingles = p.valBool;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromBool(wep->m_bReloadSingles);
return true;
})
);
static const Property RELOAD_APPLICATION_PROPORTION(
ValueType::FLOAT,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_fPctTimeBeforeReload = p.valFloat;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromFloat(wep->m_fPctTimeBeforeReload);
return true;
})
);
static const Property BURST_SHOT_COUNT(
ValueType::INTEGER,
applierAdapter<ATrVehicleWeapon_BurstShot>([](PropValue p, ATrVehicleWeapon_BurstShot* wep) {
wep->m_nBurstShotCount = p.valInt;
return true;
}, false), // Don't check class due to SDK weirdness (it gets the static class horrifically wrong)
getterAdapter<ATrVehicleWeapon_BurstShot>([](ATrVehicleWeapon_BurstShot* wep, PropValue& ret) {
ret = PropValue::fromInt(wep->m_nBurstShotCount);
return true;
}, false)
);
// Damage / Impact
static const Property DAMAGE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->Damage = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->Damage);
return true;
})
);
static const Property EXPLOSIVE_RADIUS(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->DamageRadius = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->DamageRadius);
return true;
})
);
static const Property DIRECT_HIT_MULTIPLIER(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->m_fDirectHitMultiplier = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fDirectHitMultiplier);
return true;
})
);
static const Property IMPACT_MOMENTUM(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->MomentumTransfer = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->MomentumTransfer);
return true;
})
);
static const Property ENERGY_DRAIN(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_EnergyDrainAmount = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_EnergyDrainAmount);
return true;
})
);
static const Property MAX_DAMAGE_RANGE_PROPORTION(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fMaxDamageRangePct = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fMaxDamageRangePct);
return true;
})
);
static const Property MIN_DAMAGE_RANGE_PROPORTION(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fMinDamageRangePct = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fMinDamageRangePct);
return true;
})
);
static const Property MIN_DAMAGE_PROPORTION(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fMinDamagePct = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fMinDamagePct);
return true;
})
);
static const Property BULLET_DAMAGE_RANGE(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fBulletDamageRange = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fBulletDamageRange);
return true;
})
);
static const Property DAMAGE_AGAINST_ARMOR_MULTIPLIER(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstArmor = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstArmor);
return true;
})
);
static const Property DAMAGE_AGAINST_GENERATOR_MULTIPLIER(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstGenerators = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstGenerators);
return true;
})
);
static const Property DAMAGE_AGAINST_BASE_TURRET_MULTIPLIER(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstBaseTurrets = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstBaseTurrets);
return true;
})
);
static const Property DAMAGE_AGAINST_BASE_SENSOR_MULTIPLIER(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstBaseSensors = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstBaseSensors);
return true;
})
);
static const Property DAMAGE_AGAINST_GRAVCYCLE_MULTIPLIER(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstGravCycle = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstGravCycle);
return true;
})
);
static const Property DAMAGE_AGAINST_BEOWULF_MULTIPLIER(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstBeowulf = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstBeowulf);
return true;
})
);
static const Property DAMAGE_AGAINST_SHRIKE_MULTIPLIER(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fDamageMultiplierAgainstShrike = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fDamageMultiplierAgainstShrike);
return true;
})
);
static const Property DOES_GIB_ON_KILL(
ValueType::BOOLEAN,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->bAlwaysGibs = p.valBool;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromBool(dmgType->bAlwaysGibs);
return true;
})
);
static const Property GIB_IMPULSE_RADIUS(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fGibRadius = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fGibRadius);
return true;
})
);
static const Property GIB_STRENGTH(
ValueType::FLOAT,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_fGibStrength = p.valFloat;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromFloat(dmgType->m_fGibStrength);
return true;
})
);
static const Property DOES_IMPULSE_FLAG(
ValueType::BOOLEAN,
vehDeviceDamageTypeApplierAdapter([](PropValue p, ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType) {
dmgType->m_bImpulsesFlags = p.valBool;
return true;
}),
vehDeviceDamageTypeGetterAdapter([](ATrVehicleWeapon* wep, UTrDmgType_Base* dmgType, PropValue& ret) {
ret = PropValue::fromBool(dmgType->m_bImpulsesFlags);
return true;
})
);
// Projectile
static const Property PROJECTILE_SPEED(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->Speed = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->Speed);
return true;
})
);
static const Property PROJECTILE_MAX_SPEED(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->MaxSpeed = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->MaxSpeed);
return true;
})
);
static const Property COLLISION_SIZE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->CheckRadius = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->CheckRadius);
return true;
})
);
static const Property PROJECTILE_INHERITANCE(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->m_fMaxProjInheritPct = p.valFloat;
proj->m_fProjInheritVelocityPct = p.valFloat;
proj->m_fProjInheritVelocityPctZ = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->m_fProjInheritVelocityPct);
return true;
})
);
static const Property PROJECTILE_LIFESPAN(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->LifeSpan = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->LifeSpan);
return true;
})
);
static const Property PROJECTILE_GRAVITY(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->CustomGravityScaling = p.valFloat;
if (proj->CustomGravityScaling == 0.0f) {
proj->Physics = PHYS_Projectile;
}
else {
proj->Physics = PHYS_Falling;
}
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->CustomGravityScaling);
return true;
})
);
static const Property PROJECTILE_TERMINAL_VELOCITY(
ValueType::FLOAT,
projDeviceApplierAdapter<ATrVehicleWeapon, ATrProjectile>([](PropValue p, ATrVehicleWeapon* wep, ATrProjectile* proj) {
proj->TerminalVelocity = p.valFloat;
return true;
}),
projDeviceGetterAdapter<ATrVehicleWeapon, ATrProjectile>([](ATrVehicleWeapon* wep, ATrProjectile* proj, PropValue& ret) {
ret = PropValue::fromFloat(proj->TerminalVelocity);
return true;
})
);
// Accuracy
static const Property ACCURACY(
ValueType::FLOAT,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_fDefaultAccuracy = p.valFloat;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromFloat(wep->m_fDefaultAccuracy);
return true;
})
);
static const Property ACCURACY_LOSS_ON_SHOT(
ValueType::FLOAT,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_fAccuracyLossOnShot = p.valFloat;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromFloat(wep->m_fAccuracyLossOnShot);
return true;
})
);
static const Property ACCURACY_LOSS_MAX(
ValueType::FLOAT,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_fAccuracyLossMax = p.valFloat;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromFloat(wep->m_fAccuracyLossMax);
return true;
})
);
static const Property ACCURACY_CORRECTION_RATE(
ValueType::FLOAT,
applierAdapter<ATrVehicleWeapon>([](PropValue p, ATrVehicleWeapon* wep) {
wep->m_fAccuracyCorrectionRate = p.valFloat;
return true;
}),
getterAdapter<ATrVehicleWeapon>([](ATrVehicleWeapon* wep, PropValue& ret) {
ret = PropValue::fromFloat(wep->m_fAccuracyCorrectionRate);
return true;
})
);
std::map<PropId, Property> properties = {
// Ammo
{PropId::CLIP_AMMO, CLIP_AMMO},
{PropId::SPARE_AMMO, SPARE_AMMO},
{PropId::AMMO_PER_SHOT, AMMO_PER_SHOT},
// Reload / Firing
{PropId::RELOAD_TIME, RELOAD_TIME},
{PropId::FIRE_INTERVAL, FIRE_INTERVAL},
{PropId::RELOAD_APPLICATION_PROPORTION, RELOAD_APPLICATION_PROPORTION},
{PropId::BURST_SHOT_COUNT, BURST_SHOT_COUNT},
// Damage / Impact
{PropId::DAMAGE, DAMAGE},
{PropId::EXPLOSIVE_RADIUS, EXPLOSIVE_RADIUS},
{PropId::DIRECT_HIT_MULTIPLIER, DIRECT_HIT_MULTIPLIER},
{PropId::IMPACT_MOMENTUM, IMPACT_MOMENTUM},
{PropId::ENERGY_DRAIN, ENERGY_DRAIN},
{PropId::MAX_DAMAGE_RANGE_PROPORTION, MAX_DAMAGE_RANGE_PROPORTION},
{PropId::MIN_DAMAGE_RANGE_PROPORTION, MIN_DAMAGE_RANGE_PROPORTION},
{PropId::MIN_DAMAGE_PROPORTION, MIN_DAMAGE_PROPORTION},
{PropId::BULLET_DAMAGE_RANGE, BULLET_DAMAGE_RANGE},
{PropId::DAMAGE_AGAINST_ARMOR_MULTIPLIER, DAMAGE_AGAINST_ARMOR_MULTIPLIER},
{PropId::DAMAGE_AGAINST_GENERATOR_MULTIPLIER, DAMAGE_AGAINST_GENERATOR_MULTIPLIER},
{PropId::DAMAGE_AGAINST_BASE_TURRET_MULTIPLIER, DAMAGE_AGAINST_BASE_TURRET_MULTIPLIER},
{PropId::DAMAGE_AGAINST_BASE_SENSOR_MULTIPLIER, DAMAGE_AGAINST_BASE_SENSOR_MULTIPLIER},
{PropId::DAMAGE_AGAINST_GRAVCYCLE_MULTIPLIER, DAMAGE_AGAINST_GRAVCYCLE_MULTIPLIER},
{PropId::DAMAGE_AGAINST_BEOWULF_MULTIPLIER, DAMAGE_AGAINST_BEOWULF_MULTIPLIER},
{PropId::DAMAGE_AGAINST_SHRIKE_MULTIPLIER, DAMAGE_AGAINST_SHRIKE_MULTIPLIER},
{PropId::DOES_GIB_ON_KILL, DOES_GIB_ON_KILL},
{PropId::GIB_IMPULSE_RADIUS, GIB_IMPULSE_RADIUS},
{PropId::GIB_STRENGTH, GIB_STRENGTH},
{PropId::DOES_IMPULSE_FLAG, DOES_IMPULSE_FLAG},
// Projectile
{PropId::PROJECTILE_SPEED, PROJECTILE_SPEED},
{PropId::PROJECTILE_MAX_SPEED, PROJECTILE_MAX_SPEED},
{PropId::COLLISION_SIZE, COLLISION_SIZE},
{PropId::PROJECTILE_INHERITANCE, PROJECTILE_INHERITANCE},
{PropId::PROJECTILE_LIFESPAN, PROJECTILE_LIFESPAN},
{PropId::PROJECTILE_GRAVITY, PROJECTILE_GRAVITY},
{PropId::PROJECTILE_TERMINAL_VELOCITY, PROJECTILE_TERMINAL_VELOCITY},
// Accuracy
{PropId::ACCURACY, ACCURACY},
{PropId::ACCURACY_LOSS_ON_SHOT, ACCURACY_LOSS_ON_SHOT},
{PropId::ACCURACY_LOSS_MAX, ACCURACY_LOSS_MAX},
{PropId::ACCURACY_CORRECTION_RATE, ACCURACY_CORRECTION_RATE},
};
}
} | 46.798719 | 170 | 0.582414 | [
"object"
] |
61c23f3f5bf1613c8db1d7ba77eb971c38629106 | 9,907 | cpp | C++ | mcrouter/routes/McRouteHandleProvider.cpp | hrjaco/mcrouter | 5a7b852a1ea2f3c645e0b8366c0549bc992870af | [
"BSD-3-Clause"
] | null | null | null | mcrouter/routes/McRouteHandleProvider.cpp | hrjaco/mcrouter | 5a7b852a1ea2f3c645e0b8366c0549bc992870af | [
"BSD-3-Clause"
] | null | null | null | mcrouter/routes/McRouteHandleProvider.cpp | hrjaco/mcrouter | 5a7b852a1ea2f3c645e0b8366c0549bc992870af | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "McRouteHandleProvider.h"
#include "folly/Range.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/PoolFactoryIf.h"
#include "mcrouter/ProxyClientCommon.h"
#include "mcrouter/ProxyDestinationMap.h"
#include "mcrouter/async.h"
#include "mcrouter/config.h"
#include "mcrouter/proxy.h"
#include "mcrouter/routes/ExtraRouteHandleProviderIf.h"
#include "mcrouter/routes/RateLimiter.h"
#include "mcrouter/routes/ShadowRouteIf.h"
#include "mcrouter/routes/ShardHashFunc.h"
namespace facebook { namespace memcache { namespace mcrouter {
typedef std::function<void(proxy_request_t*,
std::shared_ptr<const ProxyClientCommon>,
const mc_msg_t*,
folly::StringPiece poolName)> AsynclogFunc;
McrouterRouteHandlePtr makeAsynclogRoute(McrouterRouteHandlePtr rh,
std::string poolName,
AsynclogFunc asyncLog);
McrouterRouteHandlePtr makeDestinationRoute(
std::shared_ptr<const ProxyClientCommon> client,
std::shared_ptr<ProxyDestination> destination);
McrouterRouteHandlePtr makeDevNullRoute(const char* name);
McrouterRouteHandlePtr makeFailoverWithExptimeRoute(
RouteHandleFactory<McrouterRouteHandleIf>& factory,
const folly::dynamic& json);
McrouterRouteHandlePtr makeMigrateRoute(
RouteHandleFactory<McrouterRouteHandleIf>& factory,
const folly::dynamic& json);
McrouterRouteHandlePtr makePrefixPolicyRoute(
RouteHandleFactory<McrouterRouteHandleIf>& factory,
const folly::dynamic& json);
McrouterRouteHandlePtr makeRateLimitRoute(
McrouterRouteHandlePtr normalRoute,
RateLimiter rateLimiter);
McrouterRouteHandlePtr makeWarmUpRoute(
RouteHandleFactory<McrouterRouteHandleIf>& factory,
const folly::dynamic& json,
uint32_t exptime);
McRouteHandleProvider::McRouteHandleProvider(
proxy_t* proxy,
ProxyDestinationMap& destinationMap,
PoolFactoryIf& poolFactory)
: RouteHandleProvider<McrouterRouteHandleIf>(),
proxy_(proxy),
destinationMap_(destinationMap),
poolFactory_(poolFactory),
extraProvider_(createExtraRouteHandleProvider()) {
}
McRouteHandleProvider::~McRouteHandleProvider() {
/* Needed for forward declaration of ExtraRouteHandleProviderIf in .h */
}
McrouterRouteHandlePtr McRouteHandleProvider::getPoolHandle(
const std::string& poolName) const {
return tryGet(poolNameToHandles_, poolName, nullptr);
}
McrouterRouteHandlePtr McRouteHandleProvider::makeDestinationHandle(
std::shared_ptr<const ProxyClientCommon> client) {
assert(client);
auto pdstn = destinationMap_.fetch(*client);
auto route = makeDestinationRoute(client, std::move(pdstn));
return destinationHandles_[std::move(client)] = std::move(route);
}
std::vector<McrouterRouteHandlePtr>
McRouteHandleProvider::getDestinationHandlesForPool(
std::shared_ptr<const ProxyPool> pool) {
assert(pool);
std::vector<McrouterRouteHandlePtr> destinations;
for (auto& client : pool->clients) {
auto poolClient = client.lock();
auto it = destinationHandles_.find(poolClient);
auto destination = (it == destinationHandles_.end())
? makeDestinationHandle(poolClient)
: it->second;
destinations.push_back(destination);
}
return destinations;
}
std::vector<McrouterRouteHandlePtr>
McRouteHandleProvider::makePool(const folly::dynamic& json) {
checkLogic(json.isString(), "Pool should be a string (name of pool)");
auto pool = poolFactory_.fetchPool(json.asString());
checkLogic(pool != nullptr, "Pool not found: {}", json.asString());
auto proxyPool = std::dynamic_pointer_cast<ProxyPool>(pool);
checkLogic(proxyPool != nullptr, "Only regional/regular pools are supported");
auto existingIt = poolHandles_.find(proxyPool);
if (existingIt != poolHandles_.end()) {
return existingIt->second;
}
return poolHandles_[proxyPool] = getDestinationHandlesForPool(proxyPool);
}
McrouterRouteHandlePtr McRouteHandleProvider::makePoolRoute(
RouteHandleFactory<McrouterRouteHandleIf>& factory,
const folly::dynamic& json) {
checkLogic(json.isObject() || json.isString(),
"PoolRoute should be object or string");
std::string poolName;
std::shared_ptr<ProxyGenericPool> pool;
if (json.isObject()) {
checkLogic(json.count("pool"), "PoolRoute: no pool");
const auto& jPool = json["pool"];
if (jPool.isString()) {
poolName = jPool.asString().toStdString();
pool = poolFactory_.fetchPool(poolName);
} else {
checkLogic(jPool.count("name") && jPool["name"].isString(),
"PoolRoute: no/invalid pool name");
poolName = jPool["name"].asString().toStdString();
pool = poolFactory_.fetchPool(poolName);
if (!pool) {
pool = poolFactory_.parsePool(poolName, jPool, {});
}
}
} else {
poolName = json.asString().toStdString();
pool = poolFactory_.fetchPool(poolName);
}
checkLogic(pool != nullptr, "Pool not found: {}", poolName);
auto proxyPool = std::dynamic_pointer_cast<ProxyPool>(pool);
checkLogic(proxyPool != nullptr, "Only regional/regular pools are supported");
std::vector<McrouterRouteHandlePtr> destinations;
auto existingIt = poolHandles_.find(proxyPool);
if (existingIt != poolHandles_.end()) {
destinations = existingIt->second;
} else {
destinations = getDestinationHandlesForPool(proxyPool);
poolHandles_[proxyPool] = destinations;
}
if (json.isObject() && json.count("shadows")) {
std::string shadowPolicy = "default";
if (json.count("shadow_policy")) {
checkLogic(json["shadow_policy"].isString(),
"PoolRoute: shadow_policy is not string");
shadowPolicy = json["shadow_policy"].asString().toStdString();
}
McrouterShadowData data;
for (auto& shadow : json["shadows"]) {
checkLogic(shadow.count("target"),
"PoolRoute shadows: no target for shadow");
auto policy = std::make_shared<proxy_pool_shadowing_policy_t>(
shadow, proxy_->router);
data.emplace_back(factory.create(shadow["target"]), std::move(policy));
}
for (size_t i = 0; i < destinations.size(); ++i) {
destinations[i] = extraProvider_->makeShadow(
proxy_, destinations[i], data, i, shadowPolicy);
}
}
McrouterRouteHandlePtr route;
if (json.isObject() && json.count("hash")) {
if (json["hash"].isString()) {
route = makeHash(folly::dynamic::object("hash_func", json["hash"]),
std::move(destinations));
} else {
route = makeHash(json["hash"], std::move(destinations));
}
} else {
route = makeHash(folly::dynamic::object(), std::move(destinations));
}
if (proxy_->opts.destination_rate_limiting) {
if (json.isObject() &&
json.count("rates") &&
json["rates"].isObject()) {
route = makeRateLimitRoute(std::move(route), RateLimiter(json["rates"]));
} else if (proxyPool->rate_limiter) {
route = makeRateLimitRoute(std::move(route), *proxyPool->rate_limiter);
}
}
if (!proxy_->opts.asynclog_disable) {
bool needAsynclog = !proxyPool->devnull_asynclog;
if (json.isObject() && json.count("asynclog")) {
checkLogic(json["asynclog"].isBool(), "PoolRoute: asynclog is not bool");
needAsynclog = json["asynclog"].asBool();
}
if (needAsynclog) {
route = makeAsynclogRoute(std::move(route), proxyPool->getName(),
&asynclog_command);
}
}
// NOTE: we assume PoolRoute is unique for each ProxyPool.
// Once we have multiple PoolRoutes for same ProxyPool
// we need to change logic here.
poolNameToHandles_.emplace(proxyPool->getName(), route);
return route;
}
std::vector<McrouterRouteHandlePtr> McRouteHandleProvider::create(
RouteHandleFactory<McrouterRouteHandleIf>& factory,
const std::string& type,
const folly::dynamic& json) {
if (type == "PrefixPolicyRoute") {
return { makePrefixPolicyRoute(factory, json) };
} else if (type == "DevNullRoute") {
return { makeDevNullRoute("devnull") };
} else if (type == "FailoverWithExptimeRoute") {
return { makeFailoverWithExptimeRoute(factory, json) };
} else if (type == "WarmUpRoute") {
return { makeWarmUpRoute(factory, json,
proxy_->opts.upgrading_l1_exptime) };
} else if (type == "MigrateRoute") {
return { makeMigrateRoute(factory, json) };
} else if (type == "Pool") {
return makePool(json);
} else if (type == "PoolRoute") {
return { makePoolRoute(factory, json) };
}
auto ret = RouteHandleProvider<McrouterRouteHandleIf>::create(factory, type,
json);
checkLogic(!ret.empty(), "Unknown RouteHandle: {}", type);
return ret;
}
McrouterRouteHandlePtr McRouteHandleProvider::createHash(
const std::string& funcType,
const folly::dynamic& json,
std::vector<McrouterRouteHandlePtr> children) {
if (funcType == ConstShardHashFunc::type()) {
return makeRouteHandle<McrouterRouteHandleIf, HashRoute,
ConstShardHashFunc>(
json, std::move(children));
}
if (funcType == ShardHashFunc::type()) {
return makeRouteHandle<McrouterRouteHandleIf, HashRoute, ShardHashFunc>(
json, std::move(children));
}
auto ret = RouteHandleProvider<McrouterRouteHandleIf>::createHash(
funcType, json, std::move(children));
checkLogic(ret != nullptr, "Unknown hash function: {}", funcType);
return ret;
}
}}} // facebook::memcache::mcrouter
| 35.131206 | 80 | 0.689714 | [
"object",
"vector"
] |
61c3d0e43f05efbfb03eeb465b74e644bdc20d89 | 9,631 | hpp | C++ | headers/enduro2d/high/_high.hpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | null | null | null | headers/enduro2d/high/_high.hpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | null | null | null | headers/enduro2d/high/_high.hpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | null | null | null | /*******************************************************************************
* This file is part of the "Enduro2D"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#pragma once
#include "../core/_all.hpp"
#include <ecs.hpp/ecs.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <3rdparty/sol/sol.hpp>
namespace e2d
{
namespace ecs
{
using namespace ecs_hpp;
}
}
namespace e2d
{
class atlas_asset;
class binary_asset;
class flipbook_asset;
class font_asset;
class image_asset;
class json_asset;
class material_asset;
class mesh_asset;
class model_asset;
class prefab_asset;
class script_asset;
class shader_asset;
class shape_asset;
class sound_asset;
class spine_asset;
class sprite_asset;
class text_asset;
class texture_asset;
class xml_asset;
class actor;
class behaviour;
class camera;
class rect_collider;
class circle_collider;
class polygon_collider;
template < typename C >
class commands;
template < typename T >
class disabled;
template < typename E >
class events;
class flipbook_player;
class label;
class layout;
class model_renderer;
class named;
class renderer;
class scene;
class spine_player;
class sprite_renderer;
class touchable;
class widget;
class atlas;
class flipbook;
class model;
class prefab;
class script;
class spine;
class sprite;
class camera_system;
class flipbook_system;
class frame_system;
class gizmos_system;
class label_system;
class layout_system;
class render_system;
class script_system;
class spine_system;
class touch_system;
class world_system;
template < typename Asset, typename Content >
class content_asset;
class asset;
class factory;
class library;
class asset_store;
class asset_group;
class asset_dependencies;
class editor;
class inspector;
class luasol;
class starter;
class world;
class node;
class gobject;
template < typename T >
class gcomponent;
template < typename T >
class const_gcomponent;
}
namespace sol
{
template < typename T >
struct unique_usertype_traits<e2d::intrusive_ptr<T>> {
using type = T;
using actual_type = e2d::intrusive_ptr<T>;
static const bool value = true;
static bool is_null(const actual_type& ptr) {
return !ptr;
}
static type* get(actual_type& ptr) {
return ptr.get();
}
};
}
namespace e2d::ecsex
{
template < typename T, typename Disposer, typename... Opts >
void remove_all_components_with_disposer(
ecs::registry& owner,
Disposer&& disposer,
Opts&&... opts)
{
static thread_local vector<ecs::entity> to_remove_components;
E2D_DEFER([](){ to_remove_components.clear(); });
owner.for_each_component<T>([](const ecs::entity& e, const T&){
to_remove_components.push_back(e);
}, std::forward<Opts>(opts)...);
for ( ecs::entity& e : to_remove_components ) {
std::invoke(disposer, e, e.get_component<T>());
e.remove_component<T>();
}
}
template < typename T, typename... Opts >
void remove_all_components(ecs::registry& owner, Opts&&... opts) {
remove_all_components_with_disposer<T>(
owner,
null_disposer(),
std::forward<Opts>(opts)...);
}
}
namespace e2d::ecsex
{
template < typename... Ts, typename Iter, typename... Opts >
std::size_t extract_components(ecs::registry& owner, Iter iter, Opts&&... opts) {
std::size_t count{0u};
owner.for_joined_components<Ts...>(
[&iter, &count](const ecs::entity& e, Ts&... cs){
iter++ = std::make_tuple(e, cs...);
++count;
}, std::forward<Opts>(opts)...);
return count;
}
template < typename... Ts, typename Iter, typename... Opts >
std::size_t extract_components(const ecs::registry& owner, Iter iter, Opts&&... opts) {
std::size_t count{0u};
owner.for_joined_components<Ts...>(
[&iter, &count](const ecs::const_entity& e, const Ts&... cs){
iter++ = std::make_tuple(e, cs...);
++count;
}, std::forward<Opts>(opts)...);
return count;
}
}
namespace e2d::ecsex
{
template < typename... Ts, typename F, typename... Opts >
void for_extracted_components(ecs::registry& owner, F&& f, Opts&&... opts) {
//TODO(BlackMat): replace it to frame allocator
static thread_local vector<
std::tuple<ecs::entity, Ts...>> components;
const std::size_t begin_index = components.size();
E2D_DEFER([begin_index](){
components.erase(
components.begin() + begin_index,
components.end());
});
extract_components<Ts...>(
owner,
std::back_inserter(components),
std::forward<Opts>(opts)...);
const std::size_t end_index = components.size();
for ( std::size_t i = begin_index; i < end_index; ++i ) {
std::apply(f, components[i]);
}
}
template < typename... Ts, typename F, typename... Opts >
void for_extracted_components(const ecs::registry& owner, F&& f, Opts&&... opts) {
//TODO(BlackMat): replace it to frame allocator
static thread_local vector<
std::tuple<ecs::const_entity, Ts...>> components;
const std::size_t begin_index = components.size();
E2D_DEFER([begin_index](){
components.erase(
components.begin() + begin_index,
components.end());
});
extract_components<Ts...>(
owner,
std::back_inserter(components),
std::forward<Opts>(opts)...);
const std::size_t end_index = components.size();
for ( std::size_t i = begin_index; i < end_index; ++i ) {
std::apply(f, components[i]);
}
}
}
namespace e2d::ecsex
{
template < typename... Ts, typename Comp, typename F, typename... Opts >
void for_extracted_sorted_components(ecs::registry& owner, Comp&& comp, F&& f, Opts&&... opts) {
//TODO(BlackMat): replace it to frame allocator
static thread_local vector<
std::tuple<ecs::entity, Ts...>> components;
const std::size_t begin_index = components.size();
E2D_DEFER([begin_index](){
components.erase(
components.begin() + begin_index,
components.end());
});
extract_components<Ts...>(
owner,
std::back_inserter(components),
std::forward<Opts>(opts)...);
std::sort(
components.begin() + begin_index,
components.end(),
comp);
const std::size_t end_index = components.size();
for ( std::size_t i = begin_index; i < end_index; ++i ) {
std::apply(f, components[i]);
}
}
template < typename... Ts, typename Comp, typename F, typename... Opts >
void for_extracted_sorted_components(const ecs::registry& owner, Comp&& comp, F&& f, Opts&&... opts) {
//TODO(BlackMat): replace it to frame allocator
static thread_local vector<
std::tuple<ecs::const_entity, Ts...>> components;
const std::size_t begin_index = components.size();
E2D_DEFER([begin_index](){
components.erase(
components.begin() + begin_index,
components.end());
});
extract_components<Ts...>(
owner,
std::back_inserter(components),
std::forward<Opts>(opts)...);
std::sort(
components.begin() + begin_index,
components.end(),
comp);
const std::size_t end_index = components.size();
for ( std::size_t i = begin_index; i < end_index; ++i ) {
std::apply(f, components[i]);
}
}
}
namespace e2d::strings
{
template <>
class format_arg<ecs::entity> {
ecs::entity value_;
u8 width_;
public:
template < typename U >
explicit format_arg(U&& value, u8 width = 0) noexcept
: value_(std::forward<U>(value)), width_(width) {}
std::ptrdiff_t write(char* dst, size_t size) const {
return math::numeric_cast<std::ptrdiff_t>(
format(dst, size, "(%0,%1)",
make_format_arg(ecs::detail::entity_id_index(value_.id()), width_),
make_format_arg(ecs::detail::entity_id_version(value_.id()), width_)));
}
};
template <>
class format_arg<ecs::const_entity> {
ecs::const_entity value_;
u8 width_;
public:
template < typename U >
explicit format_arg(U&& value, u8 width = 0) noexcept
: value_(std::forward<U>(value)), width_(width) {}
std::ptrdiff_t write(char* dst, size_t size) const {
return math::numeric_cast<std::ptrdiff_t>(
format(dst, size, "(%0,%1)",
make_format_arg(ecs::detail::entity_id_index(value_.id()), width_),
make_format_arg(ecs::detail::entity_id_version(value_.id()), width_)));
}
};
}
| 28.749254 | 106 | 0.574811 | [
"vector",
"model"
] |
61c666e144e91851428603a3b3cc731870688af3 | 4,750 | cpp | C++ | src/components/StoryInformation.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 399 | 2019-01-06T17:55:18.000Z | 2022-03-21T17:41:18.000Z | src/components/StoryInformation.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 101 | 2019-04-18T21:03:53.000Z | 2022-01-08T13:27:01.000Z | src/components/StoryInformation.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 56 | 2019-04-10T10:18:27.000Z | 2022-02-08T01:23:31.000Z | #include "StoryInformation.hpp"
#include <RTTI/RTTI_StoryInformation.hpp>
#include <components/Character.hpp>
#include <components/GameWorld.hpp>
#include <exception/Throw.hpp>
#include <log/logging.hpp>
#include <scripting/ScriptSymbolQueries.hpp>
#include <scripting/ScriptVMForGameWorld.hpp>
// TODO: Refactor, so we don't access deep into the UI code here for dialogues
#include <components/GameplayUI.hpp>
#include <components/UIDialogueChoice.hpp>
namespace REGoth
{
StoryInformation::StoryInformation(const bs::HSceneObject& parent, HGameWorld gameWorld,
HCharacter self)
: bs::Component(parent)
, mGameWorld(gameWorld)
, mSelf(self)
{
setName("StoryInformation");
}
StoryInformation::~StoryInformation()
{
}
void StoryInformation::onInitialized()
{
if (mAllInfos.empty())
{
findAllInfos();
}
}
void StoryInformation::findAllInfos()
{
auto& objectStorage = mGameWorld->scriptVM().scriptObjects();
auto& symbolStorage = mGameWorld->scriptVM().scriptSymbols();
for (Scripting::ScriptObjectHandle h : mSelf->allInfosForThisCharacter())
{
auto& data = objectStorage.get(h);
DialogueInfo info;
info.name = data.instanceName;
info.priority = data.intValue("NR");
info.isPermanent = data.intValue("PERMANENT") != 0;
info.isImportant = data.intValue("IMPORTANT") != 0;
info.isTrade = data.intValue("TRADE") != 0;
info.choiceText = data.stringValue("DESCRIPTION");
info.conditionFunction =
symbolStorage.findFunctionByAddress(data.functionPointerValue("CONDITION"));
info.informationFunction =
symbolStorage.findFunctionByAddress(data.functionPointerValue("INFORMATION"));
bs::UINT32 index = mAllInfos.size();
mAllInfos.emplace_back(info);
}
}
bs::Vector<const StoryInformation::DialogueInfo*> StoryInformation::gatherAvailableDialogueLines(
HCharacter other) const
{
HStoryInformation otherInfo = other->SO()->getComponent<StoryInformation>();
bs::Vector<const StoryInformation::DialogueInfo*> result;
for (bs::UINT32 i = 0; i < (bs::UINT32)mAllInfos.size(); i++)
{
if (isDialogueInfoAvaliable(i, other, otherInfo))
{
result.push_back(&mAllInfos[i]);
}
}
return result;
}
bool StoryInformation::isDialogueInfoAvaliable(bs::UINT32 index, HCharacter other,
HStoryInformation otherInfo) const
{
const auto& info = mAllInfos[index];
if (!info.isPermanent && otherInfo->knowsInfo(info.name))
{
return false;
}
return mGameWorld->scriptVM().runInfoConditionFunction(info.conditionFunction, mSelf, other);
}
bool StoryInformation::knowsInfo(const bs::String& name) const
{
return mKnownInfos.find(name) != mKnownInfos.end();
}
void StoryInformation::giveKnowledgeAboutInfo(const bs::String& name)
{
mKnownInfos.insert(name);
}
void StoryInformation::startDialogueWith(HCharacter other)
{
gGameplayUI()->startDialogue();
for (auto info : gatherAvailableDialogueLines(other))
{
addChoice(info->name, info->choiceText, info->informationFunction);
}
gGameplayUI()->choices()->setOnChoiceCallback([this, other](UIDialogueChoice::Choice choice) {
REGOTH_LOG(Info, Uncategorized, "[StoryInformation] Choice taken: {0} ({1})", choice.text,
choice.instanceName);
if (!choice.instanceName.empty())
{
HStoryInformation otherInfo = other->SO()->getComponent<StoryInformation>();
otherInfo->giveKnowledgeAboutInfo(choice.instanceName);
}
// Re-fill the choices window before executing the script because it may call
// `Info_ClearChoices` to supply some custom choices.
clearChoices();
for (auto info : gatherAvailableDialogueLines(other))
{
addChoice(info->name, info->choiceText, info->informationFunction);
}
mGameWorld->scriptVM().runInfoFunction(choice.scriptFunction, mSelf, other);
});
}
void StoryInformation::stopDialogueWith(HCharacter other)
{
gGameplayUI()->stopDialogue();
}
void StoryInformation::addChoice(const bs::String& instanceName, const bs::String& text,
Scripting::SymbolIndex infoFunction)
{
UIDialogueChoice::Choice c;
c.instanceName = instanceName;
c.text = text;
c.scriptFunction = infoFunction;
gGameplayUI()->choices()->addChoice(c);
}
void StoryInformation::clearChoices()
{
gGameplayUI()->choices()->clearChoices();
}
REGOTH_DEFINE_RTTI(StoryInformation)
} // namespace REGoth
| 29.141104 | 99 | 0.670737 | [
"vector"
] |
61cee999597b336c99ed7fbb0c63119af87c814b | 6,339 | cc | C++ | dali/kernels/signal/window/extract_windows_cpu_test.cc | ancientmooner/DALI | 355e8db8130cee0d20e9ae3d698f195278544995 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2021-03-16T05:09:16.000Z | 2022-03-29T12:48:44.000Z | dali/kernels/signal/window/extract_windows_cpu_test.cc | MAKali4737/DALI | 3b114c6ebee38ff3815a9b4a234402e4d1affaa0 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dali/kernels/signal/window/extract_windows_cpu_test.cc | MAKali4737/DALI | 3b114c6ebee38ff3815a9b4a234402e4d1affaa0 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2021-05-08T16:51:55.000Z | 2021-07-22T09:02:44.000Z | // Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <tuple>
#include <vector>
#include <complex>
#include <cmath>
#include "dali/kernels/scratch.h"
#include "dali/kernels/signal/window/extract_windows_cpu.h"
#include "dali/kernels/signal/window/window_functions.h"
#include "dali/kernels/common/utils.h"
#include "dali/test/test_tensors.h"
#include "dali/test/tensor_test_utils.h"
namespace dali {
namespace kernels {
namespace signal {
namespace window {
namespace test {
class ExtractWindowsCpuTest : public::testing::TestWithParam<
std::tuple<std::array<int64_t, 2>, int64_t, int64_t, int64_t, int64_t, Padding>> {
public:
ExtractWindowsCpuTest()
: data_shape_(std::get<0>(GetParam()))
, window_length_(std::get<1>(GetParam()))
, window_step_(std::get<2>(GetParam()))
, axis_(std::get<3>(GetParam()))
, window_center_(std::get<4>(GetParam()))
, padding_(std::get<5>(GetParam()))
, data_(volume(data_shape_))
, in_view_(data_.data(), data_shape_) {}
~ExtractWindowsCpuTest() override = default;
protected:
void SetUp() final {
SequentialFill(in_view_, 0);
}
TensorShape<2> data_shape_;
int window_length_ = -1, window_step_ = -1, axis_ = -1, window_center_ = -1;
Padding padding_ = Padding::Zero;
std::vector<float> data_;
OutTensorCPU<float, 2> in_view_;
};
template <typename T>
void print_data(const OutTensorCPU<T, 2>& data_view) {
auto sh = data_view.shape;
for (int i0 = 0; i0 < sh[0]; i0++) {
for (int i1 = 0; i1 < sh[1]; i1++) {
int k = i0 * sh[1] + i1;
LOG_LINE << " " << data_view.data[k];
}
LOG_LINE << "\n";
}
}
template <typename T>
void print_data(const OutTensorCPU<T, 3>& data_view) {
auto sh = data_view.shape;
for (int i0 = 0; i0 < sh[0]; i0++) {
for (int i1 = 0; i1 < sh[1]; i1++) {
for (int i2 = 0; i2 < sh[2]; i2++) {
int k = i0 * sh[1] * sh[2] + i1 * sh[2] + i2;
LOG_LINE << " " << data_view.data[k];
}
LOG_LINE << "\n";
}
LOG_LINE << "\n";
}
LOG_LINE << "\n";
}
TEST_P(ExtractWindowsCpuTest, ExtractWindowsTest) {
using OutputType = float;
using InputType = float;
constexpr int Dims = 2;
constexpr int InputDims = Dims;
constexpr int OutputDims = Dims + 1;
ExtractWindowsCpu<OutputType, InputType, Dims> kernel;
check_kernel<decltype(kernel)>();
KernelContext ctx;
ExtractWindowsArgs args;
args.window_length = window_length_;
args.window_step = window_step_;
args.axis = axis_;
args.window_center = window_center_;
args.padding = padding_;
// Hamming window
std::vector<float> window_fn_data(window_length_);
HammingWindow(make_span(window_fn_data));
auto window_fn_view = OutTensorCPU<float, 1>(window_fn_data.data(), {1});
KernelRequirements reqs = kernel.Setup(ctx, in_view_, window_fn_view, args);
auto out_shape = reqs.output_shapes[0][0];
auto n = in_view_.shape[axis_];
auto nwindows = padding_ == Padding::None
? (n - window_length_) / window_step_ + 1
: n / window_step_ + 1;
auto expected_out_shape = TensorShape<DynamicDimensions>{
in_view_.shape[0], window_length_, nwindows};
ASSERT_EQ(expected_out_shape, out_shape);
auto expected_out_size = volume(expected_out_shape);
auto out_size = volume(out_shape);
ASSERT_EQ(expected_out_size, out_size);
std::vector<OutputType> expected_out(out_size);
auto expected_out_view = OutTensorCPU<OutputType, OutputDims>(
expected_out.data(), out_shape.to_static<OutputDims>());
TensorShape<> in_shape = in_view_.shape;
TensorShape<> in_strides = GetStrides(in_shape);
TensorShape<> flat_out_shape = in_shape;
flat_out_shape[InputDims-1] = nwindows * window_length_;
TensorShape<> out_strides = GetStrides(flat_out_shape);
auto in_stride = in_strides[axis_];
auto out_stride = out_strides[axis_];
int window_center_offset = 0;
if (padding_ != Padding::None)
window_center_offset = window_center_ < 0 ? window_length_ / 2 : window_center_;
for (int i = 0; i < in_view_.shape[0]; i++) {
auto *out_slice = expected_out_view.data + i * out_strides[0];
auto *in_slice = in_view_.data + i * in_strides[0];
for (int w = 0; w < nwindows; w++) {
for (int t = 0; t < window_length_; t++) {
auto out_k = w + t * nwindows;
auto in_k = w * window_step_ + t - window_center_offset;
if (padding_ == Padding::Reflect) {
while (in_k < 0 || in_k >= n) {
in_k = (in_k < 0) ? -in_k : 2*n-2-in_k;
}
}
out_slice[out_k] = (in_k >= 0 && in_k < n) ?
window_fn_data[t] * in_slice[in_k] : 0;
}
}
}
LOG_LINE << "in:\n";
print_data(in_view_);
LOG_LINE << "expected out:\n";
print_data(expected_out_view);
std::vector<OutputType> out(out_size);
auto out_view = OutTensorCPU<OutputType, OutputDims>(
out.data(), out_shape.to_static<OutputDims>());
kernel.Run(ctx, out_view, in_view_, window_fn_view, args);
LOG_LINE << "out:\n";
print_data(out_view);
for (int idx = 0; idx < volume(out_view.shape); idx++) {
ASSERT_EQ(expected_out[idx], out_view.data[idx]) <<
"Output data doesn't match reference (idx=" << idx << ")";
}
}
INSTANTIATE_TEST_SUITE_P(ExtractWindowsCpuTest, ExtractWindowsCpuTest, testing::Combine(
testing::Values(std::array<int64_t, 2>{1, 12},
std::array<int64_t, 2>{2, 12}),
testing::Values(4), // window_length
testing::Values(2), // step
testing::Values(1), // axis
testing::Values(0, 2, 4), // window offsets
testing::Values(Padding::None, Padding::Zero, Padding::Reflect))); // reflect padding
} // namespace test
} // namespace window
} // namespace signal
} // namespace kernels
} // namespace dali
| 32.675258 | 90 | 0.667929 | [
"shape",
"vector"
] |
61d1ed41c8437fed34bcf8c785e439594e6771f5 | 77 | hpp | C++ | include/lava/sill/frame-components.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 15 | 2018-02-26T08:20:03.000Z | 2022-03-06T03:25:46.000Z | include/lava/sill/frame-components.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 32 | 2018-02-26T08:26:38.000Z | 2020-09-12T17:09:38.000Z | include/lava/sill/frame-components.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | null | null | null | #pragma once
#include <lava/sill/frame-components/mesh-frame-component.hpp>
| 19.25 | 62 | 0.792208 | [
"mesh"
] |
61d2118ff79ea065f2f95160e947c94929ae7a9e | 17,029 | cpp | C++ | examples/38-bloom/bloom.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | 1 | 2022-02-22T09:26:13.000Z | 2022-02-22T09:26:13.000Z | examples/38-bloom/bloom.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | null | null | null | examples/38-bloom/bloom.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2018 Eric Arnebäck. All rights reserved.
* License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
*/
/*
* Reference(s):
* - Next Generation Post Processing in Call of Duty: Advanced Warfare
* https://web.archive.org/web/20180920045230/http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
*/
#include "common.h"
#include "bgfx_utils.h"
#include "imgui/imgui.h"
#include "camera.h"
namespace
{
// pass that render the geometry of the boxes.
#define RENDER_PASS_GEOMETRY_ID 0
// the first downsample pass.
#define RENDER_PASS_DOWNSAMPLE0_ID 1
// the first upsample pass.
#define RENDER_PASS_UPSAMPLE0_ID ( (TEX_CHAIN_LEN-1) + 1)
// the final pass the combines the bloom with the g-buffer.
#define RENDER_PASS_COMBINE_ID ( (TEX_CHAIN_LEN-1) + 1 + (TEX_CHAIN_LEN-1) )
// number of downsampled and then upsampled textures(used for bloom.)
#define TEX_CHAIN_LEN 5
static float s_texelHalf = 0.0f;
struct PosVertex
{
float m_x;
float m_y;
float m_z;
static void init()
{
ms_layout
.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.end();
}
static bgfx::VertexLayout ms_layout;
};
bgfx::VertexLayout PosVertex::ms_layout;
struct PosTexCoord0Vertex
{
float m_x;
float m_y;
float m_z;
float m_u;
float m_v;
static void init()
{
ms_layout
.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
.end();
}
static bgfx::VertexLayout ms_layout;
};
bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
constexpr float cs = 0.29f;
static PosVertex s_cubeVertices[24] =
{
{-cs, cs, cs },
{ cs, cs, cs },
{-cs, -cs, cs },
{ cs, -cs, cs },
{-cs, cs, -cs },
{ cs, cs, -cs },
{-cs, -cs, -cs },
{ cs, -cs, -cs },
{-cs, cs, cs },
{ cs, cs, cs },
{-cs, cs, -cs },
{ cs, cs, -cs },
{-cs, -cs, cs },
{ cs, -cs, cs },
{-cs, -cs, -cs },
{ cs, -cs, -cs },
{ cs, -cs, cs },
{ cs, cs, cs },
{ cs, -cs, -cs },
{ cs, cs, -cs },
{-cs, -cs, cs },
{-cs, cs, cs },
{-cs, -cs, -cs },
{-cs, cs, -cs },
};
static const uint16_t s_cubeIndices[36] =
{
0, 2, 1,
1, 2, 3,
4, 5, 6,
5, 7, 6,
8, 10, 9,
9, 10, 11,
12, 13, 14,
13, 15, 14,
16, 18, 17,
17, 18, 19,
20, 21, 22,
21, 23, 22,
};
void screenSpaceQuad(float _textureWidth, float _textureHeight, float _texelHalf, bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
{
if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout) )
{
bgfx::TransientVertexBuffer vb;
bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
const float minx = -_width;
const float maxx = _width;
const float miny = 0.0f;
const float maxy = _height*2.0f;
const float texelHalfW = _texelHalf/_textureWidth;
const float texelHalfH = _texelHalf/_textureHeight;
const float minu = -1.0f + texelHalfW;
const float maxu = 1.0f + texelHalfH;
const float zz = 0.0f;
float minv = texelHalfH;
float maxv = 2.0f + texelHalfH;
if (_originBottomLeft)
{
float temp = minv;
minv = maxv;
maxv = temp;
minv -= 1.0f;
maxv -= 1.0f;
}
vertex[0].m_x = minx;
vertex[0].m_y = miny;
vertex[0].m_z = zz;
vertex[0].m_u = minu;
vertex[0].m_v = minv;
vertex[1].m_x = maxx;
vertex[1].m_y = miny;
vertex[1].m_z = zz;
vertex[1].m_u = maxu;
vertex[1].m_v = minv;
vertex[2].m_x = maxx;
vertex[2].m_y = maxy;
vertex[2].m_z = zz;
vertex[2].m_u = maxu;
vertex[2].m_v = maxv;
bgfx::setVertexBuffer(0, &vb);
}
}
class ExampleBloom : public entry::AppI
{
public:
ExampleBloom(const char* _name, const char* _description, const char* _url)
: entry::AppI(_name, _description, _url)
{
}
void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
{
Args args(_argc, _argv);
m_width = _width;
m_height = _height;
m_debug = BGFX_DEBUG_TEXT;
m_reset = BGFX_RESET_VSYNC;
bgfx::Init init;
init.type = args.m_type;
init.vendorId = args.m_pciId;
init.resolution.width = m_width;
init.resolution.height = m_height;
init.resolution.reset = m_reset;
bgfx::init(init);
// Enable m_debug text.
bgfx::setDebug(m_debug);
// Set palette color for index 0
bgfx::setPaletteColor(0, UINT32_C(0x00000000) );
// Set geometry pass view clear state.
bgfx::setViewClear(RENDER_PASS_GEOMETRY_ID
, BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
, 1.0f
, 0
, 0
, 0
);
// we need to clear the textures in the chain, before downsampling into them.
for (uint16_t ii = 0; ii < TEX_CHAIN_LEN-1; ++ii)
{
bgfx::setViewClear(RENDER_PASS_DOWNSAMPLE0_ID + ii
, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
, 1.0f
, 0
, 0
);
}
// Create vertex stream declaration.
PosVertex::init();
PosTexCoord0Vertex::init();
// Create static vertex buffer.
m_vbh = bgfx::createVertexBuffer(
bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
, PosVertex::ms_layout
);
m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );
s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Sampler);
s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler);
s_light = bgfx::createUniform("s_light", bgfx::UniformType::Sampler);
u_pixelSize = bgfx::createUniform("u_pixelSize", bgfx::UniformType::Vec4);
u_intensity = bgfx::createUniform("u_intensity", bgfx::UniformType::Vec4);
u_color = bgfx::createUniform("u_color", bgfx::UniformType::Vec4);
u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Mat4);
// Create program from shaders.
m_geomProgram = loadProgram("vs_albedo_output", "fs_albedo_output");
m_downsampleProgram = loadProgram("vs_fullscreen", "fs_downsample");
m_upsampleProgram = loadProgram("vs_fullscreen", "fs_upsample");
m_combineProgram = loadProgram("vs_fullscreen", "fs_bloom_combine");
m_gbuffer = BGFX_INVALID_HANDLE;
for (int ii = 0; ii < TEX_CHAIN_LEN; ++ii)
{
m_texChainFb[ii] = BGFX_INVALID_HANDLE;
}
// Imgui.
imguiCreate();
m_timeOffset = bx::getHPCounter();
const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
s_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
// Get renderer capabilities info.
m_caps = bgfx::getCaps();
m_oldWidth = 0;
m_oldHeight = 0;
m_oldReset = m_reset;
m_scrollArea = 0;
cameraCreate();
cameraSetPosition({ 0.0f, 0.0f, -15.0f });
cameraSetVerticalAngle(0.0f);
}
virtual int shutdown() override
{
// Cleanup.
cameraDestroy();
imguiDestroy();
if (bgfx::isValid(m_gbuffer) )
{
bgfx::destroy(m_gbuffer);
}
for (int ii = 0; ii < TEX_CHAIN_LEN; ++ii)
{
bgfx::destroy(m_texChainFb[ii]);
}
bgfx::destroy(m_ibh);
bgfx::destroy(m_vbh);
bgfx::destroy(m_geomProgram);
bgfx::destroy(m_downsampleProgram);
bgfx::destroy(m_upsampleProgram);
bgfx::destroy(m_combineProgram);
bgfx::destroy(s_albedo);
bgfx::destroy(s_tex);
bgfx::destroy(s_depth);
bgfx::destroy(s_light);
bgfx::destroy(u_mtx);
bgfx::destroy(u_pixelSize);
bgfx::destroy(u_intensity);
bgfx::destroy(u_color);
// Shutdown bgfx.
bgfx::shutdown();
return 0;
}
bool update() override
{
if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
{
imguiBeginFrame(
m_mouseState.m_mx
, m_mouseState.m_my
, (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
, m_mouseState.m_mz
, uint16_t(m_width)
, uint16_t(m_height)
);
showExampleDialog(this);
int64_t now = bx::getHPCounter();
static int64_t last = now;
const int64_t frameTime = now - last;
last = now;
const double freq = double(bx::getHPFrequency() );
const float deltaTime = float(frameTime/freq);
float time = (float)( (now-m_timeOffset)/freq);
if (2 > m_caps->limits.maxFBAttachments)
{
// When multiple render targets (MRT) is not supported by GPU,
// implement alternative code path that doesn't use MRT.
bool blink = uint32_t(time*3.0f)&1;
bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " MRT not supported by GPU. ");
// Set view 0 default viewport.
bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::touch(0);
}
else
{
if (m_oldWidth != m_width
|| m_oldHeight != m_height
|| m_oldReset != m_reset
|| !bgfx::isValid(m_gbuffer) )
{
// Recreate variable size render targets when resolution changes.
m_oldWidth = m_width;
m_oldHeight = m_height;
m_oldReset = m_reset;
if (bgfx::isValid(m_gbuffer) )
{
bgfx::destroy(m_gbuffer);
}
const uint64_t tsFlags = 0
| BGFX_TEXTURE_RT
| BGFX_SAMPLER_U_CLAMP
| BGFX_SAMPLER_V_CLAMP
;
for (int ii = 0; ii < TEX_CHAIN_LEN; ++ii)
{
if (bgfx::isValid(m_texChainFb[ii]) )
{
bgfx::destroy(m_texChainFb[ii]);
}
m_texChainFb[ii] = bgfx::createFrameBuffer(
(uint16_t)(m_width >> ii)
, (uint16_t)(m_height >> ii)
, bgfx::TextureFormat::RGBA32F
, tsFlags
);
}
bgfx::TextureHandle gbufferTex[] =
{
bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::RGBA32F, tsFlags),
bgfx::getTexture(m_texChainFb[0]),
bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::D32F, tsFlags),
};
m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(gbufferTex), gbufferTex, true);
}
ImGui::SetNextWindowPos(
ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
, ImGuiCond_FirstUseEver
);
ImGui::SetNextWindowSize(
ImVec2(m_width / 5.0f, m_height / 6.0f)
, ImGuiCond_FirstUseEver
);
ImGui::Begin("Settings"
, NULL
, 0
);
ImGui::SliderFloat("intensity", &m_intensity, 0.0f, 3.0f);
ImGui::End();
// Update camera.
cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
float view[16];
cameraGetViewMtx(view);
float proj[16];
// Setup views
{
bgfx::setViewRect(RENDER_PASS_GEOMETRY_ID, 0, 0, uint16_t(m_width), uint16_t(m_height) );
for (uint16_t ii = 0; ii < TEX_CHAIN_LEN-1; ++ii)
{
const uint16_t shift = ii + 1;
bgfx::setViewRect(RENDER_PASS_DOWNSAMPLE0_ID + ii, 0, 0
, uint16_t(m_width >> shift)
, uint16_t(m_height >> shift)
);
}
for (uint16_t ii = 0; ii < TEX_CHAIN_LEN-1; ++ii)
{
const uint16_t shift = TEX_CHAIN_LEN - ii - 2;
bgfx::setViewRect(RENDER_PASS_UPSAMPLE0_ID + ii, 0, 0
, uint16_t(m_width >> shift)
, uint16_t(m_height >> shift)
);
}
bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 100.0f, m_caps->homogeneousDepth);
bgfx::setViewFrameBuffer(RENDER_PASS_GEOMETRY_ID, m_gbuffer);
bgfx::setViewTransform(RENDER_PASS_GEOMETRY_ID, view, proj);
bgfx::setViewRect(RENDER_PASS_COMBINE_ID, 0, 0, uint16_t(m_width), uint16_t(m_height));
bx::mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f, 0.0f, m_caps->homogeneousDepth);
for (uint16_t ii = 0; ii < TEX_CHAIN_LEN-1; ++ii)
{
bgfx::setViewTransform(RENDER_PASS_DOWNSAMPLE0_ID + ii, NULL, proj);
bgfx::setViewFrameBuffer(RENDER_PASS_DOWNSAMPLE0_ID + ii, m_texChainFb[ii+1]);
}
for (uint16_t ii = 0; ii < TEX_CHAIN_LEN-1; ++ii)
{
bgfx::setViewTransform(RENDER_PASS_UPSAMPLE0_ID + ii, NULL, proj);
bgfx::setViewFrameBuffer(RENDER_PASS_UPSAMPLE0_ID + ii, m_texChainFb[TEX_CHAIN_LEN - ii - 2]);
}
bgfx::setViewTransform(RENDER_PASS_COMBINE_ID, NULL, proj);
}
const uint32_t kNum = 9;
const int kNumColors = 5;
const float color[4*kNumColors] =
{ // Reference(s):
// - Palette
// https://web.archive.org/web/20180219034657/http://www.colourlovers.com/palette/3647908/RGB_Ice_Cream
0.847f*0.2f, 0.365f*0.2f, 0.408f*0.2f, 1.0f,
0.976f*0.2f, 0.827f*0.2f, 0.533f*0.2f, 1.0f,
0.533f*0.2f, 0.867f*0.2f, 0.741f*0.2f, 1.0f,
0.894f*0.2f, 0.620f*0.2f, 0.416f*0.2f, 1.0f,
0.584f*0.2f, 0.788f*0.2f, 0.882f*0.2f, 1.0f,
};
// Render a whole bunch of colored cubes to the g-buffer.
for (uint32_t xx = 0; xx < kNum; ++xx)
{
bgfx::setUniform(u_color, &color[4 * (xx % kNumColors)]);
float mtx[16];
bx::mtxIdentity(mtx);
const float tt = (float)xx / (float)kNum + 0.07f * time;
const float rr = bx::sin(0.47f * time * bx::kPi2) + 1.4f;
mtx[12] = bx::sin(tt * bx::kPi2)*rr;
mtx[13] = bx::cos(tt * bx::kPi2)*rr;
mtx[14] = 0.2f * (float)xx / (float)kNum;
// Set transform for draw call.
bgfx::setTransform(mtx);
// Set vertex and index buffer.
bgfx::setVertexBuffer(0, m_vbh);
bgfx::setIndexBuffer(m_ibh);
// Set render states.
bgfx::setState(0
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
| BGFX_STATE_WRITE_Z
| BGFX_STATE_DEPTH_TEST_LESS
| BGFX_STATE_MSAA
);
// Submit primitive for rendering to view 0.
bgfx::submit(RENDER_PASS_GEOMETRY_ID, m_geomProgram);
}
// Now downsample.
for (uint16_t ii = 0; ii < TEX_CHAIN_LEN-1; ++ii)
{
const uint16_t shift = ii + 1;
const float pixelSize[4] =
{
1.0f / (float)(m_width >> shift),
1.0f / (float)(m_height >> shift),
0.0f,
0.0f,
};
bgfx::setUniform(u_pixelSize, pixelSize);
bgfx::setTexture(0, s_tex, bgfx::getTexture(m_texChainFb[ii]) );
bgfx::setState(0
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
);
screenSpaceQuad( (float)m_width, (float)m_height, s_texelHalf, m_caps->originBottomLeft);
bgfx::submit(RENDER_PASS_DOWNSAMPLE0_ID + ii, m_downsampleProgram);
}
// Now upsample.
for (uint16_t ii = 0; ii < TEX_CHAIN_LEN - 1; ++ii)
{
const uint16_t shift = TEX_CHAIN_LEN - 2 - ii;
const float pixelSize[4] =
{
1.0f / (float)(m_width >> shift),
1.0f / (float)(m_height >> shift),
0.0f,
0.0f,
};
const float intensity[4] = { m_intensity, 0.0f, 0.0f, 0.0f };
bgfx::setUniform(u_pixelSize, pixelSize);
bgfx::setUniform(u_intensity, intensity);
// Combine color and light buffers.
bgfx::setTexture(0, s_tex, bgfx::getTexture(m_texChainFb[TEX_CHAIN_LEN - 1 - ii]) );
// As we upscale, we also sum with the previous mip level. We do this by alpha blending.
bgfx::setState(0
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
| BGFX_STATE_BLEND_ADD
);
screenSpaceQuad( (float)m_width, (float)m_height, s_texelHalf, m_caps->originBottomLeft);
bgfx::submit(RENDER_PASS_UPSAMPLE0_ID + ii, m_upsampleProgram);
}
// Do final pass, that combines the bloom with the g-buffer.
bgfx::setTexture(0, s_albedo, bgfx::getTexture(m_gbuffer, 0) );
bgfx::setTexture(1, s_light, bgfx::getTexture(m_texChainFb[0]) );
bgfx::setState(0
| BGFX_STATE_WRITE_RGB
| BGFX_STATE_WRITE_A
);
screenSpaceQuad( (float)m_width, (float)m_height, s_texelHalf, m_caps->originBottomLeft);
bgfx::submit(RENDER_PASS_COMBINE_ID, m_combineProgram);
}
imguiEndFrame();
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
return true;
}
return false;
}
bgfx::VertexBufferHandle m_vbh;
bgfx::IndexBufferHandle m_ibh;
bgfx::UniformHandle s_albedo;
bgfx::UniformHandle s_tex;
bgfx::UniformHandle s_depth;
bgfx::UniformHandle s_light;
bgfx::UniformHandle u_pixelSize;
bgfx::UniformHandle u_intensity;
bgfx::UniformHandle u_color;
bgfx::UniformHandle u_mtx;
bgfx::ProgramHandle m_geomProgram;
bgfx::ProgramHandle m_downsampleProgram;
bgfx::ProgramHandle m_upsampleProgram;
bgfx::ProgramHandle m_combineProgram;
bgfx::FrameBufferHandle m_gbuffer;
bgfx::FrameBufferHandle m_texChainFb[TEX_CHAIN_LEN];
uint32_t m_width;
uint32_t m_height;
uint32_t m_debug;
uint32_t m_reset;
float m_intensity = 1.0f;
uint32_t m_oldWidth;
uint32_t m_oldHeight;
uint32_t m_oldReset;
int32_t m_scrollArea;
entry::MouseState m_mouseState;
const bgfx::Caps* m_caps;
int64_t m_timeOffset;
};
} // namespace
ENTRY_IMPLEMENT_MAIN(
ExampleBloom
, "38-bloom"
, "Bloom."
, "https://bkaradzic.github.io/bgfx/examples.html#bloom"
);
| 25.762481 | 148 | 0.650244 | [
"geometry",
"render",
"transform"
] |
61d3b8f60f7ba996dc2ead40686e3ae7c44c821a | 40,237 | cpp | C++ | src/condor_dagman/job.cpp | matyasselmeci/htcondor | 743122b24ce680de5530c365e16353e96ea3456b | [
"Apache-2.0"
] | null | null | null | src/condor_dagman/job.cpp | matyasselmeci/htcondor | 743122b24ce680de5530c365e16353e96ea3456b | [
"Apache-2.0"
] | null | null | null | src/condor_dagman/job.cpp | matyasselmeci/htcondor | 743122b24ce680de5530c365e16353e96ea3456b | [
"Apache-2.0"
] | null | null | null | /***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "job.h"
#include "condor_string.h"
#include "condor_debug.h"
#include "dagman_main.h"
#include "read_multiple_logs.h"
#include "throttle_by_category.h"
#include "dag.h"
#include "dagman_metrics.h"
#include <set>
#include <forward_list>
static const char *JOB_TAG_NAME = "+job_tag_name";
static const char *PEGASUS_SITE = "+pegasus_site";
StringSpace Job::stringSpace;
//---------------------------------------------------------------------------
JobID_t Job::_jobID_counter = 0; // Initialize the static data memeber
int Job::NOOP_NODE_PROCID = INT_MAX;
int Job::_nextJobstateSeqNum = 1;
#ifdef MEMORY_HOG
#else
//EdgeID_t Edge::_edgeId_counter = 0; // Initialize the static data memmber
std::deque<std::unique_ptr<Edge>> Edge::_edgeTable;
#endif
#ifdef DEAD_CODE
//---------------------------------------------------------------------------
// NOTE: this must be kept in sync with the queue_t enum
const char *Job::queue_t_names[] = {
"Q_PARENTS",
"Q_WAITING",
"Q_CHILDREN",
};
#endif
//---------------------------------------------------------------------------
// NOTE: this must be kept in sync with the status_t enum
const char * Job::status_t_names[] = {
"STATUS_NOT_READY",
"STATUS_READY ",
"STATUS_PRERUN ",
"STATUS_SUBMITTED",
"STATUS_POSTRUN ",
"STATUS_DONE ",
"STATUS_ERROR "
};
//---------------------------------------------------------------------------
Job::~Job() {
// We _should_ free_dedup() here, but it turns out both Job and
// stringSpace objects are static, and thus the order of desrtuction when
// dagman shuts down is unknown (global desctructors). Thus dagman
// may end up segfaulting on exit. Since Job objects are never destroyed
// by dagman until it is exiting, no need to free_dedup.
//
// stringSpace.free_dedup(_directory); _directory = NULL;
// stringSpace.free_dedup(_cmdFile); _cmdFile = NULL;
free(_dagFile); _dagFile = NULL;
free(_jobName); _jobName = NULL;
#ifdef DEAD_CODE
varsFromDag->Rewind();
NodeVar *var;
while ( (var = varsFromDag->Next()) ) {
delete var;
}
delete varsFromDag;
#else
// similarly, freeing the strings from the VARS is problematic
// (and also a waste of time because we are exiting the process now anyway)
#endif
delete _scriptPre;
delete _scriptPost;
delete _scriptHold;
free(_jobTag);
}
//---------------------------------------------------------------------------
Job::Job( const char* jobName, const char *directory, const char* cmdFile )
: _scriptPre(NULL)
, _scriptPost(NULL)
, _scriptHold(NULL)
, retry_max(0)
, retries(0)
, _submitTries(0)
, retval(-1)
, retry_abort_val(0xdeadbeef)
, abort_dag_val(-1)
, abort_dag_return_val(-1)
, _dfsOrder(-1)
, _visited(false)
, have_retry_abort_val(false)
, have_abort_dag_val(false)
, have_abort_dag_return_val(false)
, is_cluster(false)
, countedAsDone(false)
, _noop(false)
, _hold(false)
, _type(NodeType::JOB)
#ifdef DEAD_CDE
, varsFromDag(new List<NodeVar>)
#else
#endif
, _queuedNodeJobProcs(0)
, _numSubmittedProcs(0)
, _explicitPriority(0)
, _effectivePriority(_explicitPriority)
, _timesHeld(0)
, _jobProcsOnHold(0)
, _directory(NULL)
, _cmdFile(NULL)
, _submitDesc(NULL)
, _dagFile(NULL)
, _jobName(NULL)
, _Status(STATUS_READY)
#ifdef MEMORY_HOG
#else
, _parent(NO_ID)
, _child(NO_ID)
, _numparents(0)
, _multiple_parents(false)
, _multiple_children(false)
, _parents_done(false)
, _spare(false)
#endif
, _jobID(-1)
, _jobstateSeqNum(0)
, _preskip(PRE_SKIP_INVALID)
, _lastEventTime(0)
, _throttleInfo(NULL)
, _jobTag(NULL)
{
ASSERT( jobName != NULL );
ASSERT( cmdFile != NULL );
debug_printf( DEBUG_DEBUG_1, "Job::Job(%s, %s, %s)\n", jobName, directory, cmdFile);
_jobName = strdup (jobName);
// Initialize _directory and _cmdFile in a de-duped stringSpace since
// these strings may be repeated in thousands of nodes
_directory = stringSpace.strdup_dedup(directory);
ASSERT(_directory);
_cmdFile = stringSpace.strdup_dedup(cmdFile);
ASSERT(_cmdFile);
// _condorID struct initializes itself
// jobID is a primary key (a database term). All should be unique
_jobID = _jobID_counter++;
error_text.clear();
return;
}
//---------------------------------------------------------------------------
void
Job::PrefixDirectory(MyString &prefix)
{
MyString newdir;
// don't add an unnecessary prefix
if (prefix == ".") {
return;
}
// If the job DIR is absolute, leave it alone
if (_directory[0] == '/') {
return;
}
// otherwise, prefix it.
newdir += prefix;
newdir += "/";
newdir += _directory;
stringSpace.free_dedup(_directory);
_directory = stringSpace.strdup_dedup(newdir.c_str());
ASSERT(_directory);
}
#ifdef DEAD_CODE
//---------------------------------------------------------------------------
bool Job::Remove (const queue_t queue, const JobID_t jobID)
{
if (_queues[queue].erase(jobID) == 0) {
return false; // element not found
}
return true;
}
#endif
//---------------------------------------------------------------------------
void Job::Dump ( const Dag *dag ) const {
dprintf( D_ALWAYS, "---------------------- Job ----------------------\n");
dprintf( D_ALWAYS, " Node Name: %s\n", _jobName );
dprintf( D_ALWAYS, " Noop: %s\n", _noop ? "true" : "false" );
dprintf( D_ALWAYS, " NodeID: %d\n", _jobID );
dprintf( D_ALWAYS, " Node Status: %s\n", GetStatusName() );
dprintf( D_ALWAYS, "Node return val: %d\n", retval );
if( _Status == STATUS_ERROR ) {
dprintf( D_ALWAYS, " Error: %s\n", error_text.c_str() );
}
dprintf( D_ALWAYS, "Job Submit File: %s\n", _cmdFile );
if( _scriptPre ) {
dprintf( D_ALWAYS, " PRE Script: %s\n", _scriptPre->GetCmd() );
}
if( _scriptPost ) {
dprintf( D_ALWAYS, " POST Script: %s\n", _scriptPost->GetCmd() );
}
if( _scriptHold ) {
dprintf( D_ALWAYS, " HOLD Script: %s\n", _scriptHold->GetCmd() );
}
if( retry_max > 0 ) {
dprintf( D_ALWAYS, " Retry: %d\n", retry_max );
}
if( _CondorID._cluster == -1 ) {
dprintf( D_ALWAYS, " %7s Job ID: [not yet submitted]\n",
JobTypeString() );
}
else {
dprintf( D_ALWAYS, " %7s Job ID: (%d.%d.%d)\n", JobTypeString(),
_CondorID._cluster, _CondorID._proc, _CondorID._subproc );
}
#ifdef DEAD_CODE
for (int i = 0 ; i < 3 ; i++) {
dprintf( D_ALWAYS, "%15s: ", queue_t_names[i] );
std::set<JobID_t>::const_iterator qit;
for (qit = _queues[i].begin(); qit != _queues[i].end(); qit++) {
Job *node = dag->Dag::FindNodeByNodeID( *qit );
dprintf( D_ALWAYS | D_NOHEADER, "%s, ", node->GetJobName() );
}
dprintf( D_ALWAYS | D_NOHEADER, "<END>\n" );
}
#else
std::string parents, children;
PrintParents(parents, 1024, dag, " ");
PrintChildren(children, 1024, dag, " ");
dprintf(D_ALWAYS, "PARENTS: %s WAITING: %d CHILDREN: %s\n", parents.c_str(), (int)IsWaiting(), children.c_str());
#endif
}
#if 0 // not used -- wenger 2015-02-17
//---------------------------------------------------------------------------
void Job::Print (bool condorID) const {
dprintf( D_ALWAYS, "ID: %4d Name: %s", _jobID, _jobName);
if (condorID) {
dprintf( D_ALWAYS, " CondorID: (%d.%d.%d)", _CondorID._cluster,
_CondorID._proc, _CondorID._subproc );
}
}
//---------------------------------------------------------------------------
void job_print (Job * job, bool condorID) {
if (job == NULL) {
dprintf( D_ALWAYS, "(UNKNOWN)");
} else {
job->Print(condorID);
}
}
#endif
const char*
Job::GetPreScriptName() const
{
if( !_scriptPre ) {
return NULL;
}
return _scriptPre->GetCmd();
}
const char*
Job::GetPostScriptName() const
{
if( !_scriptPost ) {
return NULL;
}
return _scriptPost->GetCmd();
}
const char*
Job::GetHoldScriptName() const
{
if( !_scriptHold ) {
return NULL;
}
return _scriptHold->GetCmd();
}
bool
Job::SanityCheck() const
{
bool result = true;
if( countedAsDone == true && _Status != STATUS_DONE ) {
dprintf( D_ALWAYS, "BADNESS 10000: countedAsDone == true but "
"_Status != STATUS_DONE\n" );
result = false;
}
// TODO:
//
// - make sure # of parents whose state != done+success is
// equal to waitingCount
//
// - make sure no job appear twice in the DAG
//
// - verify parent/child symmetry across entire DAG
return result;
}
bool
Job::SetStatus( status_t newStatus )
{
debug_printf( DEBUG_DEBUG_1, "Job(%s)::_Status = %s\n",
GetJobName(), status_t_names[_Status] );
debug_printf( DEBUG_DEBUG_1, "Job(%s)::SetStatus(%s)\n",
GetJobName(), status_t_names[newStatus] );
_Status = newStatus;
// TODO: add some state transition sanity-checking here?
return true;
}
//---------------------------------------------------------------------------
bool
Job::GetProcIsIdle( int proc )
{
if ( GetNoop() ) {
proc = 0;
}
#ifdef DEAD_CODE
if ( proc >= static_cast<int>( _isIdle.size() ) ) {
_isIdle.resize( proc+1, false );
}
return _isIdle[proc];
#else
if (proc >= static_cast<int>(_gotEvents.size())) {
_gotEvents.resize(proc + 1, 0);
}
return (_gotEvents[proc] & IDLE_MASK) != 0;
#endif
}
//---------------------------------------------------------------------------
void
Job::SetProcIsIdle( int proc, bool isIdle )
{
if ( GetNoop() ) {
proc = 0;
}
#ifdef DEAD_CODE
if ( proc >= static_cast<int>( _isIdle.size() ) ) {
_isIdle.resize( proc+1, false );
}
_isIdle[proc] = isIdle;
#else
if (proc >= static_cast<int>(_gotEvents.size())) {
_gotEvents.resize(proc + 1, 0);
}
if (isIdle) {
_gotEvents[proc] |= IDLE_MASK;
} else {
_gotEvents[proc] &= ~IDLE_MASK;
}
#endif
}
//---------------------------------------------------------------------------
void
Job::SetProcEvent( int proc, int event )
{
if ( GetNoop() ) {
proc = 0;
}
if (proc >= static_cast<int>(_gotEvents.size())) {
_gotEvents.resize(proc + 1, 0);
}
_gotEvents[proc] |= event;
}
//---------------------------------------------------------------------------
void
Job::PrintProcIsIdle()
{
#ifdef DEAD_CODE
for ( int proc = 0;
proc < static_cast<int>( _isIdle.size() ); ++proc ) {
debug_printf( DEBUG_QUIET, " Job(%s)::_isIdle[%d]: %d\n",
GetJobName(), proc, _isIdle[proc] );
}
#else
for (int proc = 0;
proc < static_cast<int>(_gotEvents.size()); ++proc) {
debug_printf(DEBUG_QUIET, " Job(%s)::_isIdle[%d]: %d\n",
GetJobName(), proc, (_gotEvents[proc] & IDLE_MASK) != 0);
}
#endif
}
#ifdef DEAD_CODE
//---------------------------------------------------------------------------
bool
Job::AddParent( Job* parent )
{
bool success;
MyString whynot;
success = AddParent( parent, whynot );
if( !success ) {
debug_printf( DEBUG_QUIET,
"ERROR: AddParent( %s ) failed for node %s: %s\n",
parent ? parent->GetJobName() : "(null)",
this->GetJobName(), whynot.Value() );
}
return success;
}
bool
Job::AddParent( Job* parent, MyString &whynot )
{
if( !this->CanAddParent( parent, whynot ) ) {
return false;
}
if( HasParent( parent ) ) {
debug_printf( DEBUG_QUIET,
"Warning: child %s already has parent %s\n",
GetJobName(), parent->GetJobName() );
check_warning_strictness( DAG_STRICT_3 );
return true;
}
if( !Add( Q_PARENTS, parent->GetJobID() ) ) {
whynot = "unknown error appending to PARENTS queue";
return false;
}
if( parent->GetStatus() != STATUS_DONE ) {
if( !Add( Q_WAITING, parent->GetJobID() ) ) {
// this node's dependency queues are now out of sync and
// thus the DAG state is FUBAR, so we should bail...
EXCEPT( "Failed to add parent %s to job %s",
parent->GetJobName(), GetJobName() );
return false;
}
}
whynot = "n/a";
return true;
}
#else
// visit all of the children, either marking them, or checking for cycles
int Job::CountChildren() const
{
int count = 0;
#ifdef MEMORY_HOG
count = (int)_children.size();
#else
if (_child != NO_ID) {
if (_multiple_children) {
Edge * edge = Edge::ById(_child);
ASSERT(edge);
#if 1 // if the child list has a size method
count = (int)edge->size();
#else // if it does not
for (auto it = edge->_children.begin(); it != edge->_children.end(); ++it) {
++count;
}
#endif
} else {
count = 1;
}
}
#endif
return count;
}
bool Job::ParentComplete(Job * parent)
{
bool fail = true;
int num_waiting = 0;
#ifdef MEMORY_HOG
fail = _waiting.erase(parent->GetJobID()) != 1;
num_waiting = (int)_waiting.size();
#else
#if 1
bool already_done = _parents_done;
if (_parent != NO_ID) {
if (_multiple_parents) {
WaitEdge * edge = WaitEdge::ById(_parent);
fail = ! edge->MarkDone(parent->GetJobID(), already_done);
num_waiting = edge->Waiting();
_parents_done = num_waiting == 0;
} else {
num_waiting = _parents_done ? 0 : 1;
if (parent->GetJobID() == _parent) {
fail = false;
_parents_done = true;
num_waiting = 0;
}
}
}
#else
static int log_count = 0;
if (_waiting != NO_ID) {
if (_multiple_waiting) {
Edge * edge = Edge::ById(_waiting);
PRAGMA_REMIND("if Edge instances are shared, it's ok to fail to remove a parent here..")
fail = ! edge->Remove(parent->GetJobID());
if (fail) {
if (++log_count < 10) {
debug_printf(DEBUG_QUIET,
"ERROR: ParentComplete( %s ) failed for multi-parent child node %s: waiting=%d %d parent=%d %d\n",
parent ? parent->GetJobName() : "(null)",
this->GetJobName(),
_waiting, (int)edge->size(),
_parent, (int)Edge::ById(_parent)->size());
}
fail = false;
}
if (edge->empty()) {
_waiting = NO_ID;
_multiple_waiting = false;
num_waiting = 0;
} else if (fail) {
num_waiting = (int)edge->size();
}
} else {
num_waiting = 1;
if (parent->GetJobID() == _waiting) {
fail = false;
_waiting = NO_ID;
num_waiting = 0;
}
}
if (fail) {
if (++log_count < 10) {
debug_printf(DEBUG_QUIET,
"ERROR: ParentComplete( %s ) failed for multi-parent child node %s: waiting=%d %d parent=%d %d\n",
parent ? parent->GetJobName() : "(null)",
this->GetJobName(),
_waiting, num_waiting,
_parent, (int)Edge::ById(_parent)->size());
}
fail = false;
}
}
#endif
#endif
if (fail) {
debug_printf(DEBUG_QUIET,
"ERROR: ParentComplete( %s ) failed for child node %s: num_waiting=%d\n",
parent ? parent->GetJobName() : "(null)",
this->GetJobName(),
num_waiting);
}
return ! IsWaiting();
}
int Job::PrintParents(std::string & buf, size_t bufmax, const Dag* dag, const char * sep) const
{
int count = 0;
#ifdef MEMORY_HOG
for (auto it = _parents.begin(); it != _parents.end(); ++it) {
if (buf.size() >= bufmax)
break;
Job * parent = dag->FindNodeByNodeID(*it);
ASSERT(parent != NULL);
if (count > 0) buf += sep;
buf += parent->GetJobName();
++count;
}
#else
if (_parent != NO_ID) {
if (_multiple_parents) {
Edge * edge = Edge::ById(_parent);
ASSERT(edge);
if ( ! edge->_ary.empty()) {
for (auto it = edge->_ary.begin(); it != edge->_ary.end(); ++it) {
if (buf.size() >= bufmax)
break;
Job * parent = dag->FindNodeByNodeID(*it);
ASSERT(parent != NULL);
if (count > 0) buf += sep;
buf += parent->GetJobName();
++count;
}
}
} else {
Job* parent = dag->FindNodeByNodeID(_parent);
ASSERT(parent != NULL);
buf += parent->GetJobName();
++count;
}
}
#endif
return count;
}
int Job::PrintChildren(std::string & buf, size_t bufmax, const Dag* dag, const char * sep) const
{
int count = 0;
#ifdef MEMORY_HOG
for (auto it = _children.begin(); it != _children.end(); ++it) {
if (buf.size() >= bufmax)
break;
Job * child = dag->FindNodeByNodeID(*it);
ASSERT(child != NULL);
if (count > 0) buf += sep;
buf += child->GetJobName();
++count;
}
#else
if (_child != NO_ID) {
if (_multiple_children) {
Edge * edge = Edge::ById(_child);
ASSERT(edge);
if ( ! edge->_ary.empty()) {
for (auto it = edge->_ary.begin(); it != edge->_ary.end(); ++it) {
if (buf.size() >= bufmax)
break;
Job * child = dag->FindNodeByNodeID(*it);
ASSERT(child != NULL);
if (count > 0) buf += sep;
buf += child->GetJobName();
++count;
}
}
} else {
Job* child = dag->FindNodeByNodeID(_child);
ASSERT(child != NULL);
buf += child->GetJobName();
++count;
}
}
#endif
return count;
}
// tell children that the parent is complete, and call the given function
// for children that have no more incomplete parents
//
int Job::NotifyChildren(Dag& dag, bool(*pfn)(Dag& dag, Job* child))
{
int count = 0;
#ifdef MEMORY_HOG
for (auto it = _children.begin(); it != _children.end(); ++it) {
Job * child = dag.FindNodeByNodeID(*it);
ASSERT(child != NULL);
if (child->ParentComplete(this)) { // returns ! child->IsWaiting()
if (pfn) pfn(dag, child);
}
}
#else
if (_child != NO_ID) {
if (_multiple_children) {
Edge * edge = Edge::ById(_child);
ASSERT(edge);
if ( ! edge->_ary.empty()) {
for (auto it = edge->_ary.begin(); it != edge->_ary.end(); ++it) {
Job * child = dag.FindNodeByNodeID(*it);
ASSERT(child != NULL);
if (child->ParentComplete(this)) {
if (pfn) pfn(dag, child);
}
}
}
} else {
Job* child = dag.FindNodeByNodeID(_child);
ASSERT(child != NULL);
if (child->ParentComplete(this)) {
if (pfn) pfn(dag, child);
}
}
}
#endif
return count;
}
// visit all of the children, either marking them, or checking for cycles
int Job::VisitChildren(Dag& dag, int(*pfn)(Dag& dag, Job* parent, Job* child, void* args), void* args)
{
int retval = 0;
#ifdef MEMORY_HOG
for (auto it = _children.begin(); it != _children.end(); ++it) {
Job * child = dag.FindNodeByNodeID(*it);
ASSERT(child != NULL);
retval += pfn(dag, this, child, args);
}
#else
if (_child != NO_ID) {
if (_multiple_children) {
Edge * edge = Edge::ById(_child);
ASSERT(edge);
if (! edge->_ary.empty()) {
for (auto it = edge->_ary.begin(); it != edge->_ary.end(); ++it) {
Job * child = dag.FindNodeByNodeID(*it);
ASSERT(child != NULL);
retval += pfn(dag, this, child, args);
}
}
} else {
Job* child = dag.FindNodeByNodeID(_child);
ASSERT(child != NULL);
retval += pfn(dag, this, child, args);
}
}
#endif
return retval;
}
#endif
bool
Job::CanAddParent( Job* parent, MyString &whynot )
{
if( !parent ) {
whynot = "parent == NULL";
return false;
}
if( GetType() == NodeType::FINAL ) {
whynot = "Tried to add a parent to a Final node";
return false;
}
// we don't currently allow a new parent to be added to a
// child that has already been started (unless the parent is
// already marked STATUS_DONE, e.g., when rebuilding from a
// rescue DAG) -- but this restriction might be lifted in the
// future once we figure out the right way for the DAG to
// respond...
if( _Status != STATUS_READY && parent->GetStatus() != STATUS_DONE ) {
whynot.formatstr( "%s child may not be given a new %s parent",
this->GetStatusName(), parent->GetStatusName() );
return false;
}
whynot = "n/a";
return true;
}
bool Job::CanAddChildren(std::forward_list<Job*> & children, MyString &whynot)
{
if ( GetType() == NodeType::FINAL ) {
whynot = "Tried to add a child to a final node";
return false;
}
if ( GetType() == NodeType::PROVISIONER ) {
whynot = "Tried to add a child to a provisioner node";
return false;
}
for (auto it = children.begin(); it != children.end(); ++it) {
Job* child = *it;
if ( ! child->CanAddParent(this, whynot)) {
return false;
}
}
return true;
}
bool Job::AddVar(const char *name, const char *value, const char * filename, int lineno)
{
name = dedup_str(name);
value = dedup_str(value);
auto last_var = varsFromDag.before_begin();
for (auto it = varsFromDag.begin(); it != varsFromDag.end(); ++it) {
last_var = it;
// because we dedup the names, we can just compare the pointers here.
if (name == it->_name) {
debug_printf(DEBUG_NORMAL, "Warning: VAR \"%s\" "
"is already defined in job \"%s\" "
"(Discovered at file \"%s\", line %d)\n",
name, GetJobName(), filename, lineno);
check_warning_strictness(DAG_STRICT_3);
debug_printf(DEBUG_NORMAL, "Warning: Setting VAR \"%s\" = \"%s\"\n", name, value);
it->_value = value;
return true;
}
}
varsFromDag.emplace_after(last_var, name, value);
return true;
}
int Job::PrintVars(std::string &vars)
{
int num_vars = 0;
for (auto it = varsFromDag.begin(); it != varsFromDag.end(); ++it) {
vars.push_back(' ');
vars.append(it->_name);
vars.push_back('=');
vars.push_back('\"');
// now we print the value, but we have to re-escape certain characters
const char * p = it->_value;
while (*p) {
char c = *p++;
if (c == '\"' || c == '\\') {
vars.push_back('\\');
}
vars.push_back(c);
}
vars.push_back('\"');
++num_vars;
}
return num_vars;
}
#ifdef DEAD_CODE
bool
Job::AddChild( Job* child )
{
bool success;
MyString whynot;
success = AddChild( child, whynot );
if( !success ) {
debug_printf( DEBUG_QUIET,
"ERROR: AddChild( %s ) failed for node %s: %s\n",
child ? child->GetJobName() : "(null)",
this->GetJobName(), whynot.Value() );
}
return success;
}
bool
Job::AddChild( Job* child, MyString &whynot )
{
if( !this->CanAddChild( child, whynot ) ) {
return false;
}
if( HasChild( child ) ) {
debug_printf( DEBUG_NORMAL,
"Warning: parent %s already has child %s\n",
GetJobName(), child->GetJobName() );
check_warning_strictness( DAG_STRICT_3 );
return true;
}
if( !Add( Q_CHILDREN, child->GetJobID() ) ) {
whynot = "unknown error appending to CHILDREN queue";
return false;
}
whynot = "n/a";
return true;
}
#else
bool Job::AddChildren(std::forward_list<Job*> &children, MyString &whynot)
{
// check if all of this can be our child, and if all are ok being our children
if ( ! CanAddChildren(children, whynot)) {
return false;
}
// optimize the insertion case for more than a single child
// into current a single or empty edge
if (more_than_one(children) && ! _multiple_children) {
JobID_t id = _child;
Edge * edge = Edge::PromoteToMultiple(_child, _multiple_children, id);
// count the children so we can reserve space in the edge array
int num_children = (id == NO_ID) ? 0 : 1;
for (auto it = children.begin(); it != children.end(); ++it) { ++num_children; }
edge->_ary.reserve(num_children);
// populate the edge array, since we know that children is sorted we can just push_back here.
for (auto it = children.begin(); it != children.end(); ++it) {
Job* child = *it;
edge->_ary.push_back(child->GetJobID());
// count the parents of the children so that we can allocate space in AdjustEdges
child->_numparents += 1;
}
if (id != NO_ID) { edge->Add(id); }
return true;
}
for (auto it = children.begin(); it != children.end(); ++it) {
Job* child = *it;
#ifdef MEMORY_HOG
auto ret = _children.insert(child->GetJobID());
if (ret.second == false) {
debug_printf(DEBUG_NORMAL,
"Warning: parent %s already has child %s\n",
GetJobName(), child->GetJobName());
check_warning_strictness(DAG_STRICT_3);
} else {
child->addParent(this);
}
#else
// if we have no children, add this as a direct child
if (_child == NO_ID) {
_multiple_children = false;
_child = child->GetJobID();
// count the parents of the children so that we can allocate space in AdjustEdges
child->_numparents += 1;
continue;
}
JobID_t id = NO_ID;
Edge * edge = Edge::PromoteToMultiple(_child, _multiple_children, id);
if (id != NO_ID) {
// insert the old _child id as the first id in the collection
edge->Add(id);
}
if ( ! edge->Add(child->GetJobID())) {
debug_printf(DEBUG_NORMAL,
"Warning: parent %s already has child %s\n",
GetJobName(), child->GetJobName());
check_warning_strictness(DAG_STRICT_3);
} else {
// count parents - used by AdjustEdges to reserve space
child->_numparents += 1;
}
#endif
}
return true;
}
void Job::BeginAdjustEdges(Dag* /*dag*/)
{
// resize parents to fit _numparents
if (_numparents > 1 && _parent == NO_ID) {
_parent = WaitEdge::NewWaitEdge(_numparents);
_multiple_parents = true;
}
// clearout the parent lists and done flags, we will set them in AdjustEdges
if (_multiple_parents) {
WaitEdge * wedge = WaitEdge::ById(_parent);
wedge->MarkAllWaiting();
} else {
ASSERT(_numparents <= 1);
_parent = NO_ID; // this will set set to the single parent by AdjustEdges
}
_parents_done = false;
}
// helper for AdjustEdges, assumes that _parent has been resized by BeginAdjustEdges
// we can't mark parents done here, that can only happen after we built all of the parents
void Job::AdjustEdges_AddParentToChild(Dag* dag, JobID_t child_id, Job* parent)
{
JobID_t parent_id = parent->GetJobID();
Job * child = dag->FindNodeByNodeID(child_id);
ASSERT(child != NULL);
if (child->_parent == NO_ID) {
child->_parent = parent_id;
} else if ( ! child->_multiple_parents) {
if (child->_parent == parent_id) {
debug_printf(DEBUG_QUIET, "notice : parent %d already added to single-parent child %d\n", parent_id, child_id);
} else {
debug_printf(DEBUG_QUIET, "WARNING : attempted to add parent %d to single-parent child %d that already has parent %d\n",
parent_id, child_id, child->_parent);
}
} else {
ASSERT(child->_numparents > 1);
ASSERT(child->_multiple_parents);
WaitEdge* wedge = WaitEdge::ById(child->_parent);
wedge->Add(parent_id);
}
}
// update the waiting edges to contain the unfinished parents
void Job::AdjustEdges(Dag* dag)
{
#ifdef MEMORY_HOG
for (auto it = _parents.begin(); it != _parents.end(); ++it) {
Job * job = dag->FindNodeByNodeID(*it);
if (job->GetStatus() == STATUS_DONE) {
_waiting.erase(*it);
} else {
_waiting.insert(*it);
}
}
#else
// build parents from children
if (_child != NO_ID) {
if (_multiple_children) {
Edge * edge = Edge::ById(_child);
ASSERT(edge);
if ( ! edge->_ary.empty()) {
for (auto it = edge->_ary.begin(); it != edge->_ary.end(); ++it) {
AdjustEdges_AddParentToChild(dag, *it, this);
}
}
} else {
AdjustEdges_AddParentToChild(dag, _child, this);
}
}
#endif
}
#if 0
// diabled becuase marking the children as done here confuses bootstrap
void Job::AdjustEdges_NotifyChild(Dag* dag, JobID_t child_id, Job* parent)
{
JobID_t parent_id = parent->GetJobID();
Job * child = dag->FindNodeByNodeID(child_id);
ASSERT(child != NULL);
bool already_done = child->_parents_done;
if (child->_parent == NO_ID) {
child->_parents_done = true;
} else if (child->_parent == parent_id) {
child->_parents_done = true;
} else {
ASSERT(child->_numparents > 1);
ASSERT(child->_multiple_parents);
WaitEdge* wedge = WaitEdge::ById(child->_parent);
wedge->MarkDone(parent_id, already_done);
child->_parents_done = ! wedge->Waiting();
}
}
#endif
void Job::FinalizeAdjustEdges(Dag* /*dag*/)
{
// check _numparents against number of edges
if (_numparents == 0) {
ASSERT(_parent == NO_ID);
_parents_done = true;
}
if (_numparents == 1) {
ASSERT(!_multiple_parents);
}
if (_numparents > 1) {
WaitEdge * wedge = WaitEdge::ById(_parent);
ASSERT(wedge);
ASSERT(_numparents == (int)wedge->size());
}
// if I'm done, tell my children
#if 0
// if we do this here, bootstrap will get confused
// this code is left for reference - but disabled.
if (GetStatus() == STATUS_DONE) {
if (_child != NO_ID) {
if (_multiple_children) {
Edge * edge = Edge::ById(_child);
ASSERT(edge);
if (! edge->_ary.empty()) {
for (auto it = edge->_ary.begin(); it != edge->_ary.end(); ++it) {
AdjustEdges_NotifyChild(dag, *it, this);
}
}
} else {
AdjustEdges_NotifyChild(dag, _child, this);
}
}
}
#else
ASSERT(GetStatus() != STATUS_DONE);
#endif
}
#endif
bool
Job::CanAddChild( Job* child, MyString &whynot ) const
{
if( !child ) {
whynot = "child == NULL";
return false;
}
if( GetType() == NodeType::FINAL ) {
whynot = "Tried to add a child to a final node";
return false;
}
if( GetType() == NodeType::PROVISIONER ) {
whynot = "Tried to add a child to a provisioner node";
return false;
}
whynot = "n/a";
return true;
}
bool
Job::TerminateSuccess()
{
SetStatus( STATUS_DONE );
return true;
}
bool
Job::TerminateFailure()
{
SetStatus( STATUS_ERROR );
return true;
}
#ifdef DEAD_CODE
bool
Job::Add( const queue_t queue, const JobID_t jobID )
{
std::pair<std::set<JobID_t>::iterator, bool> ret;
ret = _queues[queue].insert(jobID);
if (ret.second == false) {
dprintf( D_ALWAYS,
"ERROR: can't add Job ID %d to DAG: already present!",
jobID );
return false;
}
return true;
}
#else
#endif
bool
Job::AddScript( ScriptType script_type, const char *cmd, int defer_status, time_t defer_time, MyString &whynot )
{
if( !cmd || strcmp( cmd, "" ) == 0 ) {
whynot = "missing script name";
return false;
}
// Check if a script of the same type has already been assigned to this node
const char *old_script_name = NULL;
const char *type_name;
switch( script_type ) {
case ScriptType::PRE:
old_script_name = GetPreScriptName();
type_name = "PRE";
break;
case ScriptType::POST:
old_script_name = GetPostScriptName();
type_name = "POST";
break;
case ScriptType::HOLD:
old_script_name = GetHoldScriptName();
type_name = "HOLD";
break;
}
if( old_script_name ) {
debug_printf( DEBUG_NORMAL,
"Warning: node %s already has %s script <%s> assigned; changing "
"to <%s>\n", GetJobName(), type_name, old_script_name, cmd );
}
Script* script = new Script( script_type, cmd, defer_status, defer_time, this );
if( !script ) {
dprintf( D_ALWAYS, "ERROR: out of memory!\n" );
// we already know we're out of memory, so filling in
// whynot will likely fail, but give it a shot...
whynot = "out of memory!";
return false;
}
if( script_type == ScriptType::POST ) {
_scriptPost = script;
}
else if( script_type == ScriptType::PRE ) {
_scriptPre = script;
}
else if( script_type == ScriptType::HOLD ) {
_scriptHold = script;
}
whynot = "n/a";
return true;
}
bool
Job::AddPreSkip( int exitCode, MyString &whynot )
{
if ( exitCode < PRE_SKIP_MIN || exitCode > PRE_SKIP_MAX ) {
whynot.formatstr( "PRE_SKIP exit code must be between %d and %d\n",
PRE_SKIP_MIN, PRE_SKIP_MAX );
return false;
}
if ( exitCode == 0 ) {
debug_printf( DEBUG_NORMAL, "Warning: exit code 0 for a PRE_SKIP "
"value is weird.\n");
}
if ( _preskip != PRE_SKIP_INVALID ) {
debug_printf( DEBUG_NORMAL,
"Warning: new PRE_SKIP value %d for node %s overrides old value %d\n",
exitCode, GetJobName(), _preskip );
check_warning_strictness( DAG_STRICT_3 );
}
_preskip = exitCode;
whynot = "";
return true;
}
bool
Job::IsActive() const
{
return _Status == STATUS_PRERUN || _Status == STATUS_SUBMITTED ||
_Status == STATUS_POSTRUN;
}
const char*
Job::GetStatusName() const
{
// Put in bounds check here?
return status_t_names[_Status];
}
#ifdef DEAD_CODE
bool
Job::HasChild( Job* child ) {
JobID_t cid;
std::set<JobID_t>::iterator it;
if( !child ) {
return false;
}
cid = child->GetJobID();
it = _queues[Q_CHILDREN].find(cid);
if (it == _queues[Q_CHILDREN].end()) {
return false;
}
return true;
}
bool
Job::HasParent( Job* parent ) {
JobID_t pid;
std::set<JobID_t>::iterator it;
if( !parent ) {
return false;
}
pid = parent->GetJobID();
it = _queues[Q_PARENTS].find(pid);
if (it == _queues[Q_PARENTS].end()) {
return false;
}
return true;
}
bool
Job::RemoveChild( Job* child )
{
bool success;
MyString whynot;
success = RemoveChild( child, whynot );
if( !success ) {
debug_printf( DEBUG_QUIET,
"ERROR: RemoveChild( %s ) failed for node %s: %s\n",
child ? child->GetJobName() : "(null)",
this->GetJobName(), whynot.Value() );
}
return success;
}
bool
Job::RemoveChild( Job* child, MyString &whynot )
{
if( !child ) {
whynot = "child == NULL";
return false;
}
return RemoveDependency( Q_CHILDREN, child->GetJobID(), whynot );
}
bool
Job::RemoveParent( Job* parent, MyString &whynot )
{
if( !parent ) {
whynot = "parent == NULL";
return false;
}
return RemoveDependency( Q_PARENTS, parent->GetJobID(), whynot );
}
bool
Job::RemoveDependency( queue_t queue, JobID_t job )
{
MyString whynot;
return RemoveDependency( queue, job, whynot );
}
bool
Job::RemoveDependency( queue_t queue, JobID_t job, MyString &whynot )
{
if (_queues[queue].erase(job) == 0)
{
whynot = "no such dependency";
return false;
}
whynot = "n/a";
return true;
}
int
Job::NumParents() const
{
return _queues[Q_PARENTS].size();
}
int
Job::NumChildren() const
{
return _queues[Q_CHILDREN].size();
}
#else
#endif
void
Job::SetCategory( const char *categoryName, ThrottleByCategory &catThrottles )
{
ASSERT( _type != NodeType::FINAL );
MyString tmpName( categoryName );
if ( (_throttleInfo != NULL) &&
(tmpName != *(_throttleInfo->_category)) ) {
debug_printf( DEBUG_NORMAL, "Warning: new category %s for node %s "
"overrides old value %s\n", categoryName, GetJobName(),
_throttleInfo->_category->c_str() );
check_warning_strictness( DAG_STRICT_3 );
}
// Note: we must assign a ThrottleInfo here even if the name
// already matches, for the case of lifting splices.
ThrottleByCategory::ThrottleInfo *oldInfo = _throttleInfo;
ThrottleByCategory::ThrottleInfo *throttleInfo =
catThrottles.GetThrottleInfo( &tmpName );
if ( throttleInfo != NULL ) {
_throttleInfo = throttleInfo;
} else {
_throttleInfo = catThrottles.AddCategory( &tmpName );
}
if ( oldInfo != _throttleInfo ) {
if ( oldInfo != NULL ) {
oldInfo->_totalJobs--;
}
_throttleInfo->_totalJobs++;
}
}
void
Job::PrefixName(const MyString &prefix)
{
MyString tmp = prefix + _jobName;
free(_jobName);
_jobName = strdup(tmp.c_str());
}
#ifdef DEAD_CODE
// iterate across the Job's var values, and for any which have $(JOB) in them,
// substitute it. This substitution is draconian and will always happen.
void
Job::ResolveVarsInterpolations(void)
{
NodeVar *var;
varsFromDag->Rewind();
while( (var = varsFromDag->Next()) != NULL ) {
// XXX No way to escape $(JOB) in case, for some crazy reason, you
// want a filename component actually to be '$(JOB)'.
// It isn't hard to fix, I'll do it later.
var->_value.replaceString("$(JOB)", GetJobName());
}
}
#endif
//---------------------------------------------------------------------------
void
Job::SetDagFile(const char *dagFile)
{
if (_dagFile) free(_dagFile);
_dagFile = strdup( dagFile );
}
//---------------------------------------------------------------------------
const char *
Job::GetJobstateJobTag()
{
if ( !_jobTag ) {
MyString jobTagName = MultiLogFiles::loadValueFromSubFile(
_cmdFile, _directory, JOB_TAG_NAME );
if ( jobTagName == "" ) {
jobTagName = PEGASUS_SITE;
} else {
// Remove double-quotes
int begin = jobTagName[0] == '\"' ? 1 : 0;
int last = jobTagName.length() - 1;
int end = jobTagName[last] == '\"' ? last - 1 : last;
jobTagName = jobTagName.substr( begin, 1 + end - begin );
}
MyString tmpJobTag = MultiLogFiles::loadValueFromSubFile(
_cmdFile, _directory, jobTagName.c_str() );
if ( tmpJobTag == "" ) {
tmpJobTag = "-";
} else {
// Remove double-quotes
int begin = tmpJobTag[0] == '\"' ? 1 : 0;
int last = tmpJobTag.length() - 1;
int end = tmpJobTag[last] == '\"' ? last - 1 : last;
tmpJobTag = tmpJobTag.substr( begin, 1 + end - begin );
}
_jobTag = strdup( tmpJobTag.c_str() );
}
return _jobTag;
}
//---------------------------------------------------------------------------
int
Job::GetJobstateSequenceNum()
{
if ( _jobstateSeqNum == 0 ) {
_jobstateSeqNum = _nextJobstateSeqNum++;
}
return _jobstateSeqNum;
}
//---------------------------------------------------------------------------
void
Job::SetLastEventTime( const ULogEvent *event )
{
_lastEventTime = event->GetEventclock();
}
//---------------------------------------------------------------------------
int
Job::GetPreSkip() const
{
if( !HasPreSkip() ) {
debug_printf( DEBUG_QUIET,
"Evaluating PRE_SKIP... It is not defined.\n" );
}
return _preskip;
}
//---------------------------------------------------------------------------
bool
Job::SetCondorID(const CondorID& cid)
{
bool ret = true;
if(GetCluster() != -1) {
debug_printf( DEBUG_NORMAL, "Reassigning the id of job %s from (%d.%d.%d) to "
"(%d.%d.%d)\n", GetJobName(), GetCluster(), GetProc(), GetSubProc(),
cid._cluster, cid._proc,cid._subproc );
ret = false;
}
_CondorID = cid;
return ret;
}
//---------------------------------------------------------------------------
bool
Job::Hold(int proc)
{
#ifdef DEAD_CODE
if( proc >= static_cast<int>( _onHold.size() ) ) {
_onHold.resize( proc+1, 0 );
}
if( !_onHold[proc] ) {
_onHold[proc] = 1;
#else
if (proc >= static_cast<int>(_gotEvents.size())) {
_gotEvents.resize(proc + 1, 0);
}
if ((_gotEvents[proc] & HOLD_MASK) != HOLD_MASK) {
_gotEvents[proc] |= HOLD_MASK;
#endif
++_jobProcsOnHold;
++_timesHeld;
return true;
} else {
dprintf( D_FULLDEBUG, "Received hold event for node %s, and job %d.%d "
"is already on hold!\n", GetJobName(), GetCluster(), proc );
}
return false;
}
//---------------------------------------------------------------------------
bool
Job::Release(int proc)
{
#ifdef DEAD_CODE
if( proc >= static_cast<int>( _onHold.size() ) ) {
dprintf( D_FULLDEBUG, "Received release event for node %s, but job %d.%d "
"is not on hold\n", GetJobName(), GetCluster(), GetProc() );
return false; // We never marked this as being on hold
}
if( _onHold[proc] ) {
_onHold[proc] = 0;
#else
//PRAGMA_REMIND("tj: this should also test the flags, not just the vector size")
if (proc >= static_cast<int>(_gotEvents.size())) {
dprintf(D_FULLDEBUG, "Received release event for node %s, but job %d.%d "
"is not on hold\n", GetJobName(), GetCluster(), GetProc());
return false; // We never marked this as being on hold
}
if (_gotEvents[proc] & HOLD_MASK) {
_gotEvents[proc] &= ~HOLD_MASK;
#endif
--_jobProcsOnHold;
return true;
}
return false;
}
//---------------------------------------------------------------------------
// Note: For multi-proc jobs, if one proc failed this was getting called
// immediately, which was not correct. I changed how this was called, but
// we should probably put in code to make sure it's not called too soon,
// but is called... wenger 2015-11-05
void
Job::Cleanup()
{
#ifdef DEAD_CODE
std::vector<unsigned char> s;
_onHold.swap(s); // Free memory in _onHold
#endif
for ( int proc = 0; proc < static_cast<int>( _gotEvents.size() );
proc++ ) {
if ( _gotEvents[proc] != ( EXEC_MASK | ABORT_TERM_MASK ) ) {
debug_printf( DEBUG_NORMAL,
"Warning for node %s: unexpected _gotEvents value for proc %d: %d!\n",
GetJobName(), proc, (int)_gotEvents[proc] );
check_warning_strictness( DAG_STRICT_2 );
}
}
std::vector<unsigned char> s2;
_gotEvents.swap(s2); // Free memory in _gotEvents
#ifdef DEAD_CODE
std::vector<unsigned char> s3;
_isIdle.swap(s3); // Free memory in _isIdle
#endif
}
| 24.976412 | 123 | 0.616025 | [
"vector"
] |
61d6ee667191672c05c83d3b9d4ba625db19968d | 4,899 | cpp | C++ | src/Magnum/GL/Test/AbstractQueryGLTest.cpp | glhrmfrts/magnum | c5d08156eaa03867403c32f4b0ee6a56202331e4 | [
"MIT"
] | 1 | 2019-04-23T07:31:01.000Z | 2019-04-23T07:31:01.000Z | src/Magnum/GL/Test/AbstractQueryGLTest.cpp | glhrmfrts/magnum | c5d08156eaa03867403c32f4b0ee6a56202331e4 | [
"MIT"
] | null | null | null | src/Magnum/GL/Test/AbstractQueryGLTest.cpp | glhrmfrts/magnum | c5d08156eaa03867403c32f4b0ee6a56202331e4 | [
"MIT"
] | 1 | 2022-03-31T08:48:52.000Z | 2022-03-31T08:48:52.000Z | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/Utility/DebugStl.h>
#include "Magnum/GL/Context.h"
#include "Magnum/GL/Extensions.h"
#include "Magnum/GL/OpenGLTester.h"
#include "Magnum/GL/SampleQuery.h"
namespace Magnum { namespace GL { namespace Test { namespace {
struct AbstractQueryGLTest: OpenGLTester {
explicit AbstractQueryGLTest();
void construct();
void constructMove();
#ifndef MAGNUM_TARGET_WEBGL
void label();
#endif
};
AbstractQueryGLTest::AbstractQueryGLTest() {
addTests({&AbstractQueryGLTest::construct,
&AbstractQueryGLTest::constructMove,
#ifndef MAGNUM_TARGET_WEBGL
&AbstractQueryGLTest::label
#endif
});
}
void AbstractQueryGLTest::construct() {
#ifdef MAGNUM_TARGET_GLES2
if(!Context::current().isExtensionSupported<Extensions::EXT::occlusion_query_boolean>())
CORRADE_SKIP(Extensions::EXT::occlusion_query_boolean::string() + std::string(" is not supported."));
#endif
{
#ifndef MAGNUM_TARGET_GLES
const SampleQuery query{SampleQuery::Target::SamplesPassed};
#else
const SampleQuery query{SampleQuery::Target::AnySamplesPassed};
#endif
MAGNUM_VERIFY_NO_GL_ERROR();
CORRADE_VERIFY(query.id() > 0);
}
MAGNUM_VERIFY_NO_GL_ERROR();
}
void AbstractQueryGLTest::constructMove() {
#ifdef MAGNUM_TARGET_GLES2
if(!Context::current().isExtensionSupported<Extensions::EXT::occlusion_query_boolean>())
CORRADE_SKIP(Extensions::EXT::occlusion_query_boolean::string() + std::string(" is not supported."));
#endif
#ifndef MAGNUM_TARGET_GLES
SampleQuery a{SampleQuery::Target::SamplesPassed};
#else
SampleQuery a{SampleQuery::Target::AnySamplesPassed};
#endif
const Int id = a.id();
MAGNUM_VERIFY_NO_GL_ERROR();
CORRADE_VERIFY(id > 0);
SampleQuery b(std::move(a));
CORRADE_COMPARE(a.id(), 0);
CORRADE_COMPARE(b.id(), id);
#ifndef MAGNUM_TARGET_GLES
SampleQuery c{SampleQuery::Target::SamplesPassed};
#else
SampleQuery c{SampleQuery::Target::AnySamplesPassed};
#endif
const Int cId = c.id();
c = std::move(b);
MAGNUM_VERIFY_NO_GL_ERROR();
CORRADE_VERIFY(cId > 0);
CORRADE_COMPARE(b.id(), cId);
CORRADE_COMPARE(c.id(), id);
}
#ifndef MAGNUM_TARGET_WEBGL
void AbstractQueryGLTest::label() {
#ifdef MAGNUM_TARGET_GLES2
if(!Context::current().isExtensionSupported<Extensions::EXT::occlusion_query_boolean>())
CORRADE_SKIP(Extensions::EXT::occlusion_query_boolean::string() + std::string(" is not supported."));
#endif
/* No-Op version is tested in AbstractObjectGLTest */
if(!Context::current().isExtensionSupported<Extensions::KHR::debug>() &&
!Context::current().isExtensionSupported<Extensions::EXT::debug_label>())
CORRADE_SKIP("Required extension is not available");
#ifndef MAGNUM_TARGET_GLES
SampleQuery query{SampleQuery::Target::SamplesPassed};
#else
SampleQuery query{SampleQuery::Target::AnySamplesPassed};
#endif
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::ARB::direct_state_access>())
#endif
{
query.begin(); query.end();
CORRADE_EXPECT_FAIL("Without ARB_direct_state_access, the object must be used at least once before setting/querying label.");
CORRADE_VERIFY(false);
}
CORRADE_COMPARE(query.label(), "");
query.setLabel("MyQuery");
CORRADE_COMPARE(query.label(), "MyQuery");
MAGNUM_VERIFY_NO_GL_ERROR();
}
#endif
}}}}
CORRADE_TEST_MAIN(Magnum::GL::Test::AbstractQueryGLTest)
| 32.443709 | 133 | 0.703205 | [
"object"
] |
61d85a899e5bdd75b21f675db024cc61fe2878d0 | 11,941 | cpp | C++ | Chatserver/Chatserver/utils.cpp | danielbrendel/dnyCorvusChat | fc9f30245df2ec2bc5ac305c8bca93a002f6b6bd | [
"MIT"
] | null | null | null | Chatserver/Chatserver/utils.cpp | danielbrendel/dnyCorvusChat | fc9f30245df2ec2bc5ac305c8bca93a002f6b6bd | [
"MIT"
] | null | null | null | Chatserver/Chatserver/utils.cpp | danielbrendel/dnyCorvusChat | fc9f30245df2ec2bc5ac305c8bca93a002f6b6bd | [
"MIT"
] | null | null | null | #include "utils.h"
/*
CorvusChat Server (dnyCorvusChat) - Chatserver component
Developed by Daniel Brendel
Version: 0.5
Visit: https://github.com/danielbrendel
Mail dbrendel1988@gmail.com
File: utils.cpp: Utility function implementations
*/
//======================================================================
BOOL IsDestinationReachable(LPCSTR lpszServer)
{
//Check if server is available. This function is used to check if a TeamSpeak 3 server is online. Note: It checks only for the internet address, not the port.
if (!lpszServer)
return FALSE;
in_addr inaddr;
inaddr.S_un.S_addr = inet_addr(lpszServer);
return gethostbyaddr((char*)&inaddr, sizeof(in_addr), AF_INET) != NULL;
}
//======================================================================
//======================================================================
inline unsigned int GetHoursByMS(unsigned int dwMS)
{
//Calculate the value of hours by milliseconds
#define MS_HOUR 3600000
if (dwMS < MS_HOUR) //A hour did not pass yet
return 0;
return dwMS / MS_HOUR; //Get the hours within the defined milliseconds
}
//======================================================================
//======================================================================
const char* AddressToString(const unsigned long ulIPAddress)
{
//Setup string with the IP-Address
if (!ulIPAddress)
return NULL;
static char str[15];
memset(str, 0x00, sizeof(str));
sprintf_s(str, "%d.%d.%d.%d", *(BYTE*)&ulIPAddress, *(BYTE*)((DWORD)&ulIPAddress + 1), *(BYTE*)((DWORD)&ulIPAddress + 2), *(BYTE*)((DWORD)&ulIPAddress + 3));
return &str[0];
}
//======================================================================
//======================================================================
bool FileExists(const char* szFileName)
{
//Check if a file exists on disc
if (!szFileName)
return false;
HANDLE hFile = CreateFileA(szFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return false;
CloseHandle(hFile);
return true;
}
//======================================================================
//======================================================================
void ExtractFilePath(char *szFileName)
{
//Extract file path from a full file name
if (!szFileName)
return;
for (unsigned int i = (unsigned int)strlen(szFileName); i > 3; i--) {
if ((szFileName[i] == '\\') || (szFileName[i] == '/'))
break;
szFileName[i] = '\0';
}
}
//======================================================================
//======================================================================
void WebDirToWinDir(char* szString)
{
//Convert / chars to \ chars
if (!szString)
return;
for (unsigned int i = 0; i < strlen(szString); i++) {
if (szString[i] == '/')
szString[i] = '\\';
}
}
//======================================================================
//======================================================================
wchar_t *CharToWChar(char* szString)
{
//Convert char string to wchar string
if (!szString)
return NULL;
wchar_t* pWideString = new wchar_t[strlen(szString)+1];
if (!pWideString)
return NULL;
mbstowcs(pWideString, szString, strlen(szString)+1);
return pWideString;
}
//======================================================================
//======================================================================
char *ExtractFileName(char *filePath)
{
//This function extracts the file name of a file path.
if (!filePath)
return NULL;
static char fn[250], rev[250];
memset(fn, 0x00, sizeof(fn));
memset(rev, 0x00, sizeof(rev));
strcpy_s(rev, "");
for (unsigned int i = (unsigned int)strlen(filePath); i >= 0; i--) {
if (filePath[i] == '\\') break;
strncat_s(rev, &filePath[i], 1);
}
for (unsigned int g = 0; g <= strlen(rev); g++) {
fn[g] = rev[strlen(rev)-1-g];
}
return fn;
}
//======================================================================
//======================================================================
const char* GetCurrentDateTime(void)
{
//Get current time and date
static char szTimeDate[100];
time_t tim = time(NULL);
if (tim != -1) {
struct tm mTime;
if (!localtime_s(&mTime, &tim)) {
strftime(szTimeDate, sizeof(szTimeDate), "%Y-%m-%d %H:%M", &mTime);
return szTimeDate;
}
}
return NULL;
}
//======================================================================
//======================================================================
const char* GetCurrentDate(void)
{
//Get current date
static char szDate[100];
time_t tim = time(NULL);
if (tim != -1) {
struct tm mTime;
if (!localtime_s(&mTime, &tim)) {
strftime(szDate, sizeof(szDate), "%Y-%m-%d", &mTime);
return szDate;
}
}
return NULL;
}
//======================================================================
//======================================================================
const char* GetCurrentTime(void)
{
//Get current time
static char szTime[100];
time_t tim = time(NULL);
if (tim != -1) {
struct tm mTime;
if (!localtime_s(&mTime, &tim)) {
strftime(szTime, sizeof(szTime), "%H:%M", &mTime);
return szTime;
}
}
return NULL;
}
//======================================================================
//======================================================================
BOOL UpdateServerComponent(VOID)
{
//Update the server component
BOOL bResult = FALSE;
if (g_Objects.Update.OpenInternetHandle()) { //Initialize update component
bResult = g_Objects.Update.QueryUpdateInfo(); //Attempt to update
g_Objects.Update.CloseInternetHandle(); //Clear handle
}
return bResult;
}
//======================================================================
//======================================================================
char* CreateRandomString(BYTE bAsciiStart, BYTE bAsciiEnd, unsigned short usStrSize)
{
//Create a random string with specified length
if (!usStrSize)
return NULL;
//Allocate memory
char* pNewStr = new char[usStrSize + 1];
if (!pNewStr)
return NULL;
srand((unsigned int)time(NULL)); //Initialize random seed
//Set chars (only small alphabet letters)
for (unsigned short i = 0; i < usStrSize; i++)
pNewStr[i] = bAsciiStart + rand()%bAsciiEnd;
//Zero terminate it
pNewStr[usStrSize] = 0;
return pNewStr;
}
//======================================================================
//======================================================================
bool DirectoryExists(char* szDir)
{
//Check if a directory exists
if (!szDir)
return false;
//Try to get attributes of the directory
DWORD dwAttributes = GetFileAttributesA(szDir);
//Check if the function has succeeded (means at least the specified object exists)
if (dwAttributes == INVALID_FILE_ATTRIBUTES)
return false;
//Compare if this object is a directory
return (dwAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;
}
//======================================================================
//======================================================================
bool IsValidStrLen(const char* szString, size_t uiMaxStrLen)
{
//Check if a string has the proper length
if ((!szString) || (!uiMaxStrLen))
return false;
//Loop trough string and check for termination char in the proper range
for (size_t i = 0; i < uiMaxStrLen; i++) {
if (szString[i] == 0)
return true;
}
return false;
}
//======================================================================
//======================================================================
bool toLower(char* szString)
{
//Convert all high chars to low chars
if (!szString)
return false;
//Loop trough characters and convert them to lower
for (unsigned int i = 0; i < strlen(szString); i++) {
szString[i] = tolower(szString[i]);
}
return true;
}
//======================================================================
//======================================================================
bool IsValidString(const char* szString)
{
//Check if a string is valid
if (!szString)
return false;
CValidString vs;
return vs.IsValidString(szString, &g_VSData);
}
//======================================================================
//======================================================================
bool ClientNameAlreadyUsed(const char* szClientName)
{
//Check if a client name is already in use
if (!szClientName)
return false;
//Search in client list
for (CLIENTAMOUNT i = 0; i < ENG_GetClientCount(); i++) {
clientinfo_s* pClient = ENG_GetClientById(i);
if ((pClient) && (pClient->bHasLoggedIn) && (strcmp(pClient->userinfo.szName, szClientName)==0))
return true;
}
return false;
}
//======================================================================
//======================================================================
std::string StringReplace(std::string& stdstrExpression, const char* lpszToReplace, const char* lpszNewString)
{
//Replaces a string in a std string.
if ((!lpszToReplace) || (!lpszNewString))
return stdstrExpression;
while (stdstrExpression.find(lpszToReplace) != -1) {
stdstrExpression.replace(stdstrExpression.find(lpszToReplace), strlen(lpszToReplace), lpszNewString);
}
return stdstrExpression;
}
//======================================================================
//======================================================================
void FatalError(const char* szErrMsg, ...);
BOOL RestartProgram(VOID)
{
//Perform program restart
#define BATCH_FILE "temp_restarter_script.bat"
#define BATCH_NAME_VAR "%0"
static const char szBatchContent[] = {
"rem CorvusChat Chatserver restart script\r\n" //Just a comment
"@echo off\r\n" //Disable printing of the current path
"cls\r\n" //Clear console window content
"taskkill /PID %d /F\r\n" //Terminate the owning process
"start \"\" \"%sCorvusChat_%s.exe\"\r\n" //Restart the program
"del %s\r\n" //Delete this batch script
};
char szTempDir[MAX_PATH] = {0};
char g_szBatchFullFileName[MAX_PATH] = {0};
//Get temp directory
if (!GetTempPathA(sizeof(szTempDir), szTempDir))
return FALSE;
//Format full file name
sprintf_s(g_szBatchFullFileName, "%s" BATCH_FILE, szTempDir);
//Get process ID of owning process
DWORD dwOwnerPid = GetCurrentProcessId();
if (!dwOwnerPid)
return FALSE;
//Format script code
char szFmtScript[2048] = {0};
sprintf_s(szFmtScript, szBatchContent, dwOwnerPid, g_GlobalVars.szAppPath, PLATFORM, BATCH_NAME_VAR);
//Create batch script on disc (current directory)
std::ofstream hFile;
hFile.open(g_szBatchFullFileName);
if (!hFile.is_open())
return FALSE;
hFile.write(szFmtScript, strlen(szFmtScript));
hFile.close();
//Run it
return (int)ShellExecuteA(0, "open", g_szBatchFullFileName, NULL, g_GlobalVars.szAppPath, SW_SHOWNORMAL) > 32;
}
//======================================================================
//======================================================================
BOOL DeleteFileObject(LPCSTR lpszFolder)
{
//Delete a file object: files and folders
if (!lpszFolder)
return FALSE;
char szFolder[MAX_PATH];
//Setup string with folder name
strcpy_s(szFolder, lpszFolder);
memset(&szFolder[MAX_PATH-2], 0x00, 2); //Just to ensure the string is double-zero-terminated
//Setup SH operation structure
SHFILEOPSTRUCTA shOpStruct;
memset(&shOpStruct, 0x00, sizeof(shOpStruct));
shOpStruct.wFunc = FO_DELETE; //Delete operation
shOpStruct.pFrom = szFolder; //Name string of object to delete
shOpStruct.fFlags = FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION; //Don't show error GUI, deletion operation GUI and don't ask for confirmation
return SHFileOperationA(&shOpStruct) == ERROR_SUCCESS; //Perform operation
}
//======================================================================
| 26.954853 | 159 | 0.521816 | [
"object"
] |
61dc678a34388b8eef41ecec6b75c130ab5d1c22 | 4,648 | hpp | C++ | read_csv.hpp | Ignacio-Moral-22/TC1031_Reto | 5a7fe2400e8235d0868bd33c80359f43dfc4b23f | [
"MIT"
] | null | null | null | read_csv.hpp | Ignacio-Moral-22/TC1031_Reto | 5a7fe2400e8235d0868bd33c80359f43dfc4b23f | [
"MIT"
] | null | null | null | read_csv.hpp | Ignacio-Moral-22/TC1031_Reto | 5a7fe2400e8235d0868bd33c80359f43dfc4b23f | [
"MIT"
] | null | null | null | #ifndef read_csv_hpp
#define read_csv_hpp
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include "clase_archivo.hpp"
#include "busqueda.hpp"
std::vector<class Registros<std::string>> readRecords(){
std::ifstream valores("equipo10.csv");
std::string fecha, hora, ipFuente, puertoFuente, hostNameFuente, ipDestino, puertoDestino, hostNameDestino;
std::vector<class Registros<std::string>> registros;
while (valores.peek()!=EOF){
std::getline(valores, fecha, ',');
std::getline(valores, hora, ',');
std::getline(valores, ipFuente, ',');
std::getline(valores, puertoFuente, ',');
std::getline(valores, hostNameFuente, ',');
std::getline(valores, ipDestino, ',');
std::getline(valores, puertoDestino, ',');
std::getline(valores, hostNameDestino, '\n');
Registros<std::string> r(fecha, hora, ipFuente, puertoFuente, hostNameFuente, ipDestino, puertoDestino, hostNameDestino);
registros.push_back(r);
}
int count=0;
for(int i=0; i<registros.size(); i++){
count+=1;
}
std::cout << "El archivo tiene " << count << " registros." << std::endl;
valores.close();
return registros;
};
int segundoDia(std::vector<class Registros<std::string>> ®istros){
std::string dia1, dia2 = "";
int contador_iterativo = 0;
int contar_dia_2 = 0;
dia1=registros.at(contador_iterativo).date();
while (registros.at(contador_iterativo).date()==dia1){
contador_iterativo++;
}
dia2=registros.at(contador_iterativo).date();
while(registros.at(contador_iterativo).date()==dia2){
contar_dia_2++;
contador_iterativo++;
}
std::cout<<"El segundo dia es " << dia2 << std::endl;
return contar_dia_2;
};
void countNames(std::vector<class Registros<std::string>> ®istros){
int nameCount;
std::cout<<"Cuantos nombres quieres buscar?" << std::endl;
std::cin >> nameCount;
std::string names[nameCount], name[nameCount];
for(int i=0; i<nameCount; i++){
std::cout << "Escribe el nombre en minusculas" << std::endl;
std::cin >> name[i];
names[i]=name[i];
names[i].append(".reto.com");
};
std::vector<std::string> nombres;
for(int i=0; i<registros.size(); i++){
std::string hostDestino = registros.at(i).fuenteHost();
nombres.push_back(hostDestino);
}
int posiciones[nameCount];
for(int j=0; j<nameCount; j++){
posiciones[j]=busquedaBinaria<std::string>(0, nombres.size()-1, names[j], nombres);
if(posiciones[j]==-1){
std::cout << name[j] << " no es un empleado de la empresa." << std::endl;
} else {
std::cout << name[j] << " si trabaja en la empresa." << std::endl;
}
};
};
void direccionIP(std::vector<class Registros<std::string>> ®istros){
std::string ipCompania = registros.at(registros.size()-1).fuenteIP();
ipCompania.erase(10,ipCompania.length()-10);
ipCompania.append(".0");
std::cout << "La direccion IP de la compania es " << ipCompania << std::endl;
}
void correos(std::vector<class Registros<std::string>> ®istros){
int contarCorreos;
std::cout<<"Cuantos correos quieres buscar?" << std::endl;
std::cin >> contarCorreos;
std::string correos[contarCorreos];
for(int i=0; i<contarCorreos; i++){
std::cout << "Escribe el nombre en minusculas" << std::endl;
std::cin >> correos[i];
correos[i].append(".com");
};
std::vector<std::string> hostNames;
for(int i=0; i<registros.size(); i++){
std::string hostDestino = registros.at(i).destinoHost();
hostNames.push_back(hostDestino);
}
int posiciones[contarCorreos];
for(int j=0; j<contarCorreos; j++){
posiciones[j]=busquedaBinaria<std::string>(0, hostNames.size()-1, correos[j], hostNames);
if(posiciones[j]==-1){
std::cout << correos[j] << " no es un correo que se usa en la empresa." << std::endl;
} else {
std::cout << correos[j] << " si es un correo que se usa en la empresa." << std::endl;
}
};
}
void countPuertos(std::vector<class Registros<std::string>> ®istros){
std::vector<std::string> puertos;
int check;
for(int i=0; i<registros.size(); i++){
check=busquedaBinaria(0, puertos.size()-1, registros.at(i).destinoPuerto(), puertos);
if(check==-1){
puertos.push_back(registros.at(i).destinoPuerto());
}
}
for(int j=0; j<puertos.size(); j++){
std::cout << puertos.at(j) << std::endl;
}
}
#endif | 34.686567 | 129 | 0.611446 | [
"vector"
] |
61e8fc12003c3b1ae937706e58ead8de2a52dc0c | 1,945 | cpp | C++ | Codeforces/E1/D.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | Codeforces/E1/D.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | Codeforces/E1/D.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | #pragma comment(linker, "/STACK:2000000")
#include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long int>
#define sc(n) scanf("%d",&n);
#define scll(n) scanf("%lld",&n);
#define scld(n) scanf("%Lf",&n);
#define scr(s) {char temp[1000000];scanf("%s",temp);s = temp;}
using namespace std;
void dfs(vector<string> &v, int i,int j,int key,int**visited,int n,int m)
{
visited[i][j] = key;
if(i>0 && !visited[i-1][j] && v[i-1][j]=='.') dfs(v,i-1,j,key,visited,n,m);
if(i<n-1 && !visited[i+1][j] && v[i+1][j]=='.') dfs(v,i+1,j,key,visited,n,m);
if(j>0 && !visited[i][j-1] && v[i][j-1]=='.') dfs(v,i,j-1,key,visited,n,m);
if(j<m-1 && !visited[i][j+1] && v[i][j+1]=='.') dfs(v,i,j+1,key,visited,n,m);
}
int main()
{
int n,m,q;
// map<int,int> d;
sc(n);sc(m);sc(q);
// string*v = new string[n];
vector<string> v;
int** visited = (int**)calloc(n,sizeof(int*));
for(int i=0;i<n;i++) visited[i] = (int*)calloc(m,sizeof(int));
for(int i=0;i<n;i++)
{
string s;
scr(s);
v.pu(s);
}
int key = 1;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(visited[i][j] || v[i][j]=='*') continue;
dfs(v,i,j,key,visited,n,m);
key++;
}
}
int*d = (int*)calloc(key,sizeof(int));
// for(int i=1;i<key;i++) d[i] = 0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int count = 0;
if(i>0 && v[i-1][j]=='*') count++;
if(i<n-1 && v[i+1][j]=='*') count++;
if(j>0 && v[i][j-1]=='*') count++;
if(j<m-1 && v[i][j+1]=='*') count++;
d[visited[i][j]] +=count;
}
}
// for(int i=0;i<n;i++) {for(int j=0;j<m;j++) cout<<visited[i][j]<<" ";cout<<endl;}
for(int i=0;i<q;i++)
{
int a,b;
sc(a);sc(b);
a--;b--;
printf("%d\n",d[visited[a][b]]);
}
return 0;
} | 25.592105 | 85 | 0.515681 | [
"vector"
] |
61ea1d7cb683d856d082605a1d6bf00c61be8b97 | 11,186 | cpp | C++ | src/engine/font.cpp | ttrounce/voxelmade | 6524d77928be6bcb6358aa7fbc3b550192fc9396 | [
"MIT"
] | 1 | 2021-03-17T11:56:42.000Z | 2021-03-17T11:56:42.000Z | src/engine/font.cpp | ttrounce/voxelmade | 6524d77928be6bcb6358aa7fbc3b550192fc9396 | [
"MIT"
] | null | null | null | src/engine/font.cpp | ttrounce/voxelmade | 6524d77928be6bcb6358aa7fbc3b550192fc9396 | [
"MIT"
] | null | null | null | #include "../utility/logging.h"
#include "../utility/basicio.h"
#include "../utility/color.h"
#include "font.h"
#include "gfx.h"
#include "engine.h"
#include <map>
#include <cglm/cglm.h>
#include <glad/glad.h>
#include <ft2build.h>
#include FT_FREETYPE_H
using namespace vhm;
FT_Library library;
void vhm::InitFreeType()
{
i32 error = FT_Init_FreeType(&library);
if(error)
{
printf("%s Error initialising FreeType\n", VHM_FT_ERR);
}
else
{
printf("%s Successfully initialised FreeType\n", VHM_FT_LOG);
}
}
void vhm::FreeFreeType()
{
FT_Done_FreeType(library);
}
FONT_RENDERER::FONT_RENDERER()
{
// Generate VAO model
f32 vertices[12] = {0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0};
f32 texels[12] = {0.0, 0.0, 0.99, 0.99, 0.99, 0.0, 0.0, 0.0, 0.0, 0.99, 0.99, 0.99};
glGenVertexArrays(1, &vao.handle);
glBindVertexArray(vao.handle);
SetBufferVAO(vao, 0, 2, vertices, GL_FLOAT, 12);
SetBufferVAO(vao, 1, 2, texels, GL_FLOAT, 12);
glBindVertexArray(0);
// Create Shader Program
char* vert = ReadString("shaders/font_vert.glsl");
char* frag = ReadString("shaders/font_frag.glsl");
program = glCreateProgram();
glUseProgram(program);
CreateVertexShader(program, vert, strlen(vert));
CreateFragmentShader(program, frag, strlen(frag));
LinkProgram(program);
glUseProgram(0);
free(vert);
free(frag);
}
FONT_RENDERER::~FONT_RENDERER()
{
free(fontpath);
glDeleteProgram(program);
for(auto it = fonts.begin(); it != fonts.end(); it++)
{
FreeFTFace(it->first);
FreeFontGlyphs(it->first);
FreeFontTextures(it->first);
delete it->second;
}
fonts.clear();
glDeleteVertexArrays(1, &vao.handle);
glDeleteBuffers(vao.vbos.size(), &vao.vbos[0]);
}
u32 FONT_RENDERER::LoadFTFace(char* key, const char* filepath, u32 fontSize)
{
if(fonts.count(key) > 0)
{
printf("%s Font %s already present\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = new FONT;
i32 error = FT_New_Face(library, filepath, 0, &font->ftFace);
if(error > 0)
{
printf("%s %d %s", VHM_FT_ERR, error, FT_Error_String(error));
}
font->fontPath = (char*) malloc(strlen(filepath) + 1);
strcpy(font->fontPath, filepath);
FT_Set_Pixel_Sizes(font->ftFace, 0, fontSize);
font->assigned = true;
fonts.insert(std::make_pair(key, font));
return VHM_SUCCESS;
}
u32 FONT_RENDERER::FreeFTFace(char* key)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to free a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = fonts.at(key);
free(font->fontPath);
FT_Done_Face(font->ftFace);
return VHM_SUCCESS;
}
u32 FONT_RENDERER::LoadFontGlyphs(char* key)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to load glyphs of a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = fonts.at(key);
font->maxWidth = 0;
font->maxHeight = 0;
font->capitalBearingY = 0;
u32 gindex;
u64 charcode;
charcode = FT_Get_First_Char(font->ftFace, &gindex);
while(gindex != 0)
{
u32 error = FT_Load_Char(font->ftFace, charcode, FT_LOAD_RENDER);
if(error)
{
printf("%s Error loading character %d\n", VHM_FT_ERR, gindex);
}
if(font->ftFace->glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
{
printf("%s Error where character %c is the incorrect pixel mode (%u)\n", VHM_FT_LOG, (i32) charcode, font->ftFace->glyph->bitmap.pixel_mode);
}
GLYPH* glyph = new GLYPH;
glyph->bitmap = (u8*) malloc(sizeof(u8) * font->ftFace->glyph->bitmap.width * font->ftFace->glyph->bitmap.rows);
memcpy(glyph->bitmap, font->ftFace->glyph->bitmap.buffer, sizeof(unsigned char) * font->ftFace->glyph->bitmap.width * font->ftFace->glyph->bitmap.rows);
glyph->width = font->ftFace->glyph->bitmap.width;
glyph->height = font->ftFace->glyph->bitmap.rows;
glyph->advance = font->ftFace->glyph->advance.x / 64.0;
glyph->bearingX = font->ftFace->glyph->metrics.horiBearingX / 64.0;
glyph->bearingY = font->ftFace->glyph->metrics.horiBearingY / 64.0;
glyph->charcode = charcode;
font->glyphs.insert(std::make_pair(gindex, glyph));
if(charcode == '^')
{
font->capitalBearingY = glyph->bearingY;
}
if((i32) font->ftFace->glyph->bitmap.width > font->maxWidth)
{
font->maxWidth = font->ftFace->glyph->bitmap.width;
}
if((i32) font->ftFace->glyph->bitmap.rows > font->maxHeight)
{
font->maxHeight = font->ftFace->glyph->bitmap.rows;
}
charcode = FT_Get_Next_Char(font->ftFace, charcode, &gindex);
}
return VHM_SUCCESS;
}
u32 FONT_RENDERER::FreeFontGlyphs(char* key)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to free glyphs of a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = fonts.at(key);
for(auto it = font->glyphs.begin(); it != font->glyphs.end(); it++)
{
free(it->second->bitmap);
delete it->second;
}
font->glyphs.clear();
return VHM_SUCCESS;
}
u32 FONT_RENDERER::GenerateFontTextures(char* key)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to create glyph textures of a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = fonts.at(key);
// Delete the previous texture if it exists.
if(font->assignedGL)
{
glDeleteTextures(1, &font->textureHandleGL);
}
// Generates a texture and stores the bitmaps in an OpenGL Texture Array
glGenTextures(1, &font->textureHandleGL);
glBindTexture(GL_TEXTURE_2D_ARRAY, font->textureHandleGL);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
SetMinMag(GL_TEXTURE_2D_ARRAY, GL_LINEAR, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP);
SetTextureArrayStorage(font->textureHandleGL, GL_R8, font->maxWidth, font->maxHeight, font->glyphs.size());
for(std::map<u32, GLYPH*>::iterator it = font->glyphs.begin(); it != font->glyphs.end(); it++)
{
LoadTextureArrayLayer(font->textureHandleGL, it->second->bitmap, 0, 0, it->second->width, it->second->height, it->first, GL_RED);
}
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
font->assignedGL = true;
return VHM_SUCCESS;
}
u32 FONT_RENDERER::FreeFontTextures(char* key)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to free glyph textures of a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = fonts.at(key);
glDeleteTextures(1, &font->textureHandleGL);
return VHM_SUCCESS;
}
u32 FONT_RENDERER::LoadNewFace(char* key, const char* filepath, int fontSize)
{
if(LoadFTFace(key, filepath, fontSize) == VHM_SUCCESS)
{
if(LoadFontGlyphs(key) == VHM_SUCCESS)
{
if(GenerateFontTextures(key) == VHM_SUCCESS)
{
return VHM_SUCCESS;
}
}
}
return VHM_ERROR;
}
u32 FONT_RENDERER::DeriveFace(char* key, u32 newFontSize)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to derive from a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = fonts.at(key);
char* cpyFontPath = (char*) malloc(strlen(font->fontPath) + 1);
strcpy(cpyFontPath, font->fontPath);
FreeFTFace(key);
FreeFontGlyphs(key);
FreeFontTextures(key);
delete font;
fonts.erase(key);
if(LoadFTFace(key, cpyFontPath, newFontSize) == VHM_SUCCESS)
{
free(cpyFontPath);
if(LoadFontGlyphs(key) == VHM_SUCCESS)
{
if(GenerateFontTextures(key) == VHM_SUCCESS)
{
return VHM_SUCCESS;
}
}
}
free(cpyFontPath);
return VHM_ERROR;
}
u32 FONT_RENDERER::RenderText(char* key, const char* text, i32 screenX, i32 screenY, COLOR color)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to render a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return VHM_ERROR;
}
FONT* font = fonts.at(key);
// Binds
glUseProgram(program);
glBindVertexArray(vao.handle);
glBindTexture(GL_TEXTURE_2D_ARRAY, font->textureHandleGL);
// Color matrix uniform
UniformVec3(program, "color", color.vec);
// Orthographic matrix uniform
mat4 projection;
glm_mat4_identity(projection);
glm_ortho(0.0, GetWindowWidth(), GetWindowHeight(), 0.0, 0.0001, 10.0, projection);
UniformMat4(program, "projection", projection);
f32 caret = 0.0;
f32 scale[3] = {(f32) font->maxWidth, (f32) font->maxHeight, 1.0};
for(u32 i = 0; i < strlen(text); i++)
{
u32 charInd = FT_Get_Char_Index(font->ftFace, text[i]);
if(font->glyphs.find(charInd) == font->glyphs.end())
{
continue;
}
GLYPH ch = *font->glyphs.at(charInd);
f32 layer = (float) (i+1) / (strlen(text) + 1);
glUniform1f(glGetUniformLocation(program, "defaultLayerZ"), GFX_LAYER_GUI + layer);
f32 hb = font->capitalBearingY - ch.bearingY;
f32 advance = ch.advance;
f32 bearingX = ch.bearingX;
// Remove bearing from the first letter, so that it's aligned correctly with screenX.
if(i == 0)
{
advance -= bearingX;
bearingX = 0;
}
vec3 translate = {(f32) screenX + (caret + bearingX), (float) screenY + hb, 0.0};
mat4 transformation;
glm_mat4_identity(transformation);
glm_translate(transformation, translate);
glm_scale(transformation, scale);
UniformMat4(program, "transformation", transformation);
glUniform1i(glGetUniformLocation(program, "layer"), FT_Get_Char_Index(font->ftFace, text[i]));
// Drawing
glDrawArrays(GL_TRIANGLES, 0, 12);
caret += advance;
}
// Unbinds
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glBindVertexArray(0);
glUseProgram(0);
return VHM_SUCCESS;
}
f32 FONT_RENDERER::TextWidth(char* key, const char* text)
{
if(fonts.count(key) == 0)
{
printf("%s Unable to gauge the text width of a font (%s) that doesn't exist\n", VHM_FT_ERR, key);
return -1;
}
FONT* font = fonts.at(key);
u32 len = strlen(text);
f32 width = 0;
for(u32 i = 0; i < len; i++)
{
u32 charInd = FT_Get_Char_Index(font->ftFace, text[i]);
if(font->glyphs.find(charInd) == font->glyphs.end())
{
continue;
}
GLYPH* ch = font->glyphs.at(charInd);
if(i == len - 1)
{
width += ch->advance - ch->bearingX;
}
else
{
width += ch->advance;
}
}
return width;
} | 29.130208 | 160 | 0.608886 | [
"render",
"model"
] |
61eb749f4e40e84989415cb76df714f7ca882739 | 13,315 | cpp | C++ | src/camera.cpp | SonicMastr/librw | 5bc003d8cd51eb35ab39cdfba379671f8ddd2c78 | [
"MIT"
] | 4 | 2020-10-12T22:06:13.000Z | 2020-12-03T10:27:52.000Z | src/camera.cpp | SonicMastr/librw | 5bc003d8cd51eb35ab39cdfba379671f8ddd2c78 | [
"MIT"
] | null | null | null | src/camera.cpp | SonicMastr/librw | 5bc003d8cd51eb35ab39cdfba379671f8ddd2c78 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "rwbase.h"
#include "rwerror.h"
#include "rwplg.h"
#include "rwpipeline.h"
#include "rwobjects.h"
#include "rwengine.h"
#define PLUGIN_ID ID_CAMERA
namespace rw {
int32 Camera::numAllocated;
PluginList Camera::s_plglist(sizeof(Camera));
void
defaultBeginUpdateCB(Camera *cam)
{
engine->currentCamera = cam;
Frame::syncDirty();
engine->device.beginUpdate(cam);
}
void
defaultEndUpdateCB(Camera *cam)
{
engine->device.endUpdate(cam);
}
static void
buildPlanes(Camera *cam)
{
V3d *c = cam->frustumCorners;
FrustumPlane *p = cam->frustumPlanes;
V3d v51 = sub(c[1], c[5]);
V3d v73 = sub(c[3], c[7]);
/* Far plane */
p[0].plane.normal = cam->getFrame()->getLTM()->at;
p[0].plane.distance = dot(p[0].plane.normal, c[4]);
p[0].closestX = p[0].plane.normal.x < 0.0f ? 0 : 1;
p[0].closestY = p[0].plane.normal.y < 0.0f ? 0 : 1;
p[0].closestZ = p[0].plane.normal.z < 0.0f ? 0 : 1;
/* Near plane */
p[1].plane.normal = neg(p[0].plane.normal);
p[1].plane.distance = dot(p[1].plane.normal, c[0]);
p[1].closestX = p[1].plane.normal.x < 0.0f ? 0 : 1;
p[1].closestY = p[1].plane.normal.y < 0.0f ? 0 : 1;
p[1].closestZ = p[1].plane.normal.z < 0.0f ? 0 : 1;
/* Right plane */
p[2].plane.normal = normalize(cross(v51,
sub(c[6], c[5])));
p[2].plane.distance = dot(p[2].plane.normal, c[1]);
p[2].closestX = p[2].plane.normal.x < 0.0f ? 0 : 1;
p[2].closestY = p[2].plane.normal.y < 0.0f ? 0 : 1;
p[2].closestZ = p[2].plane.normal.z < 0.0f ? 0 : 1;
/* Top plane */
p[3].plane.normal = normalize(cross(sub(c[4], c[5]),
v51));
p[3].plane.distance = dot(p[3].plane.normal, c[1]);
p[3].closestX = p[3].plane.normal.x < 0.0f ? 0 : 1;
p[3].closestY = p[3].plane.normal.y < 0.0f ? 0 : 1;
p[3].closestZ = p[3].plane.normal.z < 0.0f ? 0 : 1;
/* Left plane */
p[4].plane.normal = normalize(cross(v73,
sub(c[4], c[7])));
p[4].plane.distance = dot(p[4].plane.normal, c[3]);
p[4].closestX = p[4].plane.normal.x < 0.0f ? 0 : 1;
p[4].closestY = p[4].plane.normal.y < 0.0f ? 0 : 1;
p[4].closestZ = p[4].plane.normal.z < 0.0f ? 0 : 1;
/* Bottom plane */
p[5].plane.normal = normalize(cross(sub(c[6], c[7]),
v73));
p[5].plane.distance = dot(p[5].plane.normal, c[3]);
p[5].closestX = p[5].plane.normal.x < 0.0f ? 0 : 1;
p[5].closestY = p[5].plane.normal.y < 0.0f ? 0 : 1;
p[5].closestZ = p[5].plane.normal.z < 0.0f ? 0 : 1;
}
static void
buildClipPersp(Camera *cam)
{
Matrix *ltm = cam->getFrame()->getLTM();
/* First we calculate the 4 points on the view window. */
V3d up = scale(ltm->up, cam->viewWindow.y);
V3d left = scale(ltm->right, cam->viewWindow.x);
V3d *c = cam->frustumCorners;
c[0] = add(add(ltm->at, up), left); // top left
c[1] = sub(add(ltm->at, up), left); // top right
c[2] = sub(sub(ltm->at, up), left); // bottom right
c[3] = add(sub(ltm->at, up), left); // bottom left
/* Now Calculate near and far corners. */
V3d off = sub(scale(ltm->up, cam->viewOffset.y),
scale(ltm->right, cam->viewOffset.x));
for(int32 i = 0; i < 4; i++){
V3d corner = sub(cam->frustumCorners[i], off);
V3d pos = add(ltm->pos, off);
c[i] = add(scale(corner, cam->nearPlane), pos);
c[i+4] = add(scale(corner, cam->farPlane), pos);
}
buildPlanes(cam);
}
static void
buildClipParallel(Camera *cam)
{
Matrix *ltm = cam->getFrame()->getLTM();
float32 nearoffx = -(1.0f - cam->nearPlane)*cam->viewOffset.x;
float32 nearoffy = (1.0f - cam->nearPlane)*cam->viewOffset.y;
float32 faroffx = -(1.0f - cam->farPlane)*cam->viewOffset.x;
float32 faroffy = (1.0f - cam->farPlane)*cam->viewOffset.y;
V3d *c = cam->frustumCorners;
c[0].x = nearoffx + cam->viewWindow.x;
c[0].y = nearoffy + cam->viewWindow.y;
c[0].z = cam->nearPlane;
c[1].x = nearoffx - cam->viewWindow.x;
c[1].y = nearoffy + cam->viewWindow.y;
c[1].z = cam->nearPlane;
c[2].x = nearoffx - cam->viewWindow.x;
c[2].y = nearoffy - cam->viewWindow.y;
c[2].z = cam->nearPlane;
c[3].x = nearoffx + cam->viewWindow.x;
c[3].y = nearoffy - cam->viewWindow.y;
c[3].z = cam->nearPlane;
c[4].x = faroffx + cam->viewWindow.x;
c[4].y = faroffy + cam->viewWindow.y;
c[4].z = cam->farPlane;
c[5].x = faroffx - cam->viewWindow.x;
c[5].y = faroffy + cam->viewWindow.y;
c[5].z = cam->farPlane;
c[6].x = faroffx - cam->viewWindow.x;
c[6].y = faroffy - cam->viewWindow.y;
c[6].z = cam->farPlane;
c[7].x = faroffx + cam->viewWindow.x;
c[7].y = faroffy - cam->viewWindow.y;
c[7].z = cam->farPlane;
V3d::transformPoints(c, c, 8, ltm);
buildPlanes(cam);
}
static void
cameraSync(ObjectWithFrame *obj)
{
/*
* RW projection matrix looks like this:
* (cf. Camera View Matrix white paper)
* w = viewWindow width
* h = viewWindow height
* o = view offset
*
* perspective:
* 1/2w 0 ox/2w + 1/2 -ox/2w
* 0 -1/2h -oy/2h + 1/2 oy/2h
* 0 0 1 0
* 0 0 1 0
*
* parallel:
* 1/2w 0 ox/2w -ox/2w + 1/2
* 0 -1/2h -oy/2h oy/2h + 1/2
* 0 0 1 0
* 0 0 0 1
*
* The view matrix transforms from world to clip space, it is however
* not used for OpenGL or D3D since transformation to camera space
* and to clip space are handled by separate matrices there.
* On these platforms the two matrices are built in the platform's
* beginUpdate function.
* On the PS2 the z- and w-rows are the same and the
* 1/2 translation/shear is removed again on the VU1 by
* subtracting the w-row/2 from the x- and y-rows.
*
* perspective:
* 1/2w 0 ox/2w -ox/2w
* 0 -1/2h -oy/2h oy/2h
* 0 0 1 0
* 0 0 1 0
*
* parallel:
* 1/2w 0 ox/2w -ox/2w
* 0 -1/2h -oy/2h oy/2h
* 0 0 1 0
* 0 0 0 1
*
* RW builds this matrix directly without using explicit
* inversion and matrix multiplication.
*/
Camera *cam = (Camera*)obj;
Matrix inv, proj;
Matrix::invertOrthonormal(&inv, cam->getFrame()->getLTM());
inv.right.x = -inv.right.x;
inv.up.x = -inv.up.x;
inv.at.x = -inv.at.x;
inv.pos.x = -inv.pos.x;
float32 xscl = 1.0f/(2.0f*cam->viewWindow.x);
float32 yscl = 1.0f/(2.0f*cam->viewWindow.y);
proj.flags = 0;
proj.right.x = xscl;
proj.right.y = 0.0f;
proj.right.z = 0.0f;
proj.up.x = 0.0f;
proj.up.y = -yscl;
proj.up.z = 0.0f;
if(cam->projection == Camera::PERSPECTIVE){
proj.pos.x = -cam->viewOffset.x*xscl;
proj.pos.y = cam->viewOffset.y*yscl;
proj.pos.z = 0.0f;
proj.at.x = -proj.pos.x + 0.5f;
proj.at.y = -proj.pos.y + 0.5f;
proj.at.z = 1.0f;
proj.optimize();
Matrix::mult(&cam->viewMatrix, &inv, &proj);
buildClipPersp(cam);
}else{
proj.at.x = cam->viewOffset.x*xscl;
proj.at.y = -cam->viewOffset.y*yscl;
proj.at.z = 1.0f;
proj.pos.x = -proj.at.x + 0.5f;
proj.pos.y = -proj.at.y + 0.5f;
proj.pos.z = 0.0f;
proj.optimize();
Matrix::mult(&cam->viewMatrix, &inv, &proj);
buildClipParallel(cam);
}
cam->frustumBoundBox.calculate(cam->frustumCorners, 8);
}
void
worldBeginUpdateCB(Camera *cam)
{
engine->currentWorld = cam->world;
cam->originalBeginUpdate(cam);
}
void
worldEndUpdateCB(Camera *cam)
{
cam->originalEndUpdate(cam);
}
static void
worldCameraSync(ObjectWithFrame *obj)
{
Camera *camera = (Camera*)obj;
camera->originalSync(obj);
}
Camera*
Camera::create(void)
{
Camera *cam = (Camera*)rwMalloc(s_plglist.size, MEMDUR_EVENT | ID_CAMERA);
if(cam == nil){
RWERROR((ERR_ALLOC, s_plglist.size));
return nil;
}
numAllocated++;
cam->object.object.init(Camera::ID, 0);
cam->object.syncCB = cameraSync;
cam->beginUpdateCB = defaultBeginUpdateCB;
cam->endUpdateCB = defaultEndUpdateCB;
cam->viewWindow.set(1.0f, 1.0f);
cam->viewOffset.set(0.0f, 0.0f);
cam->nearPlane = 0.05f;
cam->farPlane = 10.0f;
cam->fogPlane = 5.0f;
cam->projection = Camera::PERSPECTIVE;
cam->frameBuffer = nil;
cam->zBuffer = nil;
// clump extension
cam->clump = nil;
cam->inClump.init();
// world extension
cam->world = nil;
cam->originalSync = cam->object.syncCB;
cam->originalBeginUpdate = cam->beginUpdateCB;
cam->originalEndUpdate = cam->endUpdateCB;
cam->object.syncCB = worldCameraSync;
cam->beginUpdateCB = worldBeginUpdateCB;
cam->endUpdateCB = worldEndUpdateCB;
s_plglist.construct(cam);
return cam;
}
Camera*
Camera::clone(void)
{
Camera *cam = Camera::create();
if(cam == nil)
return nil;
cam->object.object.copy(&this->object.object);
cam->setFrame(this->getFrame());
cam->viewWindow = this->viewWindow;
cam->viewOffset = this->viewOffset;
cam->nearPlane = this->nearPlane;
cam->farPlane = this->farPlane;
cam->fogPlane = this->fogPlane;
cam->projection = this->projection;
cam->frameBuffer = this->frameBuffer;
cam->zBuffer = this->zBuffer;
if(this->world)
this->world->addCamera(cam);
s_plglist.copy(cam, this);
return cam;
}
void
Camera::destroy(void)
{
s_plglist.destruct(this);
assert(this->clump == nil);
assert(this->world == nil);
this->setFrame(nil);
rwFree(this);
numAllocated--;
}
void
Camera::clear(RGBA *col, uint32 mode)
{
engine->device.clearCamera(this, col, mode);
}
void
Camera::showRaster(uint32 flags)
{
this->frameBuffer->show(flags);
}
void
calczShiftScale(Camera *cam)
{
float32 n = cam->nearPlane;
float32 f = cam->farPlane;
float32 N = engine->device.zNear;
float32 F = engine->device.zFar;
// RW does this
N += (F - N)/10000.0f;
F -= (F - N)/10000.0f;
if(cam->projection == Camera::PERSPECTIVE){
cam->zScale = (N - F)*n*f/(f - n);
cam->zShift = (F*f - N*n)/(f - n);
}else{
cam->zScale = (F - N)/(f -n);
cam->zShift = (N*f - F*n)/(f - n);
}
}
void
Camera::setNearPlane(float32 near)
{
this->nearPlane = near;
calczShiftScale(this);
if(this->getFrame())
this->getFrame()->updateObjects();
}
void
Camera::setFarPlane(float32 far)
{
this->farPlane = far;
calczShiftScale(this);
if(this->getFrame())
this->getFrame()->updateObjects();
}
void
Camera::setViewWindow(const V2d *window)
{
this->viewWindow = *window;
if(this->getFrame())
this->getFrame()->updateObjects();
}
void
Camera::setViewOffset(const V2d *offset)
{
this->viewOffset = *offset;
if(this->getFrame())
this->getFrame()->updateObjects();
}
void
Camera::setProjection(int32 proj)
{
this->projection = proj;
if(this->getFrame())
this->getFrame()->updateObjects();
}
int32
Camera::frustumTestSphere(const Sphere *s) const
{
int32 res = SPHEREINSIDE;
const FrustumPlane *p = this->frustumPlanes;
for(int32 i = 0; i < 6; i++){
float32 dist = dot(p->plane.normal, s->center) - p->plane.distance;
if(s->radius < dist)
return SPHEREOUTSIDE;
if(s->radius > -dist)
res = SPHEREBOUNDARY;
p++;
}
return res;
}
struct CameraChunkData
{
V2d viewWindow;
V2d viewOffset;
float32 nearPlane, farPlane;
float32 fogPlane;
int32 projection;
};
Camera*
Camera::streamRead(Stream *stream)
{
CameraChunkData buf;
if(!findChunk(stream, ID_STRUCT, nil, nil)){
RWERROR((ERR_CHUNK, "STRUCT"));
return nil;
}
stream->read32(&buf, sizeof(CameraChunkData));
Camera *cam = Camera::create();
cam->viewWindow = buf.viewWindow;
cam->viewOffset = buf.viewOffset;
cam->nearPlane = buf.nearPlane;
cam->farPlane = buf.farPlane;
cam->fogPlane = buf.fogPlane;
cam->projection = buf.projection;
if(s_plglist.streamRead(stream, cam))
return cam;
cam->destroy();
return nil;
}
bool
Camera::streamWrite(Stream *stream)
{
CameraChunkData buf;
writeChunkHeader(stream, ID_CAMERA, this->streamGetSize());
writeChunkHeader(stream, ID_STRUCT, sizeof(CameraChunkData));
buf.viewWindow = this->viewWindow;
buf.viewOffset = this->viewOffset;
buf.nearPlane = this->nearPlane;
buf.farPlane = this->farPlane;
buf.fogPlane = this->fogPlane;
buf.projection = this->projection;
stream->write32(&buf, sizeof(CameraChunkData));
s_plglist.streamWrite(stream, this);
return true;
}
uint32
Camera::streamGetSize(void)
{
return 12 + sizeof(CameraChunkData) + 12 +
s_plglist.streamGetSize(this);
}
// Assumes horizontal FOV for 4:3, but we convert to vertical FOV
void
Camera::setFOV(float32 hfov, float32 ratio)
{
V2d v;
float w, h;
w = (float)this->frameBuffer->width;
h = (float)this->frameBuffer->height;
if(w < 1 || h < 1){
w = 1;
h = 1;
}
hfov = hfov*3.14159f/360.0f; // deg to rad and halved
float ar1 = 4.0f/3.0f;
float ar2 = w/h;
float vfov = atanf(tanf(hfov/2) / ar1) *2;
hfov = atanf(tanf(vfov/2) * ar2) *2;
float32 a = tanf(hfov);
v.set(a, a/ratio);
this->setViewWindow(&v);
v.set(0.0f, 0.0f);
this->setViewOffset(&v);
}
}
| 25.361905 | 76 | 0.601051 | [
"object"
] |
61ecd02a0d12532fb71f7976cfd37df46086d97c | 29,529 | cpp | C++ | src/server/game/AuctionHouse/AuctionHouseMgr.cpp | Arkania/ArkCORE | 2484554a7b54be0b652f9dc3c5a8beba79df9fbf | [
"OpenSSL"
] | 42 | 2015-01-05T10:00:07.000Z | 2022-02-18T14:51:33.000Z | src/server/game/AuctionHouse/AuctionHouseMgr.cpp | superllout/WOW | 3d0eeb940cccf8ab7854259172c6d75a85ee4f7d | [
"OpenSSL"
] | null | null | null | src/server/game/AuctionHouse/AuctionHouseMgr.cpp | superllout/WOW | 3d0eeb940cccf8ab7854259172c6d75a85ee4f7d | [
"OpenSSL"
] | 31 | 2015-01-09T02:04:29.000Z | 2021-09-01T13:20:20.000Z | /*
* Copyright (C) 2005 - 2013 MaNGOS <http://www.getmangos.com/>
*
* Copyright (C) 2008 - 2013 Trinity <http://www.trinitycore.org/>
*
* Copyright (C) 2010 - 2013 ProjectSkyfire <http://www.projectskyfire.org/>
*
* Copyright (C) 2011 - 2013 ArkCORE <http://www.arkania.net/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gamePCH.h"
#include "Common.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "DatabaseEnv.h"
#include "SQLStorage.h"
#include "DBCStores.h"
#include "ScriptMgr.h"
#include "AccountMgr.h"
#include "AuctionHouseMgr.h"
#include "Item.h"
#include "Language.h"
#include "Logging/Log.h"
#include <vector>
enum eAuctionHouse
{
AH_MINIMUM_DEPOSIT = 100,
};
AuctionHouseMgr::AuctionHouseMgr ()
{
}
AuctionHouseMgr::~AuctionHouseMgr ()
{
for (ItemMap::iterator itr = mAitems.begin(); itr != mAitems.end(); ++itr)
delete itr->second;
}
AuctionHouseObject * AuctionHouseMgr::GetAuctionsMap (uint32 factionTemplateId)
{
if (sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
return &mNeutralAuctions;
// team have linked auction houses
FactionTemplateEntry const* u_entry = sFactionTemplateStore.LookupEntry(factionTemplateId);
if (!u_entry)
return &mNeutralAuctions;
else if (u_entry->ourMask & FACTION_MASK_ALLIANCE)
return &mAllianceAuctions;
else if (u_entry->ourMask & FACTION_MASK_HORDE)
return &mHordeAuctions;
else
return &mNeutralAuctions;
}
uint32 AuctionHouseMgr::GetAuctionDeposit (AuctionHouseEntry const* entry, uint32 time, Item *pItem, uint32 count)
{
uint32 MSV = pItem->GetProto()->SellPrice;
if (MSV <= 0)
return AH_MINIMUM_DEPOSIT;
float multiplier = CalculatePctN(float(entry->depositPercent), 3);
uint32 timeHr = (((time / 60) / 60) / 12);
uint32 deposit = uint32(multiplier * MSV * count / 3) * timeHr * 3;
sLog->outDebug(LOG_FILTER_AUCTIONHOUSE, "MSV: %u", MSV);
sLog->outDebug(LOG_FILTER_AUCTIONHOUSE, "Items: %u", count);
sLog->outDebug(LOG_FILTER_AUCTIONHOUSE, "Multiplier: %f", multiplier);
sLog->outDebug(LOG_FILTER_AUCTIONHOUSE, "Deposit: %u", deposit);
if (deposit < AH_MINIMUM_DEPOSIT)
return AH_MINIMUM_DEPOSIT;
else
return deposit;
}
//does not clear ram
void AuctionHouseMgr::SendAuctionWonMail (AuctionEntry *auction, SQLTransaction& trans)
{
Item *pItem = GetAItem(auction->item_guidlow);
if (!pItem)
return;
uint32 bidder_accId = 0;
uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
Player *bidder = sObjectMgr->GetPlayer(bidder_guid);
// data for gm.log
if (sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE))
{
uint32 bidder_security = 0;
std::string bidder_name;
if (bidder)
{
bidder_accId = bidder->GetSession()->GetAccountId();
bidder_security = bidder->GetSession()->GetSecurity();
bidder_name = bidder->GetName();
}
else
{
bidder_accId = sObjectMgr->GetPlayerAccountIdByGUID(bidder_guid);
bidder_security = sAccountMgr->GetSecurity(bidder_accId, realmID);
if (bidder_security > SEC_PLAYER) // not do redundant DB requests
{
if (!sObjectMgr->GetPlayerNameByGUID(bidder_guid, bidder_name))
bidder_name = sObjectMgr->GetArkCoreStringForDBCLocale(LANG_UNKNOWN);
}
}
if (bidder_security > SEC_PLAYER)
{
std::string owner_name;
if (!sObjectMgr->GetPlayerNameByGUID(auction->owner, owner_name))
owner_name = sObjectMgr->GetArkCoreStringForDBCLocale(LANG_UNKNOWN);
uint32 owner_accid = sObjectMgr->GetPlayerAccountIdByGUID(auction->owner);
sLog->outCommand(bidder_accId, "GM %s (Account: %u) won item in auction: %s (Entry: %u Count: %u) and pay money: %u. Original owner %s (Account: %u)", bidder_name.c_str(), bidder_accId, pItem->GetProto()->Name1, pItem->GetEntry(), pItem->GetCount(), auction->bid, owner_name.c_str(), owner_accid);
}
}
// receiver exist
if (bidder || bidder_accId)
{
std::ostringstream msgAuctionWonSubject;
msgAuctionWonSubject << auction->item_template << ":0:" << AUCTION_WON;
std::ostringstream msgAuctionWonBody;
msgAuctionWonBody.width(16);
msgAuctionWonBody << std::right << std::hex << auction->owner;
msgAuctionWonBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
sLog->outDebug(LOG_FILTER_AUCTIONHOUSE, "AuctionWon body string : %s", msgAuctionWonBody.str().c_str());
// set owner to bidder (to prevent delete item with sender char deleting)
// owner in `data` will set at mail receive and item extracting
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_ITEM_OWNER);
stmt->setUInt32(0, auction->bidder);
stmt->setUInt32(1, pItem->GetGUIDLow());
trans->Append(stmt);
if (bidder)
{
bidder->GetSession()->SendAuctionBidderNotification(auction->GetHouseId(), auction->Id, bidder_guid, 0, 0, auction->item_template);
// FIXME: for offline player need also
bidder->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS, 1);
}
MailDraft(msgAuctionWonSubject.str(), msgAuctionWonBody.str()).AddItem(pItem).SendMailTo(trans, MailReceiver(bidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED);
}
}
void AuctionHouseMgr::SendAuctionSalePendingMail (AuctionEntry * auction, SQLTransaction& trans)
{
uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
Player *owner = sObjectMgr->GetPlayer(owner_guid);
uint32 owner_accId = sObjectMgr->GetPlayerAccountIdByGUID(owner_guid);
// owner exist (online or offline)
if (owner || owner_accId)
{
std::ostringstream msgAuctionSalePendingSubject;
msgAuctionSalePendingSubject << auction->item_template << ":0:" << AUCTION_SALE_PENDING;
std::ostringstream msgAuctionSalePendingBody;
uint32 auctionCut = auction->GetAuctionCut();
time_t distrTime = time(NULL) + sWorld->getIntConfig(CONFIG_MAIL_DELIVERY_DELAY);
msgAuctionSalePendingBody.width(16);
msgAuctionSalePendingBody << std::right << std::hex << auction->bidder;
msgAuctionSalePendingBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
msgAuctionSalePendingBody << ":" << auction->deposit << ":" << auctionCut << ":0:";
msgAuctionSalePendingBody << secsToTimeBitFields(distrTime);
sLog->outDebug(LOG_FILTER_AUCTIONHOUSE, "AuctionSalePending body string : %s", msgAuctionSalePendingBody.str().c_str());
MailDraft(msgAuctionSalePendingSubject.str(), msgAuctionSalePendingBody.str()).SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED);
}
}
//call this method to send mail to auction owner, when auction is successful, it does not clear ram
void AuctionHouseMgr::SendAuctionSuccessfulMail (AuctionEntry * auction, SQLTransaction& trans)
{
uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
Player *owner = sObjectMgr->GetPlayer(owner_guid);
uint32 owner_accId = sObjectMgr->GetPlayerAccountIdByGUID(owner_guid);
// owner exist
if (owner || owner_accId)
{
std::ostringstream msgAuctionSuccessfulSubject;
msgAuctionSuccessfulSubject << auction->item_template << ":0:" << AUCTION_SUCCESSFUL;
std::ostringstream auctionSuccessfulBody;
uint32 auctionCut = auction->GetAuctionCut();
auctionSuccessfulBody.width(16);
auctionSuccessfulBody << std::right << std::hex << auction->bidder;
auctionSuccessfulBody << std::dec << ":" << auction->bid << ":" << auction->buyout;
auctionSuccessfulBody << ":" << auction->deposit << ":" << auctionCut;
sLog->outDebug(LOG_FILTER_AUCTIONHOUSE, "AuctionSuccessful body string : %s", auctionSuccessfulBody.str().c_str());
uint64 profit = auction->bid + auction->deposit - auctionCut;
//FIXME: what do if owner offline
if (owner)
{
owner->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS, profit);
owner->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD, auction->bid);
//send auction owner notification, bidder must be current!
owner->GetSession()->SendAuctionOwnerNotification(auction);
}
MailDraft(msgAuctionSuccessfulSubject.str(), auctionSuccessfulBody.str()).AddMoney(profit).SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED, sWorld->getIntConfig(CONFIG_MAIL_DELIVERY_DELAY));
}
}
//does not clear ram
void AuctionHouseMgr::SendAuctionExpiredMail (AuctionEntry * auction, SQLTransaction& trans)
{
//return an item in auction to its owner by mail
Item *pItem = GetAItem(auction->item_guidlow);
if (!pItem)
return;
uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
Player *owner = sObjectMgr->GetPlayer(owner_guid);
uint32 owner_accId = sObjectMgr->GetPlayerAccountIdByGUID(owner_guid);
// owner exist
if (owner || owner_accId)
{
std::ostringstream subject;
subject << auction->item_template << ":0:" << AUCTION_EXPIRED << ":0:0";
if (owner)
owner->GetSession()->SendAuctionOwnerNotification(auction);
MailDraft(subject.str(), "") // TODO: fix body
.AddItem(pItem).SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED, 0);
}
}
void AuctionHouseMgr::SendAuctionRemovedMail (AuctionEntry * auction, SQLTransaction& trans)
{
uint64 owner_guid = MAKE_NEW_GUID(auction->owner, 0, HIGHGUID_PLAYER);
Player *owner = sObjectMgr->GetPlayer(owner_guid);
if (owner)
{
std::ostringstream subject;
subject << auction->item_template << ":0:" << AUCTION_CANCELED << ":0:0";
if (owner)
owner->GetSession()->SendAuctionRemovedNotification(auction);
MailDraft(subject.str(), "").SendMailTo(trans, MailReceiver(owner, auction->owner), auction, MAIL_CHECK_MASK_COPIED, 0);
}
}
//this function sends mail to old bidder
void AuctionHouseMgr::SendAuctionOutbiddedMail (AuctionEntry *auction, uint64 newPrice, Player* newBidder, SQLTransaction& trans)
{
uint64 oldBidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
Player *oldBidder = sObjectMgr->GetPlayer(oldBidder_guid);
uint32 oldBidder_accId = 0;
if (!oldBidder)
oldBidder_accId = sObjectMgr->GetPlayerAccountIdByGUID(oldBidder_guid);
// old bidder exist
if (oldBidder || oldBidder_accId)
{
std::ostringstream msgAuctionOutbiddedSubject;
msgAuctionOutbiddedSubject << auction->item_template << ":0:" << AUCTION_OUTBIDDED << ":0:0";
if (oldBidder && newBidder)
oldBidder->GetSession()->SendAuctionBidderNotification(auction->GetHouseId(), auction->Id, newBidder->GetGUID(), newPrice, auction->GetAuctionOutBid(), auction->item_template);
MailDraft(msgAuctionOutbiddedSubject.str(), "") // TODO: fix body
.AddMoney(auction->bid).SendMailTo(trans, MailReceiver(oldBidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED);
}
}
//this function sends mail, when auction is cancelled to old bidder
void AuctionHouseMgr::SendAuctionCancelledToBidderMail (AuctionEntry* auction, SQLTransaction& trans)
{
uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER);
Player *bidder = sObjectMgr->GetPlayer(bidder_guid);
uint32 bidder_accId = 0;
if (!bidder)
bidder_accId = sObjectMgr->GetPlayerAccountIdByGUID(bidder_guid);
// bidder exist
if (bidder || bidder_accId)
{
std::ostringstream msgAuctionCancelledSubject;
msgAuctionCancelledSubject << auction->item_template << ":0:" << AUCTION_CANCELLED_TO_BIDDER << ":0:0";
MailDraft(msgAuctionCancelledSubject.str(), "") // TODO: fix body
.AddMoney(auction->bid).SendMailTo(trans, MailReceiver(bidder, auction->bidder), auction, MAIL_CHECK_MASK_COPIED);
}
}
void AuctionHouseMgr::LoadAuctionItems ()
{
uint32 oldMSTime = getMSTime();
// data needs to be at first place for Item::LoadFromDB
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_AUCTION_ITEMS);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
{
sLog->outString(">> Loaded 0 auction items. DB table `auctionhouse` or `item_instance` is empty!");
sLog->outString();
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 item_guid = fields[11].GetUInt32();
uint32 item_template = fields[12].GetUInt32();
ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
if (!proto)
{
sLog->outError("AuctionHouseMgr::LoadAuctionItems: Unknown item (GUID: %u id: #%u) in auction, skipped.", item_guid, item_template);
continue;
}
Item *item = NewItemOrBag(proto);
if (!item->LoadFromDB(item_guid, 0, fields, item_template))
{
delete item;
continue;
}
AddAItem(item);
++count;
}
while (result->NextRow());
sLog->outString(">> Loaded %u auction items in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void AuctionHouseMgr::LoadAuctions ()
{
uint32 oldMSTime = getMSTime();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_AUCTIONS);
PreparedQueryResult result = CharacterDatabase.Query(stmt);
if (!result)
{
sLog->outString(">> Loaded 0 auctions. DB table `auctionhouse` is empty.");
sLog->outString();
return;
}
uint32 count = 0;
SQLTransaction trans = CharacterDatabase.BeginTransaction();
do
{
Field* fields = result->Fetch();
AuctionEntry *aItem = new AuctionEntry();
if (!aItem->LoadFromDB(fields))
{
aItem->DeleteFromDB(trans);
delete aItem;
continue;
}
GetAuctionsMap(aItem->factionTemplateId)->AddAuction(aItem);
count++;
}
while (result->NextRow());
CharacterDatabase.CommitTransaction(trans);
sLog->outString(">> Loaded %u auctions in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void AuctionHouseMgr::AddAItem (Item* it)
{
ASSERT(it);
ASSERT(mAitems.find(it->GetGUIDLow()) == mAitems.end());
mAitems[it->GetGUIDLow()] = it;
}
bool AuctionHouseMgr::RemoveAItem (uint32 id)
{
ItemMap::iterator i = mAitems.find(id);
if (i == mAitems.end())
return false;
mAitems.erase(i);
return true;
}
void AuctionHouseMgr::Update ()
{
mHordeAuctions.Update();
mAllianceAuctions.Update();
mNeutralAuctions.Update();
}
AuctionHouseEntry const* AuctionHouseMgr::GetAuctionHouseEntry (uint32 factionTemplateId)
{
uint32 houseid = 7; // goblin auction house
if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION))
{
//FIXME: found way for proper auctionhouse selection by another way
// AuctionHouse.dbc have faction field with _player_ factions associated with auction house races.
// but no easy way convert creature faction to player race faction for specific city
switch (factionTemplateId)
{
case 12:
houseid = 1;
break; // human
case 29:
houseid = 6;
break; // orc, and generic for horde
case 55:
houseid = 2;
break; // dwarf, and generic for alliance
case 68:
houseid = 4;
break; // undead
case 80:
houseid = 3;
break; // n-elf
case 104:
houseid = 5;
break; // trolls
case 120:
houseid = 7;
break; // booty bay, neutral
case 474:
houseid = 7;
break; // gadgetzan, neutral
case 855:
houseid = 7;
break; // everlook, neutral
case 1604:
houseid = 6;
break; // b-elfs,
default: // for unknown case
{
FactionTemplateEntry const* u_entry = sFactionTemplateStore.LookupEntry(factionTemplateId);
if (!u_entry)
houseid = 7; // goblin auction house
else if (u_entry->ourMask & FACTION_MASK_ALLIANCE)
houseid = 1; // human auction house
else if (u_entry->ourMask & FACTION_MASK_HORDE)
houseid = 6; // orc auction house
else
houseid = 7; // goblin auction house
break;
}
}
}
return sAuctionHouseStore.LookupEntry(houseid);
}
void AuctionHouseObject::AddAuction (AuctionEntry *auction)
{
ASSERT(auction);
AuctionsMap[auction->Id] = auction;
sScriptMgr->OnAuctionAdd(this, auction);
}
bool AuctionHouseObject::RemoveAuction (AuctionEntry *auction, uint32 /*item_template*/)
{
bool wasInMap = AuctionsMap.erase(auction->Id) ? true : false;
sScriptMgr->OnAuctionRemove(this, auction);
// we need to delete the entry, it is not referenced any more
delete auction;
return wasInMap;
}
void AuctionHouseObject::Update ()
{
time_t curTime = sWorld->GetGameTime();
///- Handle expired auctions
// If storage is empty, no need to update. next == NULL in this case.
if (AuctionsMap.empty())
return;
QueryResult result = CharacterDatabase.PQuery("SELECT id FROM auctionhouse WHERE time <= %u ORDER BY TIME ASC", (uint32) curTime + 60);
if (!result)
return;
do
{
// from auctionhousehandler.cpp, creates auction pointer & player pointer
AuctionEntry* auction = GetAuction(result->Fetch()->GetUInt32());
if (!auction)
continue;
SQLTransaction trans = CharacterDatabase.BeginTransaction();
///- Either cancel the auction if there was no bidder
if (auction->bidder == 0)
{
sAuctionMgr->SendAuctionExpiredMail(auction, trans);
sScriptMgr->OnAuctionExpire(this, auction);
}
///- Or perform the transaction
else
{
//we should send an "item sold" message if the seller is online
//we send the item to the winner
//we send the money to the seller
sAuctionMgr->SendAuctionSuccessfulMail(auction, trans);
sAuctionMgr->SendAuctionWonMail(auction, trans);
sScriptMgr->OnAuctionSuccessful(this, auction);
}
uint32 item_template = auction->item_template;
///- In any case clear the auction
auction->DeleteFromDB(trans);
CharacterDatabase.CommitTransaction(trans);
RemoveAuction(auction, item_template);
sAuctionMgr->RemoveAItem(auction->item_guidlow);
}
while (result->NextRow());
}
void AuctionHouseObject::BuildListBidderItems (WorldPacket& data, Player* player, uint32& count, uint32& totalcount)
{
for (AuctionEntryMap::const_iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); ++itr)
{
AuctionEntry *Aentry = itr->second;
if (Aentry && Aentry->bidder == player->GetGUIDLow())
{
if (itr->second->BuildAuctionInfo(data))
++count;
++totalcount;
}
}
}
void AuctionHouseObject::BuildListOwnerItems (WorldPacket& data, Player* player, uint32& count, uint32& totalcount)
{
for (AuctionEntryMap::const_iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); ++itr)
{
AuctionEntry *Aentry = itr->second;
if (Aentry && Aentry->owner == player->GetGUIDLow())
{
if (Aentry->BuildAuctionInfo(data))
++count;
++totalcount;
}
}
}
void AuctionHouseObject::BuildListAuctionItems (WorldPacket& data, Player* player, std::wstring const& wsearchedname, uint32 listfrom, uint8 levelmin, uint8 levelmax, uint8 usable, uint32 inventoryType, uint32 itemClass, uint32 itemSubClass, uint32 quality, uint32& count, uint32& totalcount)
{
int loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
int locdbc_idx = player->GetSession()->GetSessionDbcLocale();
for (AuctionEntryMap::const_iterator itr = AuctionsMap.begin(); itr != AuctionsMap.end(); ++itr)
{
AuctionEntry *Aentry = itr->second;
Item *item = sAuctionMgr->GetAItem(Aentry->item_guidlow);
if (!item)
continue;
ItemPrototype const *proto = item->GetProto();
if (itemClass != 0xffffffff && proto->Class != itemClass)
continue;
if (itemSubClass != 0xffffffff && proto->SubClass != itemSubClass)
continue;
if (inventoryType != 0xffffffff && proto->InventoryType != inventoryType)
continue;
if (quality != 0xffffffff && proto->Quality != quality)
continue;
if (levelmin != 0x00 && (proto->RequiredLevel < levelmin || (levelmax != 0x00 && proto->RequiredLevel > levelmax)))
continue;
if (usable != 0x00 && player->CanUseItem(item) != EQUIP_ERR_OK)
continue;
// Allow search by suffix (ie: of the Monkey) or partial name (ie: Monkey)
// No need to do any of this if no search term was entered
if (!wsearchedname.empty())
{
std::string name = proto->Name1;
if (name.empty())
continue;
// local name
if (loc_idx >= 0)
if (ItemLocale const *il = sObjectMgr->GetItemLocale(proto->ItemId))
sObjectMgr->GetLocaleString(il->Name, loc_idx, name);
// DO NOT use GetItemEnchantMod(proto->RandomProperty) as it may return a result
// that matches the search but it may not equal item->GetItemRandomPropertyId()
// used in BuildAuctionInfo() which then causes wrong items to be listed
int32 propRefID = item->GetItemRandomPropertyId();
if (propRefID)
{
// Append the suffix to the name (ie: of the Monkey) if one exists
// These are found in ItemRandomProperties.dbc, not ItemRandomSuffix.dbc
// even though the DBC names seem misleading
const ItemRandomPropertiesEntry *itemRandProp = sItemRandomPropertiesStore.LookupEntry(propRefID);
if (itemRandProp)
{
DBCString temp = itemRandProp->nameSuffix;
//char* temp = itemRandProp->nameSuffix;
// dbc local name
if (temp)
{
if (locdbc_idx >= 0)
{
// Append the suffix (ie: of the Monkey) to the name using localization
name += " ";
name += temp;
}
else
{
// Invalid localization? Append the suffix using default enUS
name += " ";
name += temp;
}
}
}
}
// Perform the search (with or without suffix)
if (!Utf8FitTo(name, wsearchedname))
continue;
}
// Add the item if no search term or if entered search term was found
if (count < 50 && totalcount >= listfrom)
{
++count;
Aentry->BuildAuctionInfo(data);
}
++totalcount;
}
}
//this function inserts to WorldPacket auction's data
bool AuctionEntry::BuildAuctionInfo (WorldPacket & data) const
{
Item *pItem = sAuctionMgr->GetAItem(item_guidlow);
if (!pItem)
{
sLog->outError("auction to item, that doesn't exist !!!!");
return false;
}
data << uint32(Id);
data << uint32(pItem->GetEntry());
for (uint8 i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
{
data << uint32(pItem->GetEnchantmentId(EnchantmentSlot(i)));
data << uint32(pItem->GetEnchantmentDuration(EnchantmentSlot(i)));
data << uint32(pItem->GetEnchantmentCharges(EnchantmentSlot(i)));
}
for (uint8 i = 0; i < 2; ++i)
{
data << uint32(0);
data << uint32(0);
data << uint32(0);
}
data << int32(pItem->GetItemRandomPropertyId()); //random item property id
data << uint32(pItem->GetItemSuffixFactor()); //SuffixFactor
data << uint32(pItem->GetCount()); //item->count
data << uint32(pItem->GetSpellCharges()); //item->charge FFFFFFF
data << uint32(0); //Unknown
data << uint64(owner); //Auction->owner
data << uint64(startbid); //Auction->startbid (not sure if useful)
data << uint64(bid ? GetAuctionOutBid() : 0);
//minimal outbid
data << uint64(buyout); //auction->buyout
data << uint32((expire_time - time(NULL)) * IN_MILLISECONDS); //time left
data << uint64(bidder); //auction->bidder current
data << uint64(bid); //current bid
return true;
}
uint32 AuctionEntry::GetAuctionCut () const
{
int32 cut = int32(CalculatePctU(sWorld->getRate(RATE_AUCTION_CUT), auctionHouseEntry->cutPercent)) * bid;
return std::max(cut, 0);
}
/// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c
uint64 AuctionEntry::GetAuctionOutBid () const
{
uint64 outbid = CalculatePctN(bid, 5);
return outbid ? outbid : 1;
}
void AuctionEntry::DeleteFromDB (SQLTransaction& trans) const
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_AUCTION);
stmt->setUInt32(0, Id);
trans->Append(stmt);
}
void AuctionEntry::SaveToDB (SQLTransaction& trans) const
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_AUCTION);
stmt->setUInt32(0, Id);
stmt->setUInt32(1, auctioneer);
stmt->setUInt32(2, item_guidlow);
stmt->setUInt32(3, owner);
stmt->setInt32(4, int32(buyout));
stmt->setUInt64(5, uint64(expire_time));
stmt->setUInt32(6, bidder);
stmt->setInt32(7, int32(bid));
stmt->setInt32(8, int32(startbid));
stmt->setInt32(9, int32(deposit));
trans->Append(stmt);
}
bool AuctionEntry::LoadFromDB (Field* fields)
{
Id = fields[0].GetUInt32();
auctioneer = fields[1].GetUInt32();
item_guidlow = fields[2].GetUInt32();
item_template = fields[3].GetUInt32();
owner = fields[4].GetUInt32();
buyout = fields[5].GetUInt32();
expire_time = fields[6].GetUInt32();
bidder = fields[7].GetUInt32();
bid = fields[8].GetUInt32();
startbid = fields[9].GetUInt32();
deposit = fields[10].GetUInt32();
CreatureData const* auctioneerData = sObjectMgr->GetCreatureData(auctioneer);
if (!auctioneerData)
{
sLog->outError("Auction %u has not a existing auctioneer (GUID : %u)", Id, auctioneer);
return false;
}
CreatureInfo const* auctioneerInfo = ObjectMgr::GetCreatureTemplate(auctioneerData->id);
if (!auctioneerInfo)
{
sLog->outError("Auction %u has not a existing auctioneer (GUID : %u Entry: %u)", Id, auctioneer, auctioneerData->id);
return false;
}
factionTemplateId = auctioneerInfo->faction_A;
auctionHouseEntry = AuctionHouseMgr::GetAuctionHouseEntry(factionTemplateId);
if (!auctionHouseEntry)
{
sLog->outError("Auction %u has auctioneer (GUID : %u Entry: %u) with wrong faction %u", Id, auctioneer, auctioneerData->id, factionTemplateId);
return false;
}
// check if sold item exists for guid
// and item_template in fact (GetAItem will fail if problematic in result check in AuctionHouseMgr::LoadAuctionItems)
if (!sAuctionMgr->GetAItem(item_guidlow))
{
sLog->outError("Auction %u has not a existing item : %u", Id, item_guidlow);
return false;
}
return true;
}
| 36.276413 | 309 | 0.636662 | [
"vector"
] |
61ee2ae284c4998af95d17392080f7107dda4cd3 | 48,605 | cc | C++ | src/mem/ruby/system/GPUCoalescer.cc | seanzw/UCLA-CS259-MachinesThatLearn-TensorCore | aece7fcdf97d2864fbb31e02940bfcdd470db7b9 | [
"BSD-3-Clause"
] | 135 | 2016-10-21T03:31:49.000Z | 2022-03-25T01:22:20.000Z | src/mem/ruby/system/GPUCoalescer.cc | seanzw/UCLA-CS259-MachinesThatLearn-TensorCore | aece7fcdf97d2864fbb31e02940bfcdd470db7b9 | [
"BSD-3-Clause"
] | 35 | 2017-03-10T17:57:46.000Z | 2022-02-18T17:34:16.000Z | src/mem/ruby/system/GPUCoalescer.cc | seanzw/UCLA-CS259-MachinesThatLearn-TensorCore | aece7fcdf97d2864fbb31e02940bfcdd470db7b9 | [
"BSD-3-Clause"
] | 48 | 2016-12-08T12:03:13.000Z | 2022-02-16T09:16:13.000Z | /*
* Copyright (c) 2013-2015 Advanced Micro Devices, Inc.
* All rights reserved.
*
* For use for simulation and test purposes only
*
* 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.
*
* Authors: Sooraj Puthoor
*/
#include "base/logging.hh"
#include "base/str.hh"
#include "config/the_isa.hh"
#if THE_ISA == X86_ISA
#include "arch/x86/insts/microldstop.hh"
#endif // X86_ISA
#include "mem/ruby/system/GPUCoalescer.hh"
#include "cpu/testers/rubytest/RubyTester.hh"
#include "debug/GPUCoalescer.hh"
#include "debug/MemoryAccess.hh"
#include "debug/ProtocolTrace.hh"
#include "debug/RubyPort.hh"
#include "debug/RubyStats.hh"
#include "gpu-compute/shader.hh"
#include "mem/packet.hh"
#include "mem/ruby/common/DataBlock.hh"
#include "mem/ruby/common/SubBlock.hh"
#include "mem/ruby/network/MessageBuffer.hh"
#include "mem/ruby/profiler/Profiler.hh"
#include "mem/ruby/slicc_interface/AbstractController.hh"
#include "mem/ruby/slicc_interface/RubyRequest.hh"
#include "mem/ruby/structures/CacheMemory.hh"
#include "mem/ruby/system/RubySystem.hh"
#include "params/RubyGPUCoalescer.hh"
using namespace std;
GPUCoalescer *
RubyGPUCoalescerParams::create()
{
return new GPUCoalescer(this);
}
HSAScope
reqScopeToHSAScope(const RequestPtr &req)
{
HSAScope accessScope = HSAScope_UNSPECIFIED;
if (req->isScoped()) {
if (req->isWavefrontScope()) {
accessScope = HSAScope_WAVEFRONT;
} else if (req->isWorkgroupScope()) {
accessScope = HSAScope_WORKGROUP;
} else if (req->isDeviceScope()) {
accessScope = HSAScope_DEVICE;
} else if (req->isSystemScope()) {
accessScope = HSAScope_SYSTEM;
} else {
fatal("Bad scope type");
}
}
return accessScope;
}
HSASegment
reqSegmentToHSASegment(const RequestPtr &req)
{
HSASegment accessSegment = HSASegment_GLOBAL;
if (req->isGlobalSegment()) {
accessSegment = HSASegment_GLOBAL;
} else if (req->isGroupSegment()) {
accessSegment = HSASegment_GROUP;
} else if (req->isPrivateSegment()) {
accessSegment = HSASegment_PRIVATE;
} else if (req->isKernargSegment()) {
accessSegment = HSASegment_KERNARG;
} else if (req->isReadonlySegment()) {
accessSegment = HSASegment_READONLY;
} else if (req->isSpillSegment()) {
accessSegment = HSASegment_SPILL;
} else if (req->isArgSegment()) {
accessSegment = HSASegment_ARG;
} else {
fatal("Bad segment type");
}
return accessSegment;
}
GPUCoalescer::GPUCoalescer(const Params *p)
: RubyPort(p),
issueEvent([this]{ completeIssue(); }, "Issue coalesced request",
false, Event::Progress_Event_Pri),
deadlockCheckEvent([this]{ wakeup(); }, "GPUCoalescer deadlock check")
{
m_store_waiting_on_load_cycles = 0;
m_store_waiting_on_store_cycles = 0;
m_load_waiting_on_store_cycles = 0;
m_load_waiting_on_load_cycles = 0;
m_outstanding_count = 0;
m_max_outstanding_requests = 0;
m_deadlock_threshold = 0;
m_instCache_ptr = nullptr;
m_dataCache_ptr = nullptr;
m_instCache_ptr = p->icache;
m_dataCache_ptr = p->dcache;
m_max_outstanding_requests = p->max_outstanding_requests;
m_deadlock_threshold = p->deadlock_threshold;
assert(m_max_outstanding_requests > 0);
assert(m_deadlock_threshold > 0);
assert(m_instCache_ptr);
assert(m_dataCache_ptr);
m_runningGarnetStandalone = p->garnet_standalone;
assumingRfOCoherence = p->assume_rfo;
}
GPUCoalescer::~GPUCoalescer()
{
}
void
GPUCoalescer::wakeup()
{
// Check for deadlock of any of the requests
Cycles current_time = curCycle();
// Check across all outstanding requests
int total_outstanding = 0;
RequestTable::iterator read = m_readRequestTable.begin();
RequestTable::iterator read_end = m_readRequestTable.end();
for (; read != read_end; ++read) {
GPUCoalescerRequest* request = read->second;
if (current_time - request->issue_time < m_deadlock_threshold)
continue;
panic("Possible Deadlock detected. Aborting!\n"
"version: %d request.paddr: 0x%x m_readRequestTable: %d "
"current time: %u issue_time: %d difference: %d\n", m_version,
request->pkt->getAddr(), m_readRequestTable.size(),
current_time * clockPeriod(), request->issue_time * clockPeriod(),
(current_time - request->issue_time)*clockPeriod());
}
RequestTable::iterator write = m_writeRequestTable.begin();
RequestTable::iterator write_end = m_writeRequestTable.end();
for (; write != write_end; ++write) {
GPUCoalescerRequest* request = write->second;
if (current_time - request->issue_time < m_deadlock_threshold)
continue;
panic("Possible Deadlock detected. Aborting!\n"
"version: %d request.paddr: 0x%x m_writeRequestTable: %d "
"current time: %u issue_time: %d difference: %d\n", m_version,
request->pkt->getAddr(), m_writeRequestTable.size(),
current_time * clockPeriod(), request->issue_time * clockPeriod(),
(current_time - request->issue_time) * clockPeriod());
}
total_outstanding += m_writeRequestTable.size();
total_outstanding += m_readRequestTable.size();
assert(m_outstanding_count == total_outstanding);
if (m_outstanding_count > 0) {
// If there are still outstanding requests, keep checking
schedule(deadlockCheckEvent,
m_deadlock_threshold * clockPeriod() +
curTick());
}
}
void
GPUCoalescer::resetStats()
{
m_latencyHist.reset();
m_missLatencyHist.reset();
for (int i = 0; i < RubyRequestType_NUM; i++) {
m_typeLatencyHist[i]->reset();
m_missTypeLatencyHist[i]->reset();
for (int j = 0; j < MachineType_NUM; j++) {
m_missTypeMachLatencyHist[i][j]->reset();
}
}
for (int i = 0; i < MachineType_NUM; i++) {
m_missMachLatencyHist[i]->reset();
m_IssueToInitialDelayHist[i]->reset();
m_InitialToForwardDelayHist[i]->reset();
m_ForwardToFirstResponseDelayHist[i]->reset();
m_FirstResponseToCompletionDelayHist[i]->reset();
}
}
void
GPUCoalescer::printProgress(ostream& out) const
{
}
RequestStatus
GPUCoalescer::getRequestStatus(PacketPtr pkt, RubyRequestType request_type)
{
Addr line_addr = makeLineAddress(pkt->getAddr());
if (!m_mandatory_q_ptr->areNSlotsAvailable(1, clockEdge())) {
return RequestStatus_BufferFull;
}
if (m_controller->isBlocked(line_addr) &&
request_type != RubyRequestType_Locked_RMW_Write) {
return RequestStatus_Aliased;
}
if ((request_type == RubyRequestType_ST) ||
(request_type == RubyRequestType_ATOMIC) ||
(request_type == RubyRequestType_ATOMIC_RETURN) ||
(request_type == RubyRequestType_ATOMIC_NO_RETURN) ||
(request_type == RubyRequestType_RMW_Read) ||
(request_type == RubyRequestType_RMW_Write) ||
(request_type == RubyRequestType_Load_Linked) ||
(request_type == RubyRequestType_Store_Conditional) ||
(request_type == RubyRequestType_Locked_RMW_Read) ||
(request_type == RubyRequestType_Locked_RMW_Write) ||
(request_type == RubyRequestType_FLUSH)) {
// Check if there is any outstanding read request for the same
// cache line.
if (m_readRequestTable.count(line_addr) > 0) {
m_store_waiting_on_load_cycles++;
return RequestStatus_Aliased;
}
if (m_writeRequestTable.count(line_addr) > 0) {
// There is an outstanding write request for the cache line
m_store_waiting_on_store_cycles++;
return RequestStatus_Aliased;
}
} else {
// Check if there is any outstanding write request for the same
// cache line.
if (m_writeRequestTable.count(line_addr) > 0) {
m_load_waiting_on_store_cycles++;
return RequestStatus_Aliased;
}
if (m_readRequestTable.count(line_addr) > 0) {
// There is an outstanding read request for the cache line
m_load_waiting_on_load_cycles++;
return RequestStatus_Aliased;
}
}
return RequestStatus_Ready;
}
// sets the kernelEndList
void
GPUCoalescer::insertKernel(int wavefront_id, PacketPtr pkt)
{
// Don't know if this will happen or is possible
// but I just want to be careful and not have it become
// simulator hang in the future
DPRINTF(GPUCoalescer, "inserting wf: %d to kernelEndlist\n", wavefront_id);
assert(kernelEndList.count(wavefront_id) == 0);
kernelEndList[wavefront_id] = pkt;
DPRINTF(GPUCoalescer, "kernelEndList->size() = %d\n",
kernelEndList.size());
}
// Insert the request on the correct request table. Return true if
// the entry was already present.
bool
GPUCoalescer::insertRequest(PacketPtr pkt, RubyRequestType request_type)
{
assert(getRequestStatus(pkt, request_type) == RequestStatus_Ready ||
pkt->req->isLockedRMW() ||
!m_mandatory_q_ptr->areNSlotsAvailable(1, clockEdge()));
int total_outstanding M5_VAR_USED =
m_writeRequestTable.size() + m_readRequestTable.size();
assert(m_outstanding_count == total_outstanding);
// See if we should schedule a deadlock check
if (!deadlockCheckEvent.scheduled()) {
schedule(deadlockCheckEvent, m_deadlock_threshold + curTick());
}
Addr line_addr = makeLineAddress(pkt->getAddr());
if ((request_type == RubyRequestType_ST) ||
(request_type == RubyRequestType_ATOMIC) ||
(request_type == RubyRequestType_ATOMIC_RETURN) ||
(request_type == RubyRequestType_ATOMIC_NO_RETURN) ||
(request_type == RubyRequestType_RMW_Read) ||
(request_type == RubyRequestType_RMW_Write) ||
(request_type == RubyRequestType_Load_Linked) ||
(request_type == RubyRequestType_Store_Conditional) ||
(request_type == RubyRequestType_Locked_RMW_Read) ||
(request_type == RubyRequestType_Locked_RMW_Write) ||
(request_type == RubyRequestType_FLUSH)) {
pair<RequestTable::iterator, bool> r =
m_writeRequestTable.insert(RequestTable::value_type(line_addr,
(GPUCoalescerRequest*) NULL));
if (r.second) {
RequestTable::iterator i = r.first;
i->second = new GPUCoalescerRequest(pkt, request_type,
curCycle());
DPRINTF(GPUCoalescer,
"Inserting write request for paddr %#x for type %d\n",
pkt->req->getPaddr(), i->second->m_type);
m_outstanding_count++;
} else {
return true;
}
} else {
pair<RequestTable::iterator, bool> r =
m_readRequestTable.insert(RequestTable::value_type(line_addr,
(GPUCoalescerRequest*) NULL));
if (r.second) {
RequestTable::iterator i = r.first;
i->second = new GPUCoalescerRequest(pkt, request_type,
curCycle());
DPRINTF(GPUCoalescer,
"Inserting read request for paddr %#x for type %d\n",
pkt->req->getPaddr(), i->second->m_type);
m_outstanding_count++;
} else {
return true;
}
}
m_outstandReqHist.sample(m_outstanding_count);
total_outstanding = m_writeRequestTable.size() + m_readRequestTable.size();
assert(m_outstanding_count == total_outstanding);
return false;
}
void
GPUCoalescer::markRemoved()
{
m_outstanding_count--;
assert(m_outstanding_count ==
m_writeRequestTable.size() + m_readRequestTable.size());
}
void
GPUCoalescer::removeRequest(GPUCoalescerRequest* srequest)
{
assert(m_outstanding_count ==
m_writeRequestTable.size() + m_readRequestTable.size());
Addr line_addr = makeLineAddress(srequest->pkt->getAddr());
if ((srequest->m_type == RubyRequestType_ST) ||
(srequest->m_type == RubyRequestType_RMW_Read) ||
(srequest->m_type == RubyRequestType_RMW_Write) ||
(srequest->m_type == RubyRequestType_Load_Linked) ||
(srequest->m_type == RubyRequestType_Store_Conditional) ||
(srequest->m_type == RubyRequestType_Locked_RMW_Read) ||
(srequest->m_type == RubyRequestType_Locked_RMW_Write)) {
m_writeRequestTable.erase(line_addr);
} else {
m_readRequestTable.erase(line_addr);
}
markRemoved();
}
bool
GPUCoalescer::handleLlsc(Addr address, GPUCoalescerRequest* request)
{
//
// The success flag indicates whether the LLSC operation was successful.
// LL ops will always succeed, but SC may fail if the cache line is no
// longer locked.
//
bool success = true;
if (request->m_type == RubyRequestType_Store_Conditional) {
if (!m_dataCache_ptr->isLocked(address, m_version)) {
//
// For failed SC requests, indicate the failure to the cpu by
// setting the extra data to zero.
//
request->pkt->req->setExtraData(0);
success = false;
} else {
//
// For successful SC requests, indicate the success to the cpu by
// setting the extra data to one.
//
request->pkt->req->setExtraData(1);
}
//
// Independent of success, all SC operations must clear the lock
//
m_dataCache_ptr->clearLocked(address);
} else if (request->m_type == RubyRequestType_Load_Linked) {
//
// Note: To fully follow Alpha LLSC semantics, should the LL clear any
// previously locked cache lines?
//
m_dataCache_ptr->setLocked(address, m_version);
} else if ((m_dataCache_ptr->isTagPresent(address)) &&
(m_dataCache_ptr->isLocked(address, m_version))) {
//
// Normal writes should clear the locked address
//
m_dataCache_ptr->clearLocked(address);
}
return success;
}
void
GPUCoalescer::writeCallback(Addr address, DataBlock& data)
{
writeCallback(address, MachineType_NULL, data);
}
void
GPUCoalescer::writeCallback(Addr address,
MachineType mach,
DataBlock& data)
{
writeCallback(address, mach, data, Cycles(0), Cycles(0), Cycles(0));
}
void
GPUCoalescer::writeCallback(Addr address,
MachineType mach,
DataBlock& data,
Cycles initialRequestTime,
Cycles forwardRequestTime,
Cycles firstResponseTime)
{
writeCallback(address, mach, data,
initialRequestTime, forwardRequestTime, firstResponseTime,
false);
}
void
GPUCoalescer::writeCallback(Addr address,
MachineType mach,
DataBlock& data,
Cycles initialRequestTime,
Cycles forwardRequestTime,
Cycles firstResponseTime,
bool isRegion)
{
assert(address == makeLineAddress(address));
DPRINTF(GPUCoalescer, "write callback for address %#x\n", address);
assert(m_writeRequestTable.count(makeLineAddress(address)));
RequestTable::iterator i = m_writeRequestTable.find(address);
assert(i != m_writeRequestTable.end());
GPUCoalescerRequest* request = i->second;
m_writeRequestTable.erase(i);
markRemoved();
assert((request->m_type == RubyRequestType_ST) ||
(request->m_type == RubyRequestType_ATOMIC) ||
(request->m_type == RubyRequestType_ATOMIC_RETURN) ||
(request->m_type == RubyRequestType_ATOMIC_NO_RETURN) ||
(request->m_type == RubyRequestType_RMW_Read) ||
(request->m_type == RubyRequestType_RMW_Write) ||
(request->m_type == RubyRequestType_Load_Linked) ||
(request->m_type == RubyRequestType_Store_Conditional) ||
(request->m_type == RubyRequestType_Locked_RMW_Read) ||
(request->m_type == RubyRequestType_Locked_RMW_Write) ||
(request->m_type == RubyRequestType_FLUSH));
//
// For Alpha, properly handle LL, SC, and write requests with respect to
// locked cache blocks.
//
// Not valid for Garnet_standalone protocl
//
bool success = true;
if (!m_runningGarnetStandalone)
success = handleLlsc(address, request);
if (request->m_type == RubyRequestType_Locked_RMW_Read) {
m_controller->blockOnQueue(address, m_mandatory_q_ptr);
} else if (request->m_type == RubyRequestType_Locked_RMW_Write) {
m_controller->unblock(address);
}
hitCallback(request, mach, data, success,
request->issue_time, forwardRequestTime, firstResponseTime,
isRegion);
}
void
GPUCoalescer::readCallback(Addr address, DataBlock& data)
{
readCallback(address, MachineType_NULL, data);
}
void
GPUCoalescer::readCallback(Addr address,
MachineType mach,
DataBlock& data)
{
readCallback(address, mach, data, Cycles(0), Cycles(0), Cycles(0));
}
void
GPUCoalescer::readCallback(Addr address,
MachineType mach,
DataBlock& data,
Cycles initialRequestTime,
Cycles forwardRequestTime,
Cycles firstResponseTime)
{
readCallback(address, mach, data,
initialRequestTime, forwardRequestTime, firstResponseTime,
false);
}
void
GPUCoalescer::readCallback(Addr address,
MachineType mach,
DataBlock& data,
Cycles initialRequestTime,
Cycles forwardRequestTime,
Cycles firstResponseTime,
bool isRegion)
{
assert(address == makeLineAddress(address));
assert(m_readRequestTable.count(makeLineAddress(address)));
DPRINTF(GPUCoalescer, "read callback for address %#x\n", address);
RequestTable::iterator i = m_readRequestTable.find(address);
assert(i != m_readRequestTable.end());
GPUCoalescerRequest* request = i->second;
m_readRequestTable.erase(i);
markRemoved();
assert((request->m_type == RubyRequestType_LD) ||
(request->m_type == RubyRequestType_IFETCH));
hitCallback(request, mach, data, true,
request->issue_time, forwardRequestTime, firstResponseTime,
isRegion);
}
void
GPUCoalescer::hitCallback(GPUCoalescerRequest* srequest,
MachineType mach,
DataBlock& data,
bool success,
Cycles initialRequestTime,
Cycles forwardRequestTime,
Cycles firstResponseTime,
bool isRegion)
{
PacketPtr pkt = srequest->pkt;
Addr request_address = pkt->getAddr();
Addr request_line_address = makeLineAddress(request_address);
RubyRequestType type = srequest->m_type;
// Set this cache entry to the most recently used
if (type == RubyRequestType_IFETCH) {
if (m_instCache_ptr->isTagPresent(request_line_address))
m_instCache_ptr->setMRU(request_line_address);
} else {
if (m_dataCache_ptr->isTagPresent(request_line_address))
m_dataCache_ptr->setMRU(request_line_address);
}
recordMissLatency(srequest, mach,
initialRequestTime,
forwardRequestTime,
firstResponseTime,
success, isRegion);
// update the data
//
// MUST AD DOING THIS FOR EACH REQUEST IN COALESCER
int len = reqCoalescer[request_line_address].size();
std::vector<PacketPtr> mylist;
for (int i = 0; i < len; ++i) {
PacketPtr pkt = reqCoalescer[request_line_address][i].pkt;
assert(type == reqCoalescer[request_line_address][i].primaryType);
request_address = pkt->getAddr();
request_line_address = makeLineAddress(pkt->getAddr());
if (pkt->getPtr<uint8_t>()) {
if ((type == RubyRequestType_LD) ||
(type == RubyRequestType_ATOMIC) ||
(type == RubyRequestType_ATOMIC_RETURN) ||
(type == RubyRequestType_IFETCH) ||
(type == RubyRequestType_RMW_Read) ||
(type == RubyRequestType_Locked_RMW_Read) ||
(type == RubyRequestType_Load_Linked)) {
pkt->setData(
data.getData(getOffset(request_address), pkt->getSize()));
} else {
data.setData(pkt->getPtr<uint8_t>(),
getOffset(request_address), pkt->getSize());
}
} else {
DPRINTF(MemoryAccess,
"WARNING. Data not transfered from Ruby to M5 for type " \
"%s\n",
RubyRequestType_to_string(type));
}
// If using the RubyTester, update the RubyTester sender state's
// subBlock with the recieved data. The tester will later access
// this state.
// Note: RubyPort will access it's sender state before the
// RubyTester.
if (m_usingRubyTester) {
RubyPort::SenderState *requestSenderState =
safe_cast<RubyPort::SenderState*>(pkt->senderState);
RubyTester::SenderState* testerSenderState =
safe_cast<RubyTester::SenderState*>(requestSenderState->predecessor);
testerSenderState->subBlock.mergeFrom(data);
}
mylist.push_back(pkt);
}
delete srequest;
reqCoalescer.erase(request_line_address);
assert(!reqCoalescer.count(request_line_address));
completeHitCallback(mylist, len);
}
bool
GPUCoalescer::empty() const
{
return m_writeRequestTable.empty() && m_readRequestTable.empty();
}
// Analyzes the packet to see if this request can be coalesced.
// If request can be coalesced, this request is added to the reqCoalescer table
// and makeRequest returns RequestStatus_Issued;
// If this is the first request to a cacheline, request is added to both
// newRequests queue and to the reqCoalescer table; makeRequest
// returns RequestStatus_Issued.
// If there is a pending request to this cacheline and this request
// can't be coalesced, RequestStatus_Aliased is returned and
// the packet needs to be reissued.
RequestStatus
GPUCoalescer::makeRequest(PacketPtr pkt)
{
// Check for GPU Barrier Kernel End or Kernel Begin
// Leave these to be handled by the child class
// Kernel End/Barrier = isFlush + isRelease
// Kernel Begin = isFlush + isAcquire
if (pkt->req->isKernel()) {
if (pkt->req->isAcquire()){
// This is a Kernel Begin leave handling to
// virtual xCoalescer::makeRequest
return RequestStatus_Issued;
}else if (pkt->req->isRelease()) {
// This is a Kernel End leave handling to
// virtual xCoalescer::makeRequest
// If we are here then we didn't call
// a virtual version of this function
// so we will also schedule the callback
int wf_id = 0;
if (pkt->req->hasContextId()) {
wf_id = pkt->req->contextId();
}
insertKernel(wf_id, pkt);
newKernelEnds.push_back(wf_id);
if (!issueEvent.scheduled()) {
schedule(issueEvent, curTick());
}
return RequestStatus_Issued;
}
}
// If number of outstanding requests greater than the max allowed,
// return RequestStatus_BufferFull. This logic can be extended to
// support proper backpressure.
if (m_outstanding_count >= m_max_outstanding_requests) {
return RequestStatus_BufferFull;
}
RubyRequestType primary_type = RubyRequestType_NULL;
RubyRequestType secondary_type = RubyRequestType_NULL;
if (pkt->isLLSC()) {
//
// Alpha LL/SC instructions need to be handled carefully by the cache
// coherence protocol to ensure they follow the proper semantics. In
// particular, by identifying the operations as atomic, the protocol
// should understand that migratory sharing optimizations should not
// be performed (i.e. a load between the LL and SC should not steal
// away exclusive permission).
//
if (pkt->isWrite()) {
primary_type = RubyRequestType_Store_Conditional;
} else {
assert(pkt->isRead());
primary_type = RubyRequestType_Load_Linked;
}
secondary_type = RubyRequestType_ATOMIC;
} else if (pkt->req->isLockedRMW()) {
//
// x86 locked instructions are translated to store cache coherence
// requests because these requests should always be treated as read
// exclusive operations and should leverage any migratory sharing
// optimization built into the protocol.
//
if (pkt->isWrite()) {
primary_type = RubyRequestType_Locked_RMW_Write;
} else {
assert(pkt->isRead());
primary_type = RubyRequestType_Locked_RMW_Read;
}
secondary_type = RubyRequestType_ST;
} else if (pkt->isAtomicOp()) {
//
// GPU Atomic Operation
//
primary_type = RubyRequestType_ATOMIC;
secondary_type = RubyRequestType_ATOMIC;
} else {
if (pkt->isRead()) {
if (pkt->req->isInstFetch()) {
primary_type = secondary_type = RubyRequestType_IFETCH;
} else {
#if THE_ISA == X86_ISA
uint32_t flags = pkt->req->getFlags();
bool storeCheck = flags &
(TheISA::StoreCheck << TheISA::FlagShift);
#else
bool storeCheck = false;
#endif // X86_ISA
if (storeCheck) {
primary_type = RubyRequestType_RMW_Read;
secondary_type = RubyRequestType_ST;
} else {
primary_type = secondary_type = RubyRequestType_LD;
}
}
} else if (pkt->isWrite()) {
//
// Note: M5 packets do not differentiate ST from RMW_Write
//
primary_type = secondary_type = RubyRequestType_ST;
} else if (pkt->isFlush()) {
primary_type = secondary_type = RubyRequestType_FLUSH;
} else if (pkt->req->isRelease() || pkt->req->isAcquire()) {
if (assumingRfOCoherence) {
// If we reached here, this request must be a memFence
// and the protocol implements RfO, the coalescer can
// assume sequentially consistency and schedule the callback
// immediately.
// Currently the code implements fence callbacks
// by reusing the mechanism for kernel completions.
// This should be fixed.
int wf_id = 0;
if (pkt->req->hasContextId()) {
wf_id = pkt->req->contextId();
}
insertKernel(wf_id, pkt);
newKernelEnds.push_back(wf_id);
if (!issueEvent.scheduled()) {
schedule(issueEvent, curTick());
}
return RequestStatus_Issued;
} else {
// If not RfO, return issued here and let the child coalescer
// take care of it.
return RequestStatus_Issued;
}
} else {
panic("Unsupported ruby packet type\n");
}
}
// Check if there is any pending request to this cache line from
// previous cycles.
// If there is a pending request, return aliased. Since coalescing
// across time is not permitted, aliased requests are not coalesced.
// If a request for this address has already been issued, we must block
RequestStatus status = getRequestStatus(pkt, primary_type);
if (status != RequestStatus_Ready)
return status;
Addr line_addr = makeLineAddress(pkt->getAddr());
// Check if this request can be coalesced with previous
// requests from this cycle.
if (!reqCoalescer.count(line_addr)) {
// This is the first access to this cache line.
// A new request to the memory subsystem has to be
// made in the next cycle for this cache line, so
// add this line addr to the "newRequests" queue
newRequests.push_back(line_addr);
// There was a request to this cache line in this cycle,
// let us see if we can coalesce this request with the previous
// requests from this cycle
} else if (primary_type !=
reqCoalescer[line_addr][0].primaryType) {
// can't coalesce loads, stores and atomics!
return RequestStatus_Aliased;
} else if (pkt->req->isLockedRMW() ||
reqCoalescer[line_addr][0].pkt->req->isLockedRMW()) {
// can't coalesce locked accesses, but can coalesce atomics!
return RequestStatus_Aliased;
} else if (pkt->req->hasContextId() && pkt->req->isRelease() &&
pkt->req->contextId() !=
reqCoalescer[line_addr][0].pkt->req->contextId()) {
// can't coalesce releases from different wavefronts
return RequestStatus_Aliased;
}
// in addition to the packet, we need to save both request types
reqCoalescer[line_addr].emplace_back(pkt, primary_type, secondary_type);
if (!issueEvent.scheduled())
schedule(issueEvent, curTick());
// TODO: issue hardware prefetches here
return RequestStatus_Issued;
}
void
GPUCoalescer::issueRequest(PacketPtr pkt, RubyRequestType secondary_type)
{
int proc_id = -1;
if (pkt != NULL && pkt->req->hasContextId()) {
proc_id = pkt->req->contextId();
}
// If valid, copy the pc to the ruby request
Addr pc = 0;
if (pkt->req->hasPC()) {
pc = pkt->req->getPC();
}
// At the moment setting scopes only counts
// for GPU spill space accesses
// which is pkt->req->isStack()
// this scope is REPLACE since it
// does not need to be flushed at the end
// of a kernel Private and local may need
// to be visible at the end of the kernel
HSASegment accessSegment = reqSegmentToHSASegment(pkt->req);
HSAScope accessScope = reqScopeToHSAScope(pkt->req);
Addr line_addr = makeLineAddress(pkt->getAddr());
// Creating WriteMask that records written bytes
// and atomic operations. This enables partial writes
// and partial reads of those writes
DataBlock dataBlock;
dataBlock.clear();
uint32_t blockSize = RubySystem::getBlockSizeBytes();
std::vector<bool> accessMask(blockSize,false);
std::vector< std::pair<int,AtomicOpFunctor*> > atomicOps;
uint32_t tableSize = reqCoalescer[line_addr].size();
for (int i = 0; i < tableSize; i++) {
PacketPtr tmpPkt = reqCoalescer[line_addr][i].pkt;
uint32_t tmpOffset = (tmpPkt->getAddr()) - line_addr;
uint32_t tmpSize = tmpPkt->getSize();
if (tmpPkt->isAtomicOp()) {
std::pair<int,AtomicOpFunctor *> tmpAtomicOp(tmpOffset,
tmpPkt->getAtomicOp());
atomicOps.push_back(tmpAtomicOp);
} else if (tmpPkt->isWrite()) {
dataBlock.setData(tmpPkt->getPtr<uint8_t>(),
tmpOffset, tmpSize);
}
for (int j = 0; j < tmpSize; j++) {
accessMask[tmpOffset + j] = true;
}
}
std::shared_ptr<RubyRequest> msg;
if (pkt->isAtomicOp()) {
msg = std::make_shared<RubyRequest>(clockEdge(), pkt->getAddr(),
pkt->getPtr<uint8_t>(),
pkt->getSize(), pc, secondary_type,
RubyAccessMode_Supervisor, pkt,
PrefetchBit_No, proc_id, 100,
blockSize, accessMask,
dataBlock, atomicOps,
accessScope, accessSegment);
} else {
msg = std::make_shared<RubyRequest>(clockEdge(), pkt->getAddr(),
pkt->getPtr<uint8_t>(),
pkt->getSize(), pc, secondary_type,
RubyAccessMode_Supervisor, pkt,
PrefetchBit_No, proc_id, 100,
blockSize, accessMask,
dataBlock,
accessScope, accessSegment);
}
DPRINTFR(ProtocolTrace, "%15s %3s %10s%20s %6s>%-6s %s %s\n",
curTick(), m_version, "Coal", "Begin", "", "",
printAddress(msg->getPhysicalAddress()),
RubyRequestType_to_string(secondary_type));
fatal_if(secondary_type == RubyRequestType_IFETCH,
"there should not be any I-Fetch requests in the GPU Coalescer");
Tick latency = cyclesToTicks(
m_controller->mandatoryQueueLatency(secondary_type));
assert(latency > 0);
assert(m_mandatory_q_ptr);
m_mandatory_q_ptr->enqueue(msg, clockEdge(), latency);
}
template <class KEY, class VALUE>
std::ostream &
operator<<(ostream &out, const std::unordered_map<KEY, VALUE> &map)
{
out << "[";
for (auto i = map.begin(); i != map.end(); ++i)
out << " " << i->first << "=" << i->second;
out << " ]";
return out;
}
void
GPUCoalescer::print(ostream& out) const
{
out << "[GPUCoalescer: " << m_version
<< ", outstanding requests: " << m_outstanding_count
<< ", read request table: " << m_readRequestTable
<< ", write request table: " << m_writeRequestTable
<< "]";
}
// this can be called from setState whenever coherence permissions are
// upgraded when invoked, coherence violations will be checked for the
// given block
void
GPUCoalescer::checkCoherence(Addr addr)
{
}
void
GPUCoalescer::recordRequestType(SequencerRequestType requestType) {
DPRINTF(RubyStats, "Recorded statistic: %s\n",
SequencerRequestType_to_string(requestType));
}
void
GPUCoalescer::completeIssue()
{
// newRequests has the cacheline addresses of all the
// requests which need to be issued to the memory subsystem
// in this cycle
int len = newRequests.size();
DPRINTF(GPUCoalescer, "Completing issue for %d new requests.\n", len);
for (int i = 0; i < len; ++i) {
// Get the requests from reqCoalescer table. Get only the
// first request for each cacheline, the remaining requests
// can be coalesced with the first request. So, only
// one request is issued per cacheline.
RequestDesc info = reqCoalescer[newRequests[i]][0];
PacketPtr pkt = info.pkt;
DPRINTF(GPUCoalescer, "Completing for newReq %d: paddr %#x\n",
i, pkt->req->getPaddr());
// Insert this request to the read/writeRequestTables. These tables
// are used to track aliased requests in makeRequest subroutine
bool found = insertRequest(pkt, info.primaryType);
if (found) {
panic("GPUCoalescer::makeRequest should never be called if the "
"request is already outstanding\n");
}
// Issue request to ruby subsystem
issueRequest(pkt, info.secondaryType);
}
newRequests.clear();
// have Kernel End releases been issued this cycle
len = newKernelEnds.size();
for (int i = 0; i < len; i++) {
kernelCallback(newKernelEnds[i]);
}
newKernelEnds.clear();
}
void
GPUCoalescer::evictionCallback(Addr address)
{
ruby_eviction_callback(address);
}
void
GPUCoalescer::kernelCallback(int wavefront_id)
{
assert(kernelEndList.count(wavefront_id));
ruby_hit_callback(kernelEndList[wavefront_id]);
kernelEndList.erase(wavefront_id);
}
void
GPUCoalescer::atomicCallback(Addr address,
MachineType mach,
const DataBlock& data)
{
assert(address == makeLineAddress(address));
DPRINTF(GPUCoalescer, "atomic callback for address %#x\n", address);
assert(m_writeRequestTable.count(makeLineAddress(address)));
RequestTable::iterator i = m_writeRequestTable.find(address);
assert(i != m_writeRequestTable.end());
GPUCoalescerRequest* srequest = i->second;
m_writeRequestTable.erase(i);
markRemoved();
assert((srequest->m_type == RubyRequestType_ATOMIC) ||
(srequest->m_type == RubyRequestType_ATOMIC_RETURN) ||
(srequest->m_type == RubyRequestType_ATOMIC_NO_RETURN));
// Atomics don't write to cache, so there is no MRU update...
recordMissLatency(srequest, mach,
srequest->issue_time, Cycles(0), Cycles(0), true, false);
PacketPtr pkt = srequest->pkt;
Addr request_address = pkt->getAddr();
Addr request_line_address = makeLineAddress(pkt->getAddr());
int len = reqCoalescer[request_line_address].size();
std::vector<PacketPtr> mylist;
for (int i = 0; i < len; ++i) {
PacketPtr pkt = reqCoalescer[request_line_address][i].pkt;
assert(srequest->m_type ==
reqCoalescer[request_line_address][i].primaryType);
request_address = (pkt->getAddr());
request_line_address = makeLineAddress(request_address);
if (pkt->getPtr<uint8_t>() &&
srequest->m_type != RubyRequestType_ATOMIC_NO_RETURN) {
/* atomics are done in memory, and return the data *before* the atomic op... */
pkt->setData(
data.getData(getOffset(request_address), pkt->getSize()));
} else {
DPRINTF(MemoryAccess,
"WARNING. Data not transfered from Ruby to M5 for type " \
"%s\n",
RubyRequestType_to_string(srequest->m_type));
}
// If using the RubyTester, update the RubyTester sender state's
// subBlock with the recieved data. The tester will later access
// this state.
// Note: RubyPort will access it's sender state before the
// RubyTester.
if (m_usingRubyTester) {
RubyPort::SenderState *requestSenderState =
safe_cast<RubyPort::SenderState*>(pkt->senderState);
RubyTester::SenderState* testerSenderState =
safe_cast<RubyTester::SenderState*>(requestSenderState->predecessor);
testerSenderState->subBlock.mergeFrom(data);
}
mylist.push_back(pkt);
}
delete srequest;
reqCoalescer.erase(request_line_address);
assert(!reqCoalescer.count(request_line_address));
completeHitCallback(mylist, len);
}
void
GPUCoalescer::recordCPReadCallBack(MachineID myMachID, MachineID senderMachID)
{
if (myMachID == senderMachID) {
CP_TCPLdHits++;
} else if (machineIDToMachineType(senderMachID) == MachineType_TCP) {
CP_TCPLdTransfers++;
} else if (machineIDToMachineType(senderMachID) == MachineType_TCC) {
CP_TCCLdHits++;
} else {
CP_LdMiss++;
}
}
void
GPUCoalescer::recordCPWriteCallBack(MachineID myMachID, MachineID senderMachID)
{
if (myMachID == senderMachID) {
CP_TCPStHits++;
} else if (machineIDToMachineType(senderMachID) == MachineType_TCP) {
CP_TCPStTransfers++;
} else if (machineIDToMachineType(senderMachID) == MachineType_TCC) {
CP_TCCStHits++;
} else {
CP_StMiss++;
}
}
void
GPUCoalescer::completeHitCallback(std::vector<PacketPtr> & mylist, int len)
{
for (int i = 0; i < len; ++i) {
RubyPort::SenderState *ss =
safe_cast<RubyPort::SenderState *>(mylist[i]->senderState);
MemSlavePort *port = ss->port;
assert(port != NULL);
mylist[i]->senderState = ss->predecessor;
delete ss;
port->hitCallback(mylist[i]);
trySendRetries();
}
testDrainComplete();
}
PacketPtr
GPUCoalescer::mapAddrToPkt(Addr address)
{
RequestTable::iterator i = m_readRequestTable.find(address);
assert(i != m_readRequestTable.end());
GPUCoalescerRequest* request = i->second;
return request->pkt;
}
void
GPUCoalescer::recordMissLatency(GPUCoalescerRequest* srequest,
MachineType mach,
Cycles initialRequestTime,
Cycles forwardRequestTime,
Cycles firstResponseTime,
bool success, bool isRegion)
{
RubyRequestType type = srequest->m_type;
Cycles issued_time = srequest->issue_time;
Cycles completion_time = curCycle();
assert(completion_time >= issued_time);
Cycles total_lat = completion_time - issued_time;
// cache stats (valid for RfO protocol only)
if (mach == MachineType_TCP) {
if (type == RubyRequestType_LD) {
GPU_TCPLdHits++;
} else {
GPU_TCPStHits++;
}
} else if (mach == MachineType_L1Cache_wCC) {
if (type == RubyRequestType_LD) {
GPU_TCPLdTransfers++;
} else {
GPU_TCPStTransfers++;
}
} else if (mach == MachineType_TCC) {
if (type == RubyRequestType_LD) {
GPU_TCCLdHits++;
} else {
GPU_TCCStHits++;
}
} else {
if (type == RubyRequestType_LD) {
GPU_LdMiss++;
} else {
GPU_StMiss++;
}
}
// Profile all access latency, even zero latency accesses
m_latencyHist.sample(total_lat);
m_typeLatencyHist[type]->sample(total_lat);
// Profile the miss latency for all non-zero demand misses
if (total_lat != Cycles(0)) {
m_missLatencyHist.sample(total_lat);
m_missTypeLatencyHist[type]->sample(total_lat);
if (mach != MachineType_NUM) {
m_missMachLatencyHist[mach]->sample(total_lat);
m_missTypeMachLatencyHist[type][mach]->sample(total_lat);
if ((issued_time <= initialRequestTime) &&
(initialRequestTime <= forwardRequestTime) &&
(forwardRequestTime <= firstResponseTime) &&
(firstResponseTime <= completion_time)) {
m_IssueToInitialDelayHist[mach]->sample(
initialRequestTime - issued_time);
m_InitialToForwardDelayHist[mach]->sample(
forwardRequestTime - initialRequestTime);
m_ForwardToFirstResponseDelayHist[mach]->sample(
firstResponseTime - forwardRequestTime);
m_FirstResponseToCompletionDelayHist[mach]->sample(
completion_time - firstResponseTime);
}
}
}
DPRINTFR(ProtocolTrace, "%15s %3s %10s%20s %6s>%-6s %s %d cycles\n",
curTick(), m_version, "Coal",
success ? "Done" : "SC_Failed", "", "",
printAddress(srequest->pkt->getAddr()), total_lat);
}
void
GPUCoalescer::regStats()
{
RubyPort::regStats();
// These statistical variables are not for display.
// The profiler will collate these across different
// coalescers and display those collated statistics.
m_outstandReqHist.init(10);
m_latencyHist.init(10);
m_missLatencyHist.init(10);
for (int i = 0; i < RubyRequestType_NUM; i++) {
m_typeLatencyHist.push_back(new Stats::Histogram());
m_typeLatencyHist[i]->init(10);
m_missTypeLatencyHist.push_back(new Stats::Histogram());
m_missTypeLatencyHist[i]->init(10);
}
for (int i = 0; i < MachineType_NUM; i++) {
m_missMachLatencyHist.push_back(new Stats::Histogram());
m_missMachLatencyHist[i]->init(10);
m_IssueToInitialDelayHist.push_back(new Stats::Histogram());
m_IssueToInitialDelayHist[i]->init(10);
m_InitialToForwardDelayHist.push_back(new Stats::Histogram());
m_InitialToForwardDelayHist[i]->init(10);
m_ForwardToFirstResponseDelayHist.push_back(new Stats::Histogram());
m_ForwardToFirstResponseDelayHist[i]->init(10);
m_FirstResponseToCompletionDelayHist.push_back(new Stats::Histogram());
m_FirstResponseToCompletionDelayHist[i]->init(10);
}
for (int i = 0; i < RubyRequestType_NUM; i++) {
m_missTypeMachLatencyHist.push_back(std::vector<Stats::Histogram *>());
for (int j = 0; j < MachineType_NUM; j++) {
m_missTypeMachLatencyHist[i].push_back(new Stats::Histogram());
m_missTypeMachLatencyHist[i][j]->init(10);
}
}
// GPU cache stats
GPU_TCPLdHits
.name(name() + ".gpu_tcp_ld_hits")
.desc("loads that hit in the TCP")
;
GPU_TCPLdTransfers
.name(name() + ".gpu_tcp_ld_transfers")
.desc("TCP to TCP load transfers")
;
GPU_TCCLdHits
.name(name() + ".gpu_tcc_ld_hits")
.desc("loads that hit in the TCC")
;
GPU_LdMiss
.name(name() + ".gpu_ld_misses")
.desc("loads that miss in the GPU")
;
GPU_TCPStHits
.name(name() + ".gpu_tcp_st_hits")
.desc("stores that hit in the TCP")
;
GPU_TCPStTransfers
.name(name() + ".gpu_tcp_st_transfers")
.desc("TCP to TCP store transfers")
;
GPU_TCCStHits
.name(name() + ".gpu_tcc_st_hits")
.desc("stores that hit in the TCC")
;
GPU_StMiss
.name(name() + ".gpu_st_misses")
.desc("stores that miss in the GPU")
;
// CP cache stats
CP_TCPLdHits
.name(name() + ".cp_tcp_ld_hits")
.desc("loads that hit in the TCP")
;
CP_TCPLdTransfers
.name(name() + ".cp_tcp_ld_transfers")
.desc("TCP to TCP load transfers")
;
CP_TCCLdHits
.name(name() + ".cp_tcc_ld_hits")
.desc("loads that hit in the TCC")
;
CP_LdMiss
.name(name() + ".cp_ld_misses")
.desc("loads that miss in the GPU")
;
CP_TCPStHits
.name(name() + ".cp_tcp_st_hits")
.desc("stores that hit in the TCP")
;
CP_TCPStTransfers
.name(name() + ".cp_tcp_st_transfers")
.desc("TCP to TCP store transfers")
;
CP_TCCStHits
.name(name() + ".cp_tcc_st_hits")
.desc("stores that hit in the TCC")
;
CP_StMiss
.name(name() + ".cp_st_misses")
.desc("stores that miss in the GPU")
;
}
| 35.400583 | 91 | 0.620204 | [
"vector"
] |
61f3698c48a6d0ae9a0f97ed8fc4b1f9364f6409 | 9,463 | cpp | C++ | VideoPlayer/VideoPlayer/Source/Shared/MediaHelpers.cpp | AMollis/UnityPluginCollection | 72bbc15e926e974c4debacd021f134a5a6bbeddb | [
"MIT"
] | null | null | null | VideoPlayer/VideoPlayer/Source/Shared/MediaHelpers.cpp | AMollis/UnityPluginCollection | 72bbc15e926e974c4debacd021f134a5a6bbeddb | [
"MIT"
] | null | null | null | VideoPlayer/VideoPlayer/Source/Shared/MediaHelpers.cpp | AMollis/UnityPluginCollection | 72bbc15e926e974c4debacd021f134a5a6bbeddb | [
"MIT"
] | 1 | 2020-05-31T20:54:09.000Z | 2020-05-31T20:54:09.000Z | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#pragma once
#include "pch.h"
#include "MediaHelpers.h"
#include <windows.graphics.directx.direct3d11.interop.h>
using namespace winrt;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Graphics::DirectX::Direct3D11;
using namespace winrt::Windows::Media::Playback;
HRESULT SharedTextureBuffer::Create(
_In_ ID3D11Device* d3dDevice,
_In_ IMFDXGIDeviceManager* dxgiDeviceManager,
_In_ uint32_t width,
_In_ uint32_t height,
_In_ std::weak_ptr<SharedTextureBuffer> outputBuffer)
{
NULL_CHK_HR(d3dDevice, E_INVALIDARG);
NULL_CHK_HR(dxgiDeviceManager, E_INVALIDARG);
if (width < 1 && height < 1)
{
IFR(E_INVALIDARG);
}
auto buffer = outputBuffer.lock();
NULL_CHK_HR(buffer, E_INVALIDARG);
HANDLE deviceHandle;
IFR(dxgiDeviceManager->OpenDeviceHandle(&deviceHandle));
com_ptr<ID3D11Device1> mediaDevice = nullptr;
IFR(dxgiDeviceManager->LockDevice(deviceHandle, __uuidof(ID3D11Device1), mediaDevice.put_void(), TRUE));
// since the device is locked, unlock before we exit function
HRESULT hr = S_OK;
auto textureDesc = CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_B8G8R8A8_UNORM, width, height);
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
textureDesc.MipLevels = 1;
textureDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_NTHANDLE;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
// create a texture
com_ptr<ID3D11Texture2D> spTexture = nullptr;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{};
com_ptr<ID3D11ShaderResourceView> spSRV = nullptr;
com_ptr<IDXGIResource1> spDXGIResource = nullptr;
com_ptr<ID3D11Texture2D> spMediaTexture = nullptr;
HANDLE sharedHandle = INVALID_HANDLE_VALUE;
IDirect3DSurface mediaSurface;
com_ptr<IMFMediaBuffer> dxgiMediaBuffer = nullptr;
com_ptr<IMFSample> mediaSample = nullptr;
IFG(d3dDevice->CreateTexture2D(&textureDesc, nullptr, spTexture.put()), done);
// srv for the texture
srvDesc = CD3D11_SHADER_RESOURCE_VIEW_DESC(spTexture.get(), D3D11_SRV_DIMENSION_TEXTURE2D);
IFG(d3dDevice->CreateShaderResourceView(spTexture.get(), &srvDesc, spSRV.put()), done);
IFG(spTexture->QueryInterface(__uuidof(IDXGIResource1), spDXGIResource.put_void()), done);
// create shared texture
IFG(spDXGIResource->CreateSharedHandle(
nullptr,
DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE,
nullptr,
&sharedHandle), done);
IFG(mediaDevice->OpenSharedResource1(sharedHandle, __uuidof(ID3D11Texture2D), spMediaTexture.put_void()), done);
IFG(GetSurfaceFromTexture(spMediaTexture.get(), mediaSurface), done);
// create a media buffer for the texture
IFG(MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), spMediaTexture.get(), 0, /*fBottomUpWhenLinear*/false, dxgiMediaBuffer.put()), done);
// create a sample with the buffer
IFG(MFCreateSample(mediaSample.put()), done);
IFG(mediaSample->AddBuffer(dxgiMediaBuffer.get()), done);
buffer->frameTextureDesc = textureDesc;
buffer->frameTexture.attach(spTexture.detach());
buffer->frameTextureSRV.attach(spSRV.detach());
buffer->sharedTextureHandle = sharedHandle;
buffer->mediaTexture.attach(spMediaTexture.detach());
buffer->mediaSurface = mediaSurface;
buffer->mediaBuffer.attach(dxgiMediaBuffer.detach());
buffer->mediaSample.attach(mediaSample.detach());
done:
if (FAILED(hr))
{
if (sharedHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(sharedHandle);
}
}
dxgiDeviceManager->UnlockDevice(deviceHandle, FALSE);
return hr;
}
SharedTextureBuffer::SharedTextureBuffer()
: frameTextureDesc{}
, frameTexture(nullptr)
, frameTextureSRV(nullptr)
, sharedTextureHandle(INVALID_HANDLE_VALUE)
, mediaTexture(nullptr)
, mediaSurface(nullptr)
, mediaBuffer(nullptr)
, mediaSample(nullptr)
{}
SharedTextureBuffer::~SharedTextureBuffer()
{
Reset();
}
void SharedTextureBuffer::Reset()
{
// primary texture
if (sharedTextureHandle != INVALID_HANDLE_VALUE)
{
if (CloseHandle(sharedTextureHandle))
{
sharedTextureHandle = INVALID_HANDLE_VALUE;
}
}
mediaSample = nullptr;
mediaBuffer = nullptr;
mediaSurface = nullptr;
mediaTexture = nullptr;
frameTextureSRV = nullptr;
frameTexture = nullptr;
ZeroMemory(&frameTextureDesc, sizeof(CD3D11_TEXTURE2D_DESC));
}
// Check for SDK Layer support.
inline bool SdkLayersAvailable()
{
HRESULT hr = E_NOTIMPL;
#if defined(_DEBUG)
hr = D3D11CreateDevice(
nullptr,
D3D_DRIVER_TYPE_NULL, // There is no need to create a real hardware device.
0,
D3D11_CREATE_DEVICE_DEBUG, // Check for the SDK layers.
nullptr, // Any feature level will do.
0,
D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps.
nullptr, // No need to keep the D3D device reference.
nullptr, // No need to know the feature level.
nullptr // No need to keep the D3D device context reference.
);
#endif
return SUCCEEDED(hr);
}
_Use_decl_annotations_
HRESULT CreateMediaDevice(
IDXGIAdapter* pDXGIAdapter,
ID3D11Device** ppDevice)
{
NULL_CHK_HR(ppDevice, E_INVALIDARG);
// Create the Direct3D 11 API device object and a corresponding context.
D3D_FEATURE_LEVEL featureLevel;
// This flag adds support for surfaces with a different color channel ordering
// than the API default. It is required for compatibility with Direct2D.
UINT creationFlags = D3D11_CREATE_DEVICE_VIDEO_SUPPORT | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
// If the project is in a debug build, enable debugging via SDK Layers with this flag.
if (SdkLayersAvailable())
{
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
}
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
com_ptr<ID3D11Device> spDevice;
com_ptr<ID3D11DeviceContext> spContext;
D3D_DRIVER_TYPE driverType = (nullptr != pDXGIAdapter) ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE;
// Create a device using the hardware graphics driver if adapter is not supplied
HRESULT hr = D3D11CreateDevice(
pDXGIAdapter, // if nullptr will use default adapter.
driverType,
0, // Should be 0 unless the driver is D3D_DRIVER_TYPE_SOFTWARE.
creationFlags, // Set debug and Direct2D compatibility flags.
featureLevels, // List of feature levels this app can support.
ARRAYSIZE(featureLevels), // Size of the list above.
D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION for Windows Store apps.
spDevice.put(), // Returns the Direct3D device created.
&featureLevel, // Returns feature level of device created.
spContext.put() // Returns the device immediate context.
);
if (FAILED(hr))
{
// fallback to WARP if we are not specifying an adapter
if (nullptr == pDXGIAdapter)
{
// If the initialization fails, fall back to the WARP device.
// For more information on WARP, see:
// http://go.microsoft.com/fwlink/?LinkId=286690
hr = D3D11CreateDevice(
nullptr,
D3D_DRIVER_TYPE_WARP, // Create a WARP device instead of a hardware device.
0,
creationFlags,
featureLevels,
ARRAYSIZE(featureLevels),
D3D11_SDK_VERSION,
spDevice.put(),
&featureLevel,
spContext.put());
}
IFR(hr);
}
else
{
// workaround for nvidia GPU's, cast to ID3D11VideoDevice
auto videoDevice = spDevice.as<ID3D11VideoDevice>();
}
// Turn multithreading on
auto spMultithread = spContext.as<ID3D10Multithread>();
NULL_CHK_HR(spMultithread, E_POINTER);
spMultithread->SetMultithreadProtected(TRUE);
*ppDevice = spDevice.detach();
return S_OK;
}
_Use_decl_annotations_
HRESULT GetSurfaceFromTexture(
ID3D11Texture2D* pTexture,
IDirect3DSurface& direct3dSurface)
{
com_ptr<IDXGISurface> dxgiSurface = nullptr;
IFR(pTexture->QueryInterface(__uuidof(IDXGISurface), dxgiSurface.put_void()));
com_ptr<::IInspectable> spInspectable = nullptr;
IFR(CreateDirect3D11SurfaceFromDXGISurface(dxgiSurface.get(), spInspectable.put()));
IFR(spInspectable->QueryInterface(
guid_of<IDirect3DSurface>(),
reinterpret_cast<void**>(put_abi(direct3dSurface))));
return S_OK;
}
| 33.556738 | 146 | 0.67505 | [
"object"
] |
61f410000cfd444acef7451581e6031bf17a2b6d | 2,921 | hpp | C++ | src/lib/statistics/base_column_statistics.hpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | 2 | 2019-01-22T19:44:32.000Z | 2019-01-22T19:52:33.000Z | src/lib/statistics/base_column_statistics.hpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | 69 | 2019-05-24T10:01:32.000Z | 2019-12-13T19:09:05.000Z | src/lib/statistics/base_column_statistics.hpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include "all_type_variant.hpp"
#include "types.hpp"
namespace opossum {
class BaseColumnStatistics;
// Result of a cardinality estimation of filtering by value
struct FilterByValueEstimate final {
float selectivity{0.0f};
std::shared_ptr<BaseColumnStatistics> column_statistics;
};
// Result of a cardinality estimation of filtering by comparing two columns
struct FilterByColumnComparisonEstimate {
float selectivity{0.0f};
std::shared_ptr<BaseColumnStatistics> left_column_statistics;
std::shared_ptr<BaseColumnStatistics> right_column_statistics;
};
class BaseColumnStatistics {
public:
BaseColumnStatistics(const DataType data_type, const float null_value_ratio, const float distinct_count);
virtual ~BaseColumnStatistics() = default;
BaseColumnStatistics(const BaseColumnStatistics&) = default;
BaseColumnStatistics(BaseColumnStatistics&&) = default;
BaseColumnStatistics& operator=(const BaseColumnStatistics&) = default;
BaseColumnStatistics& operator=(BaseColumnStatistics&&) = default;
/**
* @defgroup Member access
* @{
*/
DataType data_type() const;
float null_value_ratio() const;
float non_null_value_ratio() const;
float distinct_count() const;
void set_null_value_ratio(const float null_value_ratio);
/** @} */
/**
* @return a clone of the concrete ColumnStatistics object
*/
virtual std::shared_ptr<BaseColumnStatistics> clone() const = 0;
/**
* @return a clone() of this, with the null_value_ratio set to 0
*/
std::shared_ptr<BaseColumnStatistics> without_null_values() const;
/**
* @return a clone() of this, with the null_value_ratio set to 1
*/
std::shared_ptr<BaseColumnStatistics> only_null_values() const;
/**
* @defgroup Cardinality estimation
* @{
*/
/**
* Estimate a Column-Value Predicate, e.g. "a > 5"
*/
virtual FilterByValueEstimate estimate_predicate_with_value(
const PredicateCondition predicate_condition, const AllTypeVariant& value,
const std::optional<AllTypeVariant>& value2 = std::nullopt) const = 0;
/**
* Estimate a Column-ValuePlaceholder Predicate, e.g. "a > ?"
* Since the value of the ValuePlaceholder (naturally) isn't known, has to resort to magic values.
*/
virtual FilterByValueEstimate estimate_predicate_with_value_placeholder(
const PredicateCondition predicate_condition,
const std::optional<AllTypeVariant>& value2 = std::nullopt) const = 0;
/**
* Estimate a Column-Column Predicate, e.g. "a > b"
*/
virtual FilterByColumnComparisonEstimate estimate_predicate_with_column(
const PredicateCondition predicate_condition, const BaseColumnStatistics& base_right_column_statistics) const = 0;
/** @} */
virtual std::string description() const = 0;
protected:
const DataType _data_type;
float _null_value_ratio;
float _distinct_count;
};
} // namespace opossum
| 30.427083 | 120 | 0.74495 | [
"object"
] |
61fab134bc929e70b56c01bf947c3ddf488bb2eb | 304,634 | cpp | C++ | libs/exprtk/exprtk_test.cpp | alxarsenault/axLib-1 | aff63abebff118059d5daca80f06cc8464192c6d | [
"MIT"
] | 1 | 2019-10-15T05:09:34.000Z | 2019-10-15T05:09:34.000Z | libs/exprtk/exprtk_test.cpp | EQ4/axLib | aff63abebff118059d5daca80f06cc8464192c6d | [
"MIT"
] | null | null | null | libs/exprtk/exprtk_test.cpp | EQ4/axLib | aff63abebff118059d5daca80f06cc8464192c6d | [
"MIT"
] | 1 | 2021-12-18T06:30:51.000Z | 2021-12-18T06:30:51.000Z | /*
**************************************************************
* C++ Mathematical Expression Toolkit Library *
* *
* Examples and Unit-Tests *
* Author: Arash Partow (1999-2014) *
* URL: http://www.partow.net/programming/exprtk/index.html *
* *
* Copyright notice: *
* Free use of the Mathematical Expression Toolkit Library is *
* permitted under the guidelines and in accordance with the *
* most current version of the Common Public License. *
* http://www.opensource.org/licenses/cpl1.0.php *
* *
**************************************************************
*/
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <deque>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "exprtk.hpp"
typedef double numeric_type;
typedef std::pair<std::string,numeric_type> test_t;
static const test_t test_list[] =
{
// Note: Each of following tests must compile down
// to a single literal node.
test_t("0",0.0),
test_t("1",1.0),
test_t("2",2.0),
test_t("3",3.0),
test_t("4",4.0),
test_t("5",5.0),
test_t("6",6.0),
test_t("7",7.0),
test_t("8",8.0),
test_t("9",9.0),
test_t("12.12",12.12),
test_t("123.123",123.123),
test_t("1234.1234",1234.1234),
test_t("12345.12345",12345.12345),
test_t("123456.123456",123456.123456),
test_t("0.0",0.0),
test_t("1.0",1.0),
test_t("2.0",2.0),
test_t("3.0",3.0),
test_t("4.0",4.0),
test_t("5.0",5.0),
test_t("6.0",6.0),
test_t("7.0",7.0),
test_t("8.0",8.0),
test_t("9.0",9.0),
test_t("0.0",0.0),
test_t("1.1",1.1),
test_t("2.2",2.2),
test_t("3.3",3.3),
test_t("4.4",4.4),
test_t("5.5",5.5),
test_t("6.6",6.6),
test_t("7.7",7.7),
test_t("8.8",8.8),
test_t("9.9",9.9),
test_t("+0",0.0),
test_t("+1",1.0),
test_t("+2",2.0),
test_t("+3",3.0),
test_t("+4",4.0),
test_t("+5",5.0),
test_t("+6",6.0),
test_t("+7",7.0),
test_t("+8",8.0),
test_t("+9",9.0),
test_t("+0.0",0.0),
test_t("+1.0",1.0),
test_t("+2.0",2.0),
test_t("+3.0",3.0),
test_t("+4.0",4.0),
test_t("+5.0",5.0),
test_t("+6.0",6.0),
test_t("+7.0",7.0),
test_t("+8.0",8.0),
test_t("+9.0",9.0),
test_t("+0.0",0.0),
test_t("+1.1",1.1),
test_t("+2.2",2.2),
test_t("+3.3",3.3),
test_t("+4.4",4.4),
test_t("+5.5",5.5),
test_t("+6.6",6.6),
test_t("+7.7",7.7),
test_t("+8.8",8.8),
test_t("+9.9",9.9),
test_t("-0",-0.0),
test_t("-1",-1.0),
test_t("-2",-2.0),
test_t("-3",-3.0),
test_t("-4",-4.0),
test_t("-5",-5.0),
test_t("-6",-6.0),
test_t("-7",-7.0),
test_t("-8",-8.0),
test_t("-9",-9.0),
test_t("-0.0",-0.0),
test_t("-1.0",-1.0),
test_t("-2.0",-2.0),
test_t("-3.0",-3.0),
test_t("-4.0",-4.0),
test_t("-5.0",-5.0),
test_t("-6.0",-6.0),
test_t("-7.0",-7.0),
test_t("-8.0",-8.0),
test_t("-9.0",-9.0),
test_t("-0.0",-0.0),
test_t("-1.1",-1.1),
test_t("-2.2",-2.2),
test_t("-3.3",-3.3),
test_t("-4.4",-4.4),
test_t("-5.5",-5.5),
test_t("-6.6",-6.6),
test_t("-7.7",-7.7),
test_t("-8.8",-8.8),
test_t("-9.9",-9.9),
test_t("0.0e+0" ,+0.0e+0),
test_t("1.1e+1" ,+1.1e+1),
test_t("2.2e+2" ,+2.2e+2),
test_t("3.3e+3" ,+3.3e+3),
test_t("4.4e+4" ,+4.4e+4),
test_t("5.5e+5" ,+5.5e+5),
test_t("6.6e+6" ,+6.6e+6),
test_t("7.7e+7" ,+7.7e+7),
test_t("8.8e+8" ,+8.8e+8),
test_t("9.9e+9" ,+9.9e+9),
test_t("-0.0e+0",-0.0e+0),
test_t("-1.1e+1",-1.1e+1),
test_t("-2.2e+2",-2.2e+2),
test_t("-3.3e+3",-3.3e+3),
test_t("-4.4e+4",-4.4e+4),
test_t("-5.5e+5",-5.5e+5),
test_t("-6.6e+6",-6.6e+6),
test_t("-7.7e+7",-7.7e+7),
test_t("-8.8e+8",-8.8e+8),
test_t("-9.9e+9",-9.9e+9),
test_t("0.0E+0" ,+0.0E+0),
test_t("1.1E+1" ,+1.1E+1),
test_t("2.2E+2" ,+2.2E+2),
test_t("3.3E+3" ,+3.3E+3),
test_t("4.4E+4" ,+4.4E+4),
test_t("5.5E+5" ,+5.5E+5),
test_t("6.6E+6" ,+6.6E+6),
test_t("7.7E+7" ,+7.7E+7),
test_t("8.8E+8" ,+8.8E+8),
test_t("9.9E+9" ,+9.9E+9),
test_t("-0.0E+0",-0.0E+0),
test_t("-1.1E+1",-1.1E+1),
test_t("-2.2E+2",-2.2E+2),
test_t("-3.3E+3",-3.3E+3),
test_t("-4.4E+4",-4.4E+4),
test_t("-5.5E+5",-5.5E+5),
test_t("-6.6E+6",-6.6E+6),
test_t("-7.7E+7",-7.7E+7),
test_t("-8.8E+8",-8.8E+8),
test_t("-9.9E+9",-9.9E+9),
test_t("(0)",0.0),
test_t("(1)",1.0),
test_t("(2)",2.0),
test_t("(3)",3.0),
test_t("(4)",4.0),
test_t("(5)",5.0),
test_t("(6)",6.0),
test_t("(7)",7.0),
test_t("(8)",8.0),
test_t("(9)",9.0),
test_t("(0.0)",0.0),
test_t("(1.0)",1.0),
test_t("(2.0)",2.0),
test_t("(3.0)",3.0),
test_t("(4.0)",4.0),
test_t("(5.0)",5.0),
test_t("(6.0)",6.0),
test_t("(7.0)",7.0),
test_t("(8.0)",8.0),
test_t("(9.0)",9.0),
test_t("(0.0)",0.0),
test_t("(1.1)",1.1),
test_t("(2.2)",2.2),
test_t("(3.3)",3.3),
test_t("(4.4)",4.4),
test_t("(5.5)",5.5),
test_t("(6.6)",6.6),
test_t("(7.7)",7.7),
test_t("(8.8)",8.8),
test_t("(9.9)",9.9),
test_t("(+0)" ,0.0),
test_t("(+1)" ,1.0),
test_t("(+2)" ,2.0),
test_t("(+3)" ,3.0),
test_t("(+4)" ,4.0),
test_t("(+5)" ,5.0),
test_t("(+6)" ,6.0),
test_t("(+7)" ,7.0),
test_t("(+8)" ,8.0),
test_t("(+9)" ,9.0),
test_t("(+0.0)",0.0),
test_t("(+1.0)",1.0),
test_t("(+2.0)",2.0),
test_t("(+3.0)",3.0),
test_t("(+4.0)",4.0),
test_t("(+5.0)",5.0),
test_t("(+6.0)",6.0),
test_t("(+7.0)",7.0),
test_t("(+8.0)",8.0),
test_t("(+9.0)",9.0),
test_t("(+0.0)",0.0),
test_t("(+1.1)",1.1),
test_t("(+2.2)",2.2),
test_t("(+3.3)",3.3),
test_t("(+4.4)",4.4),
test_t("(+5.5)",5.5),
test_t("(+6.6)",6.6),
test_t("(+7.7)",7.7),
test_t("(+8.8)",8.8),
test_t("(+9.9)",9.9),
test_t("(-0)" ,-0.0),
test_t("(-1)" ,-1.0),
test_t("(-2)" ,-2.0),
test_t("(-3)" ,-3.0),
test_t("(-4)" ,-4.0),
test_t("(-5)" ,-5.0),
test_t("(-6)" ,-6.0),
test_t("(-7)" ,-7.0),
test_t("(-8)" ,-8.0),
test_t("(-9)" ,-9.0),
test_t("(-0.0)",-0.0),
test_t("(-1.0)",-1.0),
test_t("(-2.0)",-2.0),
test_t("(-3.0)",-3.0),
test_t("(-4.0)",-4.0),
test_t("(-5.0)",-5.0),
test_t("(-6.0)",-6.0),
test_t("(-7.0)",-7.0),
test_t("(-8.0)",-8.0),
test_t("(-9.0)",-9.0),
test_t("(-0.0)",-0.0),
test_t("(-1.1)",-1.1),
test_t("(-2.2)",-2.2),
test_t("(-3.3)",-3.3),
test_t("(-4.4)",-4.4),
test_t("(-5.5)",-5.5),
test_t("(-6.6)",-6.6),
test_t("(-7.7)",-7.7),
test_t("(-8.8)",-8.8),
test_t("(-9.9)",-9.9),
test_t("-(1.1)",-1.1),
test_t("-(1.1+2.2)",-3.3),
test_t("1234567890",1234567890),
test_t("123456789.0",123456789.0),
test_t("+1234567890",1234567890),
test_t("+123456789.0",123456789.0),
test_t("-1234567890",-1234567890),
test_t("-123456789.0",-123456789.0),
test_t("1234.567890",1234.567890),
test_t("-1234.567890",-1234.567890),
test_t("0+9",9.0),
test_t("1+8",9.0),
test_t("2+7",9.0),
test_t("3+6",9.0),
test_t("4+5",9.0),
test_t("5+4",9.0),
test_t("6+3",9.0),
test_t("7+2",9.0),
test_t("8+1",9.0),
test_t("9+0",9.0),
test_t(" 0 + 9 ",9.0),
test_t(" 1 + 8 ",9.0),
test_t(" 2 + 7 ",9.0),
test_t(" 3 + 6 ",9.0),
test_t(" 4 + 5 ",9.0),
test_t(" 5 + 4 ",9.0),
test_t(" 6 + 3 ",9.0),
test_t(" 7 + 2 ",9.0),
test_t(" 8 + 1 ",9.0),
test_t(" 9 + 0 ",9.0),
test_t("( 0 + 9 )",9.0),
test_t("( 1 + 8 )",9.0),
test_t("( 2 + 7 )",9.0),
test_t("( 3 + 6 )",9.0),
test_t("( 4 + 5 )",9.0),
test_t("( 5 + 4 )",9.0),
test_t("( 6 + 3 )",9.0),
test_t("( 7 + 2 )",9.0),
test_t("( 8 + 1 )",9.0),
test_t("( 9 + 0 )",9.0),
test_t("1+2",+3.0),
test_t("1-2",-1.0),
test_t("1*2",+2.0),
test_t("1/2",+0.5),
test_t("1.1+2.2", +3.3),
test_t("1.1-2.2", -1.1),
test_t("1.1*2.2",+2.42),
test_t("1.1/2.2", +0.5),
test_t("0-9",-9.0),
test_t("1-8",-7.0),
test_t("2-7",-5.0),
test_t("3-6",-3.0),
test_t("4-5",-1.0),
test_t("5-4",+1.0),
test_t("6-3",+3.0),
test_t("7-2",+5.0),
test_t("8-1",+7.0),
test_t("9-0",+9.0),
test_t(" 0 - 9 ",-9.0),
test_t(" 1 - 8 ",-7.0),
test_t(" 2 - 7 ",-5.0),
test_t(" 3 - 6 ",-3.0),
test_t(" 4 - 5 ",-1.0),
test_t(" 5 - 4 ",+1.0),
test_t(" 6 - 3 ",+3.0),
test_t(" 7 - 2 ",+5.0),
test_t(" 8 - 1 ",+7.0),
test_t(" 9 - 0 ",+9.0),
test_t("( 0 - 9 )",-9.0),
test_t("( 1 - 8 )",-7.0),
test_t("( 2 - 7 )",-5.0),
test_t("( 3 - 6 )",-3.0),
test_t("( 4 - 5 )",-1.0),
test_t("( 5 - 4 )",+1.0),
test_t("( 6 - 3 )",+3.0),
test_t("( 7 - 2 )",+5.0),
test_t("( 8 - 1 )",+7.0),
test_t("( 9 - 0 )",+9.0),
test_t("-(1+2)",-3.0),
test_t("+(1+2)",+3.0),
test_t("+(1-2)",-1.0),
test_t("-(1-2)",+1.0),
test_t("(-3*-6)",+18.0),
test_t("(-6*-3)",+18.0),
test_t("-(-3*-6)",-18.0),
test_t("-(-6*-3)",-18.0),
test_t("1.1+2.2+3.3",+6.6),
test_t("+1.1+2.2+3.3",+6.6),
test_t("-1.1-2.2-3.3",-6.6),
test_t("1.1*2.2*3.3",+7.986),
test_t("+1.1*2.2*3.3",+7.986),
test_t("-1.1*-2.2*-3.3",-7.986),
test_t("1 + 1/2",+1.5),
test_t("1 + (1/2)",+1.5),
test_t("1.1 + 1.1/2.2",+1.6),
test_t("1.1 + (1.1/2.2)",+1.6),
test_t("2 * 1/2",+1.0),
test_t("2 * (1/2)",+1.0),
test_t("2.2 * 1.1/2.2",+1.1),
test_t("2.2 * (1.1/2.2)",+1.1),
test_t("1^2",1.0),
test_t("2^1",2.0),
test_t("2^3",8.0),
test_t("-2^3",-8.0),
test_t("-2^4",-16.0),
test_t("(-2)^3",-8.0),
test_t("(-2)^4",+16.0),
test_t("3^2^4",43046721.0),
test_t("1.1^2.2",1.23328630055466251099),
test_t("2.2^1.1",2.3804822576003541627),
test_t("2.2^3.3",13.48946876053338489127),
test_t("3.3^2.2^1.1",17.15193942371376191362),
test_t("+3.3^2.2^1.1",17.15193942371376191362),
test_t("3.3^+2.2^1.1",17.15193942371376191362),
test_t("3.3^2.2^+1.1",17.15193942371376191362),
test_t("3.3^2.2^-1.1",1.65127293793867959137),
test_t("+3.3^+2.2^-1.1",1.65127293793867959137),
test_t("1.1^(1.1 * 2.2)",1.25941916576299080582),
test_t("2.2^(1.1 * 3.3)",17.49823848953534759743),
test_t("3.3^(1.1 * 2.2)",17.98058156638874965269),
test_t("1.1^-2.2/1.1",0.73712884727743375853),
test_t("1.1^+2.2/1.1",1.121169364140602282717273261774),
test_t("1.1^2.2/+1.1",1.121169364140602282717273261774),
test_t("1.1^+2.2/+1.1",1.121169364140602282717273261774),
test_t("1.1^+2.2/-1.1",-1.121169364140602282717273261774),
test_t("1.1^2.2/-1.1",-1.121169364140602282717273261774),
test_t("1.1^+2.2/-1.1",-1.121169364140602282717273261774),
test_t("+1.1^-2.2/1.1",0.73712884727743375853),
test_t("+1.1^+2.2/1.1",1.121169364140602282717273261774),
test_t("+1.1^2.2/+1.1",1.121169364140602282717273261774),
test_t("+1.1^+2.2/+1.1",1.121169364140602282717273261774),
test_t("+1.1^+2.2/-1.1",-1.121169364140602282717273261774),
test_t("+1.1^2.2/-1.1",-1.121169364140602282717273261774),
test_t("+1.1^+2.2/-1.1",-1.121169364140602282717273261774),
test_t("equal(1.23^3,(1.23 * 1.23 * 1.23))",1.0),
test_t("equal(1.23^-3,1/(1.23 * 1.23 * 1.23))",1.0),
test_t("equal((2.1 + 1.23^3),(2.1 + [1.23 * 1.23 * 1.23]))",1.0),
test_t("equal((2.1 - 1.23^3),(2.1 - [1.23 * 1.23 * 1.23]))",1.0),
test_t("equal((2.1 * 1.23^3),(2.1 * [1.23 * 1.23 * 1.23]))",1.0),
test_t("equal((2.1 / 1.23^3),(2.1 / [1.23 * 1.23 * 1.23]))",1.0),
test_t("equal((1.23^3 + 2.1),({1.23 * 1.23 * 1.23} + 2.1))",1.0),
test_t("equal((1.23^3 - 2.1),({1.23 * 1.23 * 1.23} - 2.1))",1.0),
test_t("equal((1.23^3 * 2.1),({1.23 * 1.23 * 1.23} * 2.1))",1.0),
test_t("equal((1.23^3 / 2.1),({1.23 * 1.23 * 1.23} / 2.1))",1.0),
test_t("equal(1.0^(1.0/2.0),sqrt(1.0))",1.0),
test_t("equal(1.0^(1.0/2.0),root(1.0,2.0))",1.0),
test_t("equal(1.0^(1.0/3.0),root(1.0,3.0))",1.0),
test_t("equal(1.0^(1.0/4.0),root(1.0,4.0))",1.0),
test_t("equal(1.0^(1.0/5.0),root(1.0,5.0))",1.0),
test_t("equal(1.0^(1.0/6.0),root(1.0,6.0))",1.0),
test_t("equal(1.0^(1.0/7.0),root(1.0,7.0))",1.0),
test_t("equal(1.0^(1.0/8.0),root(1.0,8.0))",1.0),
test_t("equal(1.0^(1.0/9.0),root(1.0,9.0))",1.0),
test_t("equal(2.0^(1.0/2.0),sqrt(2.0))",1.0),
test_t("equal(2.0^(1.0/2.0),root(2.0,2.0))",1.0),
test_t("equal(3.0^(1.0/3.0),root(3.0,3.0))",1.0),
test_t("equal(4.0^(1.0/4.0),root(4.0,4.0))",1.0),
test_t("equal(5.0^(1.0/5.0),root(5.0,5.0))",1.0),
test_t("equal(6.0^(1.0/6.0),root(6.0,6.0))",1.0),
test_t("equal(7.0^(1.0/7.0),root(7.0,7.0))",1.0),
test_t("equal(8.0^(1.0/8.0),root(8.0,8.0))",1.0),
test_t("equal(9.0^(1.0/9.0),root(9.0,9.0))",1.0),
test_t("1 < 2", 1.0),
test_t("1 <= 2", 1.0),
test_t("1.1 <= 2.2", 1.0),
test_t("(1.0 + 0.1) <= (2.0 + 0.2)", 1.0),
test_t("1 > 2", 0.0),
test_t("1 >= 2", 0.0),
test_t("1.1 >= 2.2", 0.0),
test_t("(1.0 + 0.1) >= (2.0 + 0.2)", 0.0),
test_t("1 <> 2", 1.0),
test_t("1 != 2", 1.0),
test_t("1.1 <> 2.2", 1.0),
test_t("1.1 != 2.2", 1.0),
test_t("(1.0 + 0.1) <> (2.0 + 0.2)", 1.0),
test_t("(1.0 + 0.1) != (2.0 + 0.2)", 1.0),
test_t("1 == 1", 1.0),
test_t("1.1 == 1.1", 1.0),
test_t("1 = 1", 1.0),
test_t("1.1 = 1.1", 1.0),
test_t("1 <> 1", 0.0),
test_t("1 != 1", 0.0),
test_t("1.1 <> 1.1", 0.0),
test_t("1.1 != 1.1", 0.0),
test_t("(1.0 + 0.1) <> (1.0 + 0.1)", 0.0),
test_t("(1.0 + 0.1) != (1.0 + 0.1)", 0.0),
test_t("equal(1.1,1.1)",1.0),
test_t("equal(1.1,2.2)",0.0),
test_t("not_equal(1.1,1.1)",0.0),
test_t("not_equal(1.1,2.2)",1.0),
test_t("1 and 1",1.0),
test_t("1 and 0",0.0),
test_t("0 and 1",0.0),
test_t("0 and 0",0.0),
test_t("1.0 and 1.0",1.0),
test_t("1.0 and 0.0",0.0),
test_t("0.0 and 1.0",0.0),
test_t("0.0 and 0.0",0.0),
test_t("(1 and 1)",1.0),
test_t("(1 and 0)",0.0),
test_t("(0 and 1)",0.0),
test_t("(0 and 0)",0.0),
test_t("(1.0 and 1.0)",1.0),
test_t("(1.0 and 0.0)",0.0),
test_t("(0.0 and 1.0)",0.0),
test_t("(0.0 and 0.0)",0.0),
test_t("1 or 1",1.0),
test_t("1 or 0",1.0),
test_t("0 or 1",1.0),
test_t("0 or 0",0.0),
test_t("1.0 or 1.0",1.0),
test_t("1.0 or 0.0",1.0),
test_t("0.0 or 1.0",1.0),
test_t("0.0 or 0.0",0.0),
test_t("(1 or 1)",1.0),
test_t("(1 or 0)",1.0),
test_t("(0 or 1)",1.0),
test_t("(0 or 0)",0.0),
test_t("(1.0 or 1.0)",1.0),
test_t("(1.0 or 0.0)",1.0),
test_t("(0.0 or 1.0)",1.0),
test_t("(0.0 or 0.0)",0.0),
test_t("1 nand 1",0.0),
test_t("1 nand 0",1.0),
test_t("0 nand 1",1.0),
test_t("0 nand 0",1.0),
test_t("1.0 nand 1.0",0.0),
test_t("1.0 nand 0.0",1.0),
test_t("0.0 nand 1.0",1.0),
test_t("0.0 nand 0.0",1.0),
test_t("(1 nand 1)",0.0),
test_t("(1 nand 0)",1.0),
test_t("(0 nand 1)",1.0),
test_t("(0 nand 0)",1.0),
test_t("(1.0 nand 1.0)",0.0),
test_t("(1.0 nand 0.0)",1.0),
test_t("(0.0 nand 1.0)",1.0),
test_t("(0.0 nand 0.0)",1.0),
test_t("1 nor 1",0.0),
test_t("1 nor 0",0.0),
test_t("0 nor 1",0.0),
test_t("0 nor 0",1.0),
test_t("1.0 nor 1.0",0.0),
test_t("1.0 nor 0.0",0.0),
test_t("0.0 nor 1.0",0.0),
test_t("0.0 nor 0.0",1.0),
test_t("(1 nor 1)",0.0),
test_t("(1 nor 0)",0.0),
test_t("(0 nor 1)",0.0),
test_t("(0 nor 0)",1.0),
test_t("(1.0 nor 1.0)",0.0),
test_t("(1.0 nor 0.0)",0.0),
test_t("(0.0 nor 1.0)",0.0),
test_t("(0.0 nor 0.0)",1.0),
test_t("0 xor 0",0.0),
test_t("0 xor 1",1.0),
test_t("1 xor 0",1.0),
test_t("1 xor 1",0.0),
test_t("0.0 xor 0.0",0.0),
test_t("0.0 xor 1.0",1.0),
test_t("1.0 xor 0.0",1.0),
test_t("1.0 xor 1.0",0.0),
test_t("(0 xor 0)",0.0),
test_t("(0 xor 1)",1.0),
test_t("(1 xor 0)",1.0),
test_t("(1 xor 1)",0.0),
test_t("(0.0 xor 0.0)",0.0),
test_t("(0.0 xor 1.0)",1.0),
test_t("(1.0 xor 0.0)",1.0),
test_t("(1.0 xor 1.0)",0.0),
test_t("1 & 1",1.0),
test_t("1 & 0",0.0),
test_t("0 & 1",0.0),
test_t("0 & 0",0.0),
test_t("1.0 & 1.0",1.0),
test_t("1.0 & 0.0",0.0),
test_t("0.0 & 1.0",0.0),
test_t("0.0 & 0.0",0.0),
test_t("(1 & 1)",1.0),
test_t("(1 & 0)",0.0),
test_t("(0 & 1)",0.0),
test_t("(0 & 0)",0.0),
test_t("(1.0 & 1.0)",1.0),
test_t("(1.0 & 0.0)",0.0),
test_t("(0.0 & 1.0)",0.0),
test_t("(0.0 & 0.0)",0.0),
test_t("1 | 1",1.0),
test_t("1 | 0",1.0),
test_t("0 | 1",1.0),
test_t("0 | 0",0.0),
test_t("1.0 | 1.0",1.0),
test_t("1.0 | 0.0",1.0),
test_t("0.0 | 1.0",1.0),
test_t("0.0 | 0.0",0.0),
test_t("(1 | 1)",1.0),
test_t("(1 | 0)",1.0),
test_t("(0 | 1)",1.0),
test_t("(0 | 0)",0.0),
test_t("(1.0 | 1.0)",1.0),
test_t("(1.0 | 0.0)",1.0),
test_t("(0.0 | 1.0)",1.0),
test_t("(0.0 | 0.0)",0.0),
test_t("(1 nand 1) == not(1 and 1)",1.0),
test_t("(1 nand 0) == not(1 and 0)",1.0),
test_t("(0 nand 1) == not(0 and 1)",1.0),
test_t("(0 nand 0) == not(0 and 0)",1.0),
test_t("(1 nor 1) == not(1 or 1)",1.0),
test_t("(1 nor 0) == not(1 or 0)",1.0),
test_t("(0 nor 1) == not(0 or 1)",1.0),
test_t("(0 nor 0) == not(0 or 0)",1.0),
test_t("(1.0 nand 1.0) == not(1.0 and 1.0)",1.0),
test_t("(1.0 nand 0.0) == not(1.0 and 0.0)",1.0),
test_t("(0.0 nand 1.0) == not(0.0 and 1.0)",1.0),
test_t("(0.0 nand 0.0) == not(0.0 and 0.0)",1.0),
test_t("(1.0 nor 1.0) == not(1.0 or 1.0)",1.0),
test_t("(1.0 nor 0.0) == not(1.0 or 0.0)",1.0),
test_t("(0.0 nor 1.0) == not(0.0 or 1.0)",1.0),
test_t("(0.0 nor 0.0) == not(0.0 or 0.0)",1.0),
test_t("(1 nand 1) == not(1 & 1)",1.0),
test_t("(1 nand 0) == not(1 & 0)",1.0),
test_t("(0 nand 1) == not(0 & 1)",1.0),
test_t("(0 nand 0) == not(0 & 0)",1.0),
test_t("(1 nor 1) == not(1 | 1)",1.0),
test_t("(1 nor 0) == not(1 | 0)",1.0),
test_t("(0 nor 1) == not(0 | 1)",1.0),
test_t("(0 nor 0) == not(0 | 0)",1.0),
test_t("(1.0 nand 1.0) == not(1.0 & 1.0)",1.0),
test_t("(1.0 nand 0.0) == not(1.0 & 0.0)",1.0),
test_t("(0.0 nand 1.0) == not(0.0 & 1.0)",1.0),
test_t("(0.0 nand 0.0) == not(0.0 & 0.0)",1.0),
test_t("(1.0 nor 1.0) == not(1.0 | 1.0)",1.0),
test_t("(1.0 nor 0.0) == not(1.0 | 0.0)",1.0),
test_t("(0.0 nor 1.0) == not(0.0 | 1.0)",1.0),
test_t("(0.0 nor 0.0) == not(0.0 | 0.0)",1.0),
test_t("mand(1,1)",1.0),
test_t("mand(1,0)",0.0),
test_t("mand(0,1)",0.0),
test_t("mand(0,0)",0.0),
test_t("mand(1.0,1.0)",1.0),
test_t("mand(1.0,0.0)",0.0),
test_t("mand(0.0,1.0)",0.0),
test_t("mand(0.0,0.0)",0.0),
test_t("mor(1,1)",1.0),
test_t("mor(1,0)",1.0),
test_t("mor(0,1)",1.0),
test_t("mor(0,0)",0.0),
test_t("mor(1.0,1.0)",1.0),
test_t("mor(1.0,0.0)",1.0),
test_t("mor(0.0,1.0)",1.0),
test_t("mor(0.0,0.0)",0.0),
test_t("(1 nand 1) == not(mand(1,1))",1.0),
test_t("(1 nand 0) == not(mand(1,0))",1.0),
test_t("(0 nand 1) == not(mand(0,1))",1.0),
test_t("(0 nand 0) == not(mand(0,0))",1.0),
test_t("(1 nor 1) == not(mor(1,1))",1.0),
test_t("(1 nor 0) == not(mor(1,0))",1.0),
test_t("(0 nor 1) == not(mor(0,1))",1.0),
test_t("(0 nor 0) == not(mor(0,0))",1.0),
test_t("(1.0 nand 1.0) == not(mand(1.0,1.0))",1.0),
test_t("(1.0 nand 0.0) == not(mand(1.0,0.0))",1.0),
test_t("(0.0 nand 1.0) == not(mand(0.0,1.0))",1.0),
test_t("(0.0 nand 0.0) == not(mand(0.0,0.0))",1.0),
test_t("(1.0 nor 1.0) == not(mor(1.0,1.0))",1.0),
test_t("(1.0 nor 0.0) == not(mor(1.0,0.0))",1.0),
test_t("(0.0 nor 1.0) == not(mor(0.0,1.0))",1.0),
test_t("(0.0 nor 0.0) == not(mor(0.0,0.0))",1.0),
test_t("abs(1)",1.0),
test_t("abs(-1)",1.0),
test_t("abs(1.0)",1.0),
test_t("abs(-1.0)",1.0),
test_t("min(1,2)",1.0),
test_t("min(1,2,3)",1.0),
test_t("min(1,2,3,4)",1.0),
test_t("min(1,2,3,4,5)",1.0),
test_t("min(1,2,3,4,5,6)",1.0),
test_t("min(1.1,2.2)",1.1),
test_t("min(1.1,2.2,3.3)",1.1),
test_t("min(1.1,2.2,3.3,4.4)",1.1),
test_t("min(1.1,2.2,3.3,4.4,5.5)",1.1),
test_t("min(1.1,2.2,3.3,4.4,5.5,6.6)",1.1),
test_t("min(min(1,2),min(3,4))",1.0),
test_t("max(1,2)",2.0),
test_t("max(1,2,3)",3.0),
test_t("max(1,2,3,4)",4.0),
test_t("max(1,2,3,4,5)",5.0),
test_t("max(1,2,3,4,5,6)",6.0),
test_t("max(1.1,2.2)",2.2),
test_t("max(1.1,2.2,3.3)",3.3),
test_t("max(1.1,2.2,3.3,4.4)",4.4),
test_t("max(1.1,2.2,3.3,4.4,5.5)",5.5),
test_t("max(1.1,2.2,3.3,4.4,5.5,6.6)",6.6),
test_t("max(max(1,2),max(3,4))",4.0),
test_t("avg(1,2)",1.5),
test_t("avg(1,2,3)",2.0),
test_t("avg(1,2,3,4)",2.5),
test_t("avg(1,2,3,4,5)",3.0),
test_t("avg(1.1,2.2)",1.65),
test_t("avg(1.1,2.2,3.3)",2.2),
test_t("avg(1.1,2.2,3.3,4.4)",2.75),
test_t("avg(1.1,2.2,3.3,4.4,5.5)",3.3),
test_t("avg(1.1,2.2,3.3,4.4,5.5,6.6)",3.85),
test_t("sum(1,2)",3.0),
test_t("sum(1,2,3)",6.0),
test_t("sum(1,2,3,4)",10),
test_t("sum(1,2,3,4,5)",15.0),
test_t("sum(1,2,3,4,5,6)",21),
test_t("sum(1.1,2.2)",3.3),
test_t("sum(1.1,2.2,3.3)",6.6),
test_t("sum(1.1,2.2,3.3,4.4)",11.0),
test_t("sum(1.1,2.2,3.3,4.4,5.5)",16.5),
test_t("sum(1.1,2.2,3.3,4.4,5.5,6.6)",23.1),
test_t("mul(1,2)",2.0),
test_t("mul(1,2,3)",6.0),
test_t("mul(1,2,3,4)",24.0),
test_t("mul(1,2,3,4,5)",120.0),
test_t("mul(1,2,3,4,5,6)",720.0),
test_t("mul(1.1,2.2)",2.42),
test_t("mul(1.1,2.2,3.3)",7.986),
test_t("mul(1.1,2.2,3.3,4.4)",35.1384),
test_t("mul(1.1,2.2,3.3,4.4,5.5)",193.2612),
test_t("mul(1.1,2.2,3.3,4.4,5.5,6.6)",1275.52392),
test_t("equal(sum(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9),(1.1+2.2+3.3+4.4+5.5+6.6+7.7+8.8+9.9))",1.0),
test_t("equal(mul(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9),(1.1*2.2*3.3*4.4*5.5*6.6*7.7*8.8*9.9))",1.0),
test_t("equal(min(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9),1.1)",1.0),
test_t("equal(max(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9),9.9)",1.0),
test_t("equal(avg(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9),5.5)",1.0),
test_t("floor(1.0)",1.0),
test_t("floor(1.1)",1.0),
test_t("floor(-1.0)",-1.0),
test_t("floor(-1.1)",-2.0),
test_t("ceil(1.0)",1.0),
test_t("ceil(1.1)",2.0),
test_t("ceil(-1.0)",-1.0),
test_t("ceil(-1.1)",-1.0),
test_t("round(1.1)",1.0),
test_t("round(1.49)",1.0),
test_t("round(1.5)",2.0),
test_t("round(1.9)",2.0),
test_t("roundn(1/3,2)",0.33),
test_t("roundn(1/3,5)",0.33333),
test_t("roundn(2/3,2)",0.67),
test_t("roundn(2/3,5)",0.66667),
test_t("roundn(1.0/3.0,2.0)",0.33),
test_t("roundn(1.0/3.0,5.0)",0.33333),
test_t("roundn(2.0/3.0,2.0)",0.67),
test_t("roundn(2.0/3.0,5.0)",0.66667),
test_t("cos(0.0)",1.0),
test_t("sin(0.0)",0.0),
test_t("equal(sin(pi/4.0),cos(pi/4.0))",1.0),
test_t("equal(sin(pi/6.0),cos(pi/3.0))",1.0),
test_t("(sin(pi/4.0) - cos(pi/4.0)) <= epsilon",1.0),
test_t("(cos(pi/3.0) - sin(pi/6.0)) <= epsilon",1.0),
test_t("sin(deg2rad(30))",0.5),
test_t("cos(deg2rad(60))",0.5),
test_t("sin(deg2rad(30)) + cos(deg2rad(60))",1.0),
test_t("equal(sin(deg2rad(30))/cos(deg2rad(30)),tan(deg2rad(30)))",1.0),
test_t("equal(sinh(pi),11.5487393572577483779773343153884) ",1.0),
test_t("equal(asinh(11.5487393572577483779773343153884),pi)",1.0),
test_t("equal(cosh(pi),11.5919532755215206277517520525601) ",1.0),
test_t("equal(acosh(11.5919532755215206277517520525601),pi)",1.0),
test_t("equal(tanh(pi),0.99627207622074994426469058001253) ",1.0),
test_t("equal(atanh(0.99627207622074994426469058001253),pi)",1.0),
test_t("exp(1.0)",2.71828182845904523536028747135266249775724),
test_t("exp(0.0)",1.0),
test_t("log(2.7182818284590451)",1.0),
test_t("log10(10.0)",1.0),
test_t("frac(12.34) + trunc(12.34)",12.34),
test_t("hypot(3.0,4.0)",5.0),
test_t("hypot(1.0,sqrt(3.0))",2.0),
test_t("if(1 < 2, 3, 4)",3.0),
test_t("if(1.1 < 2.2, 3.3, 4.4)",3.3),
test_t("if((1.0+1.1) < (2.0+1.2), 3.3, 4.4)",3.3),
test_t("if(1 = 2, 3, 4)",4.0),
test_t("if(1.1 = 2.2, 3.3, 4.4)",4.4),
test_t("if((1.0+1.1) = (2.0+1.2), 3.3, 4.4)",4.4),
test_t("if(1 == 2, 3, 4)",4.0),
test_t("if(1.1 == 2.2, 3.3, 4.4)",4.4),
test_t("if((1.0+1.1) == (2.0+1.2), 3.3, 4.4)",4.4),
test_t("if(1 >= 2, 3, 4)",4.0),
test_t("if(1.1 >= 2.2, 3.3, 4.4)",4.4),
test_t("if((1.0+1.1) >= (2.0+1.2), 3.3, 4.4)",4.4),
test_t("if(((1.0 + 2.0) == 3.0) and ((4.0 + 5.0) < 9.0),1,2)",2.0),
test_t("(3.0 - 1.0 - 2.0) == ((3.0 - 1.0) - 2.0)",1.0),
test_t("true == true",1.0),
test_t("false == false",1.0),
test_t("true != false",1.0),
test_t("false != true",1.0),
test_t("(1 < 2) == true",1.0),
test_t("(1 > 2) == false",1.0),
test_t("true == (1 < 2)",1.0),
test_t("false == (1 > 2)",1.0),
test_t("(1 > 2) != true",1.0),
test_t("(1 < 2) != false",1.0),
test_t("true != (1 > 2)",1.0),
test_t("false != (1 < 2)",1.0),
test_t("(true and true) == true",1.0),
test_t("(false and false) == false",1.0),
test_t("(true or true) == true",1.0),
test_t("(false or false) == false",1.0),
test_t("(true and false) == false",1.0),
test_t("(false and true) == false",1.0),
test_t("(true or false) == true",1.0),
test_t("(false or true) == true",1.0),
test_t("(true & true) == true",1.0),
test_t("(false & false) == false",1.0),
test_t("(true | true) == true",1.0),
test_t("(false | false) == false",1.0),
test_t("(true & false) == false",1.0),
test_t("(false & true) == false",1.0),
test_t("(true | false) == true",1.0),
test_t("(false | true) == true",1.0),
test_t("clamp(-1,1,+1)",1.0),
test_t("clamp(-1,-1.5,+1.0)",-1.0),
test_t("clamp(-1,+1.5,+1.0)",+1.0),
test_t("clamp(-1,-1.5,+1.0) + clamp(-1,+1.5,+1.0)",0.0),
test_t("inrange(-2,1,+2) == ((-2 <= 1) and (1 <= +2))",1.0),
test_t("inrange(-2,1,+2) == if(({-2 <= 1} and [1 <= +2]),1.0,0.0)",1.0),
test_t("sgn( 0)", 0.0),
test_t("sgn(+3)",+1.0),
test_t("sgn(-3)",-1.0),
test_t("equal($f00(1.1,2.2,3.3),(1.1+2.2)/3.3)",1.0),
test_t("equal($f01(1.1,2.2,3.3),(1.1+2.2)*3.3)",1.0),
test_t("equal($f02(1.1,2.2,3.3),(1.1+2.2)-3.3)",1.0),
test_t("equal($f03(1.1,2.2,3.3),(1.1+2.2)+3.3)",1.0),
test_t("equal($f04(1.1,2.2,3.3),(1.1-2.2)+3.3)",1.0),
test_t("equal($f05(1.1,2.2,3.3),(1.1-2.2)/3.3)",1.0),
test_t("equal($f06(1.1,2.2,3.3),(1.1-2.2)*3.3)",1.0),
test_t("equal($f07(1.1,2.2,3.3),(1.1*2.2)+3.3)",1.0),
test_t("equal($f08(1.1,2.2,3.3),(1.1*2.2)-3.3)",1.0),
test_t("equal($f09(1.1,2.2,3.3),(1.1*2.2)/3.3)",1.0),
test_t("equal($f10(1.1,2.2,3.3),(1.1*2.2)*3.3)",1.0),
test_t("equal($f11(1.1,2.2,3.3),(1.1/2.2)+3.3)",1.0),
test_t("equal($f12(1.1,2.2,3.3),(1.1/2.2)-3.3)",1.0),
test_t("equal($f13(1.1,2.2,3.3),(1.1/2.2)/3.3)",1.0),
test_t("equal($f14(1.1,2.2,3.3),(1.1/2.2)*3.3)",1.0),
test_t("equal($f15(1.1,2.2,3.3),1.1/(2.2+3.3))",1.0),
test_t("equal($f16(1.1,2.2,3.3),1.1/(2.2-3.3))",1.0),
test_t("equal($f17(1.1,2.2,3.3),1.1/(2.2*3.3))",1.0),
test_t("equal($f18(1.1,2.2,3.3),1.1/(2.2/3.3))",1.0),
test_t("equal($f19(1.1,2.2,3.3),1.1*(2.2+3.3))",1.0),
test_t("equal($f20(1.1,2.2,3.3),1.1*(2.2-3.3))",1.0),
test_t("equal($f21(1.1,2.2,3.3),1.1*(2.2*3.3))",1.0),
test_t("equal($f22(1.1,2.2,3.3),1.1*(2.2/3.3))",1.0),
test_t("equal($f23(1.1,2.2,3.3),1.1-(2.2+3.3))",1.0),
test_t("equal($f24(1.1,2.2,3.3),1.1-(2.2-3.3))",1.0),
test_t("equal($f25(1.1,2.2,3.3),1.1-(2.2/3.3))",1.0),
test_t("equal($f26(1.1,2.2,3.3),1.1-(2.2*3.3))",1.0),
test_t("equal($f27(1.1,2.2,3.3),1.1+(2.2*3.3))",1.0),
test_t("equal($f28(1.1,2.2,3.3),1.1+(2.2/3.3))",1.0),
test_t("equal($f29(1.1,2.2,3.3),1.1+(2.2+3.3))",1.0),
test_t("equal($f30(1.1,2.2,3.3),1.1+(2.2-3.3))",1.0),
test_t("equal($f31(1.1,2.2,3.3),1.1*2.2^2+3.3)",1.0),
test_t("equal($f32(1.1,2.2,3.3),1.1*2.2^3+3.3)",1.0),
test_t("equal($f33(1.1,2.2,3.3),1.1*2.2^4+3.3)",1.0),
test_t("equal($f34(1.1,2.2,3.3),1.1*2.2^5+3.3)",1.0),
test_t("equal($f35(1.1,2.2,3.3),1.1*2.2^6+3.3)",1.0),
test_t("equal($f36(1.1,2.2,3.3),1.1*2.2^7+3.3)",1.0),
test_t("equal($f37(1.1,2.2,3.3),1.1*2.2^8+3.3)",1.0),
test_t("equal($f38(1.1,2.2,3.3),1.1*2.2^9+3.3)",1.0),
test_t("equal($f39(1.1,2.2,3.3),1.1*log(2.2)+3.3)",1.0),
test_t("equal($f40(1.1,2.2,3.3),1.1*log(2.2)-3.3)",1.0),
test_t("equal($f41(1.1,2.2,3.3),1.1*log10(2.2)+3.3)",1.0),
test_t("equal($f42(1.1,2.2,3.3),1.1*log10(2.2)-3.3)",1.0),
test_t("equal($f43(1.1,2.2,3.3),1.1*sin(2.2)+3.3)",1.0),
test_t("equal($f44(1.1,2.2,3.3),1.1*sin(2.2)-3.3)",1.0),
test_t("equal($f45(1.1,2.2,3.3),1.1*cos(2.2)+3.3)",1.0),
test_t("equal($f46(1.1,2.2,3.3),1.1*cos(2.2)-3.3)",1.0),
test_t("equal($f47(1.1,2.2,3.3),if(0!=1.1,2.2,3.3))",1.0),
test_t("equal($f48(1.1,2.2,3.3,4.4),1.1+((2.2+3.3)/4.4))",1.0),
test_t("equal($f49(1.1,2.2,3.3,4.4),1.1+((2.2+3.3)*4.4))",1.0),
test_t("equal($f50(1.1,2.2,3.3,4.4),1.1+((2.2-3.3)/4.4))",1.0),
test_t("equal($f51(1.1,2.2,3.3,4.4),1.1+((2.2-3.3)*4.4))",1.0),
test_t("equal($f52(1.1,2.2,3.3,4.4),1.1+((2.2*3.3)/4.4))",1.0),
test_t("equal($f53(1.1,2.2,3.3,4.4),1.1+((2.2*3.3)*4.4))",1.0),
test_t("equal($f54(1.1,2.2,3.3,4.4),1.1+((2.2/3.3)+4.4))",1.0),
test_t("equal($f55(1.1,2.2,3.3,4.4),1.1+((2.2/3.3)/4.4))",1.0),
test_t("equal($f56(1.1,2.2,3.3,4.4),1.1+((2.2/3.3)*4.4))",1.0),
test_t("equal($f57(1.1,2.2,3.3,4.4),1.1-((2.2+3.3)/4.4))",1.0),
test_t("equal($f58(1.1,2.2,3.3,4.4),1.1-((2.2+3.3)*4.4))",1.0),
test_t("equal($f59(1.1,2.2,3.3,4.4),1.1-((2.2-3.3)/4.4))",1.0),
test_t("equal($f60(1.1,2.2,3.3,4.4),1.1-((2.2-3.3)*4.4))",1.0),
test_t("equal($f61(1.1,2.2,3.3,4.4),1.1-((2.2*3.3)/4.4))",1.0),
test_t("equal($f62(1.1,2.2,3.3,4.4),1.1-((2.2*3.3)*4.4))",1.0),
test_t("equal($f63(1.1,2.2,3.3,4.4),1.1-((2.2/3.3)/4.4))",1.0),
test_t("equal($f64(1.1,2.2,3.3,4.4),1.1-((2.2/3.3)*4.4))",1.0),
test_t("equal($f65(1.1,2.2,3.3,4.4),((1.1+2.2)*3.3)-4.4)",1.0),
test_t("equal($f66(1.1,2.2,3.3,4.4),((1.1-2.2)*3.3)-4.4)",1.0),
test_t("equal($f67(1.1,2.2,3.3,4.4),((1.1*2.2)*3.3)-4.4)",1.0),
test_t("equal($f68(1.1,2.2,3.3,4.4),((1.1/2.2)*3.3)-4.4)",1.0),
test_t("equal($f69(1.1,2.2,3.3,4.4),((1.1+2.2)/3.3)-4.4)",1.0),
test_t("equal($f70(1.1,2.2,3.3,4.4),((1.1-2.2)/3.3)-4.4)",1.0),
test_t("equal($f71(1.1,2.2,3.3,4.4),((1.1*2.2)/3.3)-4.4)",1.0),
test_t("equal($f72(1.1,2.2,3.3,4.4),((1.1/2.2)/3.3)-4.4)",1.0),
test_t("equal($f73(1.1,2.2,3.3,4.4),(1.1*2.2)+(3.3*4.4))",1.0),
test_t("equal($f74(1.1,2.2,3.3,4.4),(1.1*2.2)-(3.3*4.4))",1.0),
test_t("equal($f75(1.1,2.2,3.3,4.4),(1.1*2.2)+(3.3/4.4))",1.0),
test_t("equal($f76(1.1,2.2,3.3,4.4),(1.1*2.2)-(3.3/4.4))",1.0),
test_t("equal($f77(1.1,2.2,3.3,4.4),(1.1/2.2)+(3.3/4.4))",1.0),
test_t("equal($f78(1.1,2.2,3.3,4.4),(1.1/2.2)-(3.3/4.4))",1.0),
test_t("equal($f79(1.1,2.2,3.3,4.4),(1.1/2.2)-(3.3*4.4))",1.0),
test_t("equal($f80(1.1,2.2,3.3,4.4),1.1/(2.2+(3.3*4.4)))",1.0),
test_t("equal($f81(1.1,2.2,3.3,4.4),1.1/(2.2-(3.3*4.4)))",1.0),
test_t("equal($f82(1.1,2.2,3.3,4.4),1.1*(2.2+(3.3*4.4)))",1.0),
test_t("equal($f83(1.1,2.2,3.3,4.4),1.1*(2.2-(3.3*4.4)))",1.0),
test_t("equal($f84(1.1,2.2,3.3,4.4),1.1*2.2^2+3.3*4.4^2)",1.0),
test_t("equal($f85(1.1,2.2,3.3,4.4),1.1*2.2^3+3.3*4.4^3)",1.0),
test_t("equal($f86(1.1,2.2,3.3,4.4),1.1*2.2^4+3.3*4.4^4)",1.0),
test_t("equal($f87(1.1,2.2,3.3,4.4),1.1*2.2^5+3.3*4.4^5)",1.0),
test_t("equal($f88(1.1,2.2,3.3,4.4),1.1*2.2^6+3.3*4.4^6)",1.0),
test_t("equal($f89(1.1,2.2,3.3,4.4),1.1*2.2^7+3.3*4.4^7)",1.0),
test_t("equal($f90(1.1,2.2,3.3,4.4),1.1*2.2^8+3.3*4.4^8)",1.0),
test_t("equal($f91(1.1,2.2,3.3,4.4),1.1*2.2^9+3.3*4.4^9)",1.0),
test_t("equal($f92(1.1,2.2,3.3,4.4),if(1.1 and 2.2,3.3,4.4))",1.0),
test_t("equal($f93(1.1,2.2,3.3,4.4),if(1.1 or 2.2,3.3,4.4))",1.0),
test_t("equal($f94(1.1,2.2,3.3,4.4),if(1.1 < 2.2,3.3,4.4))",1.0),
test_t("equal($f95(1.1,2.2,3.3,4.4),if(1.1 <= 2.2,3.3,4.4))",1.0),
test_t("equal($f96(1.1,2.2,3.3,4.4),if(1.1 > 2.2,3.3,4.4))",1.0),
test_t("equal($f97(1.1,2.2,3.3,4.4),if(1.1 >= 2.2,3.3,4.4))",1.0),
test_t("equal($f98(1.1,2.2,3.3,4.4),if(equal(1.1,2.2),3.3,4.4))",1.0),
test_t("equal($f99(1.1,2.2,3.3,4.4),1.1*sin(2.2)+3.3*cos(4.4))",1.0),
test_t("equal((48.0/2.0*(9.0+3.0)),288.0)",1.0),
test_t("equal((48.0/2.0(9.0+3.0)),288.0)",1.0),
test_t("equal((6.0/2.0(1.0+2.0)),9.0)",1.0),
test_t("1+2+3+4+5+6+7+8+9+0",45.0),
test_t("1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 0",45.0),
test_t("1.0 + 2.0 + 3.0 + 4.0 + 5.0 + 6.0 + 7.0 + 8.0 + 9.0 + 0.0",45.0),
test_t("(1+2)+(3+4)+(5+6)+(7+8)+(9+0)",45.0),
test_t("(1-2)+(3-4)+(5-6)+(7-8)+(9-0)",+5.0),
test_t("(1+2)-(3+4)-(5+6)-(7+8)-(9+0)",-39.0),
test_t("(1.0+2.0)+(3.0+4.0)+(5.0+6.0)+(7.0+8.0)+(9.0+0.0)",45.0),
test_t("(1.0-2.0)+(3.0-4.0)+(5.0-6.0)+(7.0-8.0)+(9.0-0.0)",+5.0),
test_t("(1.0+2.0)-(3.0+4.0)-(5.0+6.0)-(7.0+8.0)-(9.0+0.0)",-39.0),
test_t("[(1.0+2.0)+[3.0+4.0]+(5.0+6.0)]+([7.0+8.0]+(9.0+0.0))",45.0),
test_t("([1.0-2.0]+(3.0-4.0)+[5.0-6.0])+[(7.0-8.0)+[9.0-0.0]]",+5.0),
test_t("((1.0+2.0))-[(3.0+4.0)]-((5.0+6.0))-[(7.0+8.0)]-((9.0+0.0))",-39.0),
test_t("{[(1.0+2.0)+[3.0+4.0]+({5.0+6.0})]}+({[7.0+8.0]+(9.0+0.0)})",45.0),
test_t("{([1.0-2.0]+(3.0-4.0)+[5.0-6.0])}+[({+7.0}-{+8.0})+[{+9.0-0.0}]]",+5.0),
test_t("((+1.0+2.0))-[({+3.0+4.0})]-(({+5.0+6.0}))-[({+7.0}+8.0)]-(({+9.0}+{0.0}))",-39.0),
test_t("1+2-3*4/5+6-7*8/9+0",0.37777777777777777778),
test_t("1.1+2.2-3.3*4.4/5.5+6.6-7.7*8.8/9.9+0.0",0.41555555555555555556),
test_t("(1+2)-(3*4)/(5+6)-(7*8)/(9+0)",-4.31313131313131313131),
test_t("1/1+1/2+1/3+1/4+1/5+1/6+1/7+1/8+1/9",2.82896825396825396825),
test_t("(1/1)+(1/2)+(1/3)+(1/4)+(1/5)+(1/6)+(1/7)+(1/8)+(1/9)",2.82896825396825396825),
test_t("1.0/1.0+1.0/2.0+1.0/3.0+1.0/4.0+1.0/5.0+1.0/6.0+1.0/7.0+1.0/8.0+1.0/9",2.82896825396825396825),
test_t("(1.0/1.0)+(1.0/2.0)+(1.0/3.0)+(1.0/4.0)+(1.0/5.0)+(1.0/6.0)+(1.0/7.0)+(1.0/8.0)+(1.0/9)",2.82896825396825396825),
test_t("1/1*1/2*1/3*1/4*1/5*1/6*1/7*1/8*1/9",0.00000275573192239859),
test_t("(1/1)*(1/2)*(1/3)*(1/4)*(1/5)*(1/6)*(1/7)*(1/8)*(1/9)",0.00000275573192239859),
test_t("1.0/1.0*1.0/2.0*1.0/3.0*1.0/4.0*1.0/5.0*1.0/6.0*1.0/7.0*1.0/8.0*1.0/9",0.00000275573192239859),
test_t("(1.0/1.0)*(1.0/2.0)*(1.0/3.0)*(1.0/4.0)*(1.0/5.0)*(1.0/6.0)*(1.0/7.0)*(1.0/8.0)*(1.0/9)",0.00000275573192239859),
test_t("equal(poly01(1.2345,2.2,1.1),(2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly02(1.2345,3.3,2.2,1.1),(3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly03(1.2345,4.4,3.3,2.2,1.1),(4.4*1.2345^3+3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly04(1.2345,5.5,4.4,3.3,2.2,1.1),(5.5*1.2345^4+4.4*1.2345^3+3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly05(1.2345,6.6,5.5,4.4,3.3,2.2,1.1),(6.6*1.2345^5+5.5*1.2345^4+4.4*1.2345^3+3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly06(1.2345,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(7.7*1.2345^6+6.6*1.2345^5+5.5*1.2345^4+4.4*1.2345^3+3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly07(1.2345,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(8.8*1.2345^7+7.7*1.2345^6+6.6*1.2345^5+5.5*1.2345^4+4.4*1.2345^3+3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly08(1.2345,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(9.9*1.2345^8+8.8*1.2345^7+7.7*1.2345^6+6.6*1.2345^5+5.5*1.2345^4+4.4*1.2345^3+3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly09(1.2345,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(1.1*1.2345^9+9.9*1.2345^8+8.8*1.2345^7+7.7*1.2345^6+6.6*1.2345^5+5.5*1.2345^4+4.4*1.2345^3+3.3*1.2345^2+2.2*1.2345^1+1.1))",1.0),
test_t("equal(poly10(1.37,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(2.2*1.37^10+1.1*1.37^9+9.9*1.37^8+8.8*1.37^7+7.7*1.37^6+6.6*1.37^5+5.5*1.37^4+4.4*1.37^3+3.3*1.37^2+2.2*1.37^1+1.1))",1.0),
test_t("equal(poly11(1.37,3.3,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(3.3*1.37^11+2.2*1.37^10+1.1*1.37^9+9.9*1.37^8+8.8*1.37^7+7.7*1.37^6+6.6*1.37^5+5.5*1.37^4+4.4*1.37^3+3.3*1.37^2+2.2*1.37^1+1.1))",1.0),
test_t("equal(poly12(1.37,4.4,3.3,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(4.4*1.37^12+3.3*1.37^11+2.2*1.37^10+1.1*1.37^9+9.9*1.37^8+8.8*1.37^7+7.7*1.37^6+6.6*1.37^5+5.5*1.37^4+4.4*1.37^3+3.3*1.37^2+2.2*1.37^1+1.1))",1.0),
test_t("equal(\t \n(\n \r1.1\t\t - \n\n 2.2\n\n/\r3.3\t),(1.1-2.2/3.3))",1.0),
test_t("equal((pi^2^3),(pi^8))",1.0),
test_t("equal((pi^(2^3)),(pi^8))",1.0),
test_t("equal(pi^2^3-pi^8,0)",1.0),
test_t("equal((2*pi^2^3),2*(pi^8))",1.0),
test_t("equal((pi^2^3*2),2*(pi^8))",1.0),
test_t("equal((pi^2^3/2),(pi^8)/2)",1.0),
test_t("equal((pi^2.2^3.3),(pi^13.4894687605338489))",1.0),
test_t("equal((pi^(2.2^3.3)),(pi^13.4894687605338489))",1.0),
test_t("equal((2.2*pi^2.2^3.3),2.2*(pi^13.4894687605338489))",1.0),
test_t("equal((pi^2.2^3.3*2),2*(pi^13.4894687605338489))",1.0),
test_t("equal((pi^2.2^3.3/2.2),(pi^13.4894687605338489)/2.2)",1.0),
test_t("equal((pi^-2^3),1/(pi^8))",1.0),
test_t("equal((pi^(-2^3)),1/(pi^8))",1.0),
test_t("equal((pi^2^-3),(pi^(1/8)))",1.0),
test_t("equal((pi^(2^-3)),(pi^(1/8)))",1.0),
test_t("equal((pi^-2^-3),1/(pi^(1/8)))",1.0),
test_t("equal((pi^(-2^-3)),1/(pi^(1/8)))",1.0),
test_t("equal((-pi^2^3),(-pi^8))",1.0),
test_t("equal((-pi^(2^3)),(-pi^8))",1.0),
test_t("equal(-pi^2^3--pi^8,0)",1.0),
test_t("equal((2*-pi^2^3),2*(-pi^8))",1.0),
test_t("equal((-pi^2^3*2),2*(-pi^8))",1.0),
test_t("equal((-pi^2^3/2),(-pi^8)/2)",1.0),
test_t("equal((-pi^2.2^3.3),(-pi^13.4894687605338489))",1.0),
test_t("equal((-pi^(2.2^3.3)),(-pi^13.4894687605338489))",1.0),
test_t("equal((2.2*-pi^2.2^3.3),2.2*(-pi^13.4894687605338489))",1.0),
test_t("equal((-pi^2.2^3.3*2),2*(-pi^13.4894687605338489))",1.0),
test_t("equal((-pi^2.2^3.3/2.2),(-pi^13.4894687605338489)/2.2)",1.0),
test_t("equal((-pi^-2^3),1/(-pi^8))",1.0),
test_t("equal((-pi^(-2^3)),1/(-pi^8))",1.0),
test_t("equal((-pi^2^-3),(-pi^(1/8)))",1.0),
test_t("equal((-pi^(2^-3)),(-pi^(1/8)))",1.0),
test_t("equal((-pi^-2^-3),1/(-pi^(1/8)))",1.0),
test_t("equal((-pi^(-2^-3)),1/(-pi^(1/8)))",1.0),
test_t("equal((+pi^+2^+3),(+pi^+8))",1.0),
test_t("equal((+pi^(2^3)),(+pi^+8))",1.0),
test_t("equal(+pi^+2^+3-+pi^+8,0)",1.0),
test_t("equal((+2*+pi^+2^+3),+2*(+pi^+8))",1.0),
test_t("equal((+pi^+2^+3*+2),+2*(+pi^+8))",1.0),
test_t("equal((+pi^+2^+3/+2),(+pi^+8)/+2)",1.0),
test_t("equal((+pi^+2.2^+3.3),(+pi^+13.4894687605338489))",1.0),
test_t("equal((+pi^(+2.2^+3.3)),(+pi^+13.4894687605338489))",1.0),
test_t("equal((+2.2*+pi^+2.2^+3.3),+2.2*(+pi^+13.4894687605338489))",1.0),
test_t("equal((+pi^+2.2^+3.3*+2),+2*(+pi^+13.4894687605338489))",1.0),
test_t("equal((+pi^+2.2^+3.3/+2.2),(+pi^+13.4894687605338489)/+2.2)",1.0),
test_t("equal((+pi^-2^3),1/(+pi^+8))",1.0),
test_t("equal((+pi^(-2^3)),1/(+pi^+8))",1.0),
test_t("equal((+pi^2^-3),(+pi^(+1/+8)))",1.0),
test_t("equal((+pi^(2^-3)),(+pi^(+1/+8)))",1.0),
test_t("equal((+pi^-2^-3),1/(+pi^(+1/+8)))",1.0),
test_t("equal((+pi^(-2^-3)),1/(+pi^(+1/+8)))",1.0),
test_t("equal((-pi^+2^+3),(-pi^+8))",1.0),
test_t("equal((-pi^(2^3)),(-pi^+8))",1.0),
test_t("equal(-pi^+2^+3--pi^+8,0)",1.0),
test_t("equal((+2*-pi^+2^+3),2*(-pi^+8))",1.0),
test_t("equal((-pi^+2^+3*2),2*(-pi^+8))",1.0),
test_t("equal((-pi^+2^+3/+2),(-pi^+8)/+2)",1.0),
test_t("equal((-pi^+2.2^+3.3),(-pi^+13.4894687605338489))",1.0),
test_t("equal((-pi^(2.2^3.3)),(-pi^+13.4894687605338489))",1.0),
test_t("equal((+2.2*-pi^+2.2^+3.3),2.2*(-pi^+13.4894687605338489))",1.0),
test_t("equal((-pi^+2.2^+3.3*2),2*(-pi^+13.4894687605338489))",1.0),
test_t("equal((-pi^+2.2^+3.3/+2.2),(-pi^+13.4894687605338489)/+2.2)",1.0),
test_t("equal((-pi^-2^3),1/(-pi^+8))",1.0),
test_t("equal((-pi^(-2^3)),1/(-pi^+8))",1.0),
test_t("equal((-pi^2^-3),(-pi^(+1/+8)))",1.0),
test_t("equal((-pi^(2^-3)),(-pi^(+1/+8)))",1.0),
test_t("equal((-pi^-2^-3),1/(-pi^(+1/+8)))",1.0),
test_t("equal((-pi^(-2^-3)),1/(-pi^(+1/+8)))",1.0),
test_t("switch { case (1 <= 2) : 1; default: 1.12345; }",1.0),
test_t("switch { case (1 > 2) : 0; case (1 <= 2) : 1; default: 1.12345; }",1.0),
test_t("switch { case (1 <= 2) : switch { case (1 <= 2) : 1; default: 1.12345; }; default: 1.12345; }",1.0),
test_t("switch { case [1 <= 2] : 1; default: 1.12345; }",1.0),
test_t("switch { case [1 > 2] : 0; case [1 <= 2] : 1; default: 1.12345; }",1.0),
test_t("switch { case [1 <= 2] : switch { case [1 <= 2] : 1; default: 1.12345; }; default: 1.12345; }",1.0),
test_t("switch { case {1 <= 2} : 1; default: 1.12345; }",1.0),
test_t("switch { case {1 > 2} : 0; case {1 <= 2} : 1; default: 1.12345; }",1.0),
test_t("switch { case {1 <= 2} : switch { case {1 <= 2} : 1; default: 1.12345; }; default: 1.12345; }",1.0),
test_t("switch { case [(1 <= 2)] : {1}; default: 1.12345; }",1.0),
test_t("switch { case ([1 > 2]) : [0]; case ([1 <= 2]) : 1; default: 1.12345; }",1.0),
test_t("switch { case {(1 <= 2)} : switch { case ({1 <= 2}) : 1; default: 1.12345; }; default: 1.12345; }",1.0),
test_t("switch { case 1 > 1 : 1; case 2 > 2 : 2; case 3 = 3 : 3; case 4 > 4 : 4; default : 5; }",3.0),
test_t("repeat 1.1 + 2.2 until (1 < 2)",3.3),
test_t("repeat (1.1 + 2.2) until (1 < 2)",3.3),
test_t("repeat 1.1 + 2.2; until (1 < 2)",3.3),
test_t("repeat (1.1 + 2.2); until (1 < 2)",3.3),
test_t("repeat 1.1234; 1 < 2; 1.1 + 2.2 until (1 < 2)",3.3),
test_t("repeat 1.1234; 1 < 2; (1.1 + 2.2) until (1 < 2)",3.3),
test_t("repeat 1.1234; 1 < 2; 1.1 + 2.2; until (1 < 2)",3.3),
test_t("repeat 1.1234; 1 < 2; (1.1 + 2.2); until (1 < 2)",3.3),
test_t("[*] { case 1 < 2 : 1 / 2; case (1 < 3) : 2 / 2; case 1 < 4 : 3 / 2; case (1 < 5) : 4 / 2; }",2.0),
test_t(" 0 ? 1 : 2",2.0),
test_t(" 1 ? 3 : 4",3.0),
test_t("(0 ? 1 : 2) == 2",1.0),
test_t("(1 ? 3 : 4) == 3",1.0),
test_t("[(0)] ? [(1)] : [(2)]",2.0),
test_t("([(0)] ? [(1)] : [(2)]) == 2",1.0),
test_t("([(1)] ? [(3)] : [(4)]) == 3",1.0),
test_t("(1 < 2 ? 3 : 4) == 3",1.0),
test_t("(1 > 2 ? 3 : 4) == 4",1.0),
test_t("(1 < 2 ? 3 + 5 : 4) == 8",1.0),
test_t("(1 > 2 ? 3 : 4 + 5) == 9",1.0),
test_t("(2 < 3 + 3 ? 7 : 9) == 7",1.0),
test_t("(1 + 1 < 3 ? 7 : 9) == 7",1.0),
test_t("(1 + 1 < 3 + 3 ? 7 : 9) == 7",1.0),
test_t("(2 > 3 + 3 ? 7 : 9) == 9",1.0),
test_t("(1 + 1 > 3 ? 7 : 9) == 9",1.0),
test_t("(1 + 1 > 3 + 3 ? 7 : 9) == 9",1.0),
test_t("(2 < (3 + 3) ? 7 : 9) == 7",1.0),
test_t("((1 + 1) < 3 ? 7 : 9) == 7",1.0),
test_t("((1 + 1) < (3 + 3) ? 7 : 9) == 7",1.0),
test_t("(min(1,2) ? 1 + 3 : 1 + 4) == 4",1.0),
test_t("(min(0,1) ? 1 + 3 : 1 + 4) == 5",1.0),
test_t("if(1 < 2) 3; == 3",1.0),
test_t("if(1 > 2) 3; == null",1.0),
test_t("if(1 < 2) 3; else 4; == 3",1.0),
test_t("if(1 > 2) 3; else 4; == 4",1.0),
test_t("if(1 < 2) 3; else {1+2; 4;} == 3",1.0),
test_t("if(1 > 2) 3; else {1+2; 4;} == 4",1.0),
test_t("if(1 < 2) 3; else if (1 < 2) 4; == 3",1.0),
test_t("if(1 > 2) 3; else if (1 < 2) 4; == 4",1.0),
test_t("if(1 > 2) 3; else if (1 > 2) 4; == null",1.0),
test_t("if(1 < 2) 3; else if (1 < 2) {1+2; 4;} == 3",1.0),
test_t("if(1 > 2) 3; else if (1 < 2) {1+2; 4;} == 4",1.0),
test_t("if(1 > 2) 3; else if (1 > 2) {1+2; 4;} == null",1.0),
test_t("if(1 < 2) { 1+2; 3;} == 3",1.0),
test_t("if(1 > 2) { 1+2; 3;} == null",1.0),
test_t("if(1 < 2) { 1+2; 3;} else 4; == 3",1.0),
test_t("if(1 > 2) { 1+2; 3;} else 4; == 4",1.0),
test_t("if(1 < 2) { 1+2; 3;} else {1+2; 4;} == 3",1.0),
test_t("if(1 > 2) { 1+2; 3;} else {1+2; 4;} == 4",1.0),
test_t("if(1 < 2) { 1+2; 3;} else if (1 < 2) 4; == 3",1.0),
test_t("if(1 > 2) { 1+2; 3;} else if (1 < 2) 4; == 4",1.0),
test_t("if(1 > 2) { 1+2; 3;} else if (1 > 2) 4; == null",1.0),
test_t("if(1 < 2) { 1+2; 3;} else if (1 < 2) {1+2; 4;} == 3",1.0),
test_t("if(1 > 2) { 1+2; 3;} else if (1 < 2) {1+2; 4;} == 4",1.0),
test_t("if(1 > 2) { 1+2; 3;} else if (1 > 2) {1+2; 4;} == null",1.0)
};
static const std::size_t test_list_size = sizeof(test_list) / sizeof(test_t);
template <typename T>
inline bool not_equal_impl(const T& t1,
const T& t2,
const T& epsilon = 0.0000000001/*std::numeric_limits<T>::epsilon()*/)
{
if (t1 != t1) return true;
if (t2 != t2) return true;
T diff = std::abs(t1 - t2);
T eps_norm = (std::max(T(1),std::max(std::abs(t1),std::abs(t2))) * epsilon);
return diff > eps_norm;
}
template <typename T>
inline bool not_equal(const T& t0, const T& t1,
const T& epsilon = T(0.0000000001))
{
return not_equal_impl(t0,t1,epsilon);
}
inline bool not_equal(const float& t0, const float& t1, const float& epsilon = 0.000001f)
{
return not_equal_impl(t0,t1,epsilon);
}
template <typename T>
inline bool test_expression(const std::string& expression_string, const T& expected_result)
{
exprtk::symbol_table<T> symbol_table;
symbol_table.add_constants();
exprtk::polynomial<T, 1> poly01;
exprtk::polynomial<T, 2> poly02;
exprtk::polynomial<T, 3> poly03;
exprtk::polynomial<T, 4> poly04;
exprtk::polynomial<T, 5> poly05;
exprtk::polynomial<T, 6> poly06;
exprtk::polynomial<T, 7> poly07;
exprtk::polynomial<T, 8> poly08;
exprtk::polynomial<T, 9> poly09;
exprtk::polynomial<T,10> poly10;
exprtk::polynomial<T,11> poly11;
exprtk::polynomial<T,12> poly12;
symbol_table.add_function("poly01", poly01);
symbol_table.add_function("poly02", poly02);
symbol_table.add_function("poly03", poly03);
symbol_table.add_function("poly04", poly04);
symbol_table.add_function("poly05", poly05);
symbol_table.add_function("poly06", poly06);
symbol_table.add_function("poly07", poly07);
symbol_table.add_function("poly08", poly08);
symbol_table.add_function("poly09", poly09);
symbol_table.add_function("poly10", poly10);
symbol_table.add_function("poly11", poly11);
symbol_table.add_function("poly12", poly12);
exprtk::expression<T> expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("test_expression() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
if (!exprtk::expression_helper<T>::is_constant(expression))
{
printf("test_expression() - Error: Expression did not compile to a constant! Expression: %s\n",
expression_string.c_str());
return false;
}
T result = expression.value();
if (not_equal(result,expected_result))
{
printf("test_expression() - Computation Error: Expression: [%s]\tExpected: %19.15f\tResult: %19.15f\n",
expression_string.c_str(),
(double)expected_result,
(double)result);
return false;
}
return true;
}
template <typename T>
inline bool run_test00()
{
const std::size_t rounds = 10;
for (std::size_t r = 0; r < rounds; ++r)
{
bool result = true;
for (std::size_t i = 0; i < test_list_size; ++i)
{
if (!test_expression<T>(test_list[i].first,T(test_list[i].second)))
{
result = false;
}
}
if (!result)
{
return false;
}
}
return true;
}
template <typename T>
struct test_xy
{
test_xy(std::string e, const T& v0, const T& v1, const T& r)
: expr(e),
x(v0),
y(v1),
result(r)
{}
std::string expr;
T x;
T y;
T result;
};
template <typename T>
struct test_xyzw
{
test_xyzw(std::string e, const T& v0, const T& v1, const T& v2, const T& v3, const T& r)
: expr(e),
x(v0),
y(v1),
z(v2),
w(v3),
result(r)
{}
std::string expr;
T x;
T y;
T z;
T w;
T result;
};
template <typename T>
inline bool run_test01()
{
{
static const test_xy<T> test_list[] =
{
test_xy<T>("x + y" ,T(2.2),T(3.3),T(5.5 )),
test_xy<T>("x - y" ,T(3.3),T(2.2),T(1.1 )),
test_xy<T>("x * y" ,T(3.3),T(2.2),T(7.26 )),
test_xy<T>("x / y" ,T(3.3),T(2.2),T(1.5 )),
test_xy<T>("(x + y) * (x + y)" ,T(2.2),T(3.3),T(30.25)),
test_xy<T>("(x + y) / (x + y)" ,T(2.2),T(3.3),T(1.0 )),
test_xy<T>("x + y > x and x + y > y" ,T(2.2),T(3.3),T(1.0)),
test_xy<T>("1 + (x + y)" ,T(2.2),T(3.3),T(6.5 )),
test_xy<T>("(x + y) - 1" ,T(2.2),T(3.3),T(4.5 )),
test_xy<T>("1 + (x + y) * 2" ,T(2.2),T(3.3),T(12.0 )),
test_xy<T>("2 * (x + y) - 1" ,T(2.2),T(3.3),T(10.0 )),
test_xy<T>("y + (x + 1)" ,T(2.2),T(3.3),T(6.5 )),
test_xy<T>("(x + 1) + y" ,T(2.2),T(3.3),T(6.5 )),
test_xy<T>("2 * x" ,T(2.2),T(0.0),T(4.4)),
test_xy<T>("x * 2" ,T(2.2),T(0.0),T(4.4)),
test_xy<T>("1.1 + x",T(2.2),T(0.0),T(3.3)),
test_xy<T>("x + 1.1",T(2.2),T(0.0),T(3.3)),
test_xy<T>("x * 1 == x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("1 * x == x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("y * 1 == y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("1 * y == y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("x * 0 == 0" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("0 * x == 0" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("y * 0 == 0" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("0 * y == 0" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("x + 1 == 1 + x",T(2.0),T(3.0),T(1.0)),
test_xy<T>("y + 1 == 1 + y",T(2.0),T(3.0),T(1.0)),
test_xy<T>("x + y == y + x",T(2.0),T(3.0),T(1.0)),
test_xy<T>("x * y == y * x",T(2.0),T(3.0),T(1.0)),
test_xy<T>("x < y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("y > x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("x <= y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("y >= x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("x + y > y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("x + y > x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("x * y > y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("x * y > x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("(x + y) > y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("(x + y) > x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("(x * y) > y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("(x * y) > x" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("(2x + 3y) == (2*x + 3*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("2(x + y) == (2*x + 2*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" (x + y)3 == (3*x + 3*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("2x + 3y == 2*x + 3*y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("2(x + y) == 2*x + 2*y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" (x + y)3 == 3*x + 3*y" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" (x)y == (x*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" x(y) == (x*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" (x) y == (x*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" x (y) == (x*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" ((x) y) == (x*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>(" (x (y)) == (x*y)" ,T(2.0),T(3.0),T(1.0)),
test_xy<T>("equal(x^2.2^1.1,17.15193942371376191362)" ,T(3.3),T(0.0),T(1.0)),
test_xy<T>("equal(3.3^x^1.1,17.15193942371376191362)" ,T(2.2),T(0.0),T(1.0)),
test_xy<T>("equal(3.3^2.2^x,17.15193942371376191362)" ,T(1.1),T(0.0),T(1.0)),
test_xy<T>("equal(x^2.2^y,17.15193942371376191362)" ,T(3.3),T(1.1),T(1.0)),
test_xy<T>("equal(x^y^1.1,17.15193942371376191362)" ,T(3.3),T(2.2),T(1.0)),
test_xy<T>("equal(3.3^x^y,17.15193942371376191362)" ,T(2.2),T(1.1),T(1.0)),
test_xy<T>("equal(x+y^3/7,x+(y*y*y)/7)",T(2.0),T(3.0),T(1.0)),
test_xy<T>("equal(1-x^3+y^2*7,1-(x*x*x)+(y*y)*7)",T(2.0),T(3.0),T(1.0)),
test_xy<T>("equal( x^0,1)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^1,x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^2,x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^3,x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^4,x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^5,x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^6,x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^7,x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^8,x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^9,x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^10,x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^11,x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^12,x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^13,x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^14,x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^15,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^16,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^17,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^18,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^19,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^20,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^21,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^22,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^23,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^24,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^25,x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( y^0,1)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^1,y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^2,y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^3,y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^4,y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^5,y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^6,y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^7,y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^8,y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^9,y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^10,y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^11,y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^12,y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^13,y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^14,y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^15,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^16,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^17,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^18,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^19,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^20,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^21,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^22,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^23,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^24,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^25,y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( x^-0,1/1)",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-1,1/(x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-2,1/(x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-3,1/(x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-4,1/(x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-5,1/(x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-6,1/(x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-7,1/(x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-8,1/(x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( x^-9,1/(x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-10,1/(x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-11,1/(x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-12,1/(x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-13,1/(x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-14,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-15,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-16,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-17,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-18,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-19,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-20,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-21,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-22,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-23,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-24,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal(x^-25,1/(x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x))",T(12.34),T(0.0),T(1.0)),
test_xy<T>("equal( y^-0,1/1)",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-1,1/(y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-2,1/(y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-3,1/(y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-4,1/(y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-5,1/(y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-6,1/(y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-7,1/(y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-8,1/(y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal( y^-9,1/(y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-10,1/(y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-11,1/(y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-12,1/(y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-13,1/(y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-14,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-15,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-16,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-17,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-18,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-19,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-20,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-21,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-22,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-23,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-24,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("equal(y^-25,1/(y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y*y))",T(0.0),T(12.34),T(1.0)),
test_xy<T>("(2 + x) + 7",T(3.0),T(0.0),T((2.0 + 3.0) + 7.0)),
test_xy<T>("(2 + x) - 7",T(3.0),T(0.0),T((2.0 + 3.0) - 7.0)),
test_xy<T>("(2 - x) + 7",T(3.0),T(0.0),T((2.0 - 3.0) + 7.0)),
test_xy<T>("(2 - x) - 7",T(3.0),T(0.0),T((2.0 - 3.0) - 7.0)),
test_xy<T>("(2 * x) * 7",T(3.0),T(0.0),T((2.0 * 3.0) * 7.0)),
test_xy<T>("(2 * x) / 7",T(3.0),T(0.0),T((2.0 * 3.0) / 7.0)),
test_xy<T>("(2 / x) * 7",T(3.0),T(0.0),T((2.0 / 3.0) * 7.0)),
test_xy<T>("(2 / x) / 7",T(3.0),T(0.0),T((2.0 / 3.0) / 7.0)),
test_xy<T>("2 + (x + 7)",T(3.0),T(0.0),T(2.0 + (3.0 + 7.0))),
test_xy<T>("2 + (x - 7)",T(3.0),T(0.0),T(2.0 + (3.0 - 7.0))),
test_xy<T>("2 - (x + 7)",T(3.0),T(0.0),T(2.0 - (3.0 + 7.0))),
test_xy<T>("2 - (x - 7)",T(3.0),T(0.0),T(2.0 - (3.0 - 7.0))),
test_xy<T>("2 * (x * 7)",T(3.0),T(0.0),T(2.0 * (3.0 * 7.0))),
test_xy<T>("2 * (x / 7)",T(3.0),T(0.0),T(2.0 * (3.0 / 7.0))),
test_xy<T>("2 / (x * 7)",T(3.0),T(0.0),T(2.0 / (3.0 * 7.0))),
test_xy<T>("2 / (x / 7)",T(3.0),T(0.0),T(2.0 / (3.0 / 7.0))),
test_xy<T>("2 + (7 + x)",T(3.0),T(0.0),T(2.0 + (7.0 + 3.0))),
test_xy<T>("2 + (7 - x)",T(3.0),T(0.0),T(2.0 + (7.0 - 3.0))),
test_xy<T>("2 - (7 + x)",T(3.0),T(0.0),T(2.0 - (7.0 + 3.0))),
test_xy<T>("2 - (7 - x)",T(3.0),T(0.0),T(2.0 - (7.0 - 3.0))),
test_xy<T>("2 * (7 * x)",T(3.0),T(0.0),T(2.0 * (7.0 * 3.0))),
test_xy<T>("2 * (7 / x)",T(3.0),T(0.0),T(2.0 * (7.0 / 3.0))),
test_xy<T>("2 / (7 * x)",T(3.0),T(0.0),T(2.0 / (7.0 * 3.0))),
test_xy<T>("2 / (7 / x)",T(3.0),T(0.0),T(2.0 / (7.0 / 3.0))),
test_xy<T>("(x + 2) + 7",T(3.0),T(0.0),T((3.0 + 2.0) + 7.0)),
test_xy<T>("(x + 2) - 7",T(3.0),T(0.0),T((3.0 + 2.0) - 7.0)),
test_xy<T>("(x - 2) + 7",T(3.0),T(0.0),T((3.0 - 2.0) + 7.0)),
test_xy<T>("(x - 2) - 7",T(3.0),T(0.0),T((3.0 - 2.0) - 7.0)),
test_xy<T>("(x * 2) * 7",T(3.0),T(0.0),T((3.0 * 2.0) * 7.0)),
test_xy<T>("(x * 2) / 7",T(3.0),T(0.0),T((3.0 * 2.0) / 7.0)),
test_xy<T>("(x / 2) * 7",T(3.0),T(0.0),T((3.0 / 2.0) * 7.0)),
test_xy<T>("(x / 2) / 7",T(3.0),T(0.0),T((3.0 / 2.0) / 7.0)),
test_xy<T>("((2 + x) + (3 + y))",T(7.0),T(9.0),T(((2.0 + 7.0) + (3.0 + 9.0)))),
test_xy<T>("((2 + x) - (3 + y))",T(7.0),T(9.0),T(((2.0 + 7.0) - (3.0 + 9.0)))),
test_xy<T>("((2 - x) - (3 - y))",T(7.0),T(9.0),T(((2.0 - 7.0) - (3.0 - 9.0)))),
test_xy<T>("((2 * x) * (3 * y))",T(7.0),T(9.0),T(((2.0 * 7.0) * (3.0 * 9.0)))),
test_xy<T>("((x + 2) + (y + 3))",T(7.0),T(9.0),T(((7.0 + 2.0) + (9.0 + 3.0)))),
test_xy<T>("((x + 2) - (y + 3))",T(7.0),T(9.0),T(((7.0 + 2.0) - (9.0 + 3.0)))),
test_xy<T>("((x - 2) - (y - 3))",T(7.0),T(9.0),T(((7.0 - 2.0) - (9.0 - 3.0)))),
test_xy<T>("((2 * x) * (3 * y))",T(7.0),T(9.0),T(((2.0 * 7.0) * (3.0 * 9.0)))),
test_xy<T>("((2 + x) + (y + 3))",T(7.0),T(9.0),T(((2.0 + 7.0) + (9.0 + 3.0)))),
test_xy<T>("((2 + x) - (y + 3))",T(7.0),T(9.0),T(((2.0 + 7.0) - (9.0 + 3.0)))),
test_xy<T>("((2 - x) - (y - 3))",T(7.0),T(9.0),T(((2.0 - 7.0) - (9.0 - 3.0)))),
test_xy<T>("((2 * x) * (3 * y))",T(7.0),T(9.0),T(((2.0 * 7.0) * (3.0 * 9.0)))),
test_xy<T>("((x + 2) + (3 + y))",T(7.0),T(9.0),T(((7.0 + 2.0) + (3.0 + 9.0)))),
test_xy<T>("((x + 2) - (3 + y))",T(7.0),T(9.0),T(((7.0 + 2.0) - (3.0 + 9.0)))),
test_xy<T>("((x - 2) - (3 - y))",T(7.0),T(9.0),T(((7.0 - 2.0) - (3.0 - 9.0)))),
test_xy<T>("((2 * x) * (3 * y))",T(7.0),T(9.0),T(((2.0 * 7.0) * (3.0 * 9.0)))),
test_xy<T>("((2 * x) / (3 * y))",T(7.0),T(9.0),T(((2.0 * 7.0) / (3.0 * 9.0)))),
test_xy<T>("((2 / x) * (3 / y))",T(7.0),T(9.0),T(((2.0 / 7.0) * (3.0 / 9.0)))),
test_xy<T>("((2 * x) / (3 / y))",T(7.0),T(9.0),T(((2.0 * 7.0) / (3.0 / 9.0)))),
test_xy<T>("((2 / x) / (3 * y))",T(7.0),T(9.0),T(((2.0 / 7.0) / (3.0 * 9.0)))),
test_xy<T>("((x * 2) / (y * 3))",T(7.0),T(9.0),T(((7.0 * 2.0) / (9.0 * 3.0)))),
test_xy<T>("((x / 2) * (y / 3))",T(7.0),T(9.0),T(((7.0 / 2.0) * (9.0 / 3.0)))),
test_xy<T>("((x * 2) / (y / 3))",T(7.0),T(9.0),T(((7.0 * 2.0) / (9.0 / 3.0)))),
test_xy<T>("((x / 2) / (y * 3))",T(7.0),T(9.0),T(((7.0 / 2.0) / (9.0 * 3.0)))),
test_xy<T>("((2 * x) / (y * 3))",T(7.0),T(9.0),T(((2.0 * 7.0) / (9.0 * 3.0)))),
test_xy<T>("((2 / x) * (y / 3))",T(7.0),T(9.0),T(((2.0 / 7.0) * (9.0 / 3.0)))),
test_xy<T>("((2 * x) / (y / 3))",T(7.0),T(9.0),T(((2.0 * 7.0) / (9.0 / 3.0)))),
test_xy<T>("((2 / x) / (y * 3))",T(7.0),T(9.0),T(((2.0 / 7.0) / (9.0 * 3.0)))),
test_xy<T>("((x * 2) / (3 * y))",T(7.0),T(9.0),T(((7.0 * 2.0) / (3.0 * 9.0)))),
test_xy<T>("((x / 2) * (3 / y))",T(7.0),T(9.0),T(((7.0 / 2.0) * (3.0 / 9.0)))),
test_xy<T>("((x * 2) / (3 / y))",T(7.0),T(9.0),T(((7.0 * 2.0) / (3.0 / 9.0)))),
test_xy<T>("((x / 2) / (3 * y))",T(7.0),T(9.0),T(((7.0 / 2.0) / (3.0 * 9.0)))),
test_xy<T>("([(min(x,8) + y) + 3] - 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) + 3.0) - 4.0))),
test_xy<T>("([(min(x,8) + y) + 3] + 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) + 3.0) + 4.0))),
test_xy<T>("([(min(x,8) + y) + 3] * 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) + 3.0) * 4.0))),
test_xy<T>("([(min(x,8) + y) + 3] / 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) + 3.0) / 4.0))),
test_xy<T>("([(min(x,8) + y) - 3] - 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) - 3.0) - 4.0))),
test_xy<T>("([(min(x,8) + y) - 3] + 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) - 3.0) + 4.0))),
test_xy<T>("([(min(x,8) + y) - 3] * 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) - 3.0) * 4.0))),
test_xy<T>("([(min(x,8) + y) - 3] / 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) - 3.0) / 4.0))),
test_xy<T>("([(min(x,8) + y) * 3] - 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) * 3.0) - 4.0))),
test_xy<T>("([(min(x,8) + y) * 3] + 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) * 3.0) + 4.0))),
test_xy<T>("([(min(x,8) + y) * 3] * 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) * 3.0) * 4.0))),
test_xy<T>("([(min(x,8) + y) * 3] / 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) * 3.0) / 4.0))),
test_xy<T>("([(min(x,8) + y) / 3] - 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) / 3.0) - 4.0))),
test_xy<T>("([(min(x,8) + y) / 3] + 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) / 3.0) + 4.0))),
test_xy<T>("([(min(x,8) + y) / 3] * 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) / 3.0) * 4.0))),
test_xy<T>("([(min(x,8) + y) / 3] / 4)",T(7.0),T(9.0),T((((std::min(7.0,8.0) + 9.0) / 3.0) / 4.0))),
test_xy<T>("(4 - [3 + (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 - (3.0 + (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 + [3 + (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 + (3.0 + (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 * [3 + (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 * (3.0 + (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 / [3 + (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 / (3.0 + (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 - [3 - (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 - (3.0 - (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 + [3 - (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 + (3.0 - (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 * [3 - (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 * (3.0 - (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 / [3 - (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 / (3.0 - (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 - [3 * (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 - (3.0 * (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 + [3 * (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 + (3.0 * (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 * [3 * (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 * (3.0 * (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 / [3 * (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 / (3.0 * (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 - [3 / (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 - (3.0 / (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 + [3 / (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 + (3.0 / (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 * [3 / (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 * (3.0 / (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("(4 / [3 / (min(x,8) + y)])",T(7.0),T(9.0),T((4.0 / (3.0 / (std::min(7.0,8.0) + 9.0))))),
test_xy<T>("((2 * x) + (2 * y))",T(7.0),T(9.0),T(((2.0 * 7.0) + (2.0 * 9.0)))),
test_xy<T>("((2 * x) - (2 * y))",T(7.0),T(9.0),T(((2.0 * 7.0) - (2.0 * 9.0)))),
test_xy<T>("((2 * x) + (y * 2))",T(7.0),T(9.0),T(((2.0 * 7.0) + (9.0 * 2.0)))),
test_xy<T>("((x * 2) - (y * 2))",T(7.0),T(9.0),T(((7.0 * 2.0) - (9.0 * 2.0)))),
test_xy<T>("0 * (abs (x) + acos (y) + asin (x) + atan (y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("0 * (ceil (x) + cos (y) + cosh (x) + exp (y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("0 * (floor(x) + log (y) + log10(x) + round(y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("0 * (sin (x) + sinh (y) + sqrt (x) + tan (y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("0 * (sec (x) + csc (y) + tanh (x) + cot (y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("0 * (erf (x) + erfc (y) + sgn (y) + frac (y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("0 * (log1p(x) + expm1(y) + acosh(x) + asinh(y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("0 * (deg2grad(x) + grad2deg(y) + rad2deg(x) + deg2rad(y))",T(1.0),T(1.0),T(0.0)),
test_xy<T>("switch { case (x <= y) : (y - x); default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case (x > y) : 0; case (x <= y) : (y - x); default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case (x <= y) : switch { case (x <= y) : (y - x); default: 1.12345; }; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case [x <= y] : [y - x]; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case [x > y] : 0; case [x <= y] : [y - x]; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case [x <= y] : switch { case [x <= y] : {y - x}; default: 1.12345; }; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case {x <= y} : x; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case {x > y} : 0; case {x <= y} : {y - x}; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case {x <= y} : switch { case {x <= y} : x; default: 1.12345; }; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case [(x <= y)] : {y - x}; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case ([x > y]) : [0]; case ([x <= y]) : [y - x]; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("switch { case {(x <= y)} : switch { case ({x <= y}) : x; default: 1.12345; }; default: 1.12345; }",T(1.0),T(2.0),T(1.0)),
test_xy<T>("[*]{ case x < y : x + y; case y < x : y - x; }",T(2.0),T(3.0),T(5.0)),
test_xy<T>("[*]{ case x > y : x + y; case y > x : y - x; }",T(2.0),T(3.0),T(1.0)),
test_xy<T>("[*]{ case x > y : x - y; case y < x : y + x; }",T(2.0),T(3.0),T(0.0)),
test_xy<T>("0 ? x : y" ,T(1.0),T(2.0),T( 2.0)),
test_xy<T>("1 ? x : y" ,T(1.0),T(2.0),T( 1.0)),
test_xy<T>("x ? x : y" ,T(1.0),T(2.0),T( 1.0)),
test_xy<T>("x ? x : y" ,T(0.0),T(2.0),T( 2.0)),
test_xy<T>("(x + y < 4) ? 1 : 2" ,T(1.0),T(2.0),T( 1.0)),
test_xy<T>("(x + y > 4) ? 1 : 2" ,T(1.0),T(2.0),T( 2.0)),
test_xy<T>("x < y ? x + y : x - y" ,T(1.0),T(2.0),T( 3.0)),
test_xy<T>("x > y ? x + y : x - y" ,T(1.0),T(2.0),T(-1.0)),
test_xy<T>("(x + x < y ? 7 : 9) == 7" ,T(1.0),T(3.0),T( 1.0)),
test_xy<T>("(x + x < y + y ? 7 : 9) == 7" ,T(1.0),T(3.0),T( 1.0)),
test_xy<T>("(x > y + y ? 7 : 9) == 9" ,T(1.0),T(3.0),T( 1.0)),
test_xy<T>("(x + x > y ? 7 : 9) == 9" ,T(1.0),T(3.0),T( 1.0)),
test_xy<T>("(x + x > y + 3 ? 7 : 9) == 9" ,T(1.0),T(3.0),T( 1.0)),
test_xy<T>("(x < (y + y) ? 7 : 9) == 7" ,T(1.0),T(3.0),T( 1.0)),
test_xy<T>("((x + x) < y ? 7 : 9) == 7" ,T(1.0),T(3.0),T( 1.0)),
test_xy<T>("((x + x) < (y + y) ? 7 : 9) == 7",T(1.0),T(3.0),T( 1.0)),
test_xy<T>("(x += 2 ) == 3 " ,T(1),T(3),T(1)),
test_xy<T>("(x += 2y) == 7 " ,T(1),T(3),T(1)),
test_xy<T>("(x -= 2 ) == -1 " ,T(1),T(3),T(1)),
test_xy<T>("(x -= 2y) == -5 " ,T(1),T(3),T(1)),
test_xy<T>("(x *= 2 ) == 2 " ,T(1),T(3),T(1)),
test_xy<T>("(x *= 2y) == 6 " ,T(1),T(3),T(1)),
test_xy<T>("(x /= 2 ) == (1/2)" ,T(1),T(3),T(1)),
test_xy<T>("(x /= 2y) == (1/6)" ,T(1),T(3),T(1)),
test_xy<T>("for(var i := 0; (i < 10);) { i += 1; }; x;" ,T(1),T(20),T( 1)),
test_xy<T>("for(var i := 0; (i < 10) and (i != y); i+=2) { x += i; }; x;" ,T(1),T(20),T(21)),
test_xy<T>("for(var i := 0; (i < 10) and (i != y);) { x += i; i+=2; }; x;",T(1),T(20),T(21)),
test_xy<T>("for(var i := 0; (i < y); i += 1) { if (i <= (y / 2)) x += i; else break; }; x;" ,T(0),T(10),T(15)),
test_xy<T>("for(var i := 0; (i < y); i += 1) { if (i <= (y / 2)) continue; else x += i; }; x;" ,T(0),T(10),T(30))
};
static const std::size_t test_list_size = sizeof(test_list) / sizeof(test_xy<T>);
const std::size_t rounds = 60;
for (std::size_t r = 0; r < rounds; ++r)
{
bool loop_result = true;
for (std::size_t i = 0; i < test_list_size; ++i)
{
test_xy<T>& test = const_cast<test_xy<T>&>(test_list[i]);
T x = test.x;
T y = test.y;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
exprtk::expression<T> expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(test.expr,expression))
{
printf("run_test01() - Error: %s Expression: %s\n",
parser.error().c_str(),
test.expr.c_str());
loop_result = false;
continue;
}
}
T result = expression.value();
if (not_equal(result,test.result))
{
printf("run_test01() - Computation Error: Expression: [%s]\tExpected: %19.15f\tResult: %19.15f\n",
test.expr.c_str(),
(double)test.result,
(double)result);
loop_result = false;
}
}
if (!loop_result)
{
return false;
}
}
}
{
static const test_xyzw<T> test_list[] =
{
test_xyzw<T>("((x / y) / z )",T(7.0),T(9.0),T(3.0),T(0.0),T(((7.0 / 9.0) / 3.0 ))),
test_xyzw<T>("((x / y) / 2 )",T(7.0),T(9.0),T(3.0),T(0.0),T(((7.0 / 9.0) / 2.0 ))),
test_xyzw<T>("((x / 2) / y )",T(7.0),T(9.0),T(3.0),T(0.0),T(((7.0 / 2.0) / 9.0 ))),
test_xyzw<T>("((2 / x) / y )",T(7.0),T(9.0),T(3.0),T(0.0),T(((2.0 / 7.0) / 9.0 ))),
test_xyzw<T>("( x / (y / z))",T(7.0),T(9.0),T(3.0),T(0.0),T(( 7.0 / (9.0 / 3.0)))),
test_xyzw<T>("( x / (y / 2))",T(7.0),T(9.0),T(3.0),T(0.0),T(( 7.0 / (9.0 / 2.0)))),
test_xyzw<T>("( x / (2 / y))",T(7.0),T(9.0),T(3.0),T(0.0),T(( 7.0 / (2.0 / 9.0)))),
test_xyzw<T>("( 2 / (x / y))",T(7.0),T(9.0),T(3.0),T(0.0),T(( 2.0 / (7.0 / 9.0)))),
test_xyzw<T>("([(min(x,y) + z) + 3] - 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) + 3.0) - 4.0))),
test_xyzw<T>("([(min(x,y) + z) + 3] + 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) + 3.0) + 4.0))),
test_xyzw<T>("([(min(x,y) + z) + 3] * 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) + 3.0) * 4.0))),
test_xyzw<T>("([(min(x,y) + z) + 3] / 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) + 3.0) / 4.0))),
test_xyzw<T>("([(min(x,y) + z) - 3] - 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) - 3.0) - 4.0))),
test_xyzw<T>("([(min(x,y) + z) - 3] + 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) - 3.0) + 4.0))),
test_xyzw<T>("([(min(x,y) + z) - 3] * 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) - 3.0) * 4.0))),
test_xyzw<T>("([(min(x,y) + z) - 3] / 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) - 3.0) / 4.0))),
test_xyzw<T>("([(min(x,y) + z) * 3] - 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) * 3.0) - 4.0))),
test_xyzw<T>("([(min(x,y) + z) * 3] + 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) * 3.0) + 4.0))),
test_xyzw<T>("([(min(x,y) + z) * 3] * 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) * 3.0) * 4.0))),
test_xyzw<T>("([(min(x,y) + z) * 3] / 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) * 3.0) / 4.0))),
test_xyzw<T>("([(min(x,y) + z) / 3] - 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) / 3.0) - 4.0))),
test_xyzw<T>("([(min(x,y) + z) / 3] + 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) / 3.0) + 4.0))),
test_xyzw<T>("([(min(x,y) + z) / 3] * 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) / 3.0) * 4.0))),
test_xyzw<T>("([(min(x,y) + z) / 3] / 4)",T(5.0),T(7.0),T(9.0),T(0.0),T((((std::min(5.0,7.0) + 9.0) / 3.0) / 4.0))),
test_xyzw<T>("(4 - [3 + (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 - (3.0 + (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 + [3 + (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 + (3.0 + (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 * [3 + (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 * (3.0 + (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 / [3 + (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 / (3.0 + (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 - [3 - (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 - (3.0 - (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 + [3 - (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 + (3.0 - (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 * [3 - (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 * (3.0 - (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 / [3 - (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 / (3.0 - (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 - [3 * (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 - (3.0 * (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 + [3 * (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 + (3.0 * (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 * [3 * (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 * (3.0 * (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 / [3 * (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 / (3.0 * (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 - [3 / (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 - (3.0 / (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 + [3 / (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 + (3.0 / (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 * [3 / (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 * (3.0 / (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("(4 / [3 / (min(x,y) + z)])",T(5.0),T(7.0),T(9.0),T(0.0),T((4.0 / (3.0 / (std::min(5.0,7.0) + 9.0))))),
test_xyzw<T>("if(x < y) { z+2; z;} == z" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x > y) { z+2; z;} == null" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x < y) { z+2; z;} else w; == z" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x > y) { z+2; z;} else 1 + w; == (w + 1)" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x < y) { z+2; z;} else {1+2; w;} == z" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x > y) { z+2; z;} else {1+2; w;} == w" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x < y) { z+2; z;} else if (x < y) w; == z" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x > y) { z+2; z;} else if (x < y) 1 + w; == w + 1" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x > y) { z+2; z;} else if (x > y) w; == null" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x < y) { z+2; z;} else if (x < y) {w+2; w;} == z" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x > y) { z+2; z;} else if (x < y) {w+2; w;} == w" ,T(1.0),T(2.0),T(3.0),T(4.0),T(1.0)),
test_xyzw<T>("if(x > y) { z+2; z;} else if (x > y) {w+2; w;} == null",T(1.0),T(2.0),T(3.0),T(4.0),T(1.0))
};
static const std::size_t test_list_size = sizeof(test_list) / sizeof(test_xyzw<T>);
const std::size_t rounds = 60;
for (std::size_t r = 0; r < rounds; ++r)
{
bool loop_result = true;
for (std::size_t i = 0; i < test_list_size; ++i)
{
test_xyzw<T>& test = const_cast<test_xyzw<T>&>(test_list[i]);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",test.x);
symbol_table.add_variable("y",test.y);
symbol_table.add_variable("z",test.z);
symbol_table.add_variable("w",test.w);
exprtk::expression<T> expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(test.expr,expression))
{
printf("run_test01() - Error: %s Expression: %s\n",
parser.error().c_str(),
test.expr.c_str());
loop_result = false;
continue;
}
}
T result = expression.value();
if (not_equal(result,test.result))
{
printf("run_test01() - Computation Error: Expression: [%s]\tExpected: %19.15f\tResult: %19.15f\n",
test.expr.c_str(),
(double)test.result,
(double)result);
loop_result = false;
}
}
if (!loop_result)
{
return false;
}
}
}
{
const std::string expr_list[] =
{
"((v[1] + x) == (x + v[1]))",
"((v[0] += x) == x)",
"((v[0] += x + y) == (x + y))",
"((v[0] -= x) == -x)",
"((v[0] -= (x + y)) == -(x + y))",
"((v[1] + v[2]) == (v[3 - 1] + v[2 * 1/2]))",
"(v[v[1]] == v[1])",
"(v[1] += v[1]) == v[1 + 1]",
"((v[i[1]] + x) == (x + v[i[1]]))",
"((v[i[0]] += x) == x)",
"((v[i[0]] += x + y) == (x + y))",
"((v[i[0]] -= x) == -x)",
"((v[i[0]] -= (x + y)) == -(x + y))",
"((v[i[1]] + v[2]) == (v[i[3] - i[1]] + v[i[2] * 1/2]))",
"(v[v[i[1]]] == v[i[1]])",
"(v[i[1]] += v[i[1]]) == v[i[1] + 1]"
};
const std::size_t expr_list_size = sizeof(expr_list) / sizeof(std::string);
const std::size_t rounds = 60;
for (std::size_t r = 0; r < rounds; ++r)
{
bool loop_result = true;
for (std::size_t i = 0; i < expr_list_size; ++i)
{
T v[] = { T(0.0), T(1.1), T(2.2), T(3.3), T(4.4), T(5.5) };
T index[] = { T(0) , T(1) , T(2) , T(3) , T(4) , T(5) };
T x = T(6.6);
T y = T(7.7);
T z = T(8.8);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_vector ("v",v);
symbol_table.add_vector ("i",index);
exprtk::expression<T> expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expr_list[i],expression))
{
printf("run_test01() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_list[i].c_str());
loop_result = false;
continue;
}
}
T result = expression.value();
if (not_equal(result,T(1)))
{
printf("run_test01() - Computation Error: Expression: [%s]\tExpected: %19.15f\tResult: %19.15f\n",
expr_list[i].c_str(),
(double)1.0,
(double)result);
loop_result = false;
}
}
if (!loop_result)
{
return false;
}
}
}
return true;
}
template <typename T>
struct test_ab
{
test_ab(std::string e, const std::string& v0, const std::string& v1, const T& r)
: expr(e),
a(v0),
b(v1),
c("ccc"),
result(r)
{}
std::string expr;
std::string a;
std::string b;
std::string c;
T result;
};
template <typename T>
inline bool run_test02()
{
static const test_ab<T> test_list[] =
{
test_ab<T>("'aaa' == 'aaa'" ,"","",T(1.0)),
test_ab<T>("'aaa' < 'bbb'" ,"","",T(1.0)),
test_ab<T>("'aaa' <= 'bbb'" ,"","",T(1.0)),
test_ab<T>("'bbb' > 'aaa'" ,"","",T(1.0)),
test_ab<T>("'bbb' >= 'aaa'" ,"","",T(1.0)),
test_ab<T>("'aaa' != 'aaa'" ,"","",T(0.0)),
test_ab<T>("'aaa' != 'bbb'" ,"","",T(1.0)),
test_ab<T>("'aaa' + '123' == 'aaa123'" ,"","",T(1.0)),
test_ab<T>("'aaa123' == 'aaa' + '123'" ,"","",T(1.0)),
test_ab<T>("('aaa' + '123') == 'aaa123'" ,"","",T(1.0)),
test_ab<T>("'aaa123' == ('aaa' + '123')" ,"","",T(1.0)),
test_ab<T>("'aaa' in 'aaa123'" ,"","",T(1.0)),
test_ab<T>("'123' in 'aaa123'" ,"","",T(1.0)),
test_ab<T>("'a123b' like '*123*'" ,"","",T(1.0)),
test_ab<T>("'a123b' like '*123?'" ,"","",T(1.0)),
test_ab<T>("'1XYZ2' ilike '*xyz*'" ,"","",T(1.0)),
test_ab<T>("'1XYZ2' ilike '*xyz?'" ,"","",T(1.0)),
test_ab<T>("inrange('aaa','bbb','ccc')" ,"","",T(1.0)),
test_ab<T>("a == b" ,"aaa","aaa",T(1.0)),
test_ab<T>("a != b" ,"aaa","bbb",T(1.0)),
test_ab<T>("a < b" ,"aaa","bbb",T(1.0)),
test_ab<T>("a <= b" ,"aaa","bbb",T(1.0)),
test_ab<T>("b > a" ,"aaa","bbb",T(1.0)),
test_ab<T>("b >= a" ,"aaa","bbb",T(1.0)),
test_ab<T>("a in b" ,"aaa","aaa123",T(1.0)),
test_ab<T>("a in b" ,"123","aaa123",T(1.0)),
test_ab<T>("a == 'aaa'" ,"aaa","aaa",T(1.0)),
test_ab<T>("'aaa' == a" ,"aaa","aaa",T(1.0)),
test_ab<T>("a != 'bbb'" ,"aaa","bbb",T(1.0)),
test_ab<T>("'bbb' != a" ,"aaa","bbb",T(1.0)),
test_ab<T>("a < 'bbb'" ,"aaa","bbb",T(1.0)),
test_ab<T>("a <= 'bbb'" ,"aaa","bbb",T(1.0)),
test_ab<T>("'bbb' > a" ,"aaa","bbb",T(1.0)),
test_ab<T>("'bbb' >= a" ,"aaa","bbb",T(1.0)),
test_ab<T>("a in 'aaa123'" ,"aaa","aaa123",T(1.0)),
test_ab<T>("a in 'aaa123'" ,"123","aaa123",T(1.0)),
test_ab<T>("'aaa' in b" ,"aaa","aaa123",T(1.0)),
test_ab<T>("'123' in b" ,"aaa","aaa123",T(1.0)),
test_ab<T>("(a < b) or (a == b)" ,"aaa","bbb",T(1.0)),
test_ab<T>("(a == b) or (a < b)" ,"aaa","bbb",T(1.0)),
test_ab<T>("(b > a) or (b == a)" ,"aaa","bbb",T(1.0)),
test_ab<T>("(b == a) or (b > a)" ,"aaa","bbb",T(1.0)),
test_ab<T>("(a < b) and (b > a)" ,"aaa","bbb",T(1.0)),
test_ab<T>("a like '*123*'" ,"a123b","",T(1.0)),
test_ab<T>("a like '*123?'" ,"a123b","",T(1.0)),
test_ab<T>("'a123b' like b" ,"a123b","*123*",T(1.0)),
test_ab<T>("'a123b' like b" ,"a123b","*123?",T(1.0)),
test_ab<T>("a ilike '*xyz*'" ,"1XYZ2","",T(1.0)),
test_ab<T>("a ilike '*xyz?'" ,"1XYZ2","",T(1.0)),
test_ab<T>("'1XYZ2' ilike b" ,"","*xyz*",T(1.0)),
test_ab<T>("'1XYZ2' ilike b" ,"","*xyz?",T(1.0)),
test_ab<T>("inrange(a,'bbb',c)" ,"aaa","bbb",T(1.0)),
test_ab<T>("inrange('aaa',b,'ccc')" ,"aaa","bbb",T(1.0)),
test_ab<T>("inrange(a,b,c)" ,"aaa","bbb",T(1.0)),
test_ab<T>("inrange(a,b,'ccc')" ,"aaa","bbb",T(1.0)),
test_ab<T>("inrange('aaa',b,c)" ,"aaa","bbb",T(1.0)),
test_ab<T>("inrange('aaa',b,c)" ,"aaa","bbb",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == '0123456789' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == '0123456789'[:] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == '0123456789'[0:]","","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == '0123456789'[:9]","","",T(1.0)),
test_ab<T>("'01234567890123456789'[:9] == '0123456789'[:9]","","",T(1.0)),
test_ab<T>("'01234567890123456789'[10:] == '0123456789'[:] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != '123456789' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != '123456789'[:] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != '123456789'[0:] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != '123456789'[:8] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[:9] != '123456789'[:8] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[10:] != '123456789'[:] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[2*6:10+6] == '23456' ","","",T(1.0)),
test_ab<T>("'0123456789' == '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'0123456789'[:] == '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'0123456789'[0:] == '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'0123456789'[:9] == '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'0123456789'[:9] == '01234567890123456789'[:9] ","","",T(1.0)),
test_ab<T>("'0123456789'[:] == '01234567890123456789'[10:]","","",T(1.0)),
test_ab<T>("'0123456789'[3:3] == '3'[:] ","","",T(1.0)),
test_ab<T>("'0123456789'[3:3] == '3'[0:0] ","","",T(1.0)),
test_ab<T>("'123456789' != '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'123456789'[:] != '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'123456789'[0:] != '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'123456789'[:8] != '01234567890123456789'[0:9]","","",T(1.0)),
test_ab<T>("'123456789'[:8] != '01234567890123456789'[:9] ","","",T(1.0)),
test_ab<T>("'123456789'[:] != '01234567890123456789'[10:]","","",T(1.0)),
test_ab<T>("'23456' == '01234567890123456789'[2*6:10+6] ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[r0: 6] == '23456' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[2: r1] == '23456' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[r0:3*2] == '23456' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[1+1:r1] == '23456' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[r0: ] == '234567890123456789' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[: r1] == '0123456' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[r0:r1] == '23456' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[r0:r1+2] == '2345678' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[r0+2:r1] == '456' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[r1-r0:] == '4567890123456789' ","","",T(1.0)),
test_ab<T>("'01234567890123456789'[:r1-r0] == '01234' ","","",T(1.0)),
test_ab<T>("'23456' == '01234567890123456789'[r0: 6] ","","",T(1.0)),
test_ab<T>("'23456' == '01234567890123456789'[2: r1] ","","",T(1.0)),
test_ab<T>("'23456' == '01234567890123456789'[r0:3*2] ","","",T(1.0)),
test_ab<T>("'23456' == '01234567890123456789'[1+1:r1] ","","",T(1.0)),
test_ab<T>("'234567890123456789' == '01234567890123456789'[r0: ] ","","",T(1.0)),
test_ab<T>("'0123456' == '01234567890123456789'[: r1] ","","",T(1.0)),
test_ab<T>("'23456' == '01234567890123456789'[r0:r1] ","","",T(1.0)),
test_ab<T>("'2345678' == '01234567890123456789'[r0:r1+2] ","","",T(1.0)),
test_ab<T>("'456' == '01234567890123456789'[r0+2:r1] ","","",T(1.0)),
test_ab<T>("'4567890123456789' == '01234567890123456789'[r1-r0:] ","","",T(1.0)),
test_ab<T>("'01234' == '01234567890123456789'[:r1-r0] ","","",T(1.0)),
test_ab<T>("a[r0: 6] == '23456' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[2: r1] == '23456' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[r0:3*2] == '23456' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[1+1:r1] == '23456' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[r0: ] == '234567890123456789' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[: r1] == '0123456' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[r0:r1] == '23456' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[r0:r1+2] == '2345678' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[r0+2:r1] == '456' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[r1-r0:] == '4567890123456789' ","01234567890123456789","",T(1.0)),
test_ab<T>("a[:r1-r0] == '01234' ","01234567890123456789","",T(1.0)),
test_ab<T>("'23456' == a[r0: 6] ","01234567890123456789","",T(1.0)),
test_ab<T>("'23456' == a[2: r1] ","01234567890123456789","",T(1.0)),
test_ab<T>("'23456' == a[r0:3*2] ","01234567890123456789","",T(1.0)),
test_ab<T>("'23456' == a[1+1:r1] ","01234567890123456789","",T(1.0)),
test_ab<T>("'234567890123456789' == a[r0: ] ","01234567890123456789","",T(1.0)),
test_ab<T>("'0123456' == a[: r1] ","01234567890123456789","",T(1.0)),
test_ab<T>("'23456' == a[r0:r1] ","01234567890123456789","",T(1.0)),
test_ab<T>("'2345678' == a[r0:r1+2] ","01234567890123456789","",T(1.0)),
test_ab<T>("'456' == a[r0+2:r1] ","01234567890123456789","",T(1.0)),
test_ab<T>("'4567890123456789' == a[r1-r0:] ","01234567890123456789","",T(1.0)),
test_ab<T>("'01234' == a[:r1-r0] ","01234567890123456789","",T(1.0)),
test_ab<T>("a[r0: 6] == b ","01234567890123456789","23456",T(1.0)),
test_ab<T>("a[2: r1] == b ","01234567890123456789","23456",T(1.0)),
test_ab<T>("a[r0:3*2] == b ","01234567890123456789","23456",T(1.0)),
test_ab<T>("a[1+1:r1] == b ","01234567890123456789","23456",T(1.0)),
test_ab<T>("a[r0: ] == b ","01234567890123456789","234567890123456789",T(1.0)),
test_ab<T>("a[: r1] == b ","01234567890123456789","0123456",T(1.0)),
test_ab<T>("a[r0:r1] == b ","01234567890123456789","23456",T(1.0)),
test_ab<T>("a[r0:r1+2] == b ","01234567890123456789","2345678",T(1.0)),
test_ab<T>("a[r0+2:r1] == b ","01234567890123456789","456",T(1.0)),
test_ab<T>("a[r1-r0:] == b ","01234567890123456789","4567890123456789",T(1.0)),
test_ab<T>("a[:r1-r0] == b ","01234567890123456789","01234",T(1.0)),
test_ab<T>("b == a[r0: 6] ","01234567890123456789","23456",T(1.0)),
test_ab<T>("b == a[2: r1] ","01234567890123456789","23456",T(1.0)),
test_ab<T>("b == a[r0:3*2] ","01234567890123456789","23456",T(1.0)),
test_ab<T>("b == a[1+1:r1] ","01234567890123456789","23456",T(1.0)),
test_ab<T>("b == a[r0: ] ","01234567890123456789","234567890123456789",T(1.0)),
test_ab<T>("b == a[: r1] ","01234567890123456789","0123456",T(1.0)),
test_ab<T>("b == a[r0:r1] ","01234567890123456789","23456",T(1.0)),
test_ab<T>("b == a[r0:r1+2] ","01234567890123456789","2345678",T(1.0)),
test_ab<T>("b == a[r0+2:r1] ","01234567890123456789","456",T(1.0)),
test_ab<T>("b == a[r1-r0:] ","01234567890123456789","4567890123456789",T(1.0)),
test_ab<T>("b == a[:r1-r0] ","01234567890123456789","01234",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == a ","0123456789","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == a[:] ","0123456789","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == a[0:] ","0123456789","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] == a[:9] ","0123456789","",T(1.0)),
test_ab<T>("'01234567890123456789'[:9] == a[:9] ","0123456789","",T(1.0)),
test_ab<T>("'01234567890123456789'[10:] == a[:] ","0123456789","",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != a ","123456789" ,"",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != a[:] ","123456789" ,"",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != a[0:] ","123456789" ,"",T(1.0)),
test_ab<T>("'01234567890123456789'[0:9] != a[:8] ","123456789" ,"",T(1.0)),
test_ab<T>("'01234567890123456789'[:9] != a[:8] ","123456789" ,"",T(1.0)),
test_ab<T>("'01234567890123456789'[10:] != a[:] ","123456789" ,"",T(1.0)),
test_ab<T>("'01234567890123456789'[2*6:10+6] == a","23456" ,"",T(1.0)),
test_ab<T>("'23456' == a[:] ","23456" ,"",T(1.0)),
test_ab<T>("a == '01234567890123456789'[0:9] ","0123456789","",T(1.0)),
test_ab<T>("a[:] == '01234567890123456789'[0:9] ","0123456789","",T(1.0)),
test_ab<T>("a[0:] == '01234567890123456789'[0:9] ","0123456789","",T(1.0)),
test_ab<T>("a[:9] == '01234567890123456789'[0:9] ","0123456789","",T(1.0)),
test_ab<T>("a[:9] == '01234567890123456789'[:9] ","0123456789","",T(1.0)),
test_ab<T>("a[:] == '01234567890123456789'[10:] ","0123456789","",T(1.0)),
test_ab<T>("a != '01234567890123456789'[0:9] ","123456789" ,"",T(1.0)),
test_ab<T>("a[:] != '01234567890123456789'[0:9] ","123456789" ,"",T(1.0)),
test_ab<T>("a[0:] != '01234567890123456789'[0:9] ","123456789" ,"",T(1.0)),
test_ab<T>("a[:8] != '01234567890123456789'[0:9] ","123456789" ,"",T(1.0)),
test_ab<T>("a[:8] != '01234567890123456789'[:9] ","123456789" ,"",T(1.0)),
test_ab<T>("a[:] != '01234567890123456789'[10:] ","123456789" ,"",T(1.0)),
test_ab<T>("a == '01234567890123456789'[2*6:10+6]","23456" ,"",T(1.0)),
test_ab<T>("a[:] == '23456' ","23456" ,"",T(1.0)),
test_ab<T>("a[0:9] == b ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("a[0:9] == b[:] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("a[0:9] == b[0:] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("a[0:9] == b[:9] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("a[:9] == b[:9] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("a[10:] == b[:] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("a[0:9] != b ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("a[0:9] != b[:] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("a[0:9] != b[0:] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("a[0:9] != b[:8] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("a[:9] != b[:8] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("a[10:] != b[:] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("a[2*6:10+6] == b ","01234567890123456789","23456" ,T(1.0)),
test_ab<T>("b == a[0:9] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("b[:] == a[0:9] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("b[0:] == a[0:9] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("b[:9] == a[0:9] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("b[:9] == a[:9] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("b[:] == a[10:] ","01234567890123456789","0123456789",T(1.0)),
test_ab<T>("b != a[0:9] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("b[:] != a[0:9] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("b[0:] != a[0:9] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("b[:8] != a[0:9] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("b[:8] != a[:9] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("b[:] != a[10:] ","01234567890123456789","123456789" ,T(1.0)),
test_ab<T>("b == a[2*6:10+6] ","01234567890123456789","23456" ,T(1.0)),
test_ab<T>("a[2:6] == b" ,"0123456789","23456" ,T(1.0)),
test_ab<T>("a == b[2:6]" ,"23456","0123456789" ,T(1.0)),
test_ab<T>("a[1+1:2*3] == b" ,"0123456789","23456" ,T(1.0)),
test_ab<T>("a == b[4/2:sqrt(36)]","23456","0123456789" ,T(1.0)),
test_ab<T>("a[0:6] == b" ,"0123456789","0123456",T(1.0)),
test_ab<T>("a[:6] == b" ,"0123456789","0123456",T(1.0)),
test_ab<T>("a[4/2-2:2+4] == b" ,"0123456789","0123456",T(1.0)),
test_ab<T>("a[:12/2] == b" ,"0123456789","0123456",T(1.0)),
test_ab<T>("a[0:] == b" ,"0123456","0123456" ,T(1.0)),
test_ab<T>("a[:] == b" ,"0123456","0123456" ,T(1.0)),
test_ab<T>("a == b[0:6]" ,"0123456","0123456789",T(1.0)),
test_ab<T>("a == b[:6]" ,"0123456","0123456789",T(1.0)),
test_ab<T>("a == b[4/2-2:2+4]" ,"0123456","0123456789",T(1.0)),
test_ab<T>("a == b[:12/2]" ,"0123456","0123456789",T(1.0)),
test_ab<T>("a == b[0:]" ,"0123456","0123456" ,T(1.0)),
test_ab<T>("a == b[:]" ,"0123456","0123456" ,T(1.0)),
test_ab<T>("a[:9] == b[0:9]" ,"0123456789","01234567890123456789",T(1.0)),
test_ab<T>("a[0:9] == b[0:9]" ,"0123456789","01234567890123456789",T(1.0)),
test_ab<T>("a[0:] == b[0:9]" ,"0123456789","01234567890123456789",T(1.0)),
test_ab<T>("a[:] == b[0:9]" ,"0123456789","01234567890123456789",T(1.0)),
test_ab<T>("a[:] == b[10:]" ,"0123456789","01234567890123456789",T(1.0)),
test_ab<T>("'!@#$%^&*([{}])-=' != ')]}{[(*&^%$#@!'","","",T(1.0)),
test_ab<T>("('!@#$%^&*([{}])-=') != (')]}{[(*&^%$#@!')","","",T(1.0)),
test_ab<T>("{[('a')]} == [{('a')}]","","",T(1.0)),
test_ab<T>("{[('!@#$%^&*([{}])-=')]} != [{(')]}{[(*&^%$#@!')}]","","",T(1.0)),
test_ab<T>("'!@#$%^&*([{}])-=' == '!@#$%^&*([{}])-='","","",T(1.0)),
test_ab<T>("('!@#$%^&*([{}])-=') == ('!@#$%^&*([{}])-=')","","",T(1.0)),
test_ab<T>("{[('!@#$%^&*([{}])-=')]} == [{('!@#$%^&*([{}])-=')}]","","",T(1.0)),
test_ab<T>("'1234\\\\abc\nxyz\r890\tqaz\\'567' == a","1234\\abc\nxyz\r890\tqaz'567","",T(1.0)),
test_ab<T>("a == '1234\\\\abc\nxyz\r890\tqaz\\'567'","1234\\abc\nxyz\r890\tqaz'567","",T(1.0)),
test_ab<T>("'123'[] == 3" ,"","" ,T(1.0)),
test_ab<T>("3 == '123'[]" ,"","" ,T(1.0)),
test_ab<T>("'123'[] + '1234'[] == 7" ,"","" ,T(1.0)),
test_ab<T>("abs('123'[] - '1234'[]) == 1" ,"","" ,T(1.0)),
test_ab<T>("'1234'[] == a[]" ,"1234","" ,T(1.0)),
test_ab<T>("'123'[] + a[] == 7" ,"1234","" ,T(1.0)),
test_ab<T>("abs(a[] - '12345'[]) == 1" ,"1234","" ,T(1.0)),
test_ab<T>("'1234'[] + '12345'[] == a[] + b[]" ,"1234","12345" ,T(1.0)),
test_ab<T>("abs('123'[] -'1234'[]) == abs(a[] - b[])" ,"1234","12345",T(1.0)),
test_ab<T>("(a + b) == 'abc123' ","abc","123" ,T(1.0)),
test_ab<T>("(a + '123') == 'abc123' ","abc","123" ,T(1.0)),
test_ab<T>("('abc' + b) == 'abc123' ","abc","123" ,T(1.0)),
test_ab<T>("(a + '1') == 'abc1' ","abc","123" ,T(1.0)),
test_ab<T>("('a' + b) == 'a123' ","abc","123" ,T(1.0)),
test_ab<T>("(a[2:7] + b) == 'cdefgh0123' ","abcdefghij","0123",T(1.0)),
test_ab<T>("(a + b[2:7]) == 'abc234567' ","abc","0123456789" ,T(1.0)),
test_ab<T>("(a[2:7] + '0123') == 'cdefgh0123' ","abcdefghij","0123",T(1.0)),
test_ab<T>("('abc' + b[2:7]) == 'abc234567' ","abc","0123456789" ,T(1.0)),
test_ab<T>("(a[2:2] + b[3:3]) == 'c3' ","abc","0123456789" ,T(1.0)),
test_ab<T>("(a[3:] + b) == 'defghij0123' ","abcdefghij","0123",T(1.0)),
test_ab<T>("('abc' + b[:7]) == 'abc01234567' ","abc","0123456789" ,T(1.0)),
test_ab<T>("a + '123' == 'abc'+ b ","abc" , "123" , T(1.0)),
test_ab<T>("a[0:2] + '123' == 'abc' + b[0:2] ","abcXYZ", "123XYZ", T(1.0)),
test_ab<T>("a[ :2] + '123' == 'abc' + b[ :2] ","abcXYZ", "123XYZ", T(1.0)),
test_ab<T>("a[3: ] + '123' == 'abc' + b[3: ]","XYZabc", "XYZ123", T(1.0)),
test_ab<T>("a[3:a[] - 1] + '123' == 'abc' + b[3:b[] - 1]","XYZabc", "XYZ123", T(1.0)),
test_ab<T>("(a[r0:r2] + b) == 'cdefgh0123' ","abcdefghij","0123",T(1.0)),
test_ab<T>("(a + b[r0:r2]) == 'abc234567' ","abc","0123456789" ,T(1.0)),
test_ab<T>("(a[r0:r2] + '0123') == 'cdefgh0123' ","abcdefghij","0123",T(1.0)),
test_ab<T>("('abc' + b[r0:r2]) == 'abc234567' ","abc","0123456789" ,T(1.0)),
test_ab<T>("(a[r0:r0] + b[r3:r3]) == 'c3' ","abc","0123456789" ,T(1.0)),
test_ab<T>("(a[r3:] + b) == 'defghij0123' ","abcdefghij","0123",T(1.0)),
test_ab<T>("('abc' + b[:r2]) == 'abc01234567' ","abc","0123456789" ,T(1.0)),
test_ab<T>("a[0:r0] + '123' == 'abc' + b[0:r0] ","abcXYZ", "123XYZ", T(1.0)),
test_ab<T>("a[ :r0] + '123' == 'abc' + b[ :r0] ","abcXYZ", "123XYZ", T(1.0)),
test_ab<T>("a[r3: ] + '123' == 'abc' + b[r3: ]","XYZabc", "XYZ123", T(1.0)),
test_ab<T>("a[r3:a[] - 1] + '123' == 'abc' + b[r3:b[] - 1]","XYZabc", "XYZ123", T(1.0)),
test_ab<T>("(a[r0:r0] + b[r3:r0+1]) == 'c3' ","abc","0123456789" ,T(1.0)),
test_ab<T>("(a[r0+1:] + b) == 'defghij0123' ","abcdefghij","0123",T(1.0)),
test_ab<T>("a[r0+1: ] + '123' == 'abc' + b[r0+1: ]","XYZabc", "XYZ123", T(1.0)),
test_ab<T>("a[r0+1:a[] - 1] + '123' == 'abc' + b[r0+1:b[] - 1]","XYZabc", "XYZ123", T(1.0)),
test_ab<T>("(a + b)[ :13] == 'abcdefghij0123' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a + b)[ 6: ] == 'ghij0123456789' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a + b)[ 2:3r1-1] == 'cdefghij01234567' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a[2:7] + b[2:7]) == 'cdefgh234567' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a[2:7] + b[2:7])[3:8] == 'fgh234' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a + b)[r0 - 2: r1 + r2] == 'abcdefghij0123' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a + b)[r0*r3:] == 'ghij0123456789' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a + b)[3r0: ] == 'ghij0123456789' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a + b)[2r3: ] == 'ghij0123456789' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a + b)[2:3r1 - 1] == 'cdefghij01234567' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a[r0:7] + b[r0:r2])== 'cdefgh234567' ", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a[r1 / r3:7] + b[r0:r2])[3:r2 + 1] == 'fgh234'", "abcdefghij", "0123456789" ,T(1.0)),
test_ab<T>("(a += b) == 'abc123' ", "abc","123" ,T(1.0)),
test_ab<T>("(a += '123') == 'abc123' ", "abc","123" ,T(1.0)),
test_ab<T>("(a += b[3:5]) == 'abc123' ", "abc","XXX123XXX" ,T(1.0)),
test_ab<T>("(a += 'XXX123XXX'[3:5]) == 'abc123' ", "abc","123" ,T(1.0)),
test_ab<T>("(a += b)[:] == 'abc123' ", "abc","123" ,T(1.0)),
test_ab<T>("(a += '123')[:] == 'abc123' ", "abc","123" ,T(1.0)),
test_ab<T>("(a += b[3:5])[:] == 'abc123' ", "abc","XXX123XXX" ,T(1.0)),
test_ab<T>("(a += 'XXX123XXX'[3:5])[:] == 'abc123' ", "abc","123" ,T(1.0)),
test_ab<T>("(a += b[r1/2:r1-1]) == 'abc123' ", "abc","XXX123XXX" ,T(1.0)),
test_ab<T>("(a += 'XXX123XXX'[r0+1:r1-1]) == 'abc123' ", "abc","123" ,T(1.0)),
test_ab<T>("(a += b)[] == 6 ", "abc","123" ,T(1.0)),
test_ab<T>("(a += '123')[] == 6 ", "abc","123" ,T(1.0)),
test_ab<T>("(a += b[3:5])[] == 6 ", "abc","XXX123XXX" ,T(1.0)),
test_ab<T>("(a += b[r0+1:r1-1])[] == 6 ", "abc","XXX123XXX" ,T(1.0)),
test_ab<T>("(a + b)[:][] == 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[:][:][] == 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[:][:][:][] == 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[:][:][:][:][] == 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[:][:][:][:][:][] == 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[:][:][:][:][:][:][] == 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[:][:][:][:][:][:][:][]== 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5] == 'abc123' ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5][1:4] == 'bc12' ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5][1:4][1:2] == 'c1' ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5][1:4][1:2][0:0] == 'c' ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5][] == 6 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5][1:4][] == 4 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5][1:4][1:2][] == 2 ","abc","123" ,T(1.0)),
test_ab<T>("(a + b)[0:5][1:4][1:2][0:0][] == 1 ","abc","123" ,T(1.0))
};
static const std::size_t test_list_size = sizeof(test_list) / sizeof(test_ab<T>);
const std::size_t rounds = 50;
for (std::size_t r = 0; r < rounds; ++r)
{
bool result = true;
for (std::size_t i = 0; i < test_list_size; ++i)
{
test_ab<T>& test = const_cast<test_ab<T>&>(test_list[i]);
std::string str_a;
std::string str_b;
std::string str_c;
T r0 = T(2);
T r1 = T(6);
T r2 = T(7);
T r3 = T(3);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_stringvar("a" ,str_a);
symbol_table.add_stringvar("b" ,str_b);
symbol_table.add_stringvar("c" ,str_c);
symbol_table.add_variable ("r0", r0);
symbol_table.add_variable ("r1", r1);
symbol_table.add_variable ("r2", r2);
symbol_table.add_variable ("r3", r3);
exprtk::expression<T> expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(test.expr,expression))
{
printf("run_test02() - Error: %s Expression: %s\n",
parser.error().c_str(),
test.expr.c_str());
return false;
}
}
str_a = test.a;
str_b = test.b;
str_c = test.c;
T expr_result = expression.value();
if (not_equal(expr_result,test.result))
{
printf("run_test02() - Computation Error: Expression: [%s]\tExpected: %19.15f\tResult: %19.15f\n",
test.expr.c_str(),
(double)test.result,
(double)expr_result);
result = false;
}
}
if (!result)
{
return false;
}
}
{
std::string s0;
std::string s1;
const std::string expression_str =
" s0 := 'abc'; "
" s0 := (s1 := '0123456789'[2:7]); "
" s1 := 'xyz'; "
" s0 < s1; ";
exprtk::symbol_table<T> symbol_table;
symbol_table.add_stringvar("s0" ,s0);
symbol_table.add_stringvar("s1" ,s1);
exprtk::expression<T> expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_str,expression))
{
printf("run_test02() - [2] Error: %s Expression: %s\n",
parser.error().c_str(),
expression_str.c_str());
return false;
}
}
if (T(0) == expression.value())
{
printf("run_test02() - Evaluation Error [2]: Expression: [%s]\tExpected: True\n",
expression_str.c_str());
return false;
}
else if ("234567" != s0)
{
printf("run_test02() - Evaluation Error [2]: Expression: [%s]\tInvalid value for s0\n",
expression_str.c_str());
return false;
}
else if ("xyz" != s1)
{
printf("run_test02() - Evaluation Error [2]: Expression: [%s]\tInvalid value for s1\n",
expression_str.c_str());
return false;
}
}
return true;
}
template <typename T>
inline bool run_test03()
{
std::string expression_string = "A+A0+aA+Aa0+b+B1+Bb+bB1+A+A0+AA+AA0+B+B1+BB+BB1+a+a0+aa+aa0+b+b1+bb+bb1+"
"c+C2+Cc+Cc2+D+D3+dD+dD3+C+C2+CC+CC2+D+D3+DD+DD3+c+c2+cc+cc2+d+d3+dd+dd3+"
"E+E4+eE+Ee4+f+F5+Ff+fF5+E+E4+EE+EE4+F+F5+FF+FF5+e+e4+ee+ee4+f+f5+ff+ff5+"
"g+G6+Gg+Gg6+H+H7+hH+hH7+G+G6+GG+GG6+H+H7+HH+HH7+g+g6+gg+gg6+h+h7+hh+hh7+"
"I+I8+iI+Ii8+j+J9+Jj+jJ9+I+I8+II+II8+J+J9+JJ+JJ9+i+i8+ii+ii8+j+j9+jj+jj9+"
"k+K0+Kk+Kk0+L+L1+lL+lL1+K+K0+KK+KK0+L+L1+LL+LL1+k+k0+kk+kk0+l+l1+ll+ll1+"
"M+M2+mM+Mm2+n+N3+Nn+nN3+M+M2+MM+MM2+N+N3+NN+NN3+m+m2+mm+mm2+n+n3+nn+nn3+"
"o+O4+Oo+Oo4+P+P5+pP+pP5+O+O4+OO+OO4+P+P5+PP+PP5+o+o4+oo+oo4+p+p5+pp+pp5+"
"Q+Q6+qQ+Qq6+r+R7+Rr+rR7+Q+Q6+QQ+QQ6+R+R7+RR+RR7+q+q6+qq+qq6+r+r7+rr+rr7+"
"s+S8+Ss+Ss8+T+T9+tT+tT9+S+S8+SS+SS8+T+T9+TT+TT9+s+s8+ss+ss8+t+t9+tt+tt9+"
"U+U0+uU+Uu0+v+V1+Vv+vV1+U+U0+UU+UU0+V+V1+VV+VV1+u+u0+uu+uu0+v+v1+vv+vv1+"
"w+W2+Ww+Ww2+X+X3+xX+xX3+W+W2+WW+WW2+X+X3+XX+XX3+w+w2+ww+ww2+x+x3+xx+xx3+"
"Y+Y4+yY+Yy4+z+Z5+Zz+zZ5+Y+Y4+YY+YY4+Z+Z5+ZZ+ZZ5+y+y4+yy+yy4+z+z5+zz+zz5 ";
static const std::string variable_list[] =
{
"A", "A0", "aA", "Aa0", "b", "B1", "Bb", "bB1",
"c", "C2", "Cc", "Cc2", "D", "D3", "dD", "dD3",
"E", "E4", "eE", "Ee4", "f", "F5", "Ff", "fF5",
"g", "G6", "Gg", "Gg6", "H", "H7", "hH", "hH7",
"I", "I8", "iI", "Ii8", "j", "J9", "Jj", "jJ9",
"k", "K0", "Kk", "Kk0", "L", "L1", "lL", "lL1",
"M", "M2", "mM", "Mm2", "n", "N3", "Nn", "nN3",
"o", "O4", "Oo", "Oo4", "P", "P5", "pP", "pP5",
"Q", "Q6", "qQ", "Qq6", "r", "R7", "Rr", "rR7",
"s", "S8", "Ss", "Ss8", "T", "T9", "tT", "tT9",
"U", "U0", "uU", "Uu0", "v", "V1", "Vv", "vV1",
"w", "W2", "Ww", "Ww2", "X", "X3", "xX", "xX3",
"Y", "Y4", "yY", "Yy4", "z", "Z5", "Zz", "zZ5"
};
static const std::size_t variable_list_size = sizeof(variable_list) / sizeof(std::string);
static const std::size_t rounds = 300;
for (std::size_t r = 0; r < rounds; ++r)
{
exprtk::symbol_table<T> symbol_table;
exprtk::expression<T> expression;
std::vector<T> v;
v.resize(variable_list_size);
for (std::size_t i = 0; i < variable_list_size; ++i)
{
v[i] = T(i);
symbol_table.add_variable(variable_list[i],v[i]);
}
if (variable_list_size != symbol_table.variable_count())
{
printf("run_test03() - Error - Invalid number of variables in symbol_table! Expected: %d got: %d\n",
static_cast<unsigned int>(variable_list_size),
static_cast<unsigned int>(symbol_table.variable_count()));
return false;
}
symbol_table.add_constants();
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("run_test03() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
expression.value();
}
return true;
}
template <typename T>
inline T clamp(const T& l, const T& v, const T& u)
{
return (v < l) ? l : ((v > u) ? u : v);
}
template <typename T>
inline bool run_test04()
{
std::string expression_string = "clamp(-1.0,sin(2 * pi * x) + cos(y / 2 * pi),+1.0)";
exprtk::symbol_table<T> symbol_table;
exprtk::expression<T> expression;
T x = T(-1000);
T y = T(-1000);
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_constants();
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("run_test04() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
const T pi = T(3.14159265358979323846);
const T increment = T(0.0001);
while ((x <= T(+1000)) && (y <= T(+1000)))
{
T result1 = expression.value();
T result2 = clamp<T>(-1.0,std::sin(2 * pi * x) + std::cos(y / 2 * pi),+1.0);
if (not_equal(result1,result2))
{
printf("run_test04() - Computation Error: Expression: [%s]\tExpected: %19.15f\tResult: %19.15f x:%19.15f\ty:%19.15f\n",
expression_string.c_str(),
(double)result1,
(double)result2,
(double)x,
(double)y);
return false;
}
x += increment;
y += increment;
}
return true;
}
template <typename T>
inline bool run_test05()
{
typedef exprtk::expression<T> expression_t;
std::string expression_string = "clamp(-1.0,sin(2 * pi * x_var123) + cos(y_var123 / 2 * pi),+1.0)";
exprtk::symbol_table<T> symbol_table;
std::deque<expression_t> expression_list;
T x = T(-1000);
T y = T(-1000);
symbol_table.add_variable("x_var123",x);
symbol_table.add_variable("y_var123",y);
symbol_table.add_constants();
const std::size_t expression_count = 10;
for (std::size_t i = 0; i < expression_count; ++i)
{
expression_t e;
e.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,e))
{
printf("run_test05() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
expression_list.push_back(e);
}
const T pi = T(3.14159265358979323846);
const T increment = T(0.001);
while ((x <= T(+1000)) && (y <= T(+1000)))
{
T real_result = clamp<T>(-1.0,std::sin(2 * pi * x) + std::cos(y / 2 * pi),+1.0);
for (std::size_t i = 0; i < expression_list.size(); ++i)
{
expression_t& expr = expression_list[i];
T result = expr.value();
if (not_equal(result,real_result))
{
printf("run_test05() - Computation Error: Expression: [%s]\tExpected: %19.15f\tResult: %19.15f x:%19.15f\ty:%19.15f\tIndex:%d\n",
expression_string.c_str(),
(double)real_result,
(double)result,
(double)x,
(double)y,
static_cast<unsigned int>(i));
return false;
}
}
x += increment;
y += increment;
}
return true;
}
template <typename T>
inline bool run_test06()
{
typedef exprtk::expression<T> expression_t;
std::string expression_string = "sqrt(1 - (x^2))";
T x = T(0);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
expression_t expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("run_test06() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
T total_area1 = exprtk::integrate(expression,x,T(-1),T(1));
T total_area2 = exprtk::integrate(expression,"x",T(-1),T(1));
const T pi = T(3.14159265358979323846);
if (not_equal(total_area1,total_area2,T(0.000001)))
{
printf("run_test06() - Integration Error: area1 != area2\n");
return false;
}
if (not_equal(total_area1,T(pi) / T(2),T(0.000001)))
{
printf("run_test06() - Integration Error: Expected: %19.15f\tResult: %19.15f\n",
(double)(pi / T(2)),
(double)total_area1);
return false;
}
return true;
}
template <typename T>
inline bool run_test07()
{
typedef exprtk::expression<T> expression_t;
std::string expression_string = "sin(2x + 1 / 3)";
T x = T(0);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
expression_t expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("run_test07() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
for (x = T(-200); x < T(200); x += T(0.0001))
{
{
T deriv1_real_result = T(2) * std::cos(T(2) * x + T(1.0 / 3.0));
T deriv1_result1 = exprtk::derivative(expression,x);
T deriv1_result2 = exprtk::derivative(expression,"x");
if (not_equal(deriv1_result1,deriv1_result2,T(0.00001)))
{
printf("run_test07() - 1st Derivative Error: result1 != result2\n");
return false;
}
if (not_equal(deriv1_result1,deriv1_real_result,T(0.00001)))
{
printf("run_test07() - 1st Derivative Error: x: %19.15f\tExpected: %19.15f\tResult: %19.15f\n",
(double)x,
(double)deriv1_real_result,
(double)deriv1_result1);
return false;
}
}
{
T deriv2_real_result = T(-4) * std::sin(T(2) * x + T(1.0 / 3.0));
T deriv2_result1 = exprtk::second_derivative(expression,x);
T deriv2_result2 = exprtk::second_derivative(expression,"x");
if (not_equal(deriv2_result1,deriv2_result2,T(0.0000001)))
{
printf("run_test07() - 2nd Derivative Error: result1 != result2\n");
return false;
}
if (not_equal(deriv2_result1,deriv2_real_result,T(0.01)))
{
printf("run_test07() - 2nd Derivative Error: x: %19.15f\tExpected: %19.15f\tResult: %19.15f\n",
(double)x,
(double)deriv2_real_result,
(double)deriv2_result1);
return false;
}
}
{
T deriv3_real_result = T(-8) * std::cos(T(2) * x + T(1.0 / 3.0));
T deriv3_result1 = exprtk::third_derivative(expression,x);
T deriv3_result2 = exprtk::third_derivative(expression,"x");
if (not_equal(deriv3_result1,deriv3_result2,T(0.0000001)))
{
printf("run_test07() - 3rd Derivative Error: result1 != result2\n");
return false;
}
if (not_equal(deriv3_result1,deriv3_real_result,T(0.01)))
{
printf("run_test07() - 3rd Derivative Error: x: %19.15f\tExpected: %19.15f\tResult: %19.15f\n",
(double)x,
(double)deriv3_real_result,
(double)deriv3_result1);
return false;
}
}
}
return true;
}
template <typename T>
inline bool run_test08()
{
static const std::string expr_str[] =
{
"x", "y", "z", "w", "u",
"x + y + z + w + u",
"x + y / z * w ^ u",
"x:=1.1", "y:=2.2", "z:=3.3", "w:=4.4", "u:=5.5",
"x:=x+1.1", "y:=y+2.2", "z:=z+3.3", "w:=w+4.4", "u:=u+5.5",
"x:=1.1+x", "y:=2.2+y", "z:=3.3+z", "w:=4.4+w", "u:=5.5+u",
"x:=(x <= 1.1)",
"y:=(2.2 >= y)",
"z:=(3.3 and z)",
"w:=(4.4 or w)",
"u:=(u xor 5.5)",
"min(x,y) + min(x,y,z) + min(x,y,z,w) + min(x,y,z,w,y)",
"max(x,y) + max(x,y,z) + max(x,y,z,w) + max(x,y,z,w,y)",
"avg(x,y)",
"avg(x,y,z)",
"avg(x,y,z,w)",
"avg(x,y,z,w,u)",
"(u := u := min(x:=1,y:=2,z:=3)) == 1",
"(2x+3y+4z+5w)==(2*x+3*y+4*z+5*w)",
"(3(x+y)/2+1)==(3*(x+y)/2+1)",
"((x+y)3+1/4)==((x+y)*3+1/4)",
"((x+y)z+1/2)==((x+y)*z+1/2)",
"(x+y^3/z) == (x+(y*y*y)/z)",
"(z-x^3+y^2*7) == (z-(x*x*x)+(y*y)*7)",
"(3min(x,y))==(3*min(x,y))",
"(sin(x)y)==(sin(x)*y)",
"(sin(x)cos(y)+1)==(sin(x)*cos(y)+1)",
"(sgn(sin(x))cos(sgn(y))+1)==(sgn(sin(x))*cos(sgn(y))+1)",
"equal($f00(x,y,z),(x+y)/z)",
"equal($f01(x,y,z),(x+y)*z)",
"equal($f02(x,y,z),(x+y)-z)",
"equal($f03(x,y,z),(x+y)+z)",
"equal($f04(x,y,z),(x-y)+z)",
"equal($f05(x,y,z),(x-y)/z)",
"equal($f06(x,y,z),(x-y)*z)",
"equal($f07(x,y,z),(x*y)+z)",
"equal($f08(x,y,z),(x*y)-z)",
"equal($f09(x,y,z),(x*y)/z)",
"equal($f10(x,y,z),(x*y)*z)",
"equal($f11(x,y,z),(x/y)+z)",
"equal($f12(x,y,z),(x/y)-z)",
"equal($f13(x,y,z),(x/y)/z)",
"equal($f14(x,y,z),(x/y)*z)",
"equal($f15(x,y,z),x/(y+z))",
"equal($f16(x,y,z),x/(y-z))",
"equal($f17(x,y,z),x/(y*z))",
"equal($f18(x,y,z),x/(y/z))",
"equal($f19(x,y,z),x*(y+z))",
"equal($f20(x,y,z),x*(y-z))",
"equal($f21(x,y,z),x*(y*z))",
"equal($f22(x,y,z),x*(y/z))",
"equal($f23(x,y,z),x-(y+z))",
"equal($f24(x,y,z),x-(y-z))",
"equal($f25(x,y,z),x-(y/z))",
"equal($f26(x,y,z),x-(y*z))",
"equal($f27(x,y,z),x+(y*z))",
"equal($f28(x,y,z),x+(y/z))",
"equal($f29(x,y,z),x+(y+z))",
"equal($f30(x,y,z),x+(y-z))",
"equal($f31(x,y,z),x*y^2+z)",
"equal($f32(x,y,z),x*y^3+z)",
"equal($f33(x,y,z),x*y^4+z)",
"equal($f34(x,y,z),x*y^5+z)",
"equal($f35(x,y,z),x*y^6+z)",
"equal($f36(x,y,z),x*y^7+z)",
"equal($f37(x,y,z),x*y^8+z)",
"equal($f38(x,y,z),x*y^9+z)",
"equal($f39(x,y,z),x*log(y)+z)",
"equal($f40(x,y,z),x*log(y)-z)",
"equal($f41(x,y,z),x*log10(y)+z)",
"equal($f42(x,y,z),x*log10(y)-z)",
"equal($f43(x,y,z),x*sin(y)+z)",
"equal($f44(x,y,z),x*sin(y)-z)",
"equal($f45(x,y,z),x*cos(y)+z)",
"equal($f46(x,y,z),x*cos(y)-z)",
"equal($f47(x,y,z),if(0!=x,y,z))",
"equal($f48(x,y,z,w),x+((y+z)/w))",
"equal($f49(x,y,z,w),x+((y+z)*w))",
"equal($f50(x,y,z,w),x+((y-z)/w))",
"equal($f51(x,y,z,w),x+((y-z)*w))",
"equal($f52(x,y,z,w),x+((y*z)/w))",
"equal($f53(x,y,z,w),x+((y*z)*w))",
"equal($f54(x,y,z,w),x+((y/z)+w))",
"equal($f55(x,y,z,w),x+((y/z)/w))",
"equal($f56(x,y,z,w),x+((y/z)*w))",
"equal($f57(x,y,z,w),x-((y+z)/w))",
"equal($f58(x,y,z,w),x-((y+z)*w))",
"equal($f59(x,y,z,w),x-((y-z)/w))",
"equal($f60(x,y,z,w),x-((y-z)*w))",
"equal($f61(x,y,z,w),x-((y*z)/w))",
"equal($f62(x,y,z,w),x-((y*z)*w))",
"equal($f63(x,y,z,w),x-((y/z)/w))",
"equal($f64(x,y,z,w),x-((y/z)*w))",
"equal($f65(x,y,z,w),((x+y)*z)-w)",
"equal($f66(x,y,z,w),((x-y)*z)-w)",
"equal($f67(x,y,z,w),((x*y)*z)-w)",
"equal($f68(x,y,z,w),((x/y)*z)-w)",
"equal($f69(x,y,z,w),((x+y)/z)-w)",
"equal($f70(x,y,z,w),((x-y)/z)-w)",
"equal($f71(x,y,z,w),((x*y)/z)-w)",
"equal($f72(x,y,z,w),((x/y)/z)-w)",
"equal($f73(x,y,z,w),(x*y)+(z*w))",
"equal($f74(x,y,z,w),(x*y)-(z*w))",
"equal($f75(x,y,z,w),(x*y)+(z/w))",
"equal($f76(x,y,z,w),(x*y)-(z/w))",
"equal($f77(x,y,z,w),(x/y)+(z/w))",
"equal($f78(x,y,z,w),(x/y)-(z/w))",
"equal($f79(x,y,z,w),(x/y)-(z*w))",
"equal($f80(x,y,z,w),x/(y+(z*w)))",
"equal($f81(x,y,z,w),x/(y-(z*w)))",
"equal($f82(x,y,z,w),x*(y+(z*w)))",
"equal($f83(x,y,z,w),x*(y-(z*w)))",
"equal($f84(x,y,z,w),x*y^2+z*w^2)",
"equal($f85(x,y,z,w),x*y^3+z*w^3)",
"equal($f86(x,y,z,w),x*y^4+z*w^4)",
"equal($f87(x,y,z,w),x*y^5+z*w^5)",
"equal($f88(x,y,z,w),x*y^6+z*w^6)",
"equal($f89(x,y,z,w),x*y^7+z*w^7)",
"equal($f90(x,y,z,w),x*y^8+z*w^8)",
"equal($f91(x,y,z,w),x*y^9+z*w^9)",
"equal($f92(x,y,z,w),if(x and y,z,w))",
"equal($f93(x,y,z,w),if(x or y,z,w))",
"equal($f94(x,y,z,w),if(x < y,z,w))",
"equal($f95(x,y,z,w),if(x <= y,z,w))",
"equal($f96(x,y,z,w),if(x > y,z,w))",
"equal($f97(x,y,z,w),if(x >= y,z,w))",
"equal($f98(x,y,z,w),if(equal(x,y),z,w))",
"equal($f92(x,y,z,w),x and y ? z : w)",
"equal($f93(x,y,z,w),x or y ? z : w)",
"equal($f94(x,y,z,w),x < y ? z : w)",
"equal($f95(x,y,z,w),x <= y ? z : w)",
"equal($f96(x,y,z,w),x > y ? z : w)",
"equal($f97(x,y,z,w),x >= y ? z : w)",
"equal($f98(x,y,z,w),equal(x,y) ? z : w)",
"equal($f99(x,y,z,w),x*sin(y)+z*cos(w))"
};
static const std::size_t expr_str_size = sizeof(expr_str) / sizeof(std::string);
static const std::size_t rounds = 25;
for (std::size_t i = 0; i < rounds; ++i)
{
for (std::size_t j = 0; j < expr_str_size; ++j)
{
typedef exprtk::expression<T> expression_t;
T x = T(1.12345);
T y = T(2.12345);
T z = T(3.12345);
T w = T(4.12345);
T u = T(5.12345);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_variable("w",w);
symbol_table.add_variable("u",u);
expression_t expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expr_str[j],expression))
{
printf("run_test08() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str[j].c_str());
return false;
}
}
expression.value();
}
}
return true;
}
template <typename T>
struct myfunc : public exprtk::ifunction<T>
{
myfunc() : exprtk::ifunction<T>(2) {}
inline T operator()(const T& v1, const T& v2)
{
return T(1) + (v1 * v2) / T(3);
}
};
template <typename T>
inline bool run_test09()
{
static const std::size_t rounds = 1000;
for (std::size_t i = 0; i < rounds; ++i)
{
typedef exprtk::expression<T> expression_t;
std::string expression_string = "myfunc0(sin(x * pi),y / 2) + myfunc1(sin(x * pi),y / 2)+"
"myfunc2(sin(x * pi),y / 2) + myfunc3(sin(x * pi),y / 2)+"
"myfunc4(sin(x * pi),y / 2) + myfunc5(sin(x * pi),y / 2)+"
"myfunc6(sin(x * pi),y / 2) + myfunc7(sin(x * pi),y / 2)+"
"myfunc8(sin(x * pi),y / 2) + myfunc9(sin(x * pi),y / 2)+"
"myfunc0(sin(x * pi),y / 2) + myfunc1(sin(x * pi),y / 2)+"
"myfunc2(sin(x * pi),y / 2) + myfunc3(sin(x * pi),y / 2)+"
"myfunc4(sin(x * pi),y / 2) + myfunc5(sin(x * pi),y / 2)+"
"myfunc6(sin(x * pi),y / 2) + myfunc7(sin(x * pi),y / 2)+"
"myfunc8(sin(x * pi),y / 2) + myfunc9(sin(x * pi),y / 2)+"
"myfunc0(sin(x * pi),y / 2) + myfunc1(sin(x * pi),y / 2)+"
"myfunc2(sin(x * pi),y / 2) + myfunc3(sin(x * pi),y / 2)+"
"myfunc4(sin(x * pi),y / 2) + myfunc5(sin(x * pi),y / 2)+"
"myfunc6(sin(x * pi),y / 2) + myfunc7(sin(x * pi),y / 2)+"
"myfunc8(sin(x * pi),y / 2) + myfunc9(sin(x * pi),y / 2)+"
"myfunc0(sin(x * pi),y / 2) + myfunc1(sin(x * pi),y / 2)+"
"myfunc2(sin(x * pi),y / 2) + myfunc3(sin(x * pi),y / 2)+"
"myfunc4(sin(x * pi),y / 2) + myfunc5(sin(x * pi),y / 2)+"
"myfunc6(sin(x * pi),y / 2) + myfunc7(sin(x * pi),y / 2)+"
"myfunc8(sin(x * pi),y / 2) + myfunc9(sin(x * pi),y / 2)";
T x = T(1) + (i / T(10000));
T y = T(2) + (i / T(10000));
myfunc<T> mf;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_function("myfunc0",mf);
symbol_table.add_function("myfunc1",mf);
symbol_table.add_function("myfunc2",mf);
symbol_table.add_function("myfunc3",mf);
symbol_table.add_function("myfunc4",mf);
symbol_table.add_function("myfunc5",mf);
symbol_table.add_function("myfunc6",mf);
symbol_table.add_function("myfunc7",mf);
symbol_table.add_function("myfunc8",mf);
symbol_table.add_function("myfunc9",mf);
symbol_table.add_constants();
expression_t expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("run_test09() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
const T pi = T(3.141592653589793238462);
T result = expression.value();
T expected = T(4) *
(
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2)) +
mf(sin(x*pi),y / T(2))
);
if (not_equal(result,expected,T(0.0000001)))
{
printf("run_test09() - Error Expected: %19.15f\tResult: %19.15f\n",
(double)expected,
(double)result);
return false;
}
}
return true;
}
template <typename T>
inline bool run_test10()
{
typedef exprtk::expression<T> expression_t;
T x = T(1.1);
T y = T(2.2);
T xx = T(3.3);
T yy = T(4.4);
std::string i = "A String";
std::string j = "Another String";
std::string ii = "A String";
std::string jj = "Another String";
exprtk::symbol_table<T> symbol_table;
struct test
{
static inline bool variable(exprtk::symbol_table<T>& symbol_table, const std::string& variable_name, const T& value)
{
exprtk::details::variable_node<T>* var = symbol_table.get_variable(variable_name);
if (var)
return (!not_equal(var->ref(),value));
else
return false;
}
static inline bool string(exprtk::symbol_table<T>& symbol_table, const std::string& string_name, const std::string& str)
{
exprtk::details::stringvar_node<T>* str_node = symbol_table.get_stringvar(string_name);
if (str_node)
return (str_node->ref() == str);
else
return false;
}
};
static const std::size_t rounds = 10;
for (std::size_t r = 0; r < rounds; ++r)
{
symbol_table.add_variable("x", x);
symbol_table.add_variable("y", y);
symbol_table.add_variable("xx",xx);
symbol_table.add_variable("yy",yy);
if (!symbol_table.symbol_exists("x"))
{
printf("run_test10() - Symbol 'x' does not exist!\n");
return false;
}
else if (!symbol_table.symbol_exists("y"))
{
printf("run_test10() - Symbol 'y' does not exist!\n");
return false;
}
else if (!symbol_table.symbol_exists("xx"))
{
printf("run_test10() - Symbol 'xx' does not exist!\n");
return false;
}
else if (!symbol_table.symbol_exists("yy"))
{
printf("run_test10() - Symbol 'yy' does not exist!\n");
return false;
}
else if (!test::variable(symbol_table,"x",x))
{
printf("run_test10() - Symbol 'x' value failure!\n");
return false;
}
else if (!test::variable(symbol_table,"y",y))
{
printf("run_test10() - Symbol 'y' value failure!\n");
return false;
}
else if (!test::variable(symbol_table,"xx",xx))
{
printf("run_test10() - Symbol 'xx' value failure!\n");
return false;
}
else if (!test::variable(symbol_table,"yy",yy))
{
printf("run_test10() - Symbol 'yy' value failure!\n");
return false;
}
if (!symbol_table.remove_variable("x"))
{
printf("run_test10() - Failed to remove symbol 'x'!\n");
return false;
}
else if (!symbol_table.remove_variable("y"))
{
printf("run_test10() - Failed to remove symbol 'y'!\n");
return false;
}
else if (!symbol_table.remove_variable("xx"))
{
printf("run_test10() - Failed to remove symbol 'xx'!\n");
return false;
}
else if (!symbol_table.remove_variable("yy"))
{
printf("run_test10() - Failed to remove symbol 'yy'!\n");
return false;
}
}
for (std::size_t r = 0; r < rounds; ++r)
{
myfunc<T> mf;
symbol_table.add_function("f",mf);
symbol_table.add_function("f1",mf);
if (!symbol_table.symbol_exists("f"))
{
printf("run_test10() - function 'f' does not exist!\n");
return false;
}
else if (!symbol_table.symbol_exists("f1"))
{
printf("run_test10() - function 'f1' does not exist!\n");
return false;
}
if (!symbol_table.remove_function("f"))
{
printf("run_test10() - Failed to remove function 'f'!\n");
return false;
}
else if (!symbol_table.remove_function("f1"))
{
printf("run_test10() - Failed to remove function 'f1'!\n");
return false;
}
}
for (std::size_t r = 0; r < rounds; ++r)
{
symbol_table.add_stringvar("i",i);
symbol_table.add_stringvar("j",j);
symbol_table.add_stringvar("ii",ii);
symbol_table.add_stringvar("jj",jj);
if (!symbol_table.symbol_exists("i"))
{
printf("run_test10() - String 'i' does not exist!\n");
return false;
}
else if (!symbol_table.symbol_exists("j"))
{
printf("run_test10() - String 'j' does not exist!\n");
return false;
}
else if (!symbol_table.symbol_exists("ii"))
{
printf("run_test10() - String 'ii' does not exist!\n");
return false;
}
else if (!symbol_table.symbol_exists("jj"))
{
printf("run_test10() - String 'jj' does not exist!\n");
return false;
}
else if (!test::string(symbol_table,"i",i))
{
printf("run_test10() - String 'i' value failure!\n");
return false;
}
else if (!test::string(symbol_table,"j",j))
{
printf("run_test10() - String 'j' value failure!\n");
return false;
}
else if (!test::string(symbol_table,"ii",ii))
{
printf("run_test10() - String 'ii' value failure!\n");
return false;
}
else if (!test::string(symbol_table,"jj",jj))
{
printf("run_test10() - String 'jj' value failure!\n");
return false;
}
else if (!symbol_table.remove_stringvar("i"))
{
printf("run_test10() - Failed to remove String 'i'!\n");
return false;
}
else if (!symbol_table.remove_stringvar("j"))
{
printf("run_test10() - Failed to remove String 'j'!\n");
return false;
}
else if (!symbol_table.remove_stringvar("ii"))
{
printf("run_test10() - Failed to remove String 'ii'!\n");
return false;
}
else if (!symbol_table.remove_stringvar("jj"))
{
printf("run_test10() - Failed to remove String 'jj'!\n");
return false;
}
}
for (std::size_t r = 0; r < rounds; ++r)
{
symbol_table.add_variable("x", x);
symbol_table.add_variable("y", y);
symbol_table.add_variable("xx",xx);
symbol_table.add_variable("yy",yy);
std::vector<std::string> expected_var_list;
expected_var_list.push_back( "x");
expected_var_list.push_back( "y");
expected_var_list.push_back("xx");
expected_var_list.push_back("yy");
std::deque<std::pair<std::string,T> > variable_list;
symbol_table.get_variable_list(variable_list);
if (variable_list.size() != expected_var_list.size())
{
printf("run_test10() - Failed to get variable list (1)\n");
return false;
}
std::size_t found_count = 0;
for (std::size_t i = 0; i < variable_list.size(); ++i)
{
for (std::size_t j = 0; j < expected_var_list.size(); ++j)
{
if (variable_list[i].first == expected_var_list[j])
{
++found_count;
break;
}
}
}
if (found_count != expected_var_list.size())
{
printf("run_test10() - Failed to get variable list (2)\n");
return false;
}
}
for (std::size_t r = 0; r < rounds; ++r)
{
symbol_table.add_variable("x", x);
symbol_table.add_variable("y", y);
symbol_table.add_variable("xx",xx);
symbol_table.add_variable("yy",yy);
std::vector<std::string> expected_var_list;
expected_var_list.push_back( "x");
expected_var_list.push_back( "y");
expected_var_list.push_back("xx");
expected_var_list.push_back("yy");
std::deque<std::string> variable_list;
symbol_table.get_variable_list(variable_list);
if (variable_list.size() != expected_var_list.size())
{
printf("run_test10() - Failed to get variable list (3)\n");
return false;
}
std::size_t found_count = 0;
for (std::size_t i = 0; i < variable_list.size(); ++i)
{
for (std::size_t j = 0; j < expected_var_list.size(); ++j)
{
if (variable_list[i] == expected_var_list[j])
{
++found_count;
break;
}
}
}
if (found_count != expected_var_list.size())
{
printf("run_test10() - Failed to get variable list (4)\n");
return false;
}
}
for (std::size_t r = 0; r < rounds; ++r)
{
symbol_table.add_stringvar( "i", i);
symbol_table.add_stringvar( "j", j);
symbol_table.add_stringvar("ii",ii);
symbol_table.add_stringvar("jj",jj);
std::vector<std::string> expected_var_list;
expected_var_list.push_back( "i");
expected_var_list.push_back( "j");
expected_var_list.push_back("ii");
expected_var_list.push_back("jj");
std::deque<std::pair<std::string,std::string> > stringvar_list;
symbol_table.get_stringvar_list(stringvar_list);
if (stringvar_list.size() != expected_var_list.size())
{
printf("run_test10() - Failed to get stringvar list (1)\n");
return false;
}
std::size_t found_count = 0;
for (std::size_t i = 0; i < stringvar_list.size(); ++i)
{
for (std::size_t j = 0; j < expected_var_list.size(); ++j)
{
if (stringvar_list[i].first == expected_var_list[j])
{
++found_count;
break;
}
}
}
if (found_count != expected_var_list.size())
{
printf("run_test10() - Failed to get stringvar list (2)\n");
return false;
}
}
for (std::size_t r = 0; r < rounds; ++r)
{
symbol_table.add_stringvar( "i", i);
symbol_table.add_stringvar( "j", j);
symbol_table.add_stringvar("ii",ii);
symbol_table.add_stringvar("jj",jj);
std::vector<std::string> expected_var_list;
expected_var_list.push_back( "i");
expected_var_list.push_back( "j");
expected_var_list.push_back("ii");
expected_var_list.push_back("jj");
std::deque<std::string> stringvar_list;
symbol_table.get_stringvar_list(stringvar_list);
if (stringvar_list.size() != expected_var_list.size())
{
printf("run_test10() - Failed to get stringvar list (3.0)\n");
return false;
}
if (symbol_table.stringvar_count() != expected_var_list.size())
{
printf("run_test10() - Failed to get stringvar list (3.1)\n");
return false;
}
std::size_t found_count = 0;
for (std::size_t i = 0; i < stringvar_list.size(); ++i)
{
for (std::size_t j = 0; j < expected_var_list.size(); ++j)
{
if (stringvar_list[i] == expected_var_list[j])
{
++found_count;
break;
}
}
}
if (found_count != expected_var_list.size())
{
printf("run_test10() - Failed to get stringvar list (4)\n");
return false;
}
}
{
T x0 = T(0);
T y0 = T(0);
T z0 = T(0);
std::string expression_string = "(x0 + y0) / z0";
static const std::size_t rounds = 100;
for (std::size_t i = 0; i < rounds; ++i)
{
expression_t expression0;
x0 = T(i + 1.11);
y0 = T(i + 2.22);
z0 = T(i + 3.33);
exprtk::symbol_table<T> st0;
st0.add_variable("x0",x0);
st0.add_variable("y0",y0);
st0.add_variable("z0",z0);
expression0.register_symbol_table(st0);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression0))
{
printf("run_test10() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
{
expression_t expression1;
exprtk::symbol_table<T> st1 = st0;
expression1.register_symbol_table(st1);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression1))
{
printf("run_test10() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
st1.remove_variable("x0");
st1.remove_variable("y0");
st1.remove_variable("z0");
}
}
}
{
T a = T(1);
T b = T(2);
T c = T(3);
T d = T(4);
std::string e = "string";
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable ("a",a);
symbol_table.add_variable ("b",b);
symbol_table.add_variable ("c",c);
symbol_table.add_variable ("d",d);
symbol_table.add_stringvar("e",e);
expression_t expression;
expression.register_symbol_table(symbol_table);
std::string expression_string = "(E == '1234') and (sin(a) + C) / b";
typedef exprtk::parser<T> parser_t;
typedef typename parser_t::dependent_entity_collector::symbol_t symbol_t;
std::deque<symbol_t> symbol_list;
{
parser_t parser;
parser.dec().collect_variables() = true;
parser.dec().collect_functions() = true;
if (!parser.compile(expression_string,expression))
{
printf("run_test10() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
parser.dec().symbols(symbol_list);
}
std::deque<symbol_t> expected_symbol_list;
expected_symbol_list.push_back(symbol_t("a" ,parser_t::e_st_variable));
expected_symbol_list.push_back(symbol_t("b" ,parser_t::e_st_variable));
expected_symbol_list.push_back(symbol_t("c" ,parser_t::e_st_variable));
expected_symbol_list.push_back(symbol_t("e" ,parser_t::e_st_string ));
expected_symbol_list.push_back(symbol_t("sin",parser_t::e_st_function));
bool result = (symbol_list.size() == expected_symbol_list.size()) &&
std::equal(symbol_list.begin(),
symbol_list.end(),
expected_symbol_list.begin());
if (!result)
{
printf("run_test10() - Failed variable list comparison.(5)\n");
return false;
}
}
{
T a = T(1);
T b = T(2);
T c = T(3);
T d = T(4);
std::string e = "string";
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable ("a",a);
symbol_table.add_variable ("b",b);
symbol_table.add_variable ("c",c);
symbol_table.add_variable ("d",d);
symbol_table.add_stringvar("e",e);
expression_t expression;
expression.register_symbol_table(symbol_table);
std::string expression_string = "a := b + c; "
"b := c + d; "
"c := d + 1; "
"e := e + 'abc'; ";
typedef exprtk::parser<T> parser_t;
typedef typename parser_t::dependent_entity_collector::symbol_t symbol_t;
std::deque<symbol_t> variable_list;
{
parser_t parser;
parser.dec().collect_assignments() = true;
if (!parser.compile(expression_string,expression))
{
printf("run_test10() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
parser.dec().assignment_symbols(variable_list);
}
std::deque<symbol_t> expected_assignment_list;
expected_assignment_list.push_back(symbol_t("a",parser_t::e_st_variable));
expected_assignment_list.push_back(symbol_t("b",parser_t::e_st_variable));
expected_assignment_list.push_back(symbol_t("c",parser_t::e_st_variable));
expected_assignment_list.push_back(symbol_t("e",parser_t::e_st_string ));
bool result = (variable_list.size() == expected_assignment_list.size()) &&
std::equal(variable_list.begin(),
variable_list.end(),
expected_assignment_list.begin());
if (!result)
{
printf("run_test10() - Failed variable list comparison.(6)\n");
return false;
}
}
{
exprtk::symbol_table<T> symbol_table0;
exprtk::symbol_table<T> symbol_table1;
if (symbol_table0 == symbol_table1)
{
printf("run_test10() - Error symbol_table0 and symbol_table1 are equal\n");
return false;
}
symbol_table0 = symbol_table1;
symbol_table1 = symbol_table0;
if (!(symbol_table0 == symbol_table1))
{
printf("run_test10() - Error symbol_table0 and symbol_table1 are not equal\n");
return false;
}
}
{
std::string expression_list[] =
{
"var x; 1",
"var x := 1; x",
"var x := 1; var y := 2; 1",
"var x := 1; var y := 2; x",
"var x:=6; var y:=4; x + -3 == 3",
"var x:=6; var y:=4; x - -3 == 9",
"var x:=6; var y:=4; x * -3 == -18",
"var x:=6; var y:=4; x / -3 == -2",
"var x:=6; var y:=4; -x + -3 == -9",
"var x:=6; var y:=4; -x - -3 == -3",
"var x:=6; var y:=4; -x * -3 == 18",
"var x:=6; var y:=4; -x / -3 == 2",
"var x:=6; var y:=4; -3 + -x == -9",
"var x:=6; var y:=4; -3 - -x == 3",
"var x:=6; var y:=4; -3 * -x == 18",
"var x:=6; var y:=4; -3 / -x == 0.5",
"var x:=6; var y:=4; 3 + -x == -3",
"var x:=6; var y:=4; 3 - -x == 9",
"var x:=6; var y:=4; 3 * -x == -18",
"var x:=6; var y:=4; 3 / -x == -0.5",
"var x := 3; var y := 6; x + -y == -3",
"var x := 3; var y := 6; x - -y == 9",
"var x := 3; var y := 6; -x + -y == -9",
"var x := 3; var y := 6; -x - -y == 3",
"var x := 3; var y := 6; -x * -y == 18",
"var x := 6; var y := 3; -x / -y == 2",
"var x := 3; var y := 6; -(-x * -y) == -18",
"var x := 6; var y := 3; -(-x / -y) == -2",
"var x:=1; 2+(3+abs(x)) == 6 ",
"var x:=1; (3+abs(x))+2 == 6 ",
"var x:=1; 2+(abs(x)+3) == 6 ",
"var x:=1; (abs(x)+3)+2 == 6 ",
"var x:=1; 2+(3-abs(x)) == 4 ",
"var x:=1; (3-abs(x))+2 == 4 ",
"var x:=1; 2+(abs(x)-3) == 0 ",
"var x:=1; (abs(x)-3)+2 == 0 ",
"var x:=1; 2-(3+abs(x)) == -2 ",
"var x:=1; (3+abs(x))-2 == 2 ",
"var x:=1; 2-(abs(x)+3) == -2 ",
"var x:=1; (abs(x)+3)-2 == 2 ",
"var x:=1; 2*(3*abs(x)) == 6 ",
"var x:=1; (3*abs(x))*2 == 6 ",
"var x:=1; 2*(abs(x)*3) == 6 ",
"var x:=1; (abs(x)*3)*2 == 6 ",
"var x:=1; 2*(3/abs(x)) == 6 ",
"var x:=1; (3/abs(x))*2 == 6 ",
"var x:=1; 2*(abs(x)/3) == (2/3)",
"var x:=1; (abs(x)/3)*2 == (2/3)",
"var x:=1; 2/(3*abs(x)) == (2/3)",
"var x:=1; (3*abs(x))/2 == (3/2)",
"var x:=1; 2/(abs(x)*3) == (2/3)",
"var x:=1; (abs(x)*3)/2 == (3/2)",
"var x:=1; 2/(3/abs(x)) == (2/3)",
"var x:=1; (3/abs(x))/2 == (3/2)",
"var x:=1; 2/(abs(x)/3) == 6 ",
"var x:=1; (abs(x)/3)/2 == (1/6)",
"var x:=3; var y:=6; -(-x)*-(-y) == 18",
"var x:=3; var y:=6; -(-x)*-(-(-y)) == -18",
"var x:=3; var y:=6; -(-(-x))*-(-y) == -18",
"var x:=3; var y:=6; -(-(-x))*-(-(-y)) == 18",
"var x:=3; var y:=6; -(-(x+y))*-(-(y+x)) == 81",
"var x:=3; var y:=6; -(-(-(x+y)))*-(-(y+x)) == -81",
"var x:=3; var y:=6; -(-(x+y))*-(-(-(y+x))) == -81",
"var x:=3; var y:=6; -(-(-(x+y)))*-(-(-(y+x))) == 81",
"var x:= 2; var y := 3; (-abs(x)+-abs(y)) == -5 ",
"var x:= 2; var y := 3; (-abs(x)--abs(y)) == 1 ",
"var x:= 2; var y := 3; (-abs(x)*-abs(y)) == 6 ",
"var x:= 2; var y := 3; (-abs(x)/-abs(y)) == (2/3) ",
"var x:= 2; var y := 3; (-abs(x)+abs(y)) == 1 ",
"var x:= 2; var y := 3; (-abs(x)-abs(y)) == -5 ",
"var x:= 2; var y := 3; (-abs(x)*abs(y)) == -6 ",
"var x:= 2; var y := 3; (-abs(x)/abs(y)) == -(2/3) ",
"var x:= 2; var y := 3; (abs(x)+-abs(y)) == -1 ",
"var x:= 2; var y := 3; (abs(x)--abs(y)) == 5 ",
"var x:= 2; var y := 3; (abs(x)*-abs(y)) == -6 ",
"var x:= 2; var y := 3; (abs(x)/-abs(y)) == -(2/3) ",
"var x:= 2; var y := 3; (-abs(x + 0)+-abs(y - 0)) == -5 ",
"var x:= 2; var y := 3; (-abs(x + 0)--abs(y - 0)) == 1 ",
"var x:= 2; var y := 3; (-abs(x + 0)*-abs(y - 0)) == 6 ",
"var x:= 2; var y := 3; (-abs(x + 0)/-abs(y - 0)) == (2/3) ",
"var x:= 2; var y := 3; (-abs(x + 0)+abs(y - 0)) == 1 ",
"var x:= 2; var y := 3; (-abs(x + 0)-abs(y - 0)) == -5 ",
"var x:= 2; var y := 3; (-abs(x + 0)*abs(y - 0)) == -6 ",
"var x:= 2; var y := 3; (-abs(x + 0)/abs(y - 0)) == -(2/3) ",
"var x:= 2; var y := 3; (abs(x + 0)+-abs(y - 0)) == -1 ",
"var x:= 2; var y := 3; (abs(x + 0)--abs(y - 0)) == 5 ",
"var x:= 2; var y := 3; (abs(x + 0)*-abs(y - 0)) == -6 ",
"var x:= 2; var y := 3; (abs(x + 0)/-abs(y - 0)) == -(2/3) ",
"var x := 1; var y := 2; swap(x,y); (x == 2) and (y == 1)",
"var x := 1; var y := 2; x <=> y ; (x == 2) and (y == 1)",
"var v[2] := {1,2}; swap(v[0],v[1]); (v[0] == 2) and (v[1] == 1)",
"var v[2] := {1,2}; v[0] <=> v[1] ; (v[0] == 2) and (v[1] == 1)",
"var x := 1; var y := 2; ~(swap(x,y),(x == 2) and (y == 1))",
"var x := 1; var y := 2; ~(x <=> y , (x == 2) and (y == 1))",
"var v[2] := {1,2}; ~(swap(v[0],v[1]), (v[0] == 2) and (v[1] == 1))",
"var v[2] := {1,2}; ~(v[0] <=> v[1] , (v[0] == 2) and (v[1] == 1))",
"var v[2] := {1,2}; swap(v[zero],v[one]); (v[zero] == 2) and (v[one] == 1)",
"var v[2] := {1,2}; v[zero] <=> v[one] ; (v[zero] == 2) and (v[one] == 1)",
"var v[2] := {1,2}; ~(swap(v[zero],v[one]), (v[zero] == 2) and (v[one] == 1))",
"var v[2] := {1,2}; ~(v[zero] <=> v[one] , (v[zero] == 2) and (v[one] == 1))",
"var v[2] := {1,2}; swap(v[2 * zero],v[(2 * one) / (1 + 1)]); (v[2 * zero] == 2) and (v[(2 * one) / (1 + 1)] == 1)",
"var v[2] := {1,2}; v[2 * zero] <=> v[(2*one)/(1+1)] ; (v[2 * zero] == 2) and (v[(2 * one) / (1 + 1)] == 1)",
"var v[2] := {1,2}; ~(swap(v[2 * zero],v[(2 * one) / (1 + 1)]), (v[2 * zero] == 2) and (v[(2 * one) / (1 + 1)] == 1))",
"var v[2] := {1,2}; ~(v[2 * zero] <=> v[(2 * one) / (1 + 1)] , (v[2 * zero] == 2) and (v[(2 * one) / (1 + 1)] == 1))",
"var x := 1; var y := 2; var v[2] := {3,4}; swap(x,v[0]); swap(v[1],y); (x == 3) and (y == 4)",
"var x := 1; var y := 2; var v[2] := {3,4}; x <=> v[0]; v[1] <=> y; (x == 3) and (y == 4)",
"var x := 1; var y := 2; var v[2] := {3,4}; swap(x,v[zero]); swap(v[one],y); (x == 3) and (y == 4)",
"var x := 1; var y := 2; var v[2] := {3,4}; x <=> v[zero]; v[one] <=> y; (x == 3) and (y == 4)",
"var x := 1; var y := 2; var v[2] := {3,4}; swap(x,v[2 * zero]); swap(v[(2 * one) / (1 + 1)],y); (x == 3) and (y == 4)",
"var x := 1; var y := 2; var v[2] := {3,4}; x <=> v[zero / 3]; v[(2 * one)/(1 + 1)] <=> y; (x == 3) and (y == 4)",
"~{ var x := 1 } + ~{ var x := 2 } == 3",
"(~{ var x := 1 } + ~{ var x := 2 }) == (~{ var x := 2 } + ~{ var x := 1 })",
"(~{ var x := 1 } + ~{ var x := 2 } + ~{~{ var x := 1 } + ~{ var x := 2 }}) == 6",
"(~{ var x[3] := [1] } + ~{ var x[6] := {6,5,4,3,2,1}}) == 7",
"(~{ var x[6] := {6,5,4,3,2,1} } + ~{ var x := 1 }) == 7",
"(~{ var x := 1 } + ~{ var x[6] := {6,5,4,3,2,1} }) == 7",
"var x[3] := {}; (x[0] == 0) and (x[1] == 0) and (x[2] == 0)",
"var x[3] := {1,2}; (x[0] == 1) and (x[1] == 2) and (x[2] == 0)",
"var x[3] := {1,2,3}; (x[0] == 1) and (x[1] == 2) and (x[2] == 3)",
"var x[3] := [1]; (x[0] == 1) and (x[1] == 1) and (x[2] == 1)",
"var v[3] := [1]; v += 1; (v[0] == v[1]) and (v[0] == v[2]) and (v[0] == 2)",
"var v[3] := [1]; v -= 1; (v[0] == v[1]) and (v[0] == v[2]) and (v[0] == 0)",
"var v[3] := [1]; v *= 2; (v[0] == v[1]) and (v[0] == v[2]) and (v[0] == 2)",
"var v[3] := [3]; v /= 3; (v[0] == v[1]) and (v[0] == v[2]) and (v[0] == 1)",
"var v[3] := {1,2, 3}; v += 1; (v[0] == 2) and (v[1] == 3) and (v[2] == 4)",
"var v[3] := {1,2, 3}; v -= 1; (v[0] == 0) and (v[1] == 1) and (v[2] == 2)",
"var v[3] := {1,2, 3}; v *= 2; (v[0] == 2) and (v[1] == 4) and (v[2] == 6)",
"var v[3] := {3,9,15}; v /= 3; (v[0] == 1) and (v[1] == 3) and (v[2] == 5)",
"var v0[3] := [1]; var v1[3] := [1]; v0 += v1; (v0[0] == v0[1]) and (v0[0] == v0[2]) and (v0[0] == 2)",
"var v0[3] := [1]; var v1[3] := [1]; v0 -= v1; (v0[0] == v0[1]) and (v0[0] == v0[2]) and (v0[0] == 0)",
"var v0[3] := [1]; var v1[3] := [2]; v0 *= v1; (v0[0] == v0[1]) and (v0[0] == v0[2]) and (v0[0] == 2)",
"var v0[3] := [3]; var v1[3] := [3]; v0 /= v1; (v0[0] == v0[1]) and (v0[0] == v0[2]) and (v0[0] == 1)",
"var v0[3] := {1,2, 3}; var v1[3] := {1,1,1}; v0 += v1; (v0[0] == 2) and (v0[1] == 3) and (v0[2] == 4)",
"var v0[3] := {1,2, 3}; var v1[3] := {1,1,1}; v0 -= v1; (v0[0] == 0) and (v0[1] == 1) and (v0[2] == 2)",
"var v0[3] := {1,2, 3}; var v1[3] := {2,2,2}; v0 *= v1; (v0[0] == 2) and (v0[1] == 4) and (v0[2] == 6)",
"var v0[3] := {3,9,15}; var v1[3] := {3,3,3}; v0 /= v1; (v0[0] == 1) and (v0[1] == 3) and (v0[2] == 5)",
"var x[3] := {}; var y[4] := {1,2,3,4}; x := y; (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == y[2])",
"var x[3] := {}; var y[3] := {1,2,3}; x := y; (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == y[2])",
"var x[3] := {}; var y[2] := {1,2}; x := y; (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == 0)",
"var x[3] := {}; var y[1] := {1}; x := y; (x[0] == y[0]) and (x[1] == 0) and (x[2] == 0)",
"var x[3] := {}; var y[4] := {1,2,3,4}; x := (y+=1); (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == y[2])",
"var x[3] := {}; var y[3] := {1,2,3}; x := (y+=1); (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == y[2])",
"var x[3] := {}; var y[2] := {1,2}; x := (y+=1); (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == 0)",
"var x[3] := {}; var y[1] := {1}; x := (y+=1); (x[0] == y[0]) and (x[1] == 0) and (x[2] == 0)",
"var x[3] := {}; var y[4] := {1,2,3,4}; x += (y+=1); (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == y[2])",
"var x[3] := {}; var y[3] := {1,2,3}; x += (y+=1); (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == y[2])",
"var x[3] := {}; var y[2] := {1,2}; x += (y+=1); (x[0] == y[0]) and (x[1] == y[1]) and (x[2] == 0)",
"var x[3] := {}; var y[1] := {1}; x += (y+=1); (x[0] == y[0]) and (x[1] == 0) and (x[2] == 0)",
"var x[3] := [9]; var y[4] := {1,2,3,4}; x <=> y; (x[0] == 1) and (x[1] == 2) and (x[2] == 3)",
"var x[3] := [9]; var y[3] := {1,2,3}; x <=> y; (x[0] == 1) and (x[1] == 2) and (x[2] == 3)",
"var x[3] := [9]; var y[2] := {1,2}; x <=> y; (x[0] == 1) and (x[1] == 2) and (x[2] == 9)",
"var x[3] := [9]; var y[1] := {1}; x <=> y; (x[0] == 1) and (x[1] == 9) and (x[2] == 9)",
"var x[3] := [9]; var y[4] := {1,2,3,4}; x <=> (y += 1); (x[0] == 2) and (x[1] == 3) and (x[2] == 4)",
"var x[3] := [9]; var y[3] := {1,2,3}; x <=> (y += 1); (x[0] == 2) and (x[1] == 3) and (x[2] == 4)",
"var x[3] := [9]; var y[2] := {1,2}; x <=> (y += 1); (x[0] == 2) and (x[1] == 3) and (x[2] == 9)",
"var x[3] := [9]; var y[1] := {1}; x <=> (y += 1); (x[0] == 2) and (x[1] == 9) and (x[2] == 9)",
"var x[3] := [8]; var y[4] := {1,2,3,4}; (x += 1) <=> y; (x[0] == 1) and (x[1] == 2) and (x[2] == 3)",
"var x[3] := [8]; var y[3] := {1,2,3}; (x += 1) <=> y; (x[0] == 1) and (x[1] == 2) and (x[2] == 3)",
"var x[3] := [8]; var y[2] := {1,2}; (x += 1) <=> y; (x[0] == 1) and (x[1] == 2) and (x[2] == 9)",
"var x[3] := [8]; var y[1] := {1}; (x += 1) <=> y; (x[0] == 1) and (x[1] == 9) and (x[2] == 9)",
"var x[3] := [8]; var y[4] := {1,2,3,4}; (x += 1) <=> (y += 1); (x[0] == 2) and (x[1] == 3) and (x[2] == 4)",
"var x[3] := [8]; var y[3] := {1,2,3}; (x += 1) <=> (y += 1); (x[0] == 2) and (x[1] == 3) and (x[2] == 4)",
"var x[3] := [8]; var y[2] := {1,2}; (x += 1) <=> (y += 1); (x[0] == 2) and (x[1] == 3) and (x[2] == 9)",
"var x[3] := [8]; var y[1] := {1}; (x += 1) <=> (y += 1); (x[0] == 2) and (x[1] == 9) and (x[2] == 9)",
"var x[3] := [0]; var y[4] := {1,2,3,4}; x < y",
"var x[3] := [0]; var y[3] := {1,2,3}; x < y",
"var x[3] := [0]; var y[2] := {1,2}; x < y",
"var x[3] := [0]; var y[1] := {1}; x < y",
"var x[3] := [0]; var y[4] := {1,2,3,4}; x <= y",
"var x[3] := [0]; var y[3] := {1,2,3}; x <= y",
"var x[3] := [0]; var y[2] := {1,2}; x <= y",
"var x[3] := [0]; var y[1] := {1}; x <= y",
"var x[3] := [5]; var y[4] := {1,2,3,4}; x > y",
"var x[3] := [5]; var y[3] := {1,2,3}; x > y",
"var x[3] := [5]; var y[2] := {1,2}; x > y",
"var x[3] := [5]; var y[1] := {1}; x > y",
"var x[3] := [5]; var y[4] := {1,2,3,4}; x >= y",
"var x[3] := [5]; var y[3] := {1,2,3}; x >= y",
"var x[3] := [5]; var y[2] := {1,2}; x >= y",
"var x[3] := [5]; var y[1] := {1}; x >= y",
"var x[3] := [1]; var y[4] := [1]; x == y",
"var x[3] := [1]; var y[3] := [1]; x == y",
"var x[3] := [1]; var y[2] := [1]; x == y",
"var x[3] := [1]; var y[1] := [1]; x == y",
"var x[3] := [1]; var y[4] := [2]; x != y",
"var x[3] := [1]; var y[3] := [2]; x != y",
"var x[3] := [1]; var y[2] := [2]; x != y",
"var x[3] := [1]; var y[1] := [2]; x != y",
"var x[3] := [0]; var y[4] := {5,6,7,8}; (x += 1) < y",
"var x[3] := [0]; var y[3] := {5,6,7}; (x += 1) < y",
"var x[3] := [0]; var y[2] := {5,6}; (x += 1) < y",
"var x[3] := [0]; var y[1] := {5}; (x += 1) < y",
"var x[3] := [0]; var y[4] := {1,2,3,4}; x < (y += 1)",
"var x[3] := [0]; var y[3] := {1,2,3}; x < (y += 1)",
"var x[3] := [0]; var y[2] := {1,2}; x < (y += 1)",
"var x[3] := [0]; var y[1] := {1}; x < (y += 1)",
"var x[3] := [0]; var y[4] := {5,6,7,8}; (x += 1) < (y += 1)",
"var x[3] := [0]; var y[3] := {5,6,7}; (x += 1) < (y += 1)",
"var x[3] := [0]; var y[2] := {5,6}; (x += 1) < (y += 1)",
"var x[3] := [0]; var y[1] := {5}; (x += 1) < (y += 1)",
"var x[3] := {1,2,3}; var y := 5; x < y ",
"var x[3] := {1,2,3}; var y := 3; x < y + 1 ",
"var x[3] := {1,2,3}; var y := 5; x <= y ",
"var x[3] := {1,2,3}; var y := 3; x <= y + 1",
"var x[3] := {1,1,1}; var y := 1; x == y ",
"var x[3] := {1,1,1}; var y := 2; x == y - 1",
"var x[3] := {1,2,3}; var y := 5; y > x ",
"var x[3] := {1,2,3}; var y := 3; y >= x ",
"var x[3] := {1,2,3}; var y := 5; y + 1 > x ",
"var x[3] := {1,1,1}; var y := 1; y == x ",
"var x[3] := {1,1,1}; var y := 2; y - 1 == x",
"var x[3] := {1,2,3}; var y := 5; (x += 1) < y ",
"var x[3] := {1,2,3}; var y := 3; (x -= 1) < y + 1 ",
"var x[3] := {1,2,3}; var y := 5; (x -= 1) <= y ",
"var x[3] := {2,2,2}; var y := 1; (x -= 1) == y ",
"var x[3] := {1,2,3}; var y := 5; y > (x += 1) ",
"var x[3] := {1,2,3}; var y := 5; y + 1 > (x += 1) ",
"var x[3] := {2,2,2}; var y := 1; y == (x -= 1) ",
"var x[3] := {2,2,2}; var y := 0; y + 1 == (x -= 1)",
"var x[3] := [1]; var y[4] := {1,2,3,4}; var z[3] := [1]; z := (x + y); z == (x + y)",
"var x[3] := [1]; var y[3] := {1,2,3}; var z[3] := [1]; z := (x - y); z == (x - y)",
"var x[3] := [1]; var y[2] := {1,2}; var z[3] := [1]; z := (x / y); z == (x / y)",
"var x[3] := [1]; var y[1] := {1}; var z[3] := [1]; z := (x * y); z == (x * y)",
"var x[3] := [1]; var y[4] := {1,2,3,4}; var z[3] := [1]; z := 2(x + y); z == (x + y)2",
"var x[3] := [1]; var y[3] := {1,2,3}; var z[3] := [1]; z := 2(x - y); z == (x - y)2",
"var x[3] := [1]; var y[2] := {1,2}; var z[3] := [1]; z := 2(x / y); z == (x / y)2",
"var x[3] := [1]; var y[1] := {1}; var z[3] := [1]; z := 2(x * y); z == (x * y)2",
"var x[3] := [1]; var y[4] := {1,2,3,4}; var z[3] := [1]; z := 2(x + y)/3; z == 2(x + y)/3",
"var x[3] := [1]; var y[3] := {1,2,3}; var z[3] := [1]; z := 2(x - y)/3; z == 2(x - y)/3",
"var x[3] := [1]; var y[2] := {1,2}; var z[3] := [1]; z := 2(x / y)/3; z == 2(x / y)/3",
"var x[3] := [1]; var y[1] := {1}; var z[3] := [1]; z := 2(x * y)/3; z == 2(x * y)/3",
"var x[6] := {1,2,3,4,5,6}; equal(sqrt(sum([x - avg(x)]^2) / x[]),1.7078251277)",
"var x[3] := {-1,-2,-3}; sum(abs(x) ) == 6",
"var x[3] := {0.1,0.2,0.3}; sum(trunc(x)) == 0",
"var x := 2; (~{ for (var i := 0; i < 10; i += 1) { for (var j := 0; j <= i; "
"j += 1) { var y := 3; if ((i + j + y + x) < 6) { y += x; continue; } else "
"break[i + j]; } } } + ~{ for (var i := 0; i < 10; i += 1) { for (var j := 0; "
"j <= i; j += 1) { var y := 3; if ((i + j + y + x) < 6) { y += x; continue; } "
" else break[i + j]; } } }) == 18 ",
"var x := 2; var v0[3] := {1,2,3}; ( ~{ for (var i := 0; i < 10; i += 1) { "
"for (var j := 0; j <= i; j += 1) { var y := 3; var v2[3] := {1,2,3}; if ( "
"(i + j + y + x + abs(v0[i % v0[]] - v2[j % v2[]])) < 6) { var v3[3] := "
"{1,2,3}; y += x / v3[j % v3[]]; continue; } else break[i + j]; } } } "
"+ ~{ for (var i := 0; i < 10; i += 1) { for (var j := 0; j <= i; j += 1) "
" { var y := 3; var v2[3] := {1,2,3}; if ((i + j + y + x + abs(v0[i % v0[]] - "
"v2[j % v2[]])) < 6) { var v3[3] := {1,2,3}; y += x / v3[j % v3[]]; "
"continue; } else break[i + j]; } } } ) == 18 "
};
const std::size_t expression_list_size = sizeof(expression_list) / sizeof(std::string);
exprtk::symbol_table<T> symbol_table;
T zero = T(0);
T one = T(1);
symbol_table.add_variable("zero",zero);
symbol_table.add_variable("one" , one);
bool failed = false;
for (std::size_t r = 0; r < 10; ++r)
{
for (std::size_t i = 0; i < expression_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
{
exprtk::parser<T> parser;
if (!parser.compile(expression_list[i],expression))
{
printf("run_test10() - swaps Error: %s Expression: %s\n",
parser.error().c_str(),
expression_list[i].c_str());
return false;
}
}
T result = expression.value();
if (T(1) != result)
{
printf("run_test10() - swaps evaluation error Expression: %s\n",
expression_list[i].c_str());
failed = true;
}
}
if (failed)
{
return false;
}
}
}
return true;
}
template <typename T>
inline bool run_test11()
{
typedef exprtk::expression<T> expression_t;
std::string expression_string = "(x + y) / 3";
T x = T(1.0);
T y = T(2.0);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
expression_t expression;
expression.register_symbol_table(symbol_table);
static const std::size_t rounds = 500;
for (std::size_t i = 0; i < rounds; ++i)
{
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("run_test11() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
if (not_equal(expression.value(),(x + y) / T(3),T(0.000001)))
{
printf("run_test11() - Error in evaluation!(1)\n");
return false;
}
expression.release();
if (false == (!expression))
{
printf("run_test11() - Error in evaluation!(2)\n");
return false;
}
{
exprtk::parser<T> parser;
if (!parser.compile(expression_string,expression))
{
printf("run_test11() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_string.c_str());
return false;
}
}
expression.value();
if (not_equal(expression.value(),(x + y) / T(3),T(0.000001)))
{
printf("run_test11() - Error in evaluation!(3)\n");
return false;
}
}
if (!exprtk::pgo_primer<T>())
{
printf("run_test11() - Failed PGO primer\n");
return false;
}
return true;
}
template <typename T>
inline bool run_test12()
{
typedef exprtk::expression<T> expression_t;
static const std::string expression_string[] =
{
"equal(poly01(x,2.2,1.1),(2.2x^1+1.1))",
"equal(poly02(x,3.3,2.2,1.1),(3.3x^2+2.2x^1+1.1))",
"equal(poly03(x,4.4,3.3,2.2,1.1),(4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly04(x,5.5,4.4,3.3,2.2,1.1),(5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly05(x,6.6,5.5,4.4,3.3,2.2,1.1),(6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly06(x,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly07(x,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly08(x,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly09(x,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly10(x,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(2.2x^10+1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly11(x,3.3,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(3.3x^11+2.2x^10+1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equal(poly12(x,4.4,3.3,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(4.4x^12+3.3x^11+2.2x^10+1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"EquaL(Poly01(x,2.2,1.1),(2.2x^1+1.1))",
"eQuAl(pOly02(x,3.3,2.2,1.1),(3.3x^2+2.2x^1+1.1))",
"eqUal(poLy03(x,4.4,3.3,2.2,1.1),(4.4x^3+3.3x^2+2.2x^1+1.1))",
"eQuAl(polY04(x,5.5,4.4,3.3,2.2,1.1),(5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"EquAl(pOLy05(x,6.6,5.5,4.4,3.3,2.2,1.1),(6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"EqUaL(pOly06(x,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"Equal(Poly07(x,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"eQual(PoLy08(x,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"eqUal(pOlY09(x,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equAl(POLY10(x,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(2.2x^10+1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"equaL(PolY11(x,3.3,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(3.3x^11+2.2x^10+1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))",
"EQUAL(pOLy12(x,4.4,3.3,2.2,1.1,9.9,8.8,7.7,6.6,5.5,4.4,3.3,2.2,1.1),(4.4x^12+3.3x^11+2.2x^10+1.1x^9+9.9x^8+8.8x^7+7.7x^6+6.6x^5+5.5x^4+4.4x^3+3.3x^2+2.2x^1+1.1))"
};
static const std::size_t expression_string_size = sizeof(expression_string) / sizeof(std::string);
T x = T(1.23456);
exprtk::polynomial<T, 1> poly01;
exprtk::polynomial<T, 2> poly02;
exprtk::polynomial<T, 3> poly03;
exprtk::polynomial<T, 4> poly04;
exprtk::polynomial<T, 5> poly05;
exprtk::polynomial<T, 6> poly06;
exprtk::polynomial<T, 7> poly07;
exprtk::polynomial<T, 8> poly08;
exprtk::polynomial<T, 9> poly09;
exprtk::polynomial<T,10> poly10;
exprtk::polynomial<T,11> poly11;
exprtk::polynomial<T,12> poly12;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x",x);
symbol_table.add_function("poly01", poly01);
symbol_table.add_function("poly02", poly02);
symbol_table.add_function("poly03", poly03);
symbol_table.add_function("poly04", poly04);
symbol_table.add_function("poly05", poly05);
symbol_table.add_function("poly06", poly06);
symbol_table.add_function("poly07", poly07);
symbol_table.add_function("poly08", poly08);
symbol_table.add_function("poly09", poly09);
symbol_table.add_function("poly10", poly10);
symbol_table.add_function("poly11", poly11);
symbol_table.add_function("poly12", poly12);
expression_t expression;
expression.register_symbol_table(symbol_table);
static const std::size_t rounds = 500;
for (std::size_t i = 0; i < rounds; ++i)
{
for (std::size_t j = 0; j < expression_string_size; ++j)
{
const std::string& expr_str = expression_string[j];
{
exprtk::parser<T> parser;
if (!parser.compile(expr_str,expression))
{
printf("run_test12() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str.c_str());
return false;
}
}
if (T(1) != expression.value())
{
printf("run_test12() - Error in evaluation! Expression: %s\n",expr_str.c_str());
return false;
}
}
}
return true;
}
template <typename T>
struct sine_deg : public exprtk::ifunction<T>
{
sine_deg() : exprtk::ifunction<T>(1) {}
inline T operator()(const T& v)
{
return std::sin((v * T(exprtk::details::numeric::constant::pi)) / T(180));
}
};
template <typename T>
struct cosine_deg : public exprtk::ifunction<T>
{
cosine_deg() : exprtk::ifunction<T>(1) {}
inline T operator()(const T& v)
{
return std::cos((v * T(exprtk::details::numeric::constant::pi)) / T(180));
}
};
template <typename T>
inline bool run_test13()
{
typedef exprtk::expression<T> expression_t;
static const std::string expression_string[] =
{
"equal(sin(30),0.5)",
"equal(cos(60),0.5)",
"equal(sin(60),sqrt(3)/2)",
"equal(cos(30),sqrt(3)/2)",
"equal(sin(x_deg),0.5)",
"equal(cos(y_deg),0.5)",
"equal(sin(y_deg),sqrt(3)/2)",
"equal(cos(x_deg),sqrt(3)/2)",
};
static const std::size_t expression_string_size = sizeof(expression_string) / sizeof(std::string);
T x_deg = T(30);
T y_deg = T(60);
sine_deg<T> sine;
cosine_deg<T> cosine;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_variable("x_deg",x_deg);
symbol_table.add_variable("y_deg",y_deg);
symbol_table.add_function("sine_deg",sine);
symbol_table.add_function("cosine_deg",cosine);
expression_t expression;
expression.register_symbol_table(symbol_table);
static const std::size_t rounds = 100;
for (std::size_t i = 0; i < rounds; ++i)
{
for (std::size_t j = 0; j < expression_string_size; ++j)
{
const std::string& expr_str = expression_string[j];
{
exprtk::parser<T> parser;
parser.replace_symbol("sin","sine_deg");
parser.replace_symbol("cos","cosine_deg");
if (!parser.compile(expr_str,expression))
{
printf("run_test13() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str.c_str());
return false;
}
}
if (T(1) != expression.value())
{
printf("run_test13() - Error in evaluation! Expression: %s\n",expr_str.c_str());
return false;
}
}
}
return true;
}
template <typename Allocator,
template <typename,typename> class Sequence>
inline std::size_t load_expressions(const std::string& file_name,
Sequence<std::string,Allocator>& sequence)
{
std::ifstream stream(file_name.c_str());
if (!stream) return 0;
std::string buffer;
buffer.reserve(1024);
std::size_t line_count = 0;
while (std::getline(stream,buffer))
{
if (buffer.empty())
continue;
else if ('#' == buffer[0])
continue;
++line_count;
sequence.push_back(buffer);
}
return line_count;
}
template <typename T>
inline bool run_test14()
{
typedef exprtk::expression<T> expression_t;
T x = T(0);
T y = T(0);
T z = T(0);
T w = T(0);
exprtk::polynomial<T, 1> poly01;
exprtk::polynomial<T, 2> poly02;
exprtk::polynomial<T, 3> poly03;
exprtk::polynomial<T, 4> poly04;
exprtk::polynomial<T, 5> poly05;
exprtk::polynomial<T, 6> poly06;
exprtk::polynomial<T, 7> poly07;
exprtk::polynomial<T, 8> poly08;
exprtk::polynomial<T, 9> poly09;
exprtk::polynomial<T,10> poly10;
exprtk::polynomial<T,11> poly11;
exprtk::polynomial<T,12> poly12;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_variable("w",w);
symbol_table.add_function("poly01", poly01);
symbol_table.add_function("poly02", poly02);
symbol_table.add_function("poly03", poly03);
symbol_table.add_function("poly04", poly04);
symbol_table.add_function("poly05", poly05);
symbol_table.add_function("poly06", poly06);
symbol_table.add_function("poly07", poly07);
symbol_table.add_function("poly08", poly08);
symbol_table.add_function("poly09", poly09);
symbol_table.add_function("poly10", poly10);
symbol_table.add_function("poly11", poly11);
symbol_table.add_function("poly12", poly12);
expression_t expression;
expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
std::deque<std::string> expr_str_list;
load_expressions("exprtk_functional_test.txt" ,expr_str_list);
load_expressions("exprtk_functional_ext_test.txt",expr_str_list);
if (expr_str_list.empty())
{
return true;
}
std::deque<exprtk::expression<T> > expression_list;
bool failure = false;
static const std::size_t rounds = 5;
for (std::size_t r = 0; r < rounds; ++r)
{
for (std::size_t i = 0; i < expr_str_list.size(); ++i)
{
exprtk::expression<T> current_expression;
current_expression.register_symbol_table(symbol_table);
if (!parser.compile(expr_str_list[i],current_expression))
{
printf("run_test14() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str_list[i].c_str());
failure = true;
}
else
expression_list.push_back(current_expression);
}
if (failure)
break;
for (std::size_t i = 0; i < expression_list.size(); ++i)
{
T result = expression_list[i].value();
if (result != T(1))
{
failure = true;
printf("run_test14() - Error with evaluation of expression: %s\n",
expr_str_list[i].c_str());
}
}
expression_list.clear();
if (failure)
break;
}
return !failure;
}
template <typename T>
inline bool run_test15()
{
typedef exprtk::expression<T> expression_t;
T x = T(1.1);
T y = T(2.2);
T z = T(3.3);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
static const std::string expr_str_list[] =
{
"2 - (x + y) / z//Comment 01 ",
"2 - (x + y) / z#Comment 02 ",
"2 - (x + y) / z //Comment 03 ",
"2 - (x + y) / z #Comment 04 ",
"2 - (x + y) / z//Comment 05 \n",
"2 - (x + y) / z#Comment 06 \n",
"2 - (x + y) / z //Comment 07\n",
"2 - (x + y) / z #Comment 08 \n",
"/* Comment 09*/2 - (x + y) / z",
"/* Comment 10*/2 - (x + y) / z\n",
"/* Comment 11*/2 - (x + y) / z/* Comment 12*/",
"/* Comment 13*/2 - (x + y) / z/* Comment 14*/\n",
"2 - /* Comment 15 */(x + y) / z",
"2 - /* Comment 16 */(x + y) /* Comment 17 *// z \n",
"2 - /* Comment 18 */(x + y) /* Comment 19 */ / z //Comment 20\n",
"2 - /* Comment 21 */(x + y) /* Comment 22 */ / z #Comment 23\n",
"2 - /* Comment 24 */(x + y) /* Comment 25 */ / z //Comment 26",
"2 - /* Comment 27 */(x + y) /* Comment 28 */ / z #Comment 29"
};
static const std::size_t expr_str_list_size = sizeof(expr_str_list) / sizeof(std::string);
std::deque<expression_t> expression_list;
for (std::size_t i = 0; i < expr_str_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
if (!parser.compile(expr_str_list[i],expression))
{
printf("run_test15() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str_list[i].c_str());
return false;
}
else
expression_list.push_back(expression);
}
expression_t base_expression;
const std::string base_expr_str = "2 - (x + y) / z";
{
base_expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
if (!parser.compile(base_expr_str,base_expression))
{
printf("run_test15() - Error: %s Expression: %s\n",
parser.error().c_str(),
base_expr_str.c_str());
return false;
}
}
bool failure = false;
for (std::size_t i = 0; i < expression_list.size(); ++i)
{
T base_result = base_expression.value();
T result = expression_list[i].value();
if (not_equal(base_result,result))
{
printf("run_test15() - Error in evaluation! (1) Base: %20.10f\tResult: %20.10f\tExpression: %s\n",
(double)base_result,
(double)result,
expr_str_list[i].c_str());
failure = true;
}
}
return !failure;
}
template <typename T>
struct base_func : public exprtk::ifunction<T>
{
typedef const T& type;
base_func(const std::size_t& n) : exprtk::ifunction<T>(n) {}
inline T operator()(type v0, type v1, type v2, type v3, type v4) { return (v0 + v1 + v2 + v3 + v4); }
inline T operator()(type v0, type v1, type v2, type v3) { return (v0 + v1 + v2 + v3); }
inline T operator()(type v0, type v1, type v2) { return (v0 + v1 + v2); }
inline T operator()(type v0, type v1) { return (v0 + v1); }
inline T operator()(type v0) { return v0; }
inline T operator()() { return T(1.1234); }
};
template <typename T> struct test_func5 : public base_func<T> { test_func5() : base_func<T>(5){} };
template <typename T> struct test_func4 : public base_func<T> { test_func4() : base_func<T>(4){} };
template <typename T> struct test_func3 : public base_func<T> { test_func3() : base_func<T>(3){} };
template <typename T> struct test_func2 : public base_func<T> { test_func2() : base_func<T>(2){} };
template <typename T> struct test_func1 : public base_func<T> { test_func1() : base_func<T>(1){} };
template <typename T> struct test_func0 : public base_func<T> { test_func0() : base_func<T>(0){} };
template <typename T>
inline bool run_test16()
{
typedef exprtk::expression<T> expression_t;
T x = T(1.1);
T y = T(2.2);
T z = T(3.3);
T w = T(4.4);
T u = T(5.5);
test_func0<T> test_func00;
test_func1<T> test_func01;
test_func2<T> test_func02;
test_func3<T> test_func03;
test_func4<T> test_func04;
test_func5<T> test_func05;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_variable("w",w);
symbol_table.add_variable("u",u);
symbol_table.add_function("test_func0",test_func00);
symbol_table.add_function("test_func1",test_func01);
symbol_table.add_function("test_func2",test_func02);
symbol_table.add_function("test_func3",test_func03);
symbol_table.add_function("test_func4",test_func04);
symbol_table.add_function("test_func5",test_func05);
static const std::string expr_str_list[] =
{
"test_func0 = test_func0()",
"test_func0 == test_func0()",
"equal(1.1 + test_func0,test_func0() + 1.1)",
"equal(test_func0 + 1.1,1.1 + test_func0())",
"equal((1.1 + test_func0),(test_func0() + 1.1))",
"equal((test_func0 + 1.1),(1.1 + test_func0()))",
"equal(test_func0,test_func0())",
"equal(test_func0,1.1234)",
"equal(test_func0(),1.1234)",
"equal(test_func0 + test_func0(),2 * 1.1234)",
"equal((test_func0 + test_func0()),2 * 1.1234)",
"equal((test_func0) + (test_func0()),2 * 1.1234)",
"equal(test_func1(x),(x))",
"equal(test_func2(x,y),(x + y))",
"equal(test_func3(x,y,z),(x + y + z))",
"equal(test_func4(x,y,z,w),(x + y + z + w))",
"equal(test_func5(x,y,z,w,u),(x + y + z + w + u))",
"equal(1.1 + test_func0,1.1234 + 1.1)",
"equal(1.1 + test_func0(),1.1234 + 1.1)",
"equal(1.1 + test_func1(x),(x + 1.1))",
"equal(1.1 + test_func2(x,y),(x + y + 1.1))",
"equal(1.1 + test_func3(x,y,z),(x + y + z + 1.1))",
"equal(1.1 + test_func4(x,y,z,w),(x + y + z + w + 1.1))",
"equal(1.1 + test_func5(x,y,z,w,u),(x + y + z + w + u + 1.1))",
"equal(test_func0 + 2.2,1.1234 + 2.2)",
"equal(test_func0() + 2.2,1.1234 + 2.2)",
"equal(test_func1(x) + 2.2,(x + 2.2))",
"equal(test_func2(x,y) + 2.2,(x + y + 2.2))",
"equal(test_func3(x,y,z) + 2.2,(x + y + z + 2.2))",
"equal(test_func4(x,y,z,w) + 2.2,(x + y + z + w + 2.2))",
"equal(test_func5(x,y,z,w,u) + 2.2,(x + y + z + w + u + 2.2))",
"equal({[test_func1(x)]},{[(x)]})",
"equal({[test_func2(x,y)]},{[(x + y)]})",
"equal({[test_func3(x,y,z)]},{[(x + y + z)]})",
"equal({[test_func4(x,y,z,w)]},{[(x + y + z + w)]})",
"equal({[test_func5(x,y,z,w,u)]},{[(x + y + z + w + u)]})",
"equal(test_func1(2.12),(2.12))",
"equal(test_func2(2.12,3.12),(2.12 + 3.12))",
"equal(test_func3(2.12,3.12,4.12),(2.12 + 3.12 + 4.12))",
"equal(test_func4(2.12,3.12,4.12,5.12),(2.12 + 3.12 + 4.12 + 5.12))",
"equal(test_func5(2.12,3.12,4.12,5.12,6.12),(2.12 + 3.12 + 4.12 + 5.12 + 6.12))",
"equal(1.1 + test_func1(2.12),(2.12 + 1.1))",
"equal(1.1 + test_func2(2.12,3.12),(2.12 + 3.12 + 1.1))",
"equal(1.1 + test_func3(2.12,3.12,4.12),(2.12 + 3.12 + 4.12 + 1.1))",
"equal(1.1 + test_func4(2.12,3.12,4.12,5.12),(2.12 + 3.12 + 4.12 + 5.12 + 1.1))",
"equal(1.1 + test_func5(2.12,3.12,4.12,5.12,6.12),(2.12 + 3.12 + 4.12 + 5.12 + 6.12 + 1.1))",
"equal(test_func1(2.12) + 2.2,(2.12 + 2.2))",
"equal(test_func2(2.12,3.12) + 2.2,(2.12 + 3.12 + 2.2))",
"equal(test_func3(2.12,3.12,4.12) + 2.2,(2.12 + 3.12 + 4.12 + 2.2))",
"equal(test_func4(2.12,3.12,4.12,5.12) + 2.2,(2.12 + 3.12 + 4.12 + 5.12 + 2.2))",
"equal(test_func5(2.12,3.12,4.12,5.12,6.12) + 2.2,(2.12 + 3.12 + 4.12 + 5.12 + 6.12 + 2.2))",
"equal({[test_func1(2.12)]},{[(2.12)]})",
"equal({[test_func2(2.12,3.12)]},{[(2.12 + 3.12)]})",
"equal({[test_func3(2.12,3.12,4.12)]},{[(2.12 + 3.12 + 4.12)]})",
"equal({[test_func4(2.12,3.12,4.12,5.12)]},{[(2.12 + 3.12 + 4.12 + 5.12)]})",
"equal({[test_func5(2.12,3.12,4.12,5.12,6.12)]},{[(2.12 + 3.12 + 4.12 + 5.12 + 6.12)]})",
"TeSt_FuNc0 = tEsT_fUnC0()",
"TEst_fuNC0 == tESt_fUNc0()",
"EquaL(tEsT_FuNC1(x),(x))",
"eQuAl(teSt_fUnc2(x,y),(x + y))",
"EqUaL(tEsT_fUNc3(x,y,z),(x + y + z))",
"EQUal(TEst_FunC4(x,y,z,w),(x + y + z + w))",
"eqUAL(tEsT_FuNc5(x,y,z,w,u),(x + y + z + w + u))"
};
static const std::size_t expr_str_list_size = sizeof(expr_str_list) / sizeof(std::string);
std::deque<expression_t> expression_list;
for (std::size_t i = 0; i < expr_str_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
if (!parser.compile(expr_str_list[i],expression))
{
printf("run_test16() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str_list[i].c_str());
return false;
}
else
expression_list.push_back(expression);
}
bool failure = false;
for (std::size_t i = 0; i < expression_list.size(); ++i)
{
if (T(1) != expression_list[i].value())
{
printf("run_test16() - Error in evaluation! (1) Expression: %s\n",
expr_str_list[i].c_str());
failure = true;
}
}
return !failure;
}
template <typename T>
inline bool run_test17()
{
typedef exprtk::expression<T> expression_t;
T x = T(1.1);
T y = T(2.2);
T z = T(3.3);
T w = T(4.4);
T u = T(5.5);
T v = T(6.6);
T t = T(7.7);
T one = T(1);
T zero = T(0);
exprtk::symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_variable("w",w);
symbol_table.add_variable("u",u);
symbol_table.add_variable("v",v);
symbol_table.add_variable("t",t);
symbol_table.add_variable("one",one);
symbol_table.add_variable("zero",zero);
static const std::string expr_str_list[] =
{
"equal(mand(one,one),1.0)",
"equal(mand(one,zero),0.0)",
"equal(mand(zero,one),0.0)",
"equal(mand(zero,zero),0.0)",
"equal(mand(one,one),1.0)",
"equal(mand(one,one,one),1.0)",
"equal(mand(one,one,one,one),1.0)",
"equal(mand(one,one,one,one,one),1.0)",
"equal(mand(one,one,zero),0.0)",
"equal(mand(one,one,one,zero),0.0)",
"equal(mand(one,one,one,one,zero),0.0)",
"equal(mand(one,one,one,one,one,zero),0.0)",
"equal(mor(one,one),1.0)",
"equal(mor(one,zero),1.0)",
"equal(mor(zero,one),1.0)",
"equal(mor(zero,zero),0.0)",
"equal(mor(one,one),1.0)",
"equal(mor(one,one,zero),1.0)",
"equal(mor(one,zero,one),1.0)",
"equal(mor(one,zero,one,zero),1.0)",
"equal(mor(zero,one),1.0)",
"equal(mor(zero,zero,one),1.0)",
"equal(mor(zero,zero,zero,zero,one),1.0)",
"equal(mor(zero,zero,zero,zero,zero,one),1.0)",
"equal(mor(zero,zero,zero,zero,zero,zero,zero,zero),0.0)",
"equal((one nand one),not(mand(one,one)))",
"equal((one nand zero),not(mand(one,zero)))",
"equal((zero nand one),not(mand(zero,one)))",
"equal((zero nand zero),not(mand(zero,zero)))",
"equal((one nor one),not(mor(one,one)))",
"equal((one nor zero),not(mor(one,zero)))",
"equal((zero nor one),not(mor(zero,one)))",
"equal((zero nor zero),not(mor(zero,zero)))",
"equal(sum(x,y,z,w,u,v,t),(x+y+z+w+u+v+t))",
"equal(sum(x+t,y+v,z+u,w+w,u+z,v+y,t+x),2*(x+y+z+w+u+v+t))",
"equal(mul(x,y,z,w,u,v,t),(x*y*z*w*u*v*t))",
"equal(mul(x*t,y*v,z*u,w*w,u*z,v*y,t*x),(x*y*z*w*u*v*t)^2)",
"equal(sum(x,1.0,y,2.0,z,3.0,w,4.0,u,5.0,v,6.0,t),(x+y+z+w+u+v+t+21.0))",
"equal(sum(x+1.0,y+2.0,z+3.0,w+4.0,u+5.0,v+6.0,t),(x+y+z+w+u+v+t+21.0))",
"equal(mul(x,1.0,y,2.0,z,3.0,w,4.0,u,5.0,v,6.0,t),(x*y*z*w*u*v*t*720.0))",
"equal(mul(x*1.0,y*2.0,z*3.0,w*4.0,u*5.0,v*6.0,t),(x*y*z*w*u*v*t*720.0))",
"equal(min(x,y,z,w,u,v,t,zero),zero)",
"equal(min(x+y,z+w,u+v,t,zero),zero)",
"equal(max(one,x,y,z,w,u,v,t),t)",
"equal(max(x+y,z+w,u+v,t,one),u+v)",
"equal(avg(x,y,z,w,u,v,t),(x+y+z+w+u+v+t)/7.0)",
"equal(avg(x+t,y+v,z+u,w+w,u+z,v+y,t+x),2/7*(x+y+z+w+u+v+t))"
};
static const std::size_t expr_str_list_size = sizeof(expr_str_list) / sizeof(std::string);
std::deque<expression_t> expression_list;
for (std::size_t i = 0; i < expr_str_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
if (!parser.compile(expr_str_list[i],expression))
{
printf("run_test17() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str_list[i].c_str());
return false;
}
else
expression_list.push_back(expression);
}
bool failure = false;
for (std::size_t i = 0; i < expression_list.size(); ++i)
{
if (T(1) != expression_list[i].value())
{
printf("run_test17() - Error in evaluation! (1) Expression: %s\n",
expr_str_list[i].c_str());
failure = true;
}
}
return !failure;
}
template <typename T>
struct va_func : public exprtk::ivararg_function<T>
{
inline T operator()(const std::vector<T>& arglist)
{
T result = T(0);
for (std::size_t i = 0; i < arglist.size(); ++i)
{
result += arglist[i];
}
return result;
}
};
template <typename T>
struct gen_func : public exprtk::igeneric_function<T>
{
typedef typename exprtk::igeneric_function<T>::generic_type generic_type;
typedef typename exprtk::igeneric_function<T>::parameter_list_t parameter_list_t;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
typedef typename generic_type::string_view string_t;
gen_func()
: scalar_count(0),
vector_count(0),
string_count(0)
{}
inline T operator()(parameter_list_t params)
{
for (std::size_t i = 0; i < params.size(); ++i)
{
generic_type& gt = params[i];
switch (gt.type)
{
case generic_type::e_scalar : scalar_count++;
break;
case generic_type::e_vector : vector_count++;
break;
case generic_type::e_string : {
if (
("CdEf" != exprtk::to_str(string_t(gt))) &&
("abc123" != exprtk::to_str(string_t(gt)))
)
{
return std::numeric_limits<T>::quiet_NaN();
}
else
string_count++;
}
break;
default : return std::numeric_limits<T>::quiet_NaN();
}
}
return T(0);
}
std::size_t scalar_count;
std::size_t vector_count;
std::size_t string_count;
};
template <typename T>
struct gen_func2 : public exprtk::igeneric_function<T>
{
typedef typename exprtk::igeneric_function<T>::parameter_list_t parameter_list_t;
gen_func2()
{}
inline T operator()(parameter_list_t&)
{
return T(0);
}
inline T operator()(const std::size_t&, parameter_list_t params)
{
return this->operator()(params);
}
};
template <typename T>
struct inc_func : public exprtk::igeneric_function<T>
{
typedef typename exprtk::igeneric_function<T>::generic_type generic_type;
typedef typename exprtk::igeneric_function<T>::parameter_list_t parameter_list_t;
typedef typename generic_type::scalar_view scalar_t;
typedef typename generic_type::vector_view vector_t;
typedef typename generic_type::string_view string_t;
inc_func()
{}
inline T operator()(parameter_list_t params)
{
for (std::size_t i = 0; i < params.size(); ++i)
{
generic_type& gt = params[i];
switch (gt.type)
{
case generic_type::e_scalar : {
scalar_t scalar(gt);
scalar() += T(1);
}
break;
case generic_type::e_vector : {
vector_t vector(gt);
for (std::size_t x = 0; x < vector.size(); ++x)
{
vector[x] += T(1);
}
}
break;
case generic_type::e_string : {
string_t string(gt);
for (std::size_t x = 0; x < string.size(); ++x)
{
string[x] += static_cast<typename string_t::value_t>(1);
}
}
break;
default : return std::numeric_limits<T>::quiet_NaN();
}
}
return T(0);
}
inline T operator()(const std::size_t&, parameter_list_t params)
{
return this->operator()(params);
}
};
template <typename T>
struct rem_space_and_uppercase : public exprtk::igeneric_function<T>
{
typedef typename exprtk::igeneric_function<T>::generic_type generic_type;
typedef typename exprtk::igeneric_function<T>::parameter_list_t parameter_list_t;
typedef typename generic_type::string_view string_t;
rem_space_and_uppercase()
: exprtk::igeneric_function<T>("S")
{}
inline T operator()(std::string& result, parameter_list_t params)
{
string_t string(params[0]);
result.reserve(string.size());
result.clear();
char c;
for (std::size_t i = 0; i < string.size(); ++i)
{
if (' ' != (c = string[i]))
result += std::toupper(c);
}
return T(0);
}
inline T operator()(const std::size_t& param_seq_index, std::string& result, parameter_list_t params)
{
if (1 == param_seq_index)
return this->operator()(result,params);
else
return T(0);
}
};
template <typename T>
inline bool run_test18()
{
{
typedef exprtk::expression<T> expression_t;
T x = T(1.1);
T y = T(2.2);
T z = T(3.3);
T w = T(4.4);
T u = T(5.5);
T v = T(6.6);
T t = T(7.7);
va_func<T> vaf;
exprtk::symbol_table<T> symbol_table;
symbol_table.add_constants();
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_variable("w",w);
symbol_table.add_variable("u",u);
symbol_table.add_variable("v",v);
symbol_table.add_variable("t",t);
symbol_table.add_function("va_func",vaf);
static const std::string expr_str_list[] =
{
"equal(va_func,(0))",
"equal(va_func(),(0))",
"equal(va_func(1,2,3,4,5,6,7,8,9),(1+2+3+4+5+6+7+8+9))",
"equal(va_func(1,x,3,y,5,z,7,w,9),(1+x+3+y+5+z+7+w+9))",
"equal(va_func(x,2,y,4,z,6,w,8,u),(x+2+y+4+z+6+w+8+u))",
"equal(va_func(x,y,z,w,u,v,t,1,2,3),(x+y+z+w+u+v+t+1+2+3))",
"equal(va_func(x,y,z,w,u,v,t),(x+y+z+w+u+v+t))",
"equal(va_func(x+t,y+v,z+u,w+w,u+z,v+y,t+x),2*(x+y+z+w+u+v+t))",
"equal(1+va_func(1,x,3,y,5,z,7,w,9),(1+x+3+y+5+z+7+w+9)+1)",
"equal(va_func(va_func(x,y,z,w,u,v,t),va_func(x,y,z,w,u,v,t)),2*(x+y+z+w+u+v+t))",
"equal(va_func(va_func(x),va_func(y),va_func(z)),va_func(x,y,z))",
"equal(va_func(va_func(va_func(va_func(va_func(va_func(va_func(va_func(x)))))))),x)",
"equal(va_func(va_func(va_func(va_func(va_func(va_func(va_func(va_func(123.456)))))))),123.456)",
"equal(va_func(va_func(va_func(va_func(va_func(va_func(va_func(va_func(x+1)))))))),x+1)",
"equal(va_func(va_func(va_func(va_func(va_func(va_func(va_func(va_func(x+y)))))))),x+y)"
};
static const std::size_t expr_str_list_size = sizeof(expr_str_list) / sizeof(std::string);
std::deque<expression_t> expression_list;
for (std::size_t i = 0; i < expr_str_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
if (!parser.compile(expr_str_list[i],expression))
{
printf("run_test18() - VarArg Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str_list[i].c_str());
return false;
}
else
expression_list.push_back(expression);
}
bool failure = false;
for (std::size_t i = 0; i < expression_list.size(); ++i)
{
if (T(1) != expression_list[i].value())
{
printf("run_test18() - Error in evaluation! (1) Expression: %s\n",
expr_str_list[i].c_str());
failure = true;
}
}
if (failure)
return false;
}
{
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T> expression_t;
typedef exprtk::parser<T> parser_t;
T x = T(33);
T y = T(77);
T v0[] = { T(1), T(1), T(1), T(1) };
T v1[] = { T(1), T(2), T(3), T(4) };
std::vector<T> v2;
v2.push_back(T(5));
v2.push_back(T(6));
v2.push_back(T(7));
v2.push_back(T(8));
std::string s0 = "AbCdEfGhIj";
gen_func<T> f;
symbol_table_t symbol_table;
symbol_table.add_constants();
symbol_table.add_variable ("x" , x);
symbol_table.add_variable ("y" , y);
symbol_table.add_vector ("v0" ,v0);
symbol_table.add_vector ("v1" ,v1);
symbol_table.add_vector ("v2" ,v2);
symbol_table.add_stringvar("s0", s0);
symbol_table.add_function ("gen_func", f);
std::string expression_list[] =
{
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5],v0);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(x, 2x + y, z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(2x + y, z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2], x);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2], x, 2x + y);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2], x, 2x + y, z);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func('abc123', s0[2:5],v0, v1 + v2, v0[2], x, 2x + y, z,2w / 3);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; gen_func(s0[2:5],v0, v1 + v2, v0[2], x, 2x + y, z,2w / 3, 'abc123');"
};
static const std::size_t expression_list_size = sizeof(expression_list) / sizeof(std::string);
bool failure = false;
for (std::size_t i = 0; i < expression_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
if (!parser.compile(expression_list[i],expression))
{
printf("run_test18() - GenFunc Error: %s Expression: %s [2]\n",
parser.error().c_str(),
expression_list[i].c_str());
failure = true;
continue;
}
f.scalar_count = 0;
f.vector_count = 0;
f.string_count = 0;
expression.value();
if (
(4 != f.scalar_count) ||
(3 != f.vector_count) ||
(2 != f.string_count)
)
{
printf("run_test18() - Error in evaluation! (2) Expression: %s "
"sc_count = %d "
"vr_count = %d "
"st_count = %d\n",
expression_list[i].c_str(),
static_cast<int>(f.scalar_count),
static_cast<int>(f.vector_count),
static_cast<int>(f.string_count));
failure = true;
}
}
if (failure)
return false;
}
{
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T> expression_t;
typedef exprtk::parser<T> parser_t;
T x = T(33);
T y = T(77);
T v0[] = { T(1), T(1), T(1), T(1) };
T v1[] = { T(1), T(2), T(3), T(4) };
T v2[] = { T(5), T(6), T(7), T(8) };
std::string s0 = "AbCdEfGhIj";
gen_func2<T> f;
symbol_table_t symbol_table;
symbol_table.add_constants();
symbol_table.add_variable ("x" , x);
symbol_table.add_variable ("y" , y);
symbol_table.add_vector ("v0" ,v0);
symbol_table.add_vector ("v1" ,v1);
symbol_table.add_vector ("v2" ,v2);
symbol_table.add_stringvar("s0", s0);
symbol_table.add_function ("foo", f);
std::string expression_list[] =
{
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5],v0);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(x, 2x + y, z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(2x + y, z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2], x);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(z, 2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2], x, 2x + y);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(2w / 3, 'abc123',s0[2:5],v0, v1 + v2, v0[2], x, 2x + y, z);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo('abc123', s0[2:5],v0, v1 + v2, v0[2], x, 2x + y, z,2w / 3);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(s0[2:5],v0, v1 + v2, v0[2], x, 2x + y, z,2w / 3, 'abc123');",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(s0[2:3]+s0[4:5],v0, v1 + v2, v0[2], x, 2x + y, z,2w / 3, 'abc123');",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);",
"var z := 3; var w[3] := { 1/3, 1/5, 1/7 }; foo(v0,v1 + v2, v0[2], x, 2x + y, z, 2w / 3, 'abc123',s0[2:5]);"
};
static const std::size_t expression_list_size = sizeof(expression_list) / sizeof(std::string);
std::string parameter_type_list[] =
{
"VVTTTTVSS",
"VTTTTVSSV",
"TTTTVSSVV",
"TTTVSSVVT",
"TTVSSVVT*",
"TVSSVVT*" ,
"VSSVVT*" ,
"SSVVTTTTV",
"SVVTTTTVS",
"SVVTTTTVS",
"V*T*VS*" ,
"V*TTTTVSS",
"VVT*VSS" ,
"VVTTTTVS*",
"TTTTTTT|STSTSTS|V*T*VS*" ,
"TTTTTTT|STSTSTS|V*TTTTVSS",
"TTTTTTT|STSTSTS|VVT*VSS" ,
"TTTTTTT|STSTSTS|VVTTTTVS*"
};
bool failure = false;
for (std::size_t i = 0; i < expression_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
f.parameter_sequence = parameter_type_list[i];
if (!parser.compile(expression_list[i],expression))
{
printf("run_test18() - GenFunc2 Error: %s Expression: %s Parameter Sequence: %s [3]\n",
parser.error().c_str(),
expression_list[i].c_str(),
parameter_type_list[i].c_str());
failure = true;
continue;
}
expression.value();
}
if (failure)
return false;
}
{
bool failure = false;
std::string expression_list[] =
{
"foo(v0,v1,v2,x,y,s0);",
"foo(v1,v2,x,y,s0,v0);",
"foo(v2,x,y,s0,v0,v1);",
"foo(x,y,s0,v0,v1,v2);",
"foo(y,s0,v0,v1,v2,x);",
"foo(s0,v0,v1,v2,x,y);"
};
static const std::size_t expression_list_size = sizeof(expression_list) / sizeof(std::string);
std::string parameter_type_list[] =
{
"VVVTTS",
"VVTTSV",
"VTTSVV",
"TTSVVV",
"TSVVVT",
"SVVVTT"
};
for (std::size_t i = 0; i < expression_list_size; ++i)
{
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T> expression_t;
typedef exprtk::parser<T> parser_t;
T x = T(33);
T y = T(77);
T v0[] = { T(1), T(1), T(1), T(1) };
T v1[] = { T(1), T(2), T(3), T(4) };
T v2[] = { T(5), T(6), T(7), T(8) };
std::string s0 = "AbCdEfGhIj";
T x_inc = T(34);
T y_inc = T(78);
T v0_inc[] = { T(2), T(2), T(2), T(2) };
T v1_inc[] = { T(2), T(3), T(4), T(5) };
T v2_inc[] = { T(6), T(7), T(8), T(9) };
std::size_t sizeof_vec = sizeof(v0) / sizeof(T);
std::string s0_inc = "BcDeFgHiJk";
inc_func<T> f;
symbol_table_t symbol_table;
symbol_table.add_constants();
symbol_table.add_variable ("x" , x);
symbol_table.add_variable ("y" , y);
symbol_table.add_vector ("v0" ,v0);
symbol_table.add_vector ("v1" ,v1);
symbol_table.add_vector ("v2" ,v2);
symbol_table.add_stringvar("s0", s0);
symbol_table.add_function ("foo", f);
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
f.parameter_sequence = parameter_type_list[i];
if (!parser.compile(expression_list[i],expression))
{
printf("run_test18() - IncFunc Error: %s Expression: %s Parameter Sequence: %s [4]\n",
parser.error().c_str(),
expression_list[i].c_str(),
parameter_type_list[i].c_str());
failure = true;
continue;
}
expression.value();
if (x != x_inc)
{
printf("run_test18() - Error in evaluation! (3) Expression: %s Check: x\n",
expression_list[i].c_str());
failure = true;
}
if (y != y_inc)
{
printf("run_test18() - Error in evaluation! (3) Expression: %s Check: y\n",
expression_list[i].c_str());
failure = true;
}
if (s0 != s0_inc)
{
printf("run_test18() - Error in evaluation! (3) Expression: %s Check: y\n",
expression_list[i].c_str());
failure = true;
}
if (!std::equal(v0,v0 + sizeof_vec,v0_inc))
{
printf("run_test18() - Error in evaluation! (3) Expression: %s Check: v0\n",
expression_list[i].c_str());
failure = true;
}
if (!std::equal(v1,v1 + sizeof_vec,v1_inc))
{
printf("run_test18() - Error in evaluation! (3) Expression: %s Check: v1\n",
expression_list[i].c_str());
failure = true;
}
if (!std::equal(v2,v2 + sizeof_vec,v2_inc))
{
printf("run_test18() - Error in evaluation! (3) Expression: %s Check: v2\n",
expression_list[i].c_str());
failure = true;
}
}
if (failure)
return false;
}
{
bool failure = false;
rem_space_and_uppercase<T> rsauc;
std::string s0 = "XXXXXXXXXXXXXXX";
std::string s1 = "XXXXXXXXXXXXXXX";
std::string s2 = "XXXXXXXXXXXXXXX";
std::string s3 = "XXXXXXXXXXXXXXX";
std::string s4 = "XXXXXXXXXXXXXXX";
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T> expression_t;
typedef exprtk::parser<T> parser_t;
symbol_table_t symbol_table;
symbol_table.add_constants();
symbol_table.add_stringvar("s0", s0);
symbol_table.add_stringvar("s1", s1);
symbol_table.add_stringvar("s2", s2);
symbol_table.add_stringvar("s3", s3);
symbol_table.add_stringvar("s4", s4);
symbol_table.add_function("remspc_uc",rsauc,symbol_table_t::e_ft_strfunc);
std::string program = " s0 := 'How now '; "
" s1 := 'brown cow?'; "
" s2 := remspc_uc(s0 + s1); "
" s3 := remspc_uc(s0) + s1; "
" s4 := s0 + remspc_uc(s1); "
" remspc_uc(s0 + s1) == remspc_uc(s0) + remspc_uc(s1);";
std::string parameter_type_list[] =
{
"VVVTTT|S",
"VVTTTV|S",
"VTTTVV|S",
"TTTVVV|S",
"TTVVVT|S",
"TVVVTT|S"
};
std::size_t parameter_type_list_size = sizeof(parameter_type_list) / sizeof(std::string);
for (std::size_t i = 0; i < parameter_type_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
rsauc.parameter_sequence = parameter_type_list[i];
if (!parser.compile(program,expression))
{
printf("Error: %s\tExpression: %s\n",
parser.error().c_str(),
program.c_str());
return false;
}
T result = expression.value();
if (result != T(1))
{
printf("run_test18() - Error in evaluation! (4) Expression: %s Result <> 1\n",
program.c_str());
failure = true;
}
if (result != T(1))
{
printf("run_test18() - Error in evaluation! (4) Expression: %s Check: s0\n",
program.c_str());
failure = true;
}
if ("How now " != s0)
{
printf("run_test18() - Error in evaluation! (4) Expression: %s Check: s0\n",
program.c_str());
failure = true;
}
if ("brown cow?" != s1)
{
printf("run_test18() - Error in evaluation! (4) Expression: %s Check: s1\n",
program.c_str());
failure = true;
}
if ("HOWNOWBROWNCOW?" != s2)
{
printf("run_test18() - Error in evaluation! (4) Expression: %s Check: s2\n",
program.c_str());
failure = true;
}
if ("HOWNOWbrown cow?" != s3)
{
printf("run_test18() - Error in evaluation! (4) Expression: %s Check: s3\n",
program.c_str());
failure = true;
}
if ("How now BROWNCOW?" != s4)
{
printf("run_test18() - Error in evaluation! (4) Expression: %s Check: s4\n",
program.c_str());
failure = true;
}
}
if (failure)
return false;
}
return true;
}
template <typename T>
inline bool run_test19()
{
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T> expression_t;
typedef exprtk::parser<T> parser_t;
typedef exprtk::function_compositor<T> compositor_t;
typedef typename compositor_t::function function_t;
{
T x = T(123.123);
compositor_t compositor;
// f(x) = x + 2
compositor.add("f","x + 2","x");
// g(x) = x^2-3
compositor.add("g","x^2 - 3","x");
// fof(x) = f(f(x))
compositor.add("fof","f(f(x))","x");
// gog(x) = g(g(x))
compositor.add("gog","g(g(x))","x");
// fog(x) = f(g(x))
compositor.add("fog","f(g(x))","x");
// gof(x) = g(f(x))
compositor.add("gof","g(f(x))","x");
// fogof(x) = f(g(f(x)))
compositor.add("fogof","f(g(f(x)))","x");
// gofog(x) = g(f(g(x)))
compositor.add("gofog","g(f(g(x)))","x");
symbol_table_t& symbol_table = compositor.symbol_table();
symbol_table.add_constants();
symbol_table.add_variable("x",x);
static const std::string expr_str_list[] =
{
"equal(f(x),(x + 2))",
"equal(g(x),(x^2 - 3))",
"equal(fof(x),(x + 4))",
"equal(gog(x),(x^4 - 6x^2 + 6))",
"equal(fog(x),(x^2 - 1))",
"equal(gof(x),(x^2 + 4x + 1))",
"equal(fogof(x),(x^2 + 4x + 3))",
"equal(gofog(x),(x^4 - 2x^2 - 2))"
};
static const std::size_t expr_str_list_size = sizeof(expr_str_list) / sizeof(std::string);
std::deque<expression_t> expression_list;
for (std::size_t i = 0; i < expr_str_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
if (!parser.compile(expr_str_list[i],expression))
{
printf("run_test19() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str_list[i].c_str());
return false;
}
else
expression_list.push_back(expression);
}
bool failure = false;
for (std::size_t i = 0; i < expression_list.size(); ++i)
{
if (T(1) != expression_list[i].value())
{
printf("run_test19() - Error in evaluation! (1) Expression: %s\n",
expr_str_list[i].c_str());
failure = true;
}
}
if (failure)
return false;
}
const std::size_t rounds = 100;
for (std::size_t r = 0; r < rounds; ++r)
{
T x = T(1);
T y = T(2);
T z = T(3);
T w = T(4);
T u = T(5);
T v = T(6);
compositor_t compositor;
// f0() = 6
compositor
.add("f0"," 3 * 2");
// f1(x) = 5 * (f0 + x)
compositor
.add("f1","5 * (f0 + x)","x");
// f2(x,y) = 7 * (f1(x) + f1(y))
compositor
.add("f2","7 * (f1(x) + f1(y))","x","y");
// f3(x,y,z) = 9 * (f2(x,y) + f2(y,z) + f2(x,z))
compositor
.add("f3","9 * (f2(x,y) + f2(y,z) + f2(x,z))","x","y","z");
// f4(x,y,z,w) = 11 * (f3(x,y,z) + f3(y,z,w) + f3(z,w,z))
compositor
.add("f4","11 * (f3(x,y,z) + f3(y,z,w) + f3(z,w,x))","x","y","z","w");
// f5(x,y,z,w,u) = 13 * (f4(x,y,z,w) + f4(y,z,w,u) + f4(z,w,u,x) + f4(w,u,x,y))
compositor
.add("f5",
"13 * (f4(x,y,z,w) + f4(y,z,w,u) + f4(z,w,u,x) + f4(w,u,x,y))",
"x","y","z","w","u");
// f6(x,y,z,w,u,v) = 17 * (f5(x,y,z,w,u) + f5(y,z,w,u,v) + f5(z,w,u,v,x) + f5(w,u,v,x,y))
compositor
.add(
function_t("f6")
.var("x").var("y").var("z")
.var("w").var("u").var("v")
.expression("17 * (f5(x,y,z,w,u) + f5(y,z,w,u,v) + f5(z,w,u,v,x) + f5(w,u,v,x,y))"));
symbol_table_t& symbol_table = compositor.symbol_table();
symbol_table.add_constants();
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);
symbol_table.add_variable("z",z);
symbol_table.add_variable("w",w);
symbol_table.add_variable("u",u);
symbol_table.add_variable("v",v);
parser_t parser;
const std::string expr_str_list[] =
{
"f0()",
"f1(x)",
"f2(x,x)",
"f3(x,x,x)",
"f4(x,x,x,x)",
"f5(x,x,x,x,x)",
"f6(x,x,x,x,x,x)",
"f2(x,y)",
"f3(x,y,z)",
"f4(x,y,z,w)",
"f5(x,y,z,w,u)",
"f6(x,y,z,w,u,v)"
};
const std::size_t expr_str_list_size = sizeof(expr_str_list) / sizeof(std::string);
const T result_list[] =
{
T(6 ),
T(35 ),
T(490 ),
T(13230 ),
T(436590 ),
T(22702680 ),
T(1543782240),
T(525 ),
T(15120 ),
T(533610 ),
T(29459430 ),
T(2122700580)
};
for (std::size_t i = 0; i < expr_str_list_size; ++i)
{
expression_t expression;
expression.register_symbol_table(symbol_table);
if (!parser.compile(expr_str_list[i],expression))
{
printf("run_test19() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str_list[i].c_str());
return false;
}
T result = expression.value();
if (result_list[i] != result)
{
printf("run_test19() - Error in evaluation! (2) Expression: %s Expected: %10.1f\tResult: %10.1f\n",
expr_str_list[i].c_str(),
result_list[i],
result);
return false;
}
}
}
{
T x = T(0);
compositor_t compositor;
compositor
.add("is_prime_impl1",
"if(y == 1,true, "
" if(0 == (x % y),false, "
" is_prime_impl1(x,y - 1)))",
"x","y");
compositor
.add("is_prime1",
"if(frac(x) != 0, false, "
" if(x <= 0, false, "
" is_prime_impl1(x,min(x - 1,trunc(sqrt(x)) + 1))))",
"x");
compositor
.add("is_prime_impl2",
"switch "
"{ "
" case y == 1 : true; "
" case (x % y) == 0 : false; "
" default : is_prime_impl2(x,y - 1);"
"} ",
"x","y");
compositor
.add("is_prime2",
"switch "
"{ "
" case x <= 0 : false; "
" case frac(x) != 0 : false; "
" default : is_prime_impl2(x,min(x - 1,trunc(sqrt(x)) + 1));"
"} ",
"x");
compositor
.add("is_prime_impl3",
"while (y > 0) "
"{ "
" switch "
" { "
" case y == 1 : ~(y := 0, true);"
" case (x % y) == 0 : ~(y := 0,false);"
" default : y := y - 1; "
" } "
"} ",
"x","y");
compositor
.add("is_prime3",
"switch "
"{ "
" case x <= 0 : false; "
" case frac(x) != 0 : false; "
" default : is_prime_impl3(x,min(x - 1,trunc(sqrt(x)) + 1));"
"} ",
"x");
compositor
.add("is_prime_impl4",
"switch "
"{ "
" case 1 == x : false; "
" case 2 == x : true; "
" case 3 == x : true; "
" case 5 == x : true; "
" case 7 == x : true; "
" case 0 == x % 2 : false; "
" default : "
" { "
" for (var i := 3; i < y; i += 2) "
" { "
" if ((x % i) == 0) "
" break[false]; "
" else "
" true; "
" } "
" }; "
"} ",
"x","y");
compositor
.add("is_prime4",
"switch "
"{ "
" case x <= 0 : false; "
" case frac(x) != 0 : false; "
" default : is_prime_impl4(x,min(x - 1,trunc(sqrt(x)) + 1));"
"} ",
"x");
symbol_table_t& symbol_table = compositor.symbol_table();
symbol_table.add_constants();
symbol_table.add_variable("x",x);
const std::string expression_str[] = {
"is_prime1(x)",
"is_prime2(x)",
"is_prime3(x)",
"is_prime4(x)"
};
const std::size_t expression_count = sizeof(expression_str) / sizeof(std::string);
std::vector<expression_t> expression_list;
for (std::size_t i = 0; i < expression_count; ++i)
{
parser_t parser;
expression_t expression;
expression.register_symbol_table(symbol_table);
if (!parser.compile(expression_str[i],expression))
{
printf("run_test19() - Error: %s Expression%d: %s\n",
parser.error().c_str(),
static_cast<unsigned int>(i),
expression_str[i].c_str());
return false;
}
else
expression_list.push_back(expression);
}
bool failure = false;
const std::size_t prime_list[] =
{
2, 3, 5, 7, 11, 13, 17, 19,
877, 947, 1087, 1153, 1229, 1297, 1381, 1453,
1523, 1597, 1663, 1741, 1823, 1901, 1993, 2063,
2131, 2221, 2293, 2371, 2437, 2539, 2621, 2689,
2749, 2833, 2909, 3001, 3083, 3187, 3259, 3343,
3433, 3517, 3581, 3659, 3733, 3823, 3911, 4001,
4073, 4153, 4241, 4327, 4421, 4507, 4591, 4663,
4759, 4861, 4943, 5009, 5099, 5189, 5281, 5393,
5449, 5527, 5641, 5701, 5801, 5861, 5953, 6067,
6143, 6229, 6311, 6373, 6481, 6577, 6679, 6763,
6841, 6947, 7001, 7109, 7211, 7307, 7417, 7507,
104309, 104311, 104323, 104327, 104347, 104369, 104381, 104383,
104393, 104399, 104417, 104459, 104471, 104473, 104479, 104491,
104513, 104527, 104537, 104543, 104549, 104551, 104561, 104579,
104593, 104597, 104623, 104639, 104651, 104659, 104677, 104681,
104683, 104693, 104701, 104707, 104711, 104717, 104723, 104729,
1000621, 1000639, 1000651, 1000667, 1000669, 1001023, 1001027, 1001041
};
const std::size_t prime_list_size = sizeof(prime_list) / sizeof(std::size_t);
for (std::size_t i = 0; (i < prime_list_size) && (!failure); ++i)
{
x = prime_list[i];
std::vector<T> result(expression_count,T(0));
for (std::size_t j = 0; j < expression_list.size(); ++j)
{
result[j] = expression_list[j].value();
}
for (std::size_t j = 1; j < expression_list.size(); ++j)
{
if (result[j] != result[0])
{
failure = true;
break;
}
}
if (failure)
{
printf("run_test19() - Error in evaluation! (3) Results don't match! Prime: %d\n",
static_cast<unsigned int>(prime_list[i]));
for (std::size_t j = 0; j < expression_list.size(); ++j)
{
printf("Expression[%02d]: %s = %d\n",
static_cast<unsigned int>(j),
expression_str[j].c_str(),
static_cast<unsigned int>(result[j]));
}
}
else if (T(1) != expression_list[0].value())
{
printf("run_test19() - Error in evaluation! (4) Results don't match! Prime: %d\n",
static_cast<unsigned int>(prime_list[i]));
for (std::size_t j = 0; j < expression_list.size(); ++j)
{
printf("Expression[%02d]: %s = %d\n",
static_cast<unsigned int>(j),
expression_str[j].c_str(),
static_cast<unsigned int>(result[j]));
}
}
}
if (failure)
return false;
}
{
T x = T(0);
compositor_t compositor;
compositor
.add("fibonacci1",
"if(x == 0,0, "
" if(x == 1,1, "
" fibonacci1(x - 1) + fibonacci1(x - 2)))",
"x");
compositor
.add("fibonacci2",
"switch "
"{ "
" case x == 0 : 0; "
" case x == 1 : 1; "
" default : fibonacci2(x - 1) + fibonacci2(x - 2);"
"} ",
"x");
compositor
.add("fibonacci_impl3",
"switch "
"{ "
" case x == 0 : 0; "
" case x == 1 : 1; "
" default : "
" while ((x := (x - 1)) > 0)"
" { "
" w := z; "
" z := z + y; "
" y := w; "
" z "
" }; "
"} ",
"x","y","z","w");
compositor
.add("fibonacci3",
"fibonacci_impl3(x,0,1,0)",
"x");
compositor
.add("fibonacci_impl4",
"switch "
"{ "
" case x == 0 : 0; "
" case x == 1 : 1; "
" default : "
" repeat "
" w := z; "
" z := z + y; "
" y := w; "
" x := x - 1; "
" z "
" until (x <= 1);"
"} ",
"x","y","z","w");
compositor
.add("fibonacci4",
"fibonacci_impl4(x,0,1,0)",
"x");
compositor
.add("fibonacci5",
"if ((x == 0) or (x == 1)) "
" x; "
"else "
" fibonacci5(x - 1) + fibonacci5(x - 2); ",
"x");
symbol_table_t& symbol_table = compositor.symbol_table();
symbol_table.add_constants();
symbol_table.add_variable("x",x);
const std::string expression_str[] = {
"fibonacci1(x)",
"fibonacci2(x)",
"fibonacci3(x)",
"fibonacci4(x)",
"fibonacci5(x)"
};
const std::size_t expression_count = sizeof(expression_str) / sizeof(std::string);
std::vector<expression_t> expression_list;
for (std::size_t i = 0; i < expression_count; ++i)
{
parser_t parser;
expression_t expression;
expression.register_symbol_table(symbol_table);
if (!parser.compile(expression_str[i],expression))
{
printf("run_test19() - Error: %s Expression[%02d]: %s\n",
parser.error().c_str(),
static_cast<unsigned int>(i),
expression_str[i].c_str());
return false;
}
else
expression_list.push_back(expression);
}
bool failure = false;
const std::size_t fibonacci_list[] =
{
0, 1, 1, 2,
3, 5, 8, 13,
21, 34, 55, 89,
144, 233, 377, 610,
987, 1597, 2584, 4181,
6765, 10946, 17711, 28657,
46368, 75025, 121393, 196418,
317811, 514229, 832040, 1346269
};
const std::size_t fibonacci_list_size = sizeof(fibonacci_list) / sizeof(std::size_t);
for (std::size_t i = 0; (i < fibonacci_list_size) && (!failure); ++i)
{
x = i;
std::vector<T> result(expression_count,T(0));
for (std::size_t j = 0; j < expression_list.size(); ++j)
{
result[j] = expression_list[j].value();
}
for (std::size_t j = 1; j < expression_list.size(); ++j)
{
if (result[j] != result[0])
{
failure = true;
break;
}
}
if (failure)
{
printf("run_test19() - Error in evaluation! (5) Results don't match! fibonacci(%d) = %d\n",
static_cast<unsigned int>(i),
static_cast<unsigned int>(fibonacci_list[i]));
for (std::size_t j = 0; j < expression_list.size(); ++j)
{
printf("Expression[%02d]: %s = %d\n",
static_cast<unsigned int>(j),
expression_str[j].c_str(),
static_cast<unsigned int>(result[j]));
}
}
else if (fibonacci_list[i] != expression_list[0].value())
{
printf("run_test19() - Error in evaluation! (6) Results don't match! fibonacci(%d) = %d\n",
static_cast<unsigned int>(i),
static_cast<unsigned int>(fibonacci_list[i]));
for (std::size_t j = 0; j < expression_list.size(); ++j)
{
printf("Expression[%02d]: %s = %d\n",
static_cast<unsigned int>(j),
expression_str[j].c_str(),
static_cast<unsigned int>(result[j]));
}
}
}
if (failure)
return false;
}
{
T x = T(0);
symbol_table_t symbol_table;
symbol_table.add_constants();
symbol_table.add_variable("x",x);
compositor_t compositor(symbol_table);
compositor
.add("newton_sqrt_impl",
"switch "
"{ "
" case x < 0 : -inf; "
" case x == 0 : 0; "
" case x == 1 : 1; "
" default: "
" ~{ "
" z := 100; "
" y := x / 2; "
" repeat "
" y := (1 / 2) * (y + (x / y)); "
" if (equal(y * y,x)) "
" break[y]; "
" until ((z -= 1) <= 0); "
" }; "
"} ",
"x","y","z");
compositor
.add("newton_sqrt",
"newton_sqrt_impl(x,0,0)","x");
std::string expression_str = "newton_sqrt(x)";
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
if (!parser.compile(expression_str,expression))
{
printf("run_test19() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_str.c_str());
return false;
}
bool failure = false;
for (std::size_t i = 0; i < 100; ++i)
{
x = i;
T result = expression.value();
if (not_equal(result,std::sqrt(x),T(0.0000001)))
{
printf("run_test19() - Computation Error "
"Expression: [%s]\tExpected: %12.8f\tResult: %12.8f\n",
expression_str.c_str(),
(double)std::sqrt(x),
(double)result);
failure = true;
}
}
if (failure)
return false;
}
{
symbol_table_t symbol_table;
symbol_table.add_constants();
compositor_t compositor(symbol_table);
compositor
.add("mandelbrot",
" var width := 118; "
" var height := 41; "
" var imag_max := +1; "
" var imag_min := -1; "
" var real_max := +1; "
" var real_min := -2.5; "
" var x_step := (real_max - real_min) / width; "
" var y_step := (imag_max - imag_min) / height; "
" for (var y := 0; y < height; y += 1) "
" { "
" var imag := imag_min + (y_step * y); "
" for (var x := 0; x < width; x += 1) "
" { "
" var real := real_min + x_step * x; "
" var z_real := real; "
" var z_imag := imag; "
" var plot_value; "
" for (var n := 0; n < 30; n += 1) "
" { "
" var a := z_real^2; "
" var b := z_imag^2; "
" plot_value := n; "
" if ((a + b) < 4) "
" { "
" z_imag := 2 * z_real * z_imag + imag; "
" z_real := a - b + real; "
" } "
" else "
" break; "
" }; "
" }; "
" } ");
std::string expression_str = "mandelbrot()";
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
if (!parser.compile(expression_str,expression))
{
printf("run_test19() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_str.c_str());
return false;
}
for (std::size_t i = 0; i < 100; ++i)
{
expression.value();
}
}
{
T x = T(0);
symbol_table_t symbol_table;
symbol_table.add_variable("x",x);
compositor_t compositor(symbol_table);
compositor
.add("fooboo",
" var x := input; "
" if (x > 0) "
" fooboo(x - 1) + x; "
" else "
" 0; ",
"input");
std::string expression_str = "fOoBoO(x)";
expression_t expression;
expression.register_symbol_table(symbol_table);
parser_t parser;
if (!parser.compile(expression_str,expression))
{
printf("run_test19() - Error: %s Expression: %s\n",
parser.error().c_str(),
expression_str.c_str());
return false;
}
T sum = T(0);
for (std::size_t i = 0; i < 100; ++i)
{
x = T(i);
sum += x;
T result = expression.value();
if (result != sum)
{
printf("run_test19() - FooBoo(%5.2f) Expected: %5.2f\tResult: %5.2f\n",
x,
sum,
result);
return false;
}
}
}
return true;
}
template <typename T>
struct my_usr : public exprtk::parser<T>::unknown_symbol_resolver
{
typedef typename exprtk::parser<T>::unknown_symbol_resolver usr_t;
bool process(const std::string& unknown_symbol,
typename usr_t::usr_symbol_type& st,
T& default_value,
std::string& error_message)
{
if (unknown_symbol[0] == 'v')
{
st = usr_t::e_usr_variable_type;
default_value = next_value();
error_message = "";
return true;
}
else if (unknown_symbol[0] == 'c')
{
st = usr_t::e_usr_constant_type;
default_value = next_value();
error_message = "";
return true;
}
else
{
error_message = "Unknown symbol...";
return false;
}
}
T next_value(const bool reset = false)
{
static T value = 0;
if (reset)
return (value = 0);
else
return ++value;
}
};
template <typename T>
inline bool run_test20()
{
typedef exprtk::expression<T> expression_t;
for (std::size_t i = 0; i < 100; ++i)
{
exprtk::symbol_table<T> symbol_table;
symbol_table.add_constants();
expression_t expression;
expression.register_symbol_table(symbol_table);
exprtk::parser<T> parser;
my_usr<T> musr;
musr.next_value(true);
parser.enable_unknown_symbol_resolver(&musr);
std::string expr_str = "v01+c02+v03+c04+v05+c06+v07+c08+v09+c10+"
"v11+c12+v13+c14+v15+c16+v17+c18+v19+c20+"
"v21+c22+v23+c24+v25+c26+v27+c28+v29+c30 ";
if (!parser.compile(expr_str,expression))
{
printf("run_test20() - Error: %s Expression: %s\n",
parser.error().c_str(),
expr_str.c_str());
return false;
}
T sum_1_30 = T((1 + 30) * 15);
T result = expression.value();
if (sum_1_30 != result)
{
printf("run_test20() - Error in evaluation! (1) Expression: %s\n",
expr_str.c_str());
return false;
}
}
return true;
}
template <typename T>
struct type_name { static inline std::string value() { return "unknown"; } };
template <> struct type_name<float> { static inline std::string value() { return "float"; } };
template <> struct type_name<double> { static inline std::string value() { return "double"; } };
template <> struct type_name<long double> { static inline std::string value() { return "long double"; } };
int main()
{
#define perform_test(Type,Number) \
{ \
exprtk::timer timer; \
timer.start(); \
if (!run_test##Number<Type>()) \
{ \
printf("run_test"#Number" (%s) *** FAILED! ***\n", \
type_name<Type>::value().c_str()); \
} \
else \
{ \
timer.stop(); \
printf("run_test"#Number" (%s) - Result: SUCCESS Time: %8.4fsec\n", \
type_name<Type>::value().c_str(), \
timer.time()); \
} \
} \
perform_test(numeric_type,00)
perform_test(numeric_type,01)
perform_test(numeric_type,02)
perform_test(numeric_type,03)
perform_test(numeric_type,04)
perform_test(numeric_type,05)
perform_test(numeric_type,06)
perform_test(numeric_type,07)
perform_test(numeric_type,08)
perform_test(numeric_type,09)
perform_test(numeric_type,10)
perform_test(numeric_type,11)
perform_test(numeric_type,12)
perform_test(numeric_type,13)
perform_test(numeric_type,14)
perform_test(numeric_type,15)
perform_test(numeric_type,16)
perform_test(numeric_type,17)
perform_test(numeric_type,18)
perform_test(numeric_type,19)
perform_test(numeric_type,20)
#undef perform_test
return 0;
}
| 48.516324 | 248 | 0.377588 | [
"vector"
] |
11045005adadbe66559741f2243a417261bb1322 | 1,309 | hpp | C++ | nacl/misc/poker.hpp | ToxicPie/NaCl | 8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c | [
"MIT"
] | 3 | 2021-08-31T17:51:01.000Z | 2021-11-13T16:22:25.000Z | nacl/misc/poker.hpp | ToxicPie/NaCl | 8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c | [
"MIT"
] | null | null | null | nacl/misc/poker.hpp | ToxicPie/NaCl | 8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <string>
#include <tuple>
#include <vector>
using namespace std;
struct hand {
static constexpr auto rk = [] {
array<int, 256> x{};
auto s = "23456789TJQKACDHS";
for (int i = 0; i < 17; i++) x[s[i]] = i % 13;
return x;
}();
vector<pair<int, int>> v;
vector<int> cnt, vf, vs;
int type;
hand() : cnt(4), type(0) {}
void add_card(char suit, char rank) {
++cnt[rk[suit]];
for (auto &[f, s] : v)
if (s == rk[rank]) return ++f, void();
v.emplace_back(1, rk[rank]);
}
void process() {
sort(v.rbegin(), v.rend());
for (auto [f, s] : v) vf.push_back(f), vs.push_back(s);
bool str = 0, flu = find(all(cnt), 5) != cnt.end();
if ((str = v.size() == 5))
for (int i = 1; i < 5; i++)
if (vs[i] != vs[i - 1] + 1) str = 0;
if (vs == vector<int>{12, 3, 2, 1, 0})
str = 1, vs = {3, 2, 1, 0, -1};
if (str && flu) type = 9;
else if (vf[0] == 4) type = 8;
else if (vf[0] == 3 && vf[1] == 2) type = 7;
else if (str || flu) type = 5 + flu;
else if (vf[0] == 3) type = 4;
else if (vf[0] == 2) type = 2 + (vf[1] == 2);
else type = 1;
}
bool operator<(const hand &b) const {
return make_tuple(type, vf, vs) <
make_tuple(b.type, b.vf, b.vs);
}
};
| 27.270833 | 59 | 0.496562 | [
"vector"
] |
11095c4db18458ac3426f0e9de5426c63608cb72 | 8,115 | cpp | C++ | src/legs_plugin.cpp | threeal/beine_gazebo_plugins | 787defb1238d131dde6afcb03e89de1d58e8688f | [
"MIT"
] | 1 | 2021-08-18T16:37:36.000Z | 2021-08-18T16:37:36.000Z | src/legs_plugin.cpp | threeal/beine_gazebo_plugins | 787defb1238d131dde6afcb03e89de1d58e8688f | [
"MIT"
] | 2 | 2021-04-29T09:01:37.000Z | 2021-04-30T08:06:31.000Z | src/legs_plugin.cpp | threeal/beine_gazebo_plugins | 787defb1238d131dde6afcb03e89de1d58e8688f | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Alfi Maulana
//
// 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 <beine_gazebo_plugins/legs_plugin.hpp>
#include <gazebo/physics/physics.hh>
#include <gazebo_ros/node.hpp>
#include <keisan/keisan.hpp>
#include <algorithm>
#include <map>
#include <memory>
#include <string>
namespace ksn = keisan;
namespace beine_gazebo_plugins
{
LegsPlugin::LegsPlugin()
: standing_joints_position({
{LEFT_HIP_PITCH, 0.0},
{LEFT_KNEE_PITCH, 0.0},
{LEFT_ANKLE_PITCH, 0.0},
{RIGHT_HIP_PITCH, 0.0},
{RIGHT_KNEE_PITCH, 0.0},
{RIGHT_ANKLE_PITCH, 0.0}
}),
sitting_joints_position({
{LEFT_HIP_PITCH, 45.0},
{LEFT_KNEE_PITCH, -90.0},
{LEFT_ANKLE_PITCH, 45.0},
{RIGHT_HIP_PITCH, 45.0},
{RIGHT_KNEE_PITCH, -90.0},
{RIGHT_ANKLE_PITCH, 45.0}
}),
translation_speed(2.0),
rotation_speed(2.0),
joint_force_strength(1000.0),
joint_force_smoothness(0.5)
{
}
void LegsPlugin::Load(gazebo::physics::ModelPtr model, sdf::ElementPtr sdf)
{
// Initialize the node
node = gazebo_ros::Node::Get(sdf);
// Initialize the legs consumer
{
beine_cpp::LegsConsumer::Options options;
options.legs_prefix = sdf->Get<std::string>("legs_prefix", options.legs_prefix).first;
legs_consumer = std::make_shared<beine_cpp::LegsConsumer>(node, options);
}
// Initialize the model
this->model = model;
// Initialize the joints
{
// Load joints name from the SDF
std::map<std::string, Joint> joints_name;
{
// Map of joint enum and SDF parameter
std::map<Joint, std::string> sdfs_name = {
{LEFT_HIP_PITCH, "left_hip_pitch_joint"},
{LEFT_KNEE_PITCH, "left_knee_pitch_joint"},
{LEFT_ANKLE_PITCH, "left_ankle_pitch_joint"},
{RIGHT_HIP_PITCH, "right_hip_pitch_joint"},
{RIGHT_KNEE_PITCH, "right_knee_pitch_joint"},
{RIGHT_ANKLE_PITCH, "right_ankle_pitch_joint"}
};
// Add each SDF parameter's value to joints name map
for (const auto & sdf_name_pair : sdfs_name) {
auto joint_name = sdf->Get<std::string>(sdf_name_pair.second, sdf_name_pair.second).first;
joints_name.emplace(joint_name, sdf_name_pair.first);
}
}
// Map the simulation joints according to the joint_name
for (const auto & joint : model->GetJoints()) {
// Skip if joint is fixed (does not have an axis)
if ((joint->GetType() & gazebo::physics::Joint::FIXED_JOINT) != 0) {
continue;
}
// Find joint index by name
const auto & joint_name_pair = joints_name.find(joint->GetName());
if (joint_name_pair != joints_name.end()) {
joints.emplace(joint_name_pair->second, joint);
}
}
// Log joints result
if (joints.size() > 0) {
if (joints.size() < 6) {
RCLCPP_WARN(node->get_logger(), "Some joint not found!");
}
std::stringstream ss;
ss << "\nFound joints:";
for (const auto & joint : joints) {
ss << "\n- " << joint.second->GetName();
}
RCLCPP_INFO(node->get_logger(), ss.str());
} else {
RCLCPP_WARN(node->get_logger(), "No joints found!");
}
}
// Load parameters from the SDF
{
translation_speed = sdf->Get<double>("translation_speed", translation_speed).first;
rotation_speed = sdf->Get<double>("rotation_speed", rotation_speed).first;
joint_force_strength = sdf->Get<double>("joint_force_strength", joint_force_strength).first;
joint_force_smoothness = sdf->Get<double>(
"joint_force_smoothness", joint_force_smoothness).first;
RCLCPP_INFO_STREAM(
node->get_logger(), "\nUsing the following parameters:" <<
"\n- translation_speed\t: " << translation_speed <<
"\n- rotation_speed\t\t: " << rotation_speed <<
"\n- joint_force_strength\t: " << joint_force_strength <<
"\n- joint_force_smoothness\t: " << joint_force_smoothness);
}
// Initialize the update connection
{
update_connection = gazebo::event::Events::ConnectWorldUpdateBegin(
std::bind(&LegsPlugin::Update, this)
);
RCLCPP_INFO(node->get_logger(), "Connected to the world update!");
}
}
void LegsPlugin::Update()
{
// Move Position and Orientation
MovePosition(legs_consumer->get_position());
MoveOrientation(legs_consumer->get_orientation());
// Move joints according to current stance
if (legs_consumer->get_stance().is_sitting()) {
MoveJointsPosition(sitting_joints_position);
} else {
MoveJointsPosition(standing_joints_position);
}
}
void LegsPlugin::MovePosition(const beine_cpp::Position & target_position)
{
// Get current simulation position
const auto & pos = model->WorldPose().Pos();
auto current = ksn::Point2(pos.X(), pos.Y());
// Get target position
auto target = ksn::Point2(target_position.x, target_position.y);
// Calculate velocity based on current and target position
auto velocity = target - current;
if (velocity.magnitude() > 1.0) {
velocity = velocity.normalize();
}
velocity *= translation_speed;
// Keep the gravity
auto gravity = std::min(model->WorldLinearVel().Z(), 0.0);
// Modify the simulation velocity
model->SetLinearVel({velocity.x, velocity.y, gravity});
}
void LegsPlugin::MoveOrientation(const beine_cpp::Orientation & target_orientation)
{
// Get current simulation yaw orientation
auto rot = model->WorldPose().Rot();
auto current = ksn::make_radian(rot.Yaw());
// Get target yaw orientation
auto target = ksn::make_degree(target_orientation.z);
// Calculate velocity based on current and target yaw orientation
auto velocity = current.difference_to(target).normalize();
// Modify the simulation velocity
model->SetAngularVel({0.0, 0.0, velocity.radian() * rotation_speed});
// Lock pitch and roll rotations
{
auto pose = model->RelativePose();
auto rot = pose.Rot();
// Only keep the yaw rotation
rot.Euler(0.0, 0.0, rot.Yaw());
pose.Set(pose.Pos(), rot);
model->SetRelativePose(pose);
}
}
void LegsPlugin::MoveJointsPosition(const std::map<Joint, double> & target_joints_position)
{
// For each simulation joint
for (const auto & joint_pair : joints) {
const auto & target_pair = target_joints_position.find(joint_pair.first);
if (target_pair != target_joints_position.end()) {
// Get current simulation joint position
auto current = ksn::make_radian(joint_pair.second->Position());
// Get Target joint position
auto target = ksn::make_degree(target_pair->second);
// Calculate force based on current and target joint position
auto delta = current.difference_to(target).normalize();
// This equation cause the graph to increase slowly the larger the x is
// see the graph of x ^ 1/2.
auto force = ksn::sign(delta) *
std::pow(std::abs(delta.radian()), joint_force_smoothness) * joint_force_strength;
// Modify the simulation joint force on axis 0
joint_pair.second->SetForce(0, force);
}
}
}
GZ_REGISTER_MODEL_PLUGIN(LegsPlugin)
} // namespace beine_gazebo_plugins
| 32.075099 | 98 | 0.688478 | [
"model"
] |
110d2841897b81862f716d154df1c29ab842eb82 | 237 | hh | C++ | src/Titon/Intl/locales/de/locale.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 206 | 2015-01-02T20:01:12.000Z | 2021-04-15T09:49:56.000Z | src/Titon/Intl/locales/de/locale.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 44 | 2015-01-02T06:03:43.000Z | 2017-11-20T18:29:06.000Z | src/Titon/Intl/locales/de/locale.hh | titon/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 27 | 2015-01-03T05:51:29.000Z | 2022-02-21T13:50:40.000Z | <?hh
// German (Standard)
return Map {
'code' => 'de',
'iso2' => 'de',
'iso3' => Vector {'ger', 'deu'},
'timezone' => 'Europe/Berlin',
'title' => 'German (Standard)',
'plural' => Titon\Intl\PluralRule::RULE_2
};
| 19.75 | 45 | 0.518987 | [
"vector"
] |
11135cf7b16d1f41f7e6d827db61b1f64edbb2fb | 6,348 | cpp | C++ | arbor/cv_policy.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 53 | 2018-10-18T12:08:21.000Z | 2022-03-26T22:03:51.000Z | arbor/cv_policy.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 864 | 2018-10-01T08:06:00.000Z | 2022-03-31T08:06:48.000Z | arbor/cv_policy.cpp | kanzl/arbor | 86b1eb065ac252bf0026de7cf7cbc6748a528254 | [
"BSD-3-Clause"
] | 37 | 2019-03-03T16:18:49.000Z | 2022-03-24T10:39:51.000Z | #include <utility>
#include <ostream>
#include <vector>
#include <arbor/cable_cell.hpp>
#include <arbor/cv_policy.hpp>
#include <arbor/morph/locset.hpp>
#include <arbor/morph/region.hpp>
#include "util/rangeutil.hpp"
#include "util/span.hpp"
// Discretization policy implementations:
namespace arb {
static auto unique_sum = [](auto&&... lss) {
return ls::support(sum(std::forward<decltype(lss)>(lss)...));
};
// Combinators:
// cv_policy_plus_ represents the result of operator+,
// cv_policy_bar_ represents the result of operator|.
struct cv_policy_plus_: cv_policy_base {
cv_policy_plus_(const cv_policy& lhs, const cv_policy& rhs):
lhs_(lhs), rhs_(rhs) {}
cv_policy_base_ptr clone() const override {
return cv_policy_base_ptr(new cv_policy_plus_(*this));
}
locset cv_boundary_points(const cable_cell& c) const override {
return unique_sum(lhs_.cv_boundary_points(c), rhs_.cv_boundary_points(c));
}
region domain() const override { return join(lhs_.domain(), rhs_.domain()); }
std::ostream& print(std::ostream& os) override {
os << "(join " << lhs_ << ' ' << rhs_ << ')';
return os;
}
cv_policy lhs_, rhs_;
};
cv_policy operator+(const cv_policy& lhs, const cv_policy& rhs) {
return cv_policy_plus_(lhs, rhs);
}
struct cv_policy_bar_: cv_policy_base {
cv_policy_bar_(const cv_policy& lhs, const cv_policy& rhs):
lhs_(lhs), rhs_(rhs) {}
cv_policy_base_ptr clone() const override {
return cv_policy_base_ptr(new cv_policy_bar_(*this));
}
locset cv_boundary_points(const cable_cell& c) const override {
return unique_sum(ls::restrict(lhs_.cv_boundary_points(c), complement(rhs_.domain())), rhs_.cv_boundary_points(c));
}
region domain() const override { return join(lhs_.domain(), rhs_.domain()); }
std::ostream& print(std::ostream& os) override {
os << "(replace " << lhs_ << ' ' << rhs_ << ')';
return os;
}
cv_policy lhs_, rhs_;
};
cv_policy operator|(const cv_policy& lhs, const cv_policy& rhs) {
return cv_policy_bar_(lhs, rhs);
}
// Public policy implementations:
// cv_policy_explicit
locset cv_policy_explicit::cv_boundary_points(const cable_cell& cell) const {
return
ls::support(
util::foldl(
[this](locset l, const auto& comp) {
return sum(std::move(l), ls::restrict(locs_, comp));
},
ls::boundary(domain_),
components(cell.morphology(), thingify(domain_, cell.provider()))));
}
cv_policy_base_ptr cv_policy_explicit::clone() const {
return cv_policy_base_ptr(new cv_policy_explicit(*this));
}
region cv_policy_explicit::domain() const { return domain_; }
// cv_policy_single
locset cv_policy_single::cv_boundary_points(const cable_cell&) const {
return ls::cboundary(domain_);
}
cv_policy_base_ptr cv_policy_single::clone() const {
return cv_policy_base_ptr(new cv_policy_single(*this));
}
region cv_policy_single::domain() const { return domain_; }
// cv_policy_max_extent
locset cv_policy_max_extent::cv_boundary_points(const cable_cell& cell) const {
const unsigned nbranch = cell.morphology().num_branches();
const auto& embed = cell.embedding();
if (!nbranch || max_extent_<=0) return ls::nil();
std::vector<mlocation> points;
double oomax_extent = 1./max_extent_;
auto comps = components(cell.morphology(), thingify(domain_, cell.provider()));
for (auto& comp: comps) {
for (mcable c: comp) {
double cable_length = embed.integrate_length(c);
unsigned ncv = std::ceil(cable_length*oomax_extent);
double scale = (c.dist_pos-c.prox_pos)/ncv;
if (flags_&cv_policy_flag::interior_forks) {
for (unsigned i = 0; i<ncv; ++i) {
points.push_back({c.branch, c.prox_pos+(1+2*i)*scale/2});
}
}
else {
for (unsigned i = 0; i<ncv; ++i) {
points.push_back({c.branch, c.prox_pos+i*scale});
}
points.push_back({c.branch, c.dist_pos});
}
}
}
util::sort(points);
return unique_sum(locset(std::move(points)), ls::cboundary(domain_));
}
cv_policy_base_ptr cv_policy_max_extent::clone() const {
return cv_policy_base_ptr(new cv_policy_max_extent(*this));
}
region cv_policy_max_extent::domain() const { return domain_; }
// cv_policy_fixed_per_branch
locset cv_policy_fixed_per_branch::cv_boundary_points(const cable_cell& cell) const {
const unsigned nbranch = cell.morphology().num_branches();
if (!nbranch) return ls::nil();
std::vector<mlocation> points;
double ooncv = 1./cv_per_branch_;
auto comps = components(cell.morphology(), thingify(domain_, cell.provider()));
for (auto& comp: comps) {
for (mcable c: comp) {
double scale = (c.dist_pos-c.prox_pos)*ooncv;
if (flags_&cv_policy_flag::interior_forks) {
for (unsigned i = 0; i<cv_per_branch_; ++i) {
points.push_back({c.branch, c.prox_pos+(1+2*i)*scale/2});
}
}
else {
for (unsigned i = 0; i<cv_per_branch_; ++i) {
points.push_back({c.branch, c.prox_pos+i*scale});
}
points.push_back({c.branch, c.dist_pos});
}
}
}
util::sort(points);
return unique_sum(locset(std::move(points)), ls::cboundary(domain_));
}
cv_policy_base_ptr cv_policy_fixed_per_branch::clone() const {
return cv_policy_base_ptr(new cv_policy_fixed_per_branch(*this));
}
region cv_policy_fixed_per_branch::domain() const { return domain_; }
// cv_policy_every_segment
locset cv_policy_every_segment::cv_boundary_points(const cable_cell& cell) const {
const unsigned nbranch = cell.morphology().num_branches();
if (!nbranch) return ls::nil();
return unique_sum(
ls::cboundary(domain_),
ls::restrict(ls::segment_boundaries(), domain_));
}
cv_policy_base_ptr cv_policy_every_segment::clone() const {
return cv_policy_base_ptr(new cv_policy_every_segment(*this));
}
region cv_policy_every_segment::domain() const { return domain_; }
} // namespace arb
| 31.425743 | 123 | 0.64666 | [
"vector"
] |
111af2cb6fa7665ad8847675cb64523a57746e05 | 5,881 | cpp | C++ | Source/ExistenceApps/ExistenceComponents/Entity.cpp | vivienneanthony/Urho3D-Mastercurrent-Existence | 2d75021489996e1abc2fd330ed967cd89a62f40d | [
"Apache-2.0"
] | 3 | 2015-05-22T23:39:03.000Z | 2016-04-13T03:52:59.000Z | Source/ExistenceApps/ExistenceComponents/Entity.cpp | vivienneanthony/Urho3D-Mastercurrent-Existence | 2d75021489996e1abc2fd330ed967cd89a62f40d | [
"Apache-2.0"
] | null | null | null | Source/ExistenceApps/ExistenceComponents/Entity.cpp | vivienneanthony/Urho3D-Mastercurrent-Existence | 2d75021489996e1abc2fd330ed967cd89a62f40d | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2008-2014 the Urho3D project.
//
// 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 <Urho3D/Urho3D.h>
#include "../../../Urho3D/Graphics/AnimationController.h"
#include "../../../Urho3D/Core/Context.h"
#include "../../../Urho3D/IO/MemoryBuffer.h"
#include "../../../Urho3D/Physics/PhysicsEvents.h"
#include "../../../Urho3D/Physics/PhysicsWorld.h"
#include "../../../Urho3D/Physics/RigidBody.h"
#include "../../../Urho3D/Scene/Scene.h"
#include "../../../Urho3D/Scene/SceneEvents.h"
#include "../../../Urho3D/Graphics/StaticModel.h"
#include "../../../Urho3D/Graphics/AnimatedModel.h"
#include "Character.h"
#include "Entity.h"
#include <iostream>
using namespace std;
using namespace Urho3D;
/// create a entity
Entity::Entity(Context* context) :
LogicComponent(context)
{
/// Initalize information
CharacterEntity.firstname="";
CharacterEntity.middlename="";
CharacterEntity.lastname="";
CharacterEntity.health= 0;
/// player moves for surface of planet to a ship so it relations change for the x,y,z for respective object
CharacterEntity.reputation1= 0;
CharacterEntity.reputation2= 0;
CharacterEntity.reputation3= 0;
CharacterEntity.reputation4= 0;
CharacterEntity.reputation5= 0;
/// Set player experience
CharacterEntity.experience = 0;
CharacterEntity.personalitytrait=0;
/// Charcter specs
CharacterEntity.alienrace=0;
CharacterEntity.alienalliancealigned=0;
CharacterEntity.gender=0;
// Only the physics update event is needed: unsubscribe from the rest for optimization
SetUpdateEventMask(USE_FIXEDUPDATE);
}
/// Set and get the character health
int Entity::SetHealth(int health)
{
CharacterEntity.health = health;
return 1;
}
int Entity::GetHealth(void)
{
return CharacterEntity.health;
}
/// Don nothing now;
void Entity::Start(void)
{
return;
}
int Entity::Clear(void)
{
return 1;
}
/// Get player characteristics
playercharacteristics Entity::GetCharacteristics(void)
{
/// Charcter specs
playercharacteristics Temporarycharacteristics;
Temporarycharacteristics.gender = CharacterEntity.gender;
Temporarycharacteristics.personalitytrait=CharacterEntity.personalitytrait;
return Temporarycharacteristics;
}
/// Get player alliance
playeralliance Entity::GetAlliance(void)
{
/// Charcter specs
playeralliance Temporaryalliance;
Temporaryalliance.alienrace = CharacterEntity.alienrace;
Temporaryalliance.alienalliancealigned=CharacterEntity.alienalliancealigned;
return Temporaryalliance;
}
/// Set player characteristics
int Entity::SetCharacteristics(playercharacteristics TempCharacteristics)
{
/// Set character charactistics
CharacterEntity.gender= TempCharacteristics.gender;
CharacterEntity.personalitytrait= TempCharacteristics.personalitytrait;
return 1;
}
/// Set player alliance
int Entity::SetAlliance(playeralliance TempAlliance)
{
/// Set charcter alliance
CharacterEntity.alienrace=TempAlliance.alienrace;
CharacterEntity.alienalliancealigned=TempAlliance.alienalliancealigned;
return 1;
}
int Entity::SetEntityInfo(playerbasicinfo TempEntity)
{
/// Set charcter alliance
CharacterEntity.firstname=TempEntity.firstname;
CharacterEntity.middlename=TempEntity.middlename;
CharacterEntity.lastname=TempEntity.lastname;
return 1;
}
/// Entity GetEntityInfo
playerbasicinfo Entity::GetEntityInfo(void)
{
/// Charcter specs
playerbasicinfo Temporarybasicinfo;
/// Set charcter alliance
Temporarybasicinfo.firstname = CharacterEntity.firstname;
Temporarybasicinfo.middlename = CharacterEntity.middlename;
Temporarybasicinfo.lastname = CharacterEntity.lastname;
return Temporarybasicinfo;
}
/// Entity Register Object
void Entity::RegisterObject(Context* context)
{
context->RegisterFactory<Entity>("Existence");
return;
}
/// Entity Handle Node Collision
void Entity::HandleNodeCollision(StringHash eventType, VariantMap& eventData)
{
using namespace NodeCollision;
// Get the other colliding body, make sure it is moving (has nonzero mass)
RigidBody* otherBody = (RigidBody*)eventData[P_OTHERBODY].GetPtr();
Node* otherNode = (Node*)eventData[P_OTHERNODE].GetPtr();
// If the other collision shape belongs to static geometry, perform world collision
StaticModel * staticmodelreference= otherNode->GetComponent<StaticModel>();
AnimatedModel * animatedmodelreference = otherNode->GetComponent<AnimatedModel>();
if (otherBody->GetCollisionLayer() == 2)
{
OnNodeCollision(eventType, eventData);
}
return;
}
/// Entity FixedUpdate
void Entity::FixedUpdate(float timeStep)
{
return;
}
void Entity::OnNodeCollision(StringHash eventType, VariantMap& eventData)
{
return;
}
| 27.101382 | 111 | 0.743241 | [
"geometry",
"object",
"shape"
] |
111e8b46a3dba1088b7db5e3cbfe78deb07b7316 | 4,254 | hpp | C++ | libs/tweedledum/utils/sat/solver.hpp | wjyoumans/staq | d5227bd4651ce64ba277aab5061e3a132be853bb | [
"MIT"
] | 96 | 2019-12-11T10:18:10.000Z | 2022-03-27T20:16:33.000Z | libs/tweedledum/utils/sat/solver.hpp | wjyoumans/staq | d5227bd4651ce64ba277aab5061e3a132be853bb | [
"MIT"
] | 43 | 2020-01-08T00:59:07.000Z | 2022-03-28T21:35:59.000Z | libs/tweedledum/utils/sat/solver.hpp | wjyoumans/staq | d5227bd4651ce64ba277aab5061e3a132be853bb | [
"MIT"
] | 21 | 2019-12-15T01:40:48.000Z | 2021-12-31T05:27:34.000Z | /*-------------------------------------------------------------------------------------------------
| This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
| Author(s): Bruno Schmitt
*------------------------------------------------------------------------------------------------*/
#pragma once
#include "glucose/glucose.hpp"
#include "types.hpp"
#include <cstdint>
#include <variant>
#include <vector>
namespace tweedledum::sat {
class result {
public:
using model_type = std::vector<lbool_type>;
using clause_type = std::vector<lit_type>;
enum class states : uint8_t {
satisfiable,
unsatisfiable,
undefined,
timeout,
};
result(states state = states::undefined) : state_(state) {}
result(model_type const& model)
: state_(states::satisfiable), data_(model) {}
result(clause_type const& unsat_core)
: state_(states::unsatisfiable), data_(unsat_core) {}
#pragma region Properties
inline bool is_satisfiable() const {
return (state_ == states::satisfiable);
}
inline bool is_unsatisfiable() const {
return (state_ == states::unsatisfiable);
}
inline bool is_undefined() const { return (state_ == states::undefined); }
inline model_type model() const { return std::get<model_type>(data_); }
#pragma endregion
#pragma region Overloads
inline operator bool() const { return (state_ == states::satisfiable); }
#pragma endregion
private:
states state_;
std::variant<model_type, clause_type> data_;
};
enum class solvers {
glucose_41,
};
template <solvers Solver = solvers::glucose_41>
class solver;
template <>
class solver<solvers::glucose_41> {
using solver_type = Glucose::Solver;
public:
#pragma region Constructors
solver() : solver_(std::make_unique<solver_type>()) {}
#pragma endregion
#pragma region Modifiers
var_type add_variable() { return solver_->newVar(); }
void add_variables(uint32_t num_variables = 1) {
for (auto i = 0u; i < num_variables; ++i) {
solver_->newVar();
}
}
auto add_clause(std::vector<lit_type> const& clause) {
Glucose::vec<Glucose::Lit> literals;
for (auto lit : clause) {
literals.push(
Glucose::mkLit(lit.variable(), lit.is_complemented()));
}
return solver_->addClause_(literals);
}
result solve(std::vector<lit_type> const& assumptions = {},
uint32_t conflict_limit = 0) {
assert(solver_->okay() == true);
if (conflict_limit) {
solver_->setConfBudget(conflict_limit);
}
Glucose::vec<Glucose::Lit> literals;
for (auto lit : assumptions) {
literals.push(
Glucose::mkLit(lit.variable(), lit.is_complemented()));
}
Glucose::lbool state = solver_->solveLimited(literals);
if (state == l_True) {
result::model_type model;
for (auto i = 0; i < solver_->model.size(); ++i) {
if (solver_->model[i] == l_False) {
model.emplace_back(lbool_type::false_);
} else if (solver_->model[i] == l_True) {
model.emplace_back(lbool_type::true_);
} else {
model.emplace_back(lbool_type::undefined);
}
}
return result(model);
} else if (state == l_False) {
result::clause_type unsat_core;
for (auto i = 0; i < solver_->conflict.size(); ++i) {
unsat_core.emplace_back(Glucose::var(solver_->conflict[i]),
Glucose::sign(solver_->conflict[i])
? negative_polarity
: positive_polarity);
}
return result(unsat_core);
}
return result();
}
#pragma endregion
#pragma region Properties
uint32_t num_variables() const { return solver_->nVars(); }
uint32_t num_clauses() const { return solver_->nClauses(); }
#pragma endregion
private:
std::unique_ptr<solver_type> solver_;
};
} // namespace tweedledum::sat | 29.541667 | 99 | 0.563235 | [
"vector",
"model"
] |
11213460873a01ee17cf8b15592366f0c4a5b0ce | 10,611 | hpp | C++ | include/eos/pca/pca.hpp | faceshiftlabs/eos | 13f3add0bd570855cb3d339f659694a25d366c49 | [
"Apache-2.0"
] | 1,738 | 2015-09-09T16:18:53.000Z | 2022-03-30T04:03:01.000Z | include/eos/pca/pca.hpp | faceshiftlabs/eos | 13f3add0bd570855cb3d339f659694a25d366c49 | [
"Apache-2.0"
] | 317 | 2015-09-04T13:34:19.000Z | 2022-02-04T22:41:01.000Z | include/eos/pca/pca.hpp | faceshiftlabs/eos | 13f3add0bd570855cb3d339f659694a25d366c49 | [
"Apache-2.0"
] | 565 | 2015-08-31T10:57:04.000Z | 2022-03-09T04:08:54.000Z | /*
* eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/pca/pca.hpp
*
* Copyright 2017 Patrik Huber
*
* 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
#ifndef PCA_HPP_
#define PCA_HPP_
#include "eos/morphablemodel/PcaModel.hpp"
#include "Eigen/Core"
#include "Eigen/Eigenvalues"
#include <array>
#include <cassert>
#include <utility>
#include <vector>
namespace eos {
namespace pca {
/**
* A flag specifying how to compute the covariance matrix in the PCA.
*/
enum class Covariance {
AtA, ///< Compute the traditional covariance matrix A^t*A.
AAt ///< Use the inner product, A*A^t, for the covariance matrix.
};
/**
* @brief Compute PCA on a mean-centred data matrix, and return the eigenvectors and respective eigenvalues.
*
* Computes PCA (principal component analysis) on the given mean-centred data matrix. Note that you
* should subtract the mean from the data beforehand, this function will not do so.
* The function computes PCA based on an eigendecomposition of the covariance matrix.
* If the dimensionality of the data is high, the PCA can be computed on the inner-product matrix
* A*A^t instead of the covariance matrix A^t*A by setting the flag \c Covariance::AAt.
*
* The function returns n-1 eigenvectors and eigenvalues, where n is the number of data samples given.
* The eigenvectors and eigenvalues are returned in descending order, with the largest (most significant)
* first.
*
* Note: Changing the \p covariance_type may return eigenvectors with different signs, but otherwise
* equivalent. This is completely fine as the sign of eigenvectors is arbitrary anyway.
*
*
* Developer notes:
* If you want to avoid a copy: myarray = np.array(source, order='F') (this will change
* the numpy array to colmajor, so Eigen can directly accept it.
* There is other ways how to avoid copies:
* See: https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html.
* http://pybind11.readthedocs.io/en/master/advanced/cast/eigen.html
* Also it would be nice if the function could accept any Eigen matrix types (e.g. a MatrixXf or MatrixXd).
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
MatrixXf cov;
if (covariance_type == Covariance::AtA)
{
cov = data.adjoint() * data;
} else if (covariance_type == Covariance::AAt)
{
cov = data * data.adjoint();
}
// The covariance is 1/(n-1) * AtA (or AAt), so divide by (num_samples - 1):
cov /= (data.rows() - 1);
const Eigen::SelfAdjointEigenSolver<MatrixXf> eig(cov);
const auto num_eigenvectors_to_keep = data.rows() - 1;
// Select the eigenvectors and eigenvalues that we want to keep, reverse them (from most significant to
// least): For 'n' data points, we get at most 'n - 1' non-zero eigenvalues.
VectorXf eigenvalues = eig.eigenvalues()
.bottomRows(num_eigenvectors_to_keep)
.reverse(); // eigenvalues() returns a column-vec
MatrixXf eigenvectors = eig.eigenvectors().rightCols(num_eigenvectors_to_keep).rowwise().reverse();
if (covariance_type == Covariance::AAt)
{
// Bring the AA^t variant in the right form by multiplying with A^t and 1/sqrt(eval):
// (see e.g. https://math.stackexchange.com/questions/787822/how-do-covariance-matrix-c-aat-justify-the-actual-ata-in-pca)
// (note the signs might be different from the AtA solution but that's not a problem as the sign of
// eigenvectors are arbitrary anyway)
eigenvectors = data.adjoint() * eigenvectors;
// Multiply each eigenvector (column) with one over the square root of its respective eigenvalue
// (1/sqrt(eigenvalue(i))): (this is a neat short-hand notation, see
// https://stackoverflow.com/a/42945996/1345959).
const VectorXf one_over_sqrt_eigenvalues = eigenvalues.array().rsqrt();
eigenvectors *= one_over_sqrt_eigenvalues.asDiagonal();
// Compensate for the covariance division by (n - 1) above:
eigenvectors /= std::sqrt(data.rows() - 1);
}
return { eigenvectors, eigenvalues };
};
/**
* @brief Performs PCA and returns \p num_eigenvectors_to_keep eigenvectors and eigenvalues.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance).
*
* \p num_eigenvectors_to_keep needs to be smaller or equal to n-1, where n is number of rows of data (i.e.
* number of data samples).
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] num_eigenvectors_to_keep Specifies how many eigenvectors and eigenvalues to keep.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data,
int num_eigenvectors_to_keep,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(data, covariance_type);
// Reduce the basis and eigenvalues, and return:
assert(num_eigenvectors_to_keep <= eigenvectors.size());
return { eigenvectors.leftCols(num_eigenvectors_to_keep), eigenvalues.topRows(num_eigenvectors_to_keep) };
};
/**
* @brief Performs PCA and returns the number of eigenvectors and eigenvalues to retain \p variance_to_keep
* variance of the original data.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance).
*
* \p variance_to_keep needs to be between 0.0 and 1.0.
*
* @param[in] data Mean-free data matrix, with each row being a training sample.
* @param[in] variance_to_keep Specifies how much of the variance to retain, in percent (between 0 and 1).
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A pair containing the matrix of eigenvectors and a vector with the respective eigenvalues.
*/
inline std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf> data,
float variance_to_keep,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
assert(variance_to_keep >= 0.0f && variance_to_keep <= 1.0f);
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(data, covariance_type);
// Figure out how many coeffs to keep:
// variance_explained_by_first_comp = eigenval(1)/sum(eigenvalues)
// variance_explained_by_second_comp = eigenval(2)/sum(eigenvalues), etc.
auto num_eigenvectors_to_keep = eigenvalues.size(); // In the "worst" case we return all eigenvectors.
const auto total_sum = eigenvalues.sum();
float cum_sum = 0.0f;
for (int i = 0; i < eigenvalues.size(); ++i)
{
cum_sum += eigenvalues(i);
// If the current variation explained is larger or equal to the amount of variation that
// the user requested to keep, we're done:
if (cum_sum / total_sum >= variance_to_keep)
{
num_eigenvectors_to_keep = i + 1;
break;
}
}
// Reduce the basis and eigenvalues, and return:
assert(num_eigenvectors_to_keep <= eigenvectors.size());
return { eigenvectors.leftCols(num_eigenvectors_to_keep), eigenvalues.topRows(num_eigenvectors_to_keep) };
};
/**
* @brief Performs PCA on the given data (including subtracting the mean) and returns the built PcaModel.
*
* See std::pair<Eigen::MatrixXf, Eigen::VectorXf> pca(const Eigen::Ref<const Eigen::MatrixXf>, Covariance)
* for the details on the PCA.
*
* \p data should be a (num_training_samples x num_data_dimensions) matrix, i.e. each row one data instance
* (e.g. one 3D scan).
*
* @param[in] data Data matrix (orignal, without the mean subtracted), with each row being a training sample.
* @param[in] triangle_list Triangle list to build the topology of the PcaModel mesh.
* @param[in] covariance_type Specifies whether PCA is computed on the covariance matrix AtA (default) or the
* inner-product matrix AAt.
* @return A PcaModel constructed from the given data.
*/
inline morphablemodel::PcaModel pca(const Eigen::Ref<const Eigen::MatrixXf> data,
std::vector<std::array<int, 3>> triangle_list,
Covariance covariance_type = Covariance::AtA)
{
using Eigen::MatrixXf;
using Eigen::VectorXf;
// Compute the mean and mean-free data matrix:
// Each row is one instance of data (e.g. a 3D scan)
const VectorXf mean = data.colwise().mean();
const MatrixXf meanfree_data = data.rowwise() - mean.transpose();
// Carry out PCA and return the constructed model:
VectorXf eigenvalues;
MatrixXf eigenvectors;
std::tie(eigenvectors, eigenvalues) = pca(meanfree_data, covariance_type);
return morphablemodel::PcaModel(mean, eigenvectors, eigenvalues, triangle_list);
};
} /* namespace pca */
} /* namespace eos */
#endif /* PCA_HPP_ */
| 43.310204 | 130 | 0.693431 | [
"mesh",
"vector",
"model",
"3d"
] |
11247a860ce67a768db0bab74d08c638311d6dee | 21,779 | cpp | C++ | be/src/exec/base_scanner.cpp | kuolei/incubator-doris | b14678c0021896f11efdfdaa3e2dad15b2d4868d | [
"Apache-2.0"
] | 1 | 2022-02-22T15:03:57.000Z | 2022-02-22T15:03:57.000Z | be/src/exec/base_scanner.cpp | kuolei/incubator-doris | b14678c0021896f11efdfdaa3e2dad15b2d4868d | [
"Apache-2.0"
] | null | null | null | be/src/exec/base_scanner.cpp | kuolei/incubator-doris | b14678c0021896f11efdfdaa3e2dad15b2d4868d | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "base_scanner.h"
#include <fmt/format.h>
#include "common/logging.h"
#include "common/utils.h"
#include "exec/exec_node.h"
#include "exprs/expr_context.h"
#include "runtime/descriptors.h"
#include "runtime/mem_tracker.h"
#include "runtime/raw_value.h"
#include "runtime/runtime_state.h"
#include "runtime/tuple.h"
#include "vec/data_types/data_type_factory.hpp"
namespace doris {
BaseScanner::BaseScanner(RuntimeState* state, RuntimeProfile* profile,
const TBrokerScanRangeParams& params,
const std::vector<TBrokerRangeDesc>& ranges,
const std::vector<TNetworkAddress>& broker_addresses,
const std::vector<TExpr>& pre_filter_texprs, ScannerCounter* counter)
: _state(state),
_params(params),
_ranges(ranges),
_broker_addresses(broker_addresses),
_next_range(0),
_counter(counter),
_src_tuple(nullptr),
_src_tuple_row(nullptr),
#if BE_TEST
_mem_tracker(new MemTracker()),
#else
_mem_tracker(MemTracker::create_tracker(
-1, state->query_type() == TQueryType::LOAD
? "BaseScanner:" + std::to_string(state->load_job_id())
: "BaseScanner:Select")),
#endif
_mem_pool(std::make_unique<MemPool>(_mem_tracker.get())),
_dest_tuple_desc(nullptr),
_pre_filter_texprs(pre_filter_texprs),
_strict_mode(false),
_line_counter(0),
_profile(profile),
_rows_read_counter(nullptr),
_read_timer(nullptr),
_materialize_timer(nullptr),
_success(false),
_scanner_eof(false) {
}
Status BaseScanner::open() {
RETURN_IF_ERROR(init_expr_ctxes());
if (_params.__isset.strict_mode) {
_strict_mode = _params.strict_mode;
}
if (_strict_mode && !_params.__isset.dest_sid_to_src_sid_without_trans) {
return Status::InternalError("Slot map of dest to src must be set in strict mode");
}
_rows_read_counter = ADD_COUNTER(_profile, "RowsRead", TUnit::UNIT);
_read_timer = ADD_TIMER(_profile, "TotalRawReadTime(*)");
_materialize_timer = ADD_TIMER(_profile, "MaterializeTupleTime(*)");
DCHECK(!_ranges.empty());
const auto& range = _ranges[0];
_num_of_columns_from_file = range.__isset.num_of_columns_from_file
? implicit_cast<int>(range.num_of_columns_from_file)
: implicit_cast<int>(_src_slot_descs.size());
// check consistency
if (range.__isset.num_of_columns_from_file) {
int size = range.columns_from_path.size();
for (const auto& r : _ranges) {
if (r.columns_from_path.size() != size) {
return Status::InternalError("ranges have different number of columns.");
}
}
}
return Status::OK();
}
Status BaseScanner::init_expr_ctxes() {
// Construct _src_slot_descs
const TupleDescriptor* src_tuple_desc =
_state->desc_tbl().get_tuple_descriptor(_params.src_tuple_id);
if (src_tuple_desc == nullptr) {
std::stringstream ss;
ss << "Unknown source tuple descriptor, tuple_id=" << _params.src_tuple_id;
return Status::InternalError(ss.str());
}
std::map<SlotId, SlotDescriptor*> src_slot_desc_map;
for (auto slot_desc : src_tuple_desc->slots()) {
src_slot_desc_map.emplace(slot_desc->id(), slot_desc);
}
for (auto slot_id : _params.src_slot_ids) {
auto it = src_slot_desc_map.find(slot_id);
if (it == std::end(src_slot_desc_map)) {
std::stringstream ss;
ss << "Unknown source slot descriptor, slot_id=" << slot_id;
return Status::InternalError(ss.str());
}
_src_slot_descs.emplace_back(it->second);
}
// Construct source tuple and tuple row
_src_tuple = (Tuple*)_mem_pool->allocate(src_tuple_desc->byte_size());
_src_tuple_row = (TupleRow*)_mem_pool->allocate(sizeof(Tuple*));
_src_tuple_row->set_tuple(0, _src_tuple);
_row_desc.reset(new RowDescriptor(_state->desc_tbl(),
std::vector<TupleId>({_params.src_tuple_id}),
std::vector<bool>({false})));
// preceding filter expr should be initialized by using `_row_desc`, which is the source row descriptor
if (!_pre_filter_texprs.empty()) {
if (_state->enable_vectorized_exec()) {
// for vectorized, preceding filter exprs should be compounded to one passed from fe.
DCHECK(_pre_filter_texprs.size() == 1);
_vpre_filter_ctx_ptr.reset(new doris::vectorized::VExprContext*);
RETURN_IF_ERROR(vectorized::VExpr::create_expr_tree(
_state->obj_pool(), _pre_filter_texprs[0], _vpre_filter_ctx_ptr.get()));
RETURN_IF_ERROR((*_vpre_filter_ctx_ptr)->prepare(_state, *_row_desc, _mem_tracker));
RETURN_IF_ERROR((*_vpre_filter_ctx_ptr)->open(_state));
} else {
RETURN_IF_ERROR(Expr::create_expr_trees(_state->obj_pool(), _pre_filter_texprs,
&_pre_filter_ctxs));
RETURN_IF_ERROR(Expr::prepare(_pre_filter_ctxs, _state, *_row_desc, _mem_tracker));
RETURN_IF_ERROR(Expr::open(_pre_filter_ctxs, _state));
}
}
// Construct dest slots information
_dest_tuple_desc = _state->desc_tbl().get_tuple_descriptor(_params.dest_tuple_id);
if (_dest_tuple_desc == nullptr) {
std::stringstream ss;
ss << "Unknown dest tuple descriptor, tuple_id=" << _params.dest_tuple_id;
return Status::InternalError(ss.str());
}
bool has_slot_id_map = _params.__isset.dest_sid_to_src_sid_without_trans;
for (auto slot_desc : _dest_tuple_desc->slots()) {
if (!slot_desc->is_materialized()) {
continue;
}
auto it = _params.expr_of_dest_slot.find(slot_desc->id());
if (it == std::end(_params.expr_of_dest_slot)) {
std::stringstream ss;
ss << "No expr for dest slot, id=" << slot_desc->id()
<< ", name=" << slot_desc->col_name();
return Status::InternalError(ss.str());
}
if (_state->enable_vectorized_exec()) {
vectorized::VExprContext* ctx = nullptr;
RETURN_IF_ERROR(
vectorized::VExpr::create_expr_tree(_state->obj_pool(), it->second, &ctx));
RETURN_IF_ERROR(ctx->prepare(_state, *_row_desc.get(), _mem_tracker));
RETURN_IF_ERROR(ctx->open(_state));
_dest_vexpr_ctx.emplace_back(ctx);
} else {
ExprContext* ctx = nullptr;
RETURN_IF_ERROR(Expr::create_expr_tree(_state->obj_pool(), it->second, &ctx));
RETURN_IF_ERROR(ctx->prepare(_state, *_row_desc.get(), _mem_tracker));
RETURN_IF_ERROR(ctx->open(_state));
_dest_expr_ctx.emplace_back(ctx);
}
if (has_slot_id_map) {
auto it = _params.dest_sid_to_src_sid_without_trans.find(slot_desc->id());
if (it == std::end(_params.dest_sid_to_src_sid_without_trans)) {
_src_slot_descs_order_by_dest.emplace_back(nullptr);
} else {
auto _src_slot_it = src_slot_desc_map.find(it->second);
if (_src_slot_it == std::end(src_slot_desc_map)) {
std::stringstream ss;
ss << "No src slot " << it->second << " in src slot descs";
return Status::InternalError(ss.str());
}
_src_slot_descs_order_by_dest.emplace_back(_src_slot_it->second);
}
}
}
return Status::OK();
}
Status BaseScanner::fill_dest_tuple(Tuple* dest_tuple, MemPool* mem_pool, bool* fill_tuple) {
RETURN_IF_ERROR(_fill_dest_tuple(dest_tuple, mem_pool));
if (_success) {
free_expr_local_allocations();
*fill_tuple = true;
} else {
*fill_tuple = false;
}
return Status::OK();
}
Status BaseScanner::_fill_dest_tuple(Tuple* dest_tuple, MemPool* mem_pool) {
// filter src tuple by preceding filter first
if (!ExecNode::eval_conjuncts(&_pre_filter_ctxs[0], _pre_filter_ctxs.size(), _src_tuple_row)) {
_counter->num_rows_unselected++;
_success = false;
return Status::OK();
}
// convert and fill dest tuple
int ctx_idx = 0;
for (auto slot_desc : _dest_tuple_desc->slots()) {
if (!slot_desc->is_materialized()) {
continue;
}
int dest_index = ctx_idx++;
ExprContext* ctx = _dest_expr_ctx[dest_index];
void* value = ctx->get_value(_src_tuple_row);
if (value == nullptr) {
// Only when the expr return value is null, we will check the error message.
std::string expr_error = ctx->get_error_msg();
if (!expr_error.empty()) {
RETURN_IF_ERROR(_state->append_error_msg_to_file(
[&]() -> std::string {
return _src_tuple_row->to_string(*(_row_desc.get()));
},
[&]() -> std::string { return expr_error; }, &_scanner_eof));
_counter->num_rows_filtered++;
// The ctx is reused, so must clear the error state and message.
ctx->clear_error_msg();
_success = false;
return Status::OK();
}
// If _strict_mode is false, _src_slot_descs_order_by_dest size could be zero
if (_strict_mode && (_src_slot_descs_order_by_dest[dest_index] != nullptr) &&
!_src_tuple->is_null(
_src_slot_descs_order_by_dest[dest_index]->null_indicator_offset())) {
RETURN_IF_ERROR(_state->append_error_msg_to_file(
[&]() -> std::string {
return _src_tuple_row->to_string(*(_row_desc.get()));
},
[&]() -> std::string {
// Type of the slot is must be Varchar in _src_tuple.
StringValue* raw_value = _src_tuple->get_string_slot(
_src_slot_descs_order_by_dest[dest_index]->tuple_offset());
std::string raw_string;
if (raw_value != nullptr) { //is not null then get raw value
raw_string = raw_value->to_string();
}
fmt::memory_buffer error_msg;
fmt::format_to(error_msg,
"column({}) value is incorrect while strict mode is {}, "
"src value is {}",
slot_desc->col_name(), _strict_mode, raw_string);
return fmt::to_string(error_msg);
},
&_scanner_eof));
_counter->num_rows_filtered++;
_success = false;
return Status::OK();
}
if (!slot_desc->is_nullable()) {
RETURN_IF_ERROR(_state->append_error_msg_to_file(
[&]() -> std::string {
return _src_tuple_row->to_string(*(_row_desc.get()));
},
[&]() -> std::string {
fmt::memory_buffer error_msg;
fmt::format_to(
error_msg,
"column({}) values is null while columns is not nullable",
slot_desc->col_name());
return fmt::to_string(error_msg);
},
&_scanner_eof));
_counter->num_rows_filtered++;
_success = false;
return Status::OK();
}
dest_tuple->set_null(slot_desc->null_indicator_offset());
continue;
}
if (slot_desc->is_nullable()) {
dest_tuple->set_not_null(slot_desc->null_indicator_offset());
}
void* slot = dest_tuple->get_slot(slot_desc->tuple_offset());
RawValue::write(value, slot, slot_desc->type(), mem_pool);
}
_success = true;
return Status::OK();
}
Status BaseScanner::_filter_src_block() {
auto origin_column_num = _src_block.columns();
// filter block
auto old_rows = _src_block.rows();
RETURN_IF_ERROR(vectorized::VExprContext::filter_block(_vpre_filter_ctx_ptr, &_src_block,
origin_column_num));
_counter->num_rows_unselected += old_rows - _src_block.rows();
return Status::OK();
}
Status BaseScanner::_materialize_dest_block(vectorized::Block* dest_block) {
// Do vectorized expr here
int ctx_idx = 0;
size_t rows = _src_block.rows();
auto filter_column = vectorized::ColumnUInt8::create(rows, 1);
auto& filter_map = filter_column->get_data();
for (auto slot_desc : _dest_tuple_desc->slots()) {
if (!slot_desc->is_materialized()) {
continue;
}
int dest_index = ctx_idx++;
auto* ctx = _dest_vexpr_ctx[dest_index];
int result_column_id = -1;
// PT1 => dest primitive type
RETURN_IF_ERROR(ctx->execute(&_src_block, &result_column_id));
auto column_ptr = _src_block.get_by_position(result_column_id).column;
DCHECK(column_ptr != nullptr);
// because of src_slot_desc is always be nullable, so the column_ptr after do dest_expr
// is likely to be nullable
if (LIKELY(column_ptr->is_nullable())) {
auto nullable_column =
reinterpret_cast<const vectorized::ColumnNullable*>(column_ptr.get());
for (int i = 0; i < rows; ++i) {
if (filter_map[i] && nullable_column->is_null_at(i)) {
if (_strict_mode && (_src_slot_descs_order_by_dest[dest_index]) &&
!_src_block.get_by_position(dest_index).column->is_null_at(i)) {
RETURN_IF_ERROR(_state->append_error_msg_to_file(
[&]() -> std::string {
return _src_block.dump_one_line(i, _num_of_columns_from_file);
},
[&]() -> std::string {
auto raw_value =
_src_block.get_by_position(ctx_idx).column->get_data_at(
i);
std::string raw_string = raw_value.to_string();
fmt::memory_buffer error_msg;
fmt::format_to(error_msg,
"column({}) value is incorrect while strict "
"mode is {}, "
"src value is {}",
slot_desc->col_name(), _strict_mode, raw_string);
return fmt::to_string(error_msg);
},
&_scanner_eof));
filter_map[i] = false;
} else if (!slot_desc->is_nullable()) {
RETURN_IF_ERROR(_state->append_error_msg_to_file(
[&]() -> std::string {
return _src_block.dump_one_line(i, _num_of_columns_from_file);
},
[&]() -> std::string {
fmt::memory_buffer error_msg;
fmt::format_to(error_msg,
"column({}) values is null while columns is not "
"nullable",
slot_desc->col_name());
return fmt::to_string(error_msg);
},
&_scanner_eof));
filter_map[i] = false;
}
}
}
if (!slot_desc->is_nullable()) column_ptr = nullable_column->get_nested_column_ptr();
} else if (slot_desc->is_nullable()) {
column_ptr = vectorized::make_nullable(column_ptr);
}
dest_block->insert(vectorized::ColumnWithTypeAndName(
std::move(column_ptr), slot_desc->get_data_type_ptr(), slot_desc->col_name()));
}
// after do the dest block insert operation, clear _src_block to remove the reference of origin column
_src_block.clear();
size_t dest_size = dest_block->columns();
// do filter
dest_block->insert(vectorized::ColumnWithTypeAndName(
std::move(filter_column), std::make_shared<vectorized::DataTypeUInt8>(),
"filter column"));
RETURN_IF_ERROR(vectorized::Block::filter_block(dest_block, dest_size, dest_size));
_counter->num_rows_filtered += rows - dest_block->rows();
return Status::OK();
}
// TODO: opt the reuse of src_block or dest_block column. some case we have to
// shallow copy the column of src_block to dest block
Status BaseScanner::_init_src_block() {
DCHECK(_src_block.columns() == 0);
for (auto i = 0; i < _num_of_columns_from_file; ++i) {
SlotDescriptor* slot_desc = _src_slot_descs[i];
if (slot_desc == nullptr) {
continue;
}
auto data_type = slot_desc->get_data_type_ptr();
_src_block.insert(vectorized::ColumnWithTypeAndName(
data_type->create_column(), slot_desc->get_data_type_ptr(), slot_desc->col_name()));
}
return Status::OK();
}
Status BaseScanner::_fill_dest_block(vectorized::Block* dest_block, bool* eof) {
*eof = _scanner_eof;
_fill_columns_from_path();
if (LIKELY(_src_block.rows() > 0)) {
RETURN_IF_ERROR(BaseScanner::_filter_src_block());
RETURN_IF_ERROR(BaseScanner::_materialize_dest_block(dest_block));
}
return Status::OK();
}
void BaseScanner::fill_slots_of_columns_from_path(
int start, const std::vector<std::string>& columns_from_path) {
// values of columns from path can not be null
for (int i = 0; i < columns_from_path.size(); ++i) {
auto slot_desc = _src_slot_descs.at(i + start);
_src_tuple->set_not_null(slot_desc->null_indicator_offset());
void* slot = _src_tuple->get_slot(slot_desc->tuple_offset());
auto* str_slot = reinterpret_cast<StringValue*>(slot);
const std::string& column_from_path = columns_from_path[i];
str_slot->ptr = const_cast<char*>(column_from_path.c_str());
str_slot->len = column_from_path.size();
}
}
void BaseScanner::free_expr_local_allocations() {
if (++_line_counter % RELEASE_CONTEXT_COUNTER == 0) {
ExprContext::free_local_allocations(_dest_expr_ctx);
}
}
void BaseScanner::close() {
if (!_pre_filter_ctxs.empty()) {
Expr::close(_pre_filter_ctxs, _state);
}
if (_vpre_filter_ctx_ptr) {
(*_vpre_filter_ctx_ptr)->close(_state);
}
}
void BaseScanner::_fill_columns_from_path() {
const TBrokerRangeDesc& range = _ranges.at(_next_range - 1);
if (range.__isset.num_of_columns_from_file) {
size_t start = range.num_of_columns_from_file;
size_t rows = _src_block.rows();
for (size_t i = 0; i < range.columns_from_path.size(); ++i) {
auto slot_desc = _src_slot_descs.at(i + start);
if (slot_desc == nullptr) continue;
auto is_nullable = slot_desc->is_nullable();
auto data_type = vectorized::DataTypeFactory::instance().create_data_type(TYPE_VARCHAR,
is_nullable);
auto data_column = data_type->create_column();
const std::string& column_from_path = range.columns_from_path[i];
for (size_t j = 0; j < rows; ++j) {
data_column->insert_data(const_cast<char*>(column_from_path.c_str()),
column_from_path.size());
}
_src_block.insert(vectorized::ColumnWithTypeAndName(std::move(data_column), data_type,
slot_desc->col_name()));
}
}
}
} // namespace doris
| 44.905155 | 107 | 0.565912 | [
"vector"
] |
1126006f1b5f8233551cb629f9a026090a277e42 | 3,381 | cpp | C++ | CLRS/DynamicProgramming/MaximumSubarray.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/DynamicProgramming/MaximumSubarray.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | CLRS/DynamicProgramming/MaximumSubarray.cpp | ComputerProgrammerStorager/DataStructureAlgorithm | 508f7e37898c907ea7ea6ec40749621a2349e93f | [
"MIT"
] | null | null | null | /*
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [0]
Output: 0
Example 4:
Input: nums = [-1]
Output: -1
Example 5:
Input: nums = [-100000]
Output: -100000
Constraints:
1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
*/
// the key point is to identify the inflection point, it's the current sum is less than 0
// dynamic programming: dp[i]: represent the maximum sum of nums[0...i].
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
if ( n == 0 )
return 0;
int global_sum = nums[0];
for ( int i = 1; i < n; i++)
{
if ( nums[i-1] >= 0 )
{
nums[i] += nums[i-1];
}
global_sum = max(global_sum,nums[i]);
}
return global_sum;
}
};
// whenever we have a currently accumulative sum is less then 0, then we reset the current sum
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
if ( n == 0 )
return 0;
int global_sum = INT_MIN;
int cur_sum = 0;
for ( int i = 0; i < n; i++)
{
if ( cur_sum < 0 )
{
cur_sum = 0;
}
cur_sum += nums[i];
global_sum = max(global_sum,cur_sum);
}
return global_sum;
}
};
// Greedy algorithm: constantly maintain a local optimal and update the global sum every time the local optimal is updated
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
if ( n == 0 )
return 0;
int global_sum = nums[0];
int cur_sum = nums[0];
for ( int i = 1; i < n; i++)
{
cur_sum = max(nums[i],cur_sum+nums[i]);
global_sum = max(cur_sum,global_sum);
}
return global_sum;
}
};
// Divide and conquer
class Solution {
public:
int maxSubArray(vector<int>& nums) {
return helper(nums,0,nums.size()-1);
}
int CrossSum( vector<int> const &nums, int l, int h, int c )
{
if ( l == h )
return nums[l];
int left_sum = INT_MIN, right_sum = INT_MIN;
int cur_sum = 0;
for ( int i = c; i >= l; i-- )
{
cur_sum += nums[i];
left_sum = max(cur_sum,left_sum);
}
cur_sum = 0;
for ( int i = c + 1; i <= h; i++ )
{
cur_sum += nums[i];
right_sum = max(cur_sum,right_sum);
}
return left_sum + right_sum;
}
int helper( vector<int> const &nums, int l, int h)
{
if ( l == h )
return nums[l];
int mid = (l+h)/2;
int left_sum = helper(nums,l,mid);
int right_sum = helper(nums, mid+1,h);
int cross_sum = CrossSum(nums,l,h,mid);
return max(left_sum,max(right_sum,cross_sum));
}
}; | 23.809859 | 142 | 0.521148 | [
"vector"
] |
11278b1aa7c43183cb94e5d22f36c083b601ddf7 | 3,893 | hpp | C++ | include/codegen/include/Zenject/PrefabInstantiatorCached.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/Zenject/PrefabInstantiatorCached.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/Zenject/PrefabInstantiatorCached.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:46 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: Zenject.IPrefabInstantiator
#include "Zenject/IPrefabInstantiator.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: GameObject
class GameObject;
// Forward declaring type: Object
class Object;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
// Forward declaring type: Action
class Action;
}
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: GameObjectCreationParameters
class GameObjectCreationParameters;
// Forward declaring type: InjectContext
class InjectContext;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.PrefabInstantiatorCached
class PrefabInstantiatorCached : public ::Il2CppObject, public Zenject::IPrefabInstantiator {
public:
// private readonly Zenject.IPrefabInstantiator _subInstantiator
// Offset: 0x10
Zenject::IPrefabInstantiator* subInstantiator;
// private UnityEngine.GameObject _gameObject
// Offset: 0x18
UnityEngine::GameObject* gameObject;
// public System.Void .ctor(Zenject.IPrefabInstantiator subInstantiator)
// Offset: 0xFAE9F0
static PrefabInstantiatorCached* New_ctor(Zenject::IPrefabInstantiator* subInstantiator);
// public System.Collections.Generic.List`1<Zenject.TypeValuePair> get_ExtraArguments()
// Offset: 0xFAF840
// Implemented from: Zenject.IPrefabInstantiator
// Base method: System.Collections.Generic.List`1<Zenject.TypeValuePair> IPrefabInstantiator::get_ExtraArguments()
System::Collections::Generic::List_1<Zenject::TypeValuePair>* get_ExtraArguments();
// public System.Type get_ArgumentTarget()
// Offset: 0xFAF8F4
// Implemented from: Zenject.IPrefabInstantiator
// Base method: System.Type IPrefabInstantiator::get_ArgumentTarget()
System::Type* get_ArgumentTarget();
// public Zenject.GameObjectCreationParameters get_GameObjectCreationParameters()
// Offset: 0xFAF9A4
// Implemented from: Zenject.IPrefabInstantiator
// Base method: Zenject.GameObjectCreationParameters IPrefabInstantiator::get_GameObjectCreationParameters()
Zenject::GameObjectCreationParameters* get_GameObjectCreationParameters();
// public UnityEngine.Object GetPrefab()
// Offset: 0xFAFA58
// Implemented from: Zenject.IPrefabInstantiator
// Base method: UnityEngine.Object IPrefabInstantiator::GetPrefab()
UnityEngine::Object* GetPrefab();
// public UnityEngine.GameObject Instantiate(Zenject.InjectContext context, System.Collections.Generic.List`1<Zenject.TypeValuePair> args, System.Action injectAction)
// Offset: 0xFAFB0C
// Implemented from: Zenject.IPrefabInstantiator
// Base method: UnityEngine.GameObject IPrefabInstantiator::Instantiate(Zenject.InjectContext context, System.Collections.Generic.List`1<Zenject.TypeValuePair> args, System.Action injectAction)
UnityEngine::GameObject* Instantiate(Zenject::InjectContext* context, System::Collections::Generic::List_1<Zenject::TypeValuePair>* args, System::Action*& injectAction);
}; // Zenject.PrefabInstantiatorCached
}
DEFINE_IL2CPP_ARG_TYPE(Zenject::PrefabInstantiatorCached*, "Zenject", "PrefabInstantiatorCached");
#pragma pack(pop)
| 45.267442 | 197 | 0.761367 | [
"object"
] |
112ae7450fc9632ba09553a9f233f24e77e689a5 | 8,087 | cpp | C++ | catdoor_v2/libs/m0_hf_pwm/src/m0_hf_pwm.cpp | flupes/catdoor | bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f | [
"Apache-2.0"
] | null | null | null | catdoor_v2/libs/m0_hf_pwm/src/m0_hf_pwm.cpp | flupes/catdoor | bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f | [
"Apache-2.0"
] | null | null | null | catdoor_v2/libs/m0_hf_pwm/src/m0_hf_pwm.cpp | flupes/catdoor | bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f | [
"Apache-2.0"
] | null | null | null | // Configure three pins (D5, D6 and D11) on a TCC timer on the Adafruit Feather
// M0 (SAMD21) for fast PWM (higher frequency than a cat can perceive > 73KHz,
// otherwise the solenoid is singing and the catdoor assembly resonate very
// loudly;-)
// Inspired from: MartinL @ https://forum.arduino.cc/index.php?topic=346731.0
// Essentially post #2, #6, #107 and #109
// Pinout for the feather:
// https://cdn-learn.adafruit.com/assets/assets/000/041/593/original/Adafruit_Feather_M0_WiFi_v1_0.pdf?1494356530
// Atmel SAMD21 documentation:
// http://ww1.microchip.com/downloads/en/DeviceDoc/40001882A.pdf
// Somehow, PlatformIO does not linl correctly .c files, so despite being C,
// this file has the .cpp extension!
#include "m0_hf_pwm.h"
#include "LedCtrl.h"
#include "Solenoids.h"
#include <Arduino.h>
static const unsigned char g_gen_clock_pwm = 4;
static const uint32_t g_max_per = 512;
uint32_t pwm_get_max() { return g_max_per; }
void pwm_configure() {
REG_GCLK_GENDIV =
GCLK_GENDIV_DIV(
1) | // Divide the 48MHz clock source by divisor 1: 48MHz/4=12MHz
GCLK_GENDIV_ID(g_gen_clock_pwm); // Select Generic Clock (GCLK) 4
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC | // Set the duty cycle to 50/50 HIGH/LOW
GCLK_GENCTRL_GENEN | // Enable GCLK4
GCLK_GENCTRL_SRC_DFLL48M | // Set the 48MHz clock source
GCLK_GENCTRL_ID(g_gen_clock_pwm); // Select GCLK4
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// Enable the port multiplexer for digital pon D5(PA15), D6(PA20) and
// D11(PA16)
PORT->Group[g_APinDescription[5].ulPort]
.PINCFG[g_APinDescription[5].ulPin]
.bit.PMUXEN = 1;
PORT->Group[g_APinDescription[6].ulPort]
.PINCFG[g_APinDescription[6].ulPin]
.bit.PMUXEN = 1;
PORT->Group[g_APinDescription[11].ulPort]
.PINCFG[g_APinDescription[11].ulPin]
.bit.PMUXEN = 1;
// Connect TCC0 timer to PA15=D5 (ODD pin, Function F --> TTC0/WO[5] = CCB1)
// Why we access PA15 from D2 is still totally magic too me.
// It would be so much easier to reference the actual SAMD21 port/pin
// directly...
PORT->Group[g_APinDescription[2].ulPort]
.PMUX[g_APinDescription[2].ulPin >> 1]
.reg = PORT_PMUX_PMUXO_F;
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// Connect TCC0 timer to PA20=D6 (EVEN pin, Function F --> TTC0/WO[6] = CCB2)
PORT->Group[g_APinDescription[6].ulPort]
.PMUX[g_APinDescription[6].ulPin >> 1]
.reg = PORT_PMUX_PMUXE_F;
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// Connect TCC2 timer to PA16=D11 (EVEN pin, Function E --> TTC2/WO[0] = CCB0)
PORT->Group[g_APinDescription[11].ulPort]
.PMUX[g_APinDescription[11].ulPin >> 1]
.reg = PORT_PMUX_PMUXE_E;
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// Feed GCLK4 to TCC0 (and TCC1)
REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN | // Enable GCLK4 to TCC0 and TCC1
GCLK_CLKCTRL_GEN_GCLK4 | // Select GCLK4
GCLK_CLKCTRL_ID_TCC0_TCC1; // Feed GCLK4 to TCC0 and TCC1
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// Feed GCLK4 to TCC2 (and TC3)
REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN | // Enable GCLK4 to TCC2 (and TC3)
GCLK_CLKCTRL_GEN_GCLK4 | // Select GCLK4
GCLK_CLKCTRL_ID_TCC2_TC3; // Feed GCLK4 to TCC2 (and TC3)
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// Normal (single slope) PWM operation: timers countinuously count up to PER
// register value and then is reset to 0
REG_TCC0_WAVE |= TCC_WAVE_WAVEGEN_NPWM; // Setup single slope PWM on TCC1
while (TCC0->SYNCBUSY.bit.WAVE)
; // Wait for synchronization
REG_TCC2_WAVE |= TCC_WAVE_WAVEGEN_NPWM; // Setup single slope PWM on TCC1
while (TCC2->SYNCBUSY.bit.WAVE)
; // Wait for synchronization
// Each timer counts up to a maximum or TOP value set by the PER register,
// this determines the frequency of the PWM operation 12MHz / 512 = 93.75kHz
REG_TCC0_PER = g_max_per; // Set the frequency of the PWM on TCC0 to 93kHz >
// cat auditible range
while (TCC0->SYNCBUSY.bit.PER)
;
REG_TCC2_PER = g_max_per; // Set the frequency of the PWM on TCC2 to 93kHz
while (TCC2->SYNCBUSY.bit.PER)
;
// It is possible to invert the wave of D5 controlled by TCC0/WO[5]
// REG_TCC0_DRVCTRL |= TCC_DRVCTRL_INVEN5;
// The CCBx register value corresponds to the pulsewidth. Default is set to
// 50%
REG_TCC0_CC1 = 0;
// Set the duty cycle of the PWM on TCC0 W[2] to 50% (for D10)
// REG_TCC0_CC1 = 256;
while (TCC0->SYNCBUSY.bit.CC1)
;
REG_TCC0_CC2 = 0;
// Set the duty cycle of the PWM on TCC0 W[3] to 50% (for D12)
// REG_TCC0_CC2 = 256;
while (TCC0->SYNCBUSY.bit.CC2)
;
REG_TCC2_CC0 = 0;
// REG_TCC2_CC0 = 256;
while (TCC2->SYNCBUSY.bit.CC0)
;
// Enable TCC0 timer
REG_TCC0_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 | // Divide GCLK4 by 1
TCC_CTRLA_ENABLE; // Enable the TCC0 output
while (TCC0->SYNCBUSY.bit.ENABLE)
; // Wait for synchronization
// Enable TCC2 timer
REG_TCC2_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 | // Divide GCLK4 by 1
TCC_CTRLA_ENABLE; // Enable the TCC0 output
while (TCC2->SYNCBUSY.bit.ENABLE)
; // Wait for synchronization
// In addition use the same clock to trigger an ISR using TC4
// http://forum.arduino.cc/index.php?topic=425385.0
// Feed GCLK4 to TC4 and TC5
REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN | // Enable GCLK4 to TC4 and TC5
GCLK_CLKCTRL_GEN_GCLK4 | // Select GCLK4
GCLK_CLKCTRL_ID_TC4_TC5; // Feed the GCLK4 to TC4 and TC5
while (GCLK->STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// REG_TC4_COUNT16_CC0 = 0xB71A; // Set the TC4 CC0 register as the TOP value
// in match frequency mode --> 1s per to CC0
REG_TC4_COUNT16_CC0 = 0x0249; // Configure to trigger at every 20ms
while (TC4->COUNT16.STATUS.bit.SYNCBUSY)
; // Wait for synchronization
// NVIC_DisableIRQ(TC4_IRQn);
// NVIC_ClearPendingIRQ(TC4_IRQn);
NVIC_SetPriority(TC4_IRQn, 2); // Set the Nested Vector Interrupt Controller
// (NVIC) priority for TC4 to 0 (highest)
NVIC_EnableIRQ(
TC4_IRQn); // Connect TC4 to Nested Vector Interrupt Controller (NVIC)
REG_TC4_INTFLAG |= TC_INTFLAG_OVF; // Clear the interrupt flags
REG_TC4_INTENSET = TC_INTENSET_OVF; // Enable TC4 interrupts
// REG_TC4_INTENCLR = TC_INTENCLR_OVF; // Disable TC4 interrupts
REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 | // Set prescaler to 1024,
// 48MHz/1024 = 46.875kHz
TC_CTRLA_WAVEGEN_MFRQ | // Put the timer TC4 into match
// frequency (MFRQ) mode
TC_CTRLA_ENABLE; // Enable TC4
while (TC4->COUNT16.STATUS.bit.SYNCBUSY)
; // Wait for synchronization
}
int pwm_set(uint8_t pin, uint32_t width) {
if (width > g_max_per) return 0;
if (pin == 5) {
REG_TCC0_CC1 = width;
while (TCC0->SYNCBUSY.bit.CC1)
;
} else if (pin == 6) {
REG_TCC0_CC2 = width;
while (TCC0->SYNCBUSY.bit.CC2)
;
} else if (pin == 11) {
REG_TCC2_CC0 = width;
while (TCC2->SYNCBUSY.bit.CC0)
;
} else {
return 0;
}
return 1;
}
// Define ISR base on the internal timer:
// call update for LedCtrl and Solenoid
void TC4_Handler() // Interrupt Service Routine (ISR) for timer TC4
{
// Check for overflow (OVF) interrupt
if (TC4->COUNT16.INTFLAG.bit.OVF && TC4->COUNT16.INTENSET.bit.OVF) {
Solenoids::Instance().update();
LedCtrl::Instance().update();
REG_TC4_INTFLAG = TC_INTFLAG_OVF; // Clear the OVF interrupt flag
}
}
| 37.613953 | 113 | 0.655991 | [
"vector"
] |
112f0a9a5ed47ea78951c8afae192e75d70b609b | 1,384 | hpp | C++ | Section 6/Video 10, 11, 12/account.hpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | 17 | 2019-10-10T21:09:51.000Z | 2022-01-13T15:54:24.000Z | Section 6/Video 10, 11, 12/account.hpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | null | null | null | Section 6/Video 10, 11, 12/account.hpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | 16 | 2019-10-10T21:09:55.000Z | 2022-02-13T11:42:52.000Z | #ifndef _ACCOUNT_HPP_
#define _ACCOUNT_HPP_
#include <vector>
#include <algorithm>
#include <iterator>
#include "transaction.hpp"
#define BEGIN_ACCOUNT "BACCT"
/**
* This class defines a money account which stores financial transactions
* and maintains a balance.
*/
class Account {
std::string name;
std::vector<Transaction> transactions;
public :
Account() : name({}), transactions({}) {}
Account(const std::string& name) : name(name), transactions({}) {}
const std::string& getName() const {
return name;
}
const std::vector<Transaction>& getTransactions() const {
return transactions;
}
void addTransaction(Transaction& t) {
transactions.push_back(t);
}
long double balance() const {
long double sum = 0;
sum = std::accumulate(std::begin(transactions), std::end(transactions), sum,
[](const long double& a, const Transaction& b) {
return a + b.getAmount();
});
return sum;
}
friend std::ostream& operator<<(std::ostream& os, const Account& a);
friend std::istream& operator>>(std::istream& is, Account& a);
};
std::ostream& operator<<(std::ostream& os, const Account& a) {
os << BEGIN_ACCOUNT << " "
<< a.name << "\n";
return os;
}
std::istream& operator>>(std::istream& is, Account& a) {
is >> a.name;
return is;
}
#endif
| 21.968254 | 82 | 0.625 | [
"vector"
] |
113268d22f8702d838910851d8e0b55f2afd7690 | 9,116 | cpp | C++ | src/particle_filter.cpp | kommander-keene/CarND-Kidnapped-Vehicle-Project | 49e371c75c7704a2f32f2f8e50b23129a867abde | [
"MIT"
] | null | null | null | src/particle_filter.cpp | kommander-keene/CarND-Kidnapped-Vehicle-Project | 49e371c75c7704a2f32f2f8e50b23129a867abde | [
"MIT"
] | null | null | null | src/particle_filter.cpp | kommander-keene/CarND-Kidnapped-Vehicle-Project | 49e371c75c7704a2f32f2f8e50b23129a867abde | [
"MIT"
] | null | null | null | /**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
using std::string;
using std::vector;
static int NUM_PARTICLES = 128;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
std::normal_distribution<double> x_normal(x, std[0]);
std::normal_distribution<double> y_normal(y, std[1]);
std::normal_distribution<double> theta_normal(theta, std[2]);
std::default_random_engine random;
num_particles = NUM_PARTICLES;
particles.resize(num_particles);
for (auto& p: particles) {
//set equals
p.x = x_normal(random);
p.y = y_normal(random);
p.theta = theta_normal(random);
p.weight = 1.0;
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
std::default_random_engine random;
std::normal_distribution<double> x_N(0, std_pos[0]);
std::normal_distribution<double> y_N(0, std_pos[1]);
std::normal_distribution<double> theta_N(0, std_pos[2]);
for (auto& p: particles) {
double th = p.theta;
//Add measurements
if (fabs(yaw_rate) < 0.0001) { //returns if yaw_rate is about 0
p.x += velocity * delta_t * cos(th); //x = vcos(0)*t
p.y += velocity * delta_t * sin(th); //y = vsin(0)*t
} else { //use the formulas
p.x += (velocity/yaw_rate) * (sin(th + delta_t*yaw_rate -sin(th)));
p.y += (velocity/yaw_rate) * (cos(th)-cos(th+yaw_rate*delta_t));
p.theta += (yaw_rate*delta_t);
}
//Add noise
p.x += x_N(random);
p.y += y_N(random);
p.theta += theta_N(random);
}
}
//generates associations between observations and particles
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted, vector<LandmarkObs>& observations) {
//predicted landmarks
for (const auto p: predicted) {
double min = std::numeric_limits<double>::max();
//current observations
for (auto& o: observations) {
double d = dist(p.x, p.y, o.x, o.y);
if (d < min) {
min = d;
o.id = p.id;
}
}
}
}
std::vector<double> transform(std::vector<double> x, std::vector<double> y, double theta) {
// x[0] is xp
// x[1] is xc
// transforms coordinates with a -90º rotation.
double xm = x[0] + (cos(theta)*x[1]) - (sin(theta) * y[1]);
double ym = x[0] + (cos(theta)*x[1]) - (sin(theta) * y[1]);;
return std::vector<double>(xm,ym);
}
std::vector<LandmarkObs> nearest_neighbor_association(double sensor_range, const Particle particle, const Map &map_landmarks) {
std::vector<LandmarkObs> nna;
//for all of the map landmarks
for (const auto map: map_landmarks.landmark_list) {
double map_x = map.x_f;
double map_y = map.y_f;
int map_id = map.id_i;
double p_x = particle.x;
double p_y = particle.y;
//Record all of the valid landmarks that apply to this one particle as LandMarkObs types
if (dist(map_x, map_y, p_x, p_y) <= sensor_range) {
LandmarkObs copy_mark = LandmarkObs{map_id, map_x, map_y};
nna.push_back(copy_mark);
}
}
return nna;
}
std::vector<LandmarkObs> transformObs(const vector<LandmarkObs> &obs, Particle p) {
vector<LandmarkObs> to_return;
for (const auto o: obs) {
vector<double>x_set(p.x, o.x);
vector<double>y_set(p.y, o.y);
transform(x_set, y_set, p.theta);
}
return to_return;
}
double multivariate_weightUpdates(double x, double y, double mean_x, double mean_y, double s_x, double s_y) {
double x_stuff = (pow((x-mean_x), 2)/(2*pow(s_x, 2)));
double y_stuff = (pow((y-mean_y), 2)/(2*pow(s_y, 2)));
double power_op = -(x_stuff + y_stuff);
double P = (1.0/(2.0*M_PI*s_x*s_y) * (exp(power_op)));
return P;
}
LandmarkObs findCurrentLandmark(int id, const std::vector<LandmarkObs> obs) {
for (auto m: obs) {
if (m.id == id) {
return m;
}
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const vector<LandmarkObs> &observations, const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
for (Particle p : particles) {
//valid map landmarks
std::vector<LandmarkObs> valid;
//transformed observations
std::vector<LandmarkObs> t_obs;
p.weight = 1.0;
valid = nearest_neighbor_association(sensor_range, p, map_landmarks);
t_obs = transformObs(observations, p);
//associates valid results and observations together
dataAssociation(valid, t_obs);
//factor in that observation's gaussian in order to greater weight different things
//think of the mean as the expected value, or the actual value of the landmark.
int index = 0;
for (int i = 0; i < observations.size(); i++) {
LandmarkObs obs = observations[i];
//get current landmark associated with this observation
LandmarkObs landmark = findCurrentLandmark(obs.id, valid);
p.weight *= multivariate_weightUpdates(obs.x, obs.y, landmark.x, landmark.y, std_landmark[0], std_landmark[1]);
}
}
}
double maximumWeights(std::vector<double>& weights, const std::vector<Particle> particles) {
double mini = std::numeric_limits<double>::min();
for (const Particle p: particles) {
weights.push_back(p.weight);
if (p.weight > mini) {
mini = p.weight;
}
}
return mini;
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
//random vars
std::random_device random;
std::mt19937 wtf(random());
//a random selection of the indicides
std::vector<Particle> resampled;
int index = rand() % (num_particles-1);
double beta = 0.0;
double max = maximumWeights(weights, particles);
//a random selection of a distribution of weights
std::discrete_distribution<double> N_w(weights.begin(), weights.end());
for (int i=0; i < num_particles; i++) {
beta += N_w(wtf)*2*max;
while (weights[index] < beta) {
beta -= weights[index];
index = (index + 1);
}
resampled.push_back(particles[index]);
}
particles = resampled;
weights.clear();
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
| 34.142322 | 147 | 0.632514 | [
"vector",
"transform"
] |
1132e7229f8990ca2770179e272aac6a27b32bd6 | 14,085 | hpp | C++ | src/AFQMC/Walkers/WalkerIO.hpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | src/AFQMC/Walkers/WalkerIO.hpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | src/AFQMC/Walkers/WalkerIO.hpp | djstaros/qmcpack | 280f67e638bae280448b47fa618f05b848c530d2 | [
"NCSA"
] | null | null | null | //////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source
// License. See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by:
// Miguel A. Morales, moralessilva2@llnl.gov
// Lawrence Livermore National Laboratory
//
// File created by:
// Miguel A. Morales, moralessilva2@llnl.gov
// Lawrence Livermore National Laboratory
////////////////////////////////////////////////////////////////////////////////
#ifndef AFQMC_WALKERIO_HPP
#define AFQMC_WALKERIO_HPP
#include <cassert>
#include <cstdlib>
#include <vector>
#include <type_traits>
#include "type_traits/container_traits_multi.h"
#include "Configuration.h"
#include "AFQMC/config.h"
namespace qmcplusplus
{
namespace afqmc
{
template<class WalkerSet, typename = typename std::enable_if<(WalkerSet::contiguous_walker)>::type>
bool dumpSamplesHDF5(WalkerSet& wset, hdf_archive& dump, int nW_to_file)
{
return true;
APP_ABORT("Finish \n");
return true;
/*
if(nW_to_file==0) return true;
if(head) {
int nW = numWalkers();
std::vector<int> from(nproc_heads);
MPI_Allgather(&nW,1,MPI_INT,from.data(),1,MPI_INT,TG.TG_heads().impl_);
int nWtot = std::accumulate(from.begin(),from.end(),int(0));
int w0 = std::accumulate(from.begin(),from.begin()+rank_heads,int(0));
if(nW_to_file<0) nW_to_file=nWtot;
nW_to_file = std::min(nW_to_file,nWtot);
// careful here, avoid sending extra information (e.g. B mats for back propg)
int wlk_nterms = (9 + nrow*ncol);
int wlk_sz = wlk_nterms*sizeof(ComplexType);
int nwlk_per_block = std::min(std::max(1,hdf_block_size/wlk_sz),nW_to_file);
int nblks = nW_to_file/nwlk_per_block + ((nW_to_file%nwlk_per_block>0)?1:0);
std::vector<int> wlk_per_blk;
if(rank_heads==0) {
// check that restart data doesnot exist
counts.resize(nproc_heads);
displ.resize(nproc_heads);
wlk_per_blk.reserve(nblks);
commBuff.reserve(wlk_nterms*nwlk_per_block);
std::vector<int> Idata(6);
Idata[0]=nW_to_file;
Idata[1]=nblks;
Idata[2]=wlk_nterms;
Idata[3]=wlk_sz;
Idata[4]=nrow;
Idata[5]=ncol;
dump.push("Walkers");
dump.write(Idata,"dims");
}
// to extract a single walker from walker storage
MPI_Datatype rtype, stype;
{
MPI_Datatype stype_;
MPI_Type_contiguous(2*wlk_nterms, MPI_DOUBLE, &stype_);
MPI_Type_commit(&stype_);
MPI_Aint loc0, loc1;
MPI_Get_address(walkers.values(), &loc0);
MPI_Get_address(walkers.values()+walker_size, &loc1);
MPI_Aint dis = loc1-loc0;
MPI_Type_create_resized(stype_,0,dis,&stype);
MPI_Type_commit(&stype);
MPI_Type_free(&stype_);
// to deposit a single walker on contiguous memory
MPI_Type_contiguous(2*wlk_nterms, MPI_DOUBLE, &rtype);
MPI_Type_commit(&rtype);
}
int nsent=0;
// ready to send walkers to head in blocks
for(int i=0, ndone=0; i<nblks; i++, ndone+=nwlk_per_block) {
int nwlk_tot = std::min(nwlk_per_block,nW_to_file-ndone);
int nw_to_send=0;
if( w0+nsent >= ndone && w0+nsent < ndone + nwlk_tot)
nw_to_send = std::min(nW-nsent,(ndone+nwlk_tot)-(w0+nsent));
if(rank_heads==0) {
for(int p=0, nt=0; p<nproc_heads; p++) {
int n_ = 0;
int nn = nt + nW;
if( ndone+nwlk_tot > nt && ndone < nt+nW ) {
if(ndone <= nt)
n_ = std::min(nW,(ndone+nwlk_tot)-nt);
else
n_ = std::min(nt+nW-ndone,nwlk_tot);
}
counts[p]=n_;
nt+=from[p];
}
displ[0]=0;
for(int p=1, nt=0; p<nproc_heads; p++) {
nt += counts[p-1];
displ[p]=nt;
}
commBuff.resize(wlk_nterms*nwlk_tot);
}
// assumes current storage structure
MPI_Gatherv( getSM(nsent), nw_to_send, stype,
commBuff.data(), counts.data(), displ.data(), rtype,
0, TG.TG_heads().impl_);
nsent += nw_to_send;
if(rank_heads==0) {
dump.write(commBuff,std::string("walkers_")+std::to_string(i));
wlk_per_blk.push_back(nwlk_tot);
}
}
if(rank_heads==0) {
dump.write(wlk_per_blk,"wlk_per_blk");
dump.pop();
}
MPI_Type_free(&rtype);
MPI_Type_free(&stype);
}
TG.global_barrier();
return true;
*/
}
template<class WalkerSet, typename = typename std::enable_if<(WalkerSet::contiguous_walker)>::type>
bool restartFromHDF5(WalkerSet& wset,
int nW_per_tg,
std::string hdf_read_restart,
hdf_archive& read,
bool set_to_target)
{
TaskGroup_& TG = wset.getTG();
std::vector<int> Idata(7);
if (read.is_parallel())
{
app_error() << " Error: hdf_archive can't be parallel in restartFromHDF5().\n";
APP_ABORT("");
}
if (TG.TG_local().root())
{
if (!read.open(hdf_read_restart, H5F_ACC_RDONLY))
APP_ABORT("Problem opening restart file");
std::string path = "/Walkers/WalkerSet";
if (!read.is_group(path))
{
app_error()
<< " ERROR: H5Group could not find /Walkers/WalkerSet group in file. No restart data for walkers. \n";
return false;
}
if (!read.push("Walkers"))
return false;
if (!read.push("WalkerSet"))
return false;
if (!read.readEntry(Idata, "dims"))
return false;
}
TG.TG_local().broadcast_n(Idata.begin(), Idata.size());
int nWtot = Idata[0];
int wlk_nterms = Idata[2];
int NMO = Idata[4];
int NAEA = Idata[5];
int NAEB = Idata[6];
if (wlk_nterms != wset.walkerSizeIO())
{
app_error() << " Inconsistent walker restart file: IO size, NMO, NAEA, NAEB, WalkerType:" << wset.walkerSizeIO()
<< " " << NMO << " " << NAEA << " " << NAEB << " " << wset.getWalkerType() << std::endl;
APP_ABORT("");
}
// walker range belonging to this TG
int nW0, nWN;
if (set_to_target)
{
if (nWtot < nW_per_tg * TG.TG_heads().size())
APP_ABORT(" Error: Not enough walkers in restart file.\n");
nW0 = nW_per_tg * TG.TG_heads().rank();
nWN = nW0 + nW_per_tg;
}
else
{
if (nWtot % TG.TG_heads().size() != 0)
APP_ABORT(" Error: Number of walkers in restart file must be divisible by number of task groups.\n");
nW0 = (nWtot / TG.TG_heads().size()) * TG.TG_heads().rank();
nWN = nW0 + nWtot / TG.TG_heads().size();
}
int nw_local = nWN - nW0;
{ // to limit scope
boost::multi::array<ComplexType, 2> PsiA, PsiB;
if (TG.TG_local().root())
{
PsiA.reextent({NMO, NAEA});
if (wset.getWalkerType() == COLLINEAR)
PsiB.reextent({NMO, NAEB});
}
// PsiA/B only meaningful at root
wset.resize(nw_local, PsiA, PsiB);
}
// only head of WalkerSet reads
if (TG.TG_local().root())
{
std::vector<int> wlk_per_blk;
read.read(wlk_per_blk, "wlk_per_blk");
boost::multi::array<ComplexType, 2> Data;
// loop through blocks and read when necessary
int ni = 0, nread = 0, bi = 0;
while (nread < nw_local)
{
if (ni + wlk_per_blk[bi] > nW0)
{
// determine block of walkers to read
int w0 = std::max(0, nW0 - ni);
int nw_ = std::min(ni + wlk_per_blk[bi], nWN) - std::max(ni, nW0);
Data.reextent({nw_, wlk_nterms});
hyperslab_proxy<boost::multi::array_ref<ComplexType, 2>, 2> hslab(Data,
std::array<int, 2>{wlk_per_blk[bi],
wlk_nterms},
std::array<int, 2>{nw_, wlk_nterms},
std::array<int, 2>{w0, 0});
read.read(hslab, std::string("walkers_") + std::to_string(bi));
for (int n = 0; n < nw_; n++, nread++)
wset.copyFromIO(Data[n], nread);
}
ni += wlk_per_blk[bi++];
}
}
TG.global_barrier();
read.close();
return true;
}
template<class WalkerSet, typename = typename std::enable_if<(WalkerSet::contiguous_walker)>::type>
bool dumpToHDF5(WalkerSet& wset, hdf_archive& dump)
{
TaskGroup_& TG = wset.getTG();
if (TG.TG_local().root())
{
int nW = wset.size();
auto nw_per_tg = TG.TG_heads().all_gather_value(nW);
int nWtot = std::accumulate(nw_per_tg.begin(), nw_per_tg.end(), int(0));
int w0 = std::accumulate(nw_per_tg.begin(), nw_per_tg.begin() + TG.TG_heads().rank(), int(0));
auto walker_type = wset.getWalkerType();
// careful here, avoid sending extra information (e.g. B mats for back propg)
int wlk_nterms = wset.walkerSizeIO();
int wlk_sz = wlk_nterms * sizeof(ComplexType);
#if defined(__ENABLE_PHDF5__)
// parallel I/O
APP_ABORT("Restarting with parallel HDF5 not implemented yet.\n");
int nwlk_per_block = std::min(std::max(1, WALKER_HDF_BLOCK_SIZE / wlk_sz), nW);
int nblks = (nW - 1) / nwlk_per_block + 1;
auto nblks_per_tg = TG.TG_heads().all_gather_value(nblks);
int nblkTot = std::accumulate(nblks_per_tg.begin(), nblks_per_tg.end(), int(0));
int blk0 = std::accumulate(nblks_per_tg.begin(), nblks_per_tg.begin() + TG.TG_heads().rank(), int(0));
std::vector<int> wlk_per_blk(nblks);
// if(TG.TG_heads().root()) {
// check that restart data doesnot exist
std::string path = "/Walkers/WalkerSet";
if (dump.is_group(path))
{
app_error() << " ERROR: H5Group /Walkers/WalkerSet already exists in restart file. This is a bug and should not "
"happen. Contact a developer.\n";
return false;
}
int NMO, NAEA, NAEB = 0;
{ // to limit the scope
auto w = wset[0];
NMO = (*w.SlaterMatrix(Alpha)).size(0);
NAEA = (*w.SlaterMatrix(Alpha)).size(1);
if (walker_type == COLLINEAR)
NAEB = (*w.SlaterMatrix(Beta)).size(1)
}
std::vector<int> Idata(7);
Idata[0] = nWtot;
Idata[1] = nblkTot;
Idata[2] = wlk_nterms;
Idata[3] = wlk_sz;
Idata[4] = NMO;
Idata[5] = NAEA;
Idata[6] = NAEB;
dump.push("Walkers");
dump.push("WalkerSet");
dump.write(Idata, "dims");
// }
APP_ABORT("FINISH.\n");
// loop through blocks and use double hyperslabs
#else
// communicate to root
int nwlk_per_block = std::min(std::max(1, WALKER_HDF_BLOCK_SIZE / wlk_sz), nWtot);
int nblks = (nWtot - 1) / nwlk_per_block + 1;
std::vector<int> wlk_per_blk;
boost::multi::array<ComplexType, 2> RecvBuff;
boost::multi::array<int, 1> counts, displ;
if (TG.TG_heads().root())
{
// check that restart data doesnot exist
std::string path = "/Walkers/WalkerSet";
if (dump.is_group(path))
{
app_error() << " ERROR: H5Group /Walkers/WalkerSet already exists in restart file. This is a bug and should "
"not happen. Contact a developer.\n";
return false;
}
counts.reextent({TG.TG_heads().size()});
displ.reextent({TG.TG_heads().size()});
wlk_per_blk.reserve(nblks);
int NMO, NAEA, NAEB = 0;
{ // to limit the scope
auto w = wset[0];
NMO = (*w.SlaterMatrix(Alpha)).size(0);
NAEA = (*w.SlaterMatrix(Alpha)).size(1);
if (walker_type == COLLINEAR)
NAEB = (*w.SlaterMatrix(Beta)).size(1);
}
std::vector<int> Idata(7);
Idata[0] = nWtot;
Idata[1] = nblks;
Idata[2] = wlk_nterms;
Idata[3] = wlk_sz;
Idata[4] = NMO;
Idata[5] = NAEA;
Idata[6] = NAEB;
dump.push("Walkers");
dump.push("WalkerSet");
dump.write(Idata, "dims");
}
int nsent = 0;
// ready to send walkers to head in blocks
for (int i = 0, ndone = 0; i < nblks; i++, ndone += nwlk_per_block)
{
boost::multi::array<ComplexType, 2> SendBuff;
int nwlk_tot = std::min(nwlk_per_block, nWtot - ndone);
int nw_to_send = 0;
if (w0 + nsent >= ndone && w0 + nsent < ndone + nwlk_tot)
nw_to_send = std::min(nW - nsent, (ndone + nwlk_tot) - (w0 + nsent));
if (TG.TG_heads().root())
{
for (int p = 0, nt = 0; p < TG.TG_heads().size(); p++)
{
int n_ = 0;
if (ndone + nwlk_tot > nt && ndone < nt + nW)
{
if (ndone <= nt)
n_ = std::min(nW, (ndone + nwlk_tot) - nt);
else
n_ = std::min(nt + nW - ndone, nwlk_tot);
}
counts[p] = n_ * wlk_nterms;
nt += nw_per_tg[p];
}
displ[0] = 0;
for (int p = 1, nt = 0; p < TG.TG_heads().size(); p++)
{
nt += counts[p - 1];
displ[p] = nt;
}
RecvBuff.reextent({nwlk_tot, wlk_nterms});
}
if (nw_to_send > 0)
{
SendBuff.reextent({nw_to_send, wlk_nterms});
for (int p = 0; p < nw_to_send; p++)
{
wset.copyToIO(SendBuff[p], nsent + p);
}
}
TG.TG_heads().gatherv_n(SendBuff.origin(), SendBuff.num_elements(), RecvBuff.origin(), counts.data(),
displ.data(), 0);
nsent += nw_to_send;
if (TG.TG_heads().root())
{
dump.write(RecvBuff, std::string("walkers_") + std::to_string(i));
wlk_per_blk.push_back(nwlk_tot);
}
// not sure if necessary, but avoids avalanche of messages on head node
TG.TG_heads().barrier();
}
if (TG.TG_heads().root())
{
dump.write(wlk_per_blk, "wlk_per_blk");
dump.pop();
dump.pop();
}
#endif
}
TG.global_barrier();
return true;
}
} // namespace afqmc
} // namespace qmcplusplus
#endif
| 29.652632 | 119 | 0.565779 | [
"vector"
] |
1134c40dd6b1e3775e02148e7eedca2ceebc8c54 | 11,186 | cpp | C++ | Game.cpp | NateBoi4/Artificial-Intelligence-in-Video-Games-Formations-Technique | 49112e2cef45cf0e6d382981754e77814d82b1b8 | [
"MIT"
] | null | null | null | Game.cpp | NateBoi4/Artificial-Intelligence-in-Video-Games-Formations-Technique | 49112e2cef45cf0e6d382981754e77814d82b1b8 | [
"MIT"
] | null | null | null | Game.cpp | NateBoi4/Artificial-Intelligence-in-Video-Games-Formations-Technique | 49112e2cef45cf0e6d382981754e77814d82b1b8 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <assert.h>
#include <iostream>
#include <sstream>
#include "Game.h"
#include <System.h>
#include <GraphicsSystem.h>
#include <GraphicsBuffer.h>
#include <Font.h>
#include <FontManager.h>
#include <GraphicsBufferManager.h>
#include <InputSystem.h>
#include "GameMessageManager.h"
#include <Sprite.h>
#include "SpriteManager.h"
#include <Timer.h>
#include <DataRepository.h>
#include "PlayerMoveToMessage.h"
#include "CreateUnitMessage.h"
#include "ComponentManager.h"
#include "UnitManager.h"
#include "DataLoader.h"
#include "ExtraColors.h"
#include "StateMachine.h"
#include "WanderState.h"
#include "HealState.h"
#include "ChaseState.h"
Game* gpGame = NULL;
Game::Game()
:Trackable("game class")
,mpSystem(NULL)
,mpGraphicsBufferManager(NULL)
,mpSpriteManager(NULL)
,mpFontManager(NULL)
,mpLoopTimer(NULL)
,mpMasterTimer(NULL)
,mpFont(NULL)
,mShouldExit(false)
,mBackgroundBufferID("")
,mpMessageManager(NULL)
,mpComponentManager(NULL)
,mpUnitManager(NULL)
,mpRepository(NULL)
,mTimeLastFrame(0.0f)
{
}
Game::~Game()
{
cleanup();
}
bool Game::init()
{
mShouldExit = false;
//create Timers
mpLoopTimer = new Timer;
mpMasterTimer = new Timer;
mpRepository = new DataRepository;
DataLoader loader("data.txt", mpRepository);
//create and init GraphicsSystem
mpSystem = new System();
bool goodGraphics = mpSystem->init( mpRepository->getEntry(DataKeyEnum::SCREEN_WIDTH).getUIntVal(), mpRepository->getEntry(DataKeyEnum::SCREEN_HEIGHT).getUIntVal());
if(!goodGraphics)
{
fprintf(stderr, "failed to initialize GraphicsSystem object!\n");
return false;
}
mpGraphicsBufferManager = new GraphicsBufferManager(mpSystem->getGraphicsSystem());
mpSpriteManager = new SpriteManager;
mpFontManager = new FontManager;
mpMessageManager = new GameMessageManager();
UINT maxUnits = mpRepository->getEntry(DataKeyEnum::MAX_UNITS).getUIntVal();
mpComponentManager = new ComponentManager(maxUnits);
mpUnitManager = new UnitManager(maxUnits);
//load buffers
GraphicsBuffer* pBuff;
pBuff = mpGraphicsBufferManager->loadBuffer(mBackgroundBufferID,"wallpaper.bmp");
assert(pBuff);
pBuff = mpGraphicsBufferManager->loadBuffer(mPlayerIconBufferID,"arrow.png");
assert(pBuff);
pBuff = mpGraphicsBufferManager->loadBuffer(mEnemyIconBufferID, "enemy-arrow.png");
assert(pBuff);
pBuff = mpGraphicsBufferManager->loadBuffer(mEnemyChaseIconBufferID, "enemy-arrow-chase.png");
assert(pBuff);
pBuff = mpGraphicsBufferManager->loadBuffer(mEnemyHealIconBufferID, "enemy-arrow-heal.png");
assert(pBuff);
pBuff = mpGraphicsBufferManager->loadBuffer(mHealIconBufferID, "heal.png");
assert(pBuff);
pBuff = mpGraphicsBufferManager->loadBuffer(mTargetBufferID,"target.png");
assert(pBuff);
//load Font
mpFont = mpFontManager->createAndManageFont(COUR_24_FONT_ID, "cour.ttf", 24);
//setup sprites
GraphicsBuffer* pBackGroundBuffer = mpGraphicsBufferManager->getBuffer( mBackgroundBufferID );
if( pBackGroundBuffer != NULL )
{
mpSpriteManager->createAndManageSprite( BACKGROUND_SPRITE_ID, pBackGroundBuffer, 0, 0, (float)pBackGroundBuffer->getWidth(), (float)pBackGroundBuffer->getHeight() );
}
GraphicsBuffer* pPlayerBuffer = mpGraphicsBufferManager->getBuffer( mPlayerIconBufferID );
Sprite* pArrowSprite = NULL;
if( pPlayerBuffer != NULL )
{
pArrowSprite = mpSpriteManager->createAndManageSprite( PLAYER_ICON_SPRITE_ID, pPlayerBuffer, 0, 0, (float)pPlayerBuffer->getWidth(), (float)pPlayerBuffer->getHeight() );
}
GraphicsBuffer* pAIBuffer = mpGraphicsBufferManager->getBuffer(mEnemyIconBufferID);
Sprite* pEnemyArrow = NULL;
if (pAIBuffer != NULL)
{
pEnemyArrow = mpSpriteManager->createAndManageSprite(AI_ICON_SPRITE_ID, pAIBuffer, 0, 0, (float)pAIBuffer->getWidth(), (float)pAIBuffer->getHeight());
}
GraphicsBuffer* pAIChaseBuffer = mpGraphicsBufferManager->getBuffer(mEnemyChaseIconBufferID);
if (pAIChaseBuffer != NULL)
{
mpSpriteManager->createAndManageSprite(AI_CHASE_ICON_SPRITE_ID, pAIChaseBuffer, 0, 0, (float)pAIChaseBuffer->getWidth(), (float)pAIChaseBuffer->getHeight());
}
GraphicsBuffer* pAIHealBuffer = mpGraphicsBufferManager->getBuffer(mEnemyHealIconBufferID);
if (pAIHealBuffer != NULL)
{
mpSpriteManager->createAndManageSprite(AI_HEAL_ICON_SPRITE_ID, pAIHealBuffer, 0, 0, (float)pAIHealBuffer->getWidth(), (float)pAIHealBuffer->getHeight());
}
GraphicsBuffer* pHealBuffer = mpGraphicsBufferManager->getBuffer(mHealIconBufferID);
if (pAIHealBuffer != NULL)
{
mpSpriteManager->createAndManageSprite(HEAL_ICON_SPRITE_ID, pHealBuffer, 0, 0, (float)pHealBuffer->getWidth(), (float)pHealBuffer->getHeight());
}
GraphicsBuffer* pTargetBuffer = mpGraphicsBufferManager->getBuffer(mTargetBufferID);
if (pTargetBuffer != NULL)
{
mpSpriteManager->createAndManageSprite(TARGET_SPRITE_ID, pTargetBuffer, 0, 0, (float)pTargetBuffer->getWidth(), (float)pTargetBuffer->getHeight());
}
//setup units
Unit* pUnit = NULL;
if (pArrowSprite)
{
Vector2D center((int)getGraphicsSystem()->getDisplayWidth() / 2, (int)getGraphicsSystem()->getDisplayHeight() / 2);
//pUnit = mpUnitManager->createPlayerUnit(*pArrowSprite, false, PositionData(center, 0.0f));
//pUnit->setShowTarget(true);
//pUnit->setSteering(Steering::SEEK, Vector2D((int)getGraphicsSystem()->getDisplayWidth() / 2, 600));
}
//pUnit = mpUnitManager->createUnit(*mpSpriteManager->getSprite(HEAL_ICON_SPRITE_ID), false, PositionData(),PhysicsData(), HEAL_UNIT_ID);
mTargetFPS = mpRepository->getEntry(DataKeyEnum::TARGET_FPS).getUIntVal();
mTargetElapsedTime = 1000.0f / mTargetFPS;
return true;
}
void Game::cleanup()
{
//delete the timers
delete mpLoopTimer;
mpLoopTimer = NULL;
delete mpMasterTimer;
mpMasterTimer = NULL;
delete mpFontManager;
mpFontManager = NULL;
delete mpRepository;
mpRepository = NULL;
mpFont = NULL;
//delete the graphics system
delete mpSystem;
mpSystem = NULL;
delete mpGraphicsBufferManager;
mpGraphicsBufferManager = NULL;
delete mpSpriteManager;
mpSpriteManager = NULL;
delete mpMessageManager;
mpMessageManager = NULL;
delete mpUnitManager;
mpUnitManager = NULL;
delete mpComponentManager;
mpComponentManager = NULL;
}
void Game::doLoop()
{
//game loop
while (!mShouldExit)
{
gpPerformanceTracker->clearTracker("loop");
gpPerformanceTracker->startTracking("loop");
gpGame->beginLoop();
gpPerformanceTracker->clearTracker("process");
gpPerformanceTracker->startTracking("process");
gpGame->processLoop();
gpPerformanceTracker->stopTracking("process");
gpGame->endLoop();
gpPerformanceTracker->stopTracking("loop");
//std::cout << "loop took:" << gpPerformanceTracker->getElapsedTime("loop") << "ms ";
//std::cout << "processing took:" << gpPerformanceTracker->getElapsedTime("process") << "ms\n";
mTimeLastFrame = (float)gpPerformanceTracker->getElapsedTime("loop");
}
}
void Game::beginLoop()
{
mpLoopTimer->start();
}
void Game::processLoop()
{
InputSystem* pInputSystem = mpSystem->getInputSystem();
float dt = (mTargetElapsedTime * mTimeMult) / 1000.0f;
mpUnitManager->updateAll(dt);
mpComponentManager->update(dt);
pInputSystem->update(dt);
//potentially move the heal loc
updateHealLoc();
Sprite* pBackgroundSprite = mpSpriteManager->getSprite(BACKGROUND_SPRITE_ID);
GraphicsSystem::draw(Vector2D(0, 0), *pBackgroundSprite);
//draw units
mpUnitManager->drawAll();
if (mDrawDebugData)
{
drawDebugData();
}
mpSystem->getGraphicsSystem()->flip();
Vector2D pos = pInputSystem->getCurrentMousePos();
mpMessageManager->processMessagesForThisframe();
if(pInputSystem->isMouseButtonPressed(InputSystem::LEFT))
{
GameMessage* pMessage = new PlayerMoveToMessage( pos );
MESSAGE_MANAGER->addMessage( pMessage, 0 );
}
if(pInputSystem->isKeyPressed(InputSystem::ESCAPE_KEY))
{
mShouldExit = true;
}
if (pInputSystem->isKeyPressed(InputSystem::M_KEY))
{
for (int i = 0; i < mpRepository->getEntry(DataKeyEnum::MAX_UNITS).getUIntVal(); i++)
{
GameMessage* pMessage = new CreateUnitMessage;
MESSAGE_MANAGER->addMessage(pMessage, 100);
}
}
if (pInputSystem->isKeyPressed(InputSystem::UP_KEY))
{
GameMessage* pMessage = new CreateUnitMessage;
MESSAGE_MANAGER->addMessage(pMessage);
}
else if (pInputSystem->isKeyPressed(InputSystem::DOWN_KEY))
{
mpUnitManager->deleteRandomUnit();
}
if (pInputSystem->isKeyPressed(InputSystem::LEFT_KEY))
{
mTimeMult -= 0.1f;
if (mTimeMult < 0.0f)
mTimeMult = 0.0f;
}
else if (pInputSystem->isKeyPressed(InputSystem::RIGHT_KEY))
{
mTimeMult += 0.1f;
}
else if (pInputSystem->isKeyPressed(InputSystem::SPACE_KEY))
{
mTimeMult = 1.0f;
}
if (pInputSystem->isKeyPressed(InputSystem::D_KEY))
{
mDrawDebugData = false;
}
else
{
mDrawDebugData = true;
}
}
void Game::endLoop()
{
mpUnitManager->cleanupDeadUnits();
//mpMasterTimer->start();
mpLoopTimer->sleepUntilElapsed( mTargetElapsedTime );
}
void Game::drawDebugData()
{
//InputSystem* pInputSystem = mpSystem->getInputSystem();
//Vector2D pos = pInputSystem->getCurrentMousePos();
//create mouse text
std::stringstream textStream;
//textStream << pos;
//write text at mouse position
//GraphicsSystem::writeText(pos, *mpFont, BLACK_COLOR, textStream.str(), Font::RIGHT);
textStream.str("");
textStream.clear();
//write out current number of Units
//Uint32 numUnits = mpUnitManager->getNumUnits();
textStream << "Cycle through scalable formations with 1, 2, and 3."; ///<< numUnits;
GraphicsSystem::writeText(Vector2D(GraphicsSystem::getDisplayWidth() / 2, 0), *mpFont, BLACK_COLOR, textStream.str(), Font::CENTER);
textStream.str("");
textStream.clear();
//write out current fps
//int fps = (int)((1000.0f / mTimeLastFrame) + .5f);//+.5f does rounding
textStream << "Scale Formations with 4 and 5.";
GraphicsSystem::writeText(Vector2D(GraphicsSystem::getDisplayWidth() / 2, 20), *mpFont, BLACK_COLOR, textStream.str(), Font::CENTER);
textStream.str("");
textStream.clear();
//write out time multiple
textStream << "Spawn units with M. Can be used twice."; //<< mTimeMult;
GraphicsSystem::writeText(Vector2D(GraphicsSystem::getDisplayWidth() / 2, 40), *mpFont, BLACK_COLOR, textStream.str(), Font::CENTER);
}
void Game::updateHealLoc()
{
if (rand() % 100 == 99)
{
Vector2D loc = Vector2D((float)(rand() % GraphicsSystem::getDisplayWidth()), (float)(rand() % GraphicsSystem::getDisplayHeight()));
Unit* pUnit = mpUnitManager->getUnit(HEAL_UNIT_ID);
if (pUnit)
{
pUnit->getPositionComponent()->setPosition(loc);
}
}
}
GraphicsSystem* Game::getGraphicsSystem() const
{
return mpSystem->getGraphicsSystem();
}
float genRandomBinomial()
{
return genRandomFloat() - genRandomFloat();
}
float genRandomFloat()
{
float r = (float)rand()/(float)RAND_MAX;
return r;
}
| 28.318987 | 172 | 0.71956 | [
"object"
] |
11417223eeb6a0366a96d7e95b53dcf2f8892c33 | 1,154 | hpp | C++ | include/EmbGen/Parser/XmlElement.hpp | xxAtrain223/EmbGenParser | c6debf74579349c152170f1d4316525a29985960 | [
"MIT"
] | null | null | null | include/EmbGen/Parser/XmlElement.hpp | xxAtrain223/EmbGenParser | c6debf74579349c152170f1d4316525a29985960 | [
"MIT"
] | null | null | null | include/EmbGen/Parser/XmlElement.hpp | xxAtrain223/EmbGenParser | c6debf74579349c152170f1d4316525a29985960 | [
"MIT"
] | null | null | null | #ifndef EMBGEN_PARSER_XMLELEMENT_HPP
#define EMBGEN_PARSER_XMLELEMENT_HPP
#include <map>
#include <vector>
#include <string>
namespace tinyxml2
{
class XMLElement;
class XMLAttribute;
}
namespace emb
{
namespace gen
{
namespace parser
{
class XmlElement
{
const tinyxml2::XMLElement* m_tinyElement;
std::map<std::string, const tinyxml2::XMLAttribute*> m_attributes;
std::multimap<std::string, const tinyxml2::XMLElement*> m_elements;
protected:
XmlElement();
public:
XmlElement(const tinyxml2::XMLElement* xml);
std::string getName() const;
virtual std::string getText() const;
int getLineNum() const;
const tinyxml2::XMLAttribute* getAttribute(std::string name);
bool isAttributesEmpty() const;
std::vector<const tinyxml2::XMLElement*> getElements(std::string name);
bool isElementsEmpty() const;
};
}
}
}
#endif // EMBGEN_PARSER_XMLELEMENT_HPP | 23.08 | 87 | 0.576256 | [
"vector"
] |
11464dabe071291c49b3633714cceec54c645f02 | 4,255 | cpp | C++ | src/lp2cpp/language/Program.cpp | WaspWithCompilation/WASP_C | b4672295ebb7aa514d7a706ca0746ca2c6831d44 | [
"Apache-2.0"
] | null | null | null | src/lp2cpp/language/Program.cpp | WaspWithCompilation/WASP_C | b4672295ebb7aa514d7a706ca0746ca2c6831d44 | [
"Apache-2.0"
] | null | null | null | src/lp2cpp/language/Program.cpp | WaspWithCompilation/WASP_C | b4672295ebb7aa514d7a706ca0746ca2c6831d44 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright 2016 Bernardo Cuteri, Francesco Ricca.
*
* 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 <map>
#include <list>
#include <set>
#include <iostream>
#include "Program.h"
using namespace std;
aspc::Program::Program() {
}
aspc::Program::~Program() {
}
void aspc::Program::addRule(const Rule & r) {
rules.push_back(r);
for (const Literal & literal : r.getBodyLiterals()) {
rules_by_type[r.getType()][literal.getPredicateName()].insert(rules.size()-1);
}
}
void aspc::Program::addFact(const aspc::Atom & r) {
facts.push_back(r);
}
const aspc::Rule & aspc::Program::getRule(unsigned i) const {
return rules[i];
}
unsigned aspc::Program::getRulesSize() const {
return rules.size();
}
const vector<aspc::Rule>& aspc::Program::getRules() const{
return rules;
}
vector<aspc::Rule>& aspc::Program::getRules() {
return rules;
}
const aspc::Atom & aspc::Program::getFact(unsigned i) const {
return facts[i];
}
const vector<aspc::Atom>& aspc::Program::getFacts() const {
return facts;
}
unsigned aspc::Program::getFactsSize() const {
return facts.size();
}
const map<RuleType, map<string, set<unsigned> > >& aspc::Program::getRulesByType() const {
return rules_by_type;
}
const set<unsigned> & aspc::Program::getRulesByTypeAndPredicateName(const string & predicateName, RuleType type) const {
return rules_by_type.at(type).at(predicateName);
}
void aspc::Program::clearFacts() {
facts.clear();
}
void aspc::Program::print() const {
for (const Rule & rule : rules) {
rule.print();
}
}
void aspc::Program::addPredicate(const string& name, const unsigned ariety) {
predicates.insert(pair<string, unsigned>(name,ariety));
}
const set<pair<string, unsigned> >& aspc::Program::getPredicates() const {
return predicates;
}
const std::set< std::pair<std::string, unsigned> >& aspc::Program::getAggregatePredicates() const{
return aggregatePredicates;
}
void aspc::Program::addAggregatePredicate(const std::string& name, const unsigned ariety){
aggregatePredicates.insert(pair<string, unsigned>(name,ariety));
}
void aspc::Program::addArithmeticRelationToRule(unsigned index,aspc::ArithmeticRelationWithAggregate r){
rules[index].addArithmeticRelationsWithAggregate(r);
}
void aspc::Program::changeCompareTypeToRule(unsigned index,int aggrIndex,aspc::ComparisonType type){
rules[index].changeCompareTypeToAggregate(aggrIndex,type);
}
set<string> aspc::Program::getBodyPredicates() const {
set<string> res;
for(const Rule & r:rules) {
for(const Literal & l: r.getBodyLiterals()) {
res.insert(l.getPredicateName());
}
//added for aggregate
for(ArithmeticRelationWithAggregate aggr : r.getArithmeticRelationsWithAggregate()){
for(Literal l : aggr.getAggregate().getAggregateLiterals()){
res.insert(l.getPredicateName());
}
}
}
return res;
}
set<string> aspc::Program::getHeadPredicates() const {
set<string> res;
for(const Rule & r:rules) {
for(const Atom & a: r.getHead()) {
res.insert(a.getPredicateName());
}
}
return res;
}
bool aspc::Program::hasConstraintWithLiteral() const{
for(const Rule & r: rules) {
if(r.isConstraint() && r.containsLiteral()) {
return true;
}
}
return false;
}
bool aspc::Program::hasConstraint() const {
for(const Rule & r: rules) {
if(r.isConstraint()) {
return true;
}
}
return false;
}
| 26.93038 | 121 | 0.647004 | [
"vector"
] |
1146ae66093fab6603502e297edd4fbc4d68ac33 | 1,413 | cpp | C++ | 1_term/made_2019_algorithms/05/Haffman algorithm/bits_workers.cpp | Ilyabasharov/made_mail.ru | a81bfd874ab80eb8c7eaad8a4acf723f327f2f50 | [
"MIT"
] | 1 | 2020-02-15T06:20:30.000Z | 2020-02-15T06:20:30.000Z | 1_term/made_2019_algorithms/05/Haffman algorithm/bits_workers.cpp | Ilyabasharov/made_mail.ru | a81bfd874ab80eb8c7eaad8a4acf723f327f2f50 | [
"MIT"
] | null | null | null | 1_term/made_2019_algorithms/05/Haffman algorithm/bits_workers.cpp | Ilyabasharov/made_mail.ru | a81bfd874ab80eb8c7eaad8a4acf723f327f2f50 | [
"MIT"
] | 1 | 2021-08-31T08:47:24.000Z | 2021-08-31T08:47:24.000Z | //
// bits_writer.cpp
// Haffman algorithm
//
// Created by Илья Башаров on 10/12/2019.
// Copyright © 2019 MIPT. All rights reserved.
//
#include "bits_workers.hpp"
void BitsWriter::WriteBit(bool bit)
{
accumulator |= bit << bits_count++;
if (bits_count == 8)
{
bits_count = 0;
buffer.push_back(accumulator);
accumulator = 0;
}
}
void BitsWriter::WriteByte(byte byte_)
{
if (bits_count == 0)
buffer.push_back(byte_);
else
{
accumulator |= byte_ << bits_count;
buffer.push_back(accumulator);
accumulator = byte_ >> (8 - bits_count);
}
}
std::vector<byte> BitsWriter::GetResult()
{
if (bits_count != 0)
buffer.push_back(accumulator);
buffer.push_back(static_cast<byte>(bits_count));
return std::move(buffer);
}
bool BitsReader::ReadBit(IInputStream &stream, bool& input)
{
if (bits_count == 8)
{
bits_count = 0;
if (!stream.Read(value))
return false;
}
input = (value >> bits_count++) & true;
return true;
}
bool BitsReader::ReadByte(IInputStream& stream, byte& input)
{
if (bits_count == 8)
return stream.Read(input);
byte temp = 0;
if (!stream.Read(temp))
return false;
value = value >> bits_count;
value |= temp << (8 - bits_count);
input = value;
value = temp;
return true;
}
| 19.901408 | 60 | 0.58811 | [
"vector"
] |
114b73d973455b988c66e310fdc2d95da5f50e8b | 64,191 | cxx | C++ | MUON/MUONrec/AliMUONVTrackReconstructor.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | MUON/MUONrec/AliMUONVTrackReconstructor.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | MUON/MUONrec/AliMUONVTrackReconstructor.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-----------------------------------------------------------------------------
/// \class AliMUONVTrackReconstructor
/// Virtual MUON track reconstructor in ALICE (class renamed from AliMUONEventReconstructor)
///
/// This class contains as data a pointer to the array of reconstructed tracks
///
/// It contains as methods, among others:
/// * EventReconstruct to build the muon tracks
/// * EventReconstructTrigger to build the trigger tracks
/// * ValidateTracksWithTrigger to match tracker/trigger tracks
///
/// Several options and adjustable parameters are available for both KALMAN and ORIGINAL
/// tracking algorithms. They can be changed through the AliMUONRecoParam object
/// set in the reconstruction macro or read from the CDB
/// (see methods in AliMUONRecoParam.h file for details)
///
/// Main parameters and options are:
/// - *fgkSigmaToCutForTracking* : quality cut used to select new clusters to be
/// attached to the track candidate and to select good tracks.
/// - *fgkMakeTrackCandidatesFast* : if this flag is set to 'true', the track candidates
/// are made assuming linear propagation between stations 4 and 5.
/// - *fgkTrackAllTracks* : according to the value of this flag, in case that several
/// new clusters pass the quality cut, either we consider all the possibilities
/// (duplicating tracks) or we attach only the best cluster.
/// - *fgkRecoverTracks* : if this flag is set to 'true', we try to recover the tracks
/// lost during the tracking by removing the worst of the 2 clusters attached in the
/// previous station.
/// - *fgkImproveTracks* : if this flag is set to 'true', we try to improve the quality
/// of the tracks at the end of the tracking by removing clusters that do not pass
/// new quality cut (the track is removed is it does not contain enough cluster anymore).
/// - *fgkComplementTracks* : if this flag is set to 'true', we try to improve the quality
/// of the tracks at the end of the tracking by adding potentially missing clusters
/// (we may have 2 clusters in the same chamber because of the overlapping of detection
/// elements, which is not handle by the tracking algorithm).
/// - *fgkSigmaToCutForImprovement* : quality cut used when we try to improve the
/// quality of the tracks.
///
/// \author Philippe Pillot
//-----------------------------------------------------------------------------
#include "AliMUONVTrackReconstructor.h"
#include "AliMUONConstants.h"
#include "AliMUONObjectPair.h"
#include "AliMUONTriggerTrack.h"
#include "AliMUONTriggerCircuit.h"
#include "AliMUONLocalTrigger.h"
#include "AliMUONGlobalTrigger.h"
#include "AliMUONTrack.h"
#include "AliMUONTrackParam.h"
#include "AliMUONTrackExtrap.h"
#include "AliMUONTrackHitPattern.h"
#include "AliMUONVTrackStore.h"
#include "AliMUONVClusterStore.h"
#include "AliMUONVCluster.h"
#include "AliMUONVClusterServer.h"
#include "AliMUONVTriggerStore.h"
#include "AliMUONVTriggerTrackStore.h"
#include "AliMUONRecoParam.h"
#include "AliMUONGeometryTransformer.h"
#include "AliMUONVDigit.h"
#include "AliMpDEManager.h"
#include "AliMpArea.h"
#include "AliMpDDLStore.h"
#include "AliMpVSegmentation.h"
#include "AliMpSegmentation.h"
#include "AliMpPad.h"
#include "AliMpDetElement.h"
#include "AliMpCathodType.h"
#include "AliLog.h"
#include "AliCodeTimer.h"
#include "AliTracker.h"
#include <TClonesArray.h>
#include <TMath.h>
#include <TMatrixD.h>
#include <TVector2.h>
#include <Riostream.h>
using std::cout;
using std::endl;
/// \cond CLASSIMP
ClassImp(AliMUONVTrackReconstructor) // Class implementation in ROOT context
/// \endcond
//__________________________________________________________________________
AliMUONVTrackReconstructor::AliMUONVTrackReconstructor(const AliMUONRecoParam* recoParam,
AliMUONVClusterServer* clusterServer,
const AliMUONGeometryTransformer* transformer)
: TObject(),
fRecTracksPtr(0x0),
fNRecTracks(0),
fClusterServer(clusterServer),
fkRecoParam(recoParam),
fkTransformer(transformer),
fMaxMCSAngle2(0x0)
{
/// Constructor for class AliMUONVTrackReconstructor
/// WARNING: if clusterServer=0x0, no clusterization will be possible at this level
// Memory allocation for the TClonesArray of reconstructed tracks
fRecTracksPtr = new TClonesArray("AliMUONTrack", 100);
// set the magnetic field for track extrapolations
AliMUONTrackExtrap::SetField();
// set the maximum MCS angle in chamber from the minimum acceptable momentum
AliMUONTrackParam param;
Double_t inverseBendingP = (GetRecoParam()->GetMinBendingMomentum() > 0.) ? 1./GetRecoParam()->GetMinBendingMomentum() : 1.;
param.SetInverseBendingMomentum(inverseBendingP);
fMaxMCSAngle2 = new Double_t [AliMUONConstants::NTrackingCh()];
for (Int_t iCh=0; iCh<AliMUONConstants::NTrackingCh(); iCh++)
fMaxMCSAngle2[iCh] = AliMUONTrackExtrap::GetMCSAngle2(param, AliMUONConstants::ChamberThicknessInX0(iCh), 1.);
}
//__________________________________________________________________________
AliMUONVTrackReconstructor::~AliMUONVTrackReconstructor()
{
/// Destructor for class AliMUONVTrackReconstructor
delete fRecTracksPtr;
delete[] fMaxMCSAngle2;
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::ResetTracks()
{
/// To reset the TClonesArray of reconstructed tracks
if (fRecTracksPtr) fRecTracksPtr->Clear("C");
fNRecTracks = 0;
return;
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::EventReconstruct(AliMUONVClusterStore& clusterStore, AliMUONVTrackStore& trackStore)
{
/// To reconstruct one event
AliDebug(1,"");
AliCodeTimerAuto("",0);
// Reset array of tracks
ResetTracks();
// Look for candidates from clusters in stations(1..) 4 and 5 (abort in case of failure)
if (!MakeTrackCandidates(clusterStore)) return;
// Look for extra candidates from clusters in stations(1..) 4 and 5 (abort in case of failure)
if (GetRecoParam()->MakeMoreTrackCandidates()) {
if (!MakeMoreTrackCandidates(clusterStore)) return;
}
// Stop tracking if no candidate found
if (fRecTracksPtr->GetEntriesFast() == 0) return;
// Follow tracks in stations(1..) 3, 2 and 1 (abort in case of failure)
if (!FollowTracks(clusterStore)) return;
// Complement the reconstructed tracks
if (GetRecoParam()->ComplementTracks()) {
if (ComplementTracks(clusterStore)) RemoveIdenticalTracks();
}
// Improve the reconstructed tracks
if (GetRecoParam()->ImproveTracks()) ImproveTracks();
// Remove connected tracks
RemoveConnectedTracks(3, 4, kFALSE);
RemoveConnectedTracks(2, 2, kFALSE);
if (GetRecoParam()->RemoveConnectedTracksInSt12()) RemoveConnectedTracks(0, 1, kFALSE);
// Fill AliMUONTrack data members
Finalize();
if (!GetRecoParam()->RemoveConnectedTracksInSt12()) TagConnectedTracks(0, 1, kTRUE);
// Make sure there is no bad track left
RemoveBadTracks();
// Refit the reconstructed tracks with a different resolution for mono-cathod clusters
if (GetRecoParam()->DiscardMonoCathodClusters()) DiscardMonoCathodClusters();
// Add tracks to MUON data container
for (Int_t i=0; i<fNRecTracks; ++i)
{
AliMUONTrack * track = (AliMUONTrack*) fRecTracksPtr->At(i);
track->SetUniqueID(i+1);
trackStore.Add(*track);
}
}
//__________________________________________________________________________
Bool_t AliMUONVTrackReconstructor::IsAcceptable(AliMUONTrackParam &trackParam)
{
/// Return kTRUE if the track is within given limits on momentum/angle/origin
const TMatrixD& kParamCov = trackParam.GetCovariances();
Int_t chamber = trackParam.GetClusterPtr()->GetChamberId();
Double_t z = trackParam.GetZ();
Double_t sigmaCut = GetRecoParam()->GetSigmaCutForTracking();
// MCS dipersion
Double_t angleMCS2 = 0.;
Double_t impactMCS2 = 0.;
if (AliMUONTrackExtrap::IsFieldON() && chamber < 6) {
// track momentum is known
for (Int_t iCh=0; iCh<=chamber; iCh++) {
Double_t localMCS2 = AliMUONTrackExtrap::GetMCSAngle2(trackParam, AliMUONConstants::ChamberThicknessInX0(iCh), 1.);
angleMCS2 += localMCS2;
impactMCS2 += AliMUONConstants::DefaultChamberZ(chamber) * AliMUONConstants::DefaultChamberZ(chamber) * localMCS2;
}
} else {
// track momentum is unknown
for (Int_t iCh=0; iCh<=chamber; iCh++) {
angleMCS2 += fMaxMCSAngle2[iCh];
impactMCS2 += AliMUONConstants::DefaultChamberZ(chamber) * AliMUONConstants::DefaultChamberZ(chamber) * fMaxMCSAngle2[iCh];
}
}
// ------ track selection in non bending direction ------
if (GetRecoParam()->SelectOnTrackSlope()) {
// check if non bending slope is within tolerances
Double_t nonBendingSlopeErr = TMath::Sqrt(kParamCov(1,1) + angleMCS2);
if ((TMath::Abs(trackParam.GetNonBendingSlope()) - sigmaCut * nonBendingSlopeErr) > GetRecoParam()->GetMaxNonBendingSlope()) return kFALSE;
} else {
// or check if non bending impact parameter is within tolerances
Double_t nonBendingImpactParam = TMath::Abs(trackParam.GetNonBendingCoor() - z * trackParam.GetNonBendingSlope());
Double_t nonBendingImpactParamErr = TMath::Sqrt(kParamCov(0,0) + z * z * kParamCov(1,1) - 2. * z * kParamCov(0,1) + impactMCS2);
if ((nonBendingImpactParam - sigmaCut * nonBendingImpactParamErr) > (3. * GetRecoParam()->GetNonBendingVertexDispersion())) return kFALSE;
}
// ------ track selection in bending direction ------
if (AliMUONTrackExtrap::IsFieldON()) { // depending whether the field is ON or OFF
// check if bending momentum is within tolerances
Double_t bendingMomentum = TMath::Abs(1. / trackParam.GetInverseBendingMomentum());
Double_t bendingMomentumErr = TMath::Sqrt(kParamCov(4,4)) * bendingMomentum * bendingMomentum;
if (chamber < 6 && (bendingMomentum + sigmaCut * bendingMomentumErr) < GetRecoParam()->GetMinBendingMomentum()) return kFALSE;
else if ((bendingMomentum + 3. * bendingMomentumErr) < GetRecoParam()->GetMinBendingMomentum()) return kFALSE;
} else {
if (GetRecoParam()->SelectOnTrackSlope()) {
// check if bending slope is within tolerances
Double_t bendingSlopeErr = TMath::Sqrt(kParamCov(3,3) + angleMCS2);
if ((TMath::Abs(trackParam.GetBendingSlope()) - sigmaCut * bendingSlopeErr) > GetRecoParam()->GetMaxBendingSlope()) return kFALSE;
} else {
// or check if bending impact parameter is within tolerances
Double_t bendingImpactParam = TMath::Abs(trackParam.GetBendingCoor() - z * trackParam.GetBendingSlope());
Double_t bendingImpactParamErr = TMath::Sqrt(kParamCov(2,2) + z * z * kParamCov(3,3) - 2. * z * kParamCov(2,3) + impactMCS2);
if ((bendingImpactParam - sigmaCut * bendingImpactParamErr) > (3. * GetRecoParam()->GetBendingVertexDispersion())) return kFALSE;
}
}
return kTRUE;
}
//__________________________________________________________________________
TClonesArray* AliMUONVTrackReconstructor::MakeSegmentsBetweenChambers(const AliMUONVClusterStore& clusterStore, Int_t ch1, Int_t ch2)
{
/// To make the list of segments from the list of clusters in the 2 given chambers.
/// Return a TClonesArray of new segments (segments made in a previous call of this function are removed).
AliDebug(1,Form("Enter MakeSegmentsBetweenChambers (1..) %d-%d", ch1+1, ch2+1));
AliCodeTimerAuto("",0);
AliMUONVCluster *cluster1, *cluster2;
AliMUONObjectPair *segment;
Double_t z1 = 0., z2 = 0., dZ = 0.;
Double_t nonBendingSlope = 0., nonBendingSlopeErr = 0., nonBendingImpactParam = 0., nonBendingImpactParamErr = 0.;
Double_t bendingSlope = 0., bendingSlopeErr = 0., bendingImpactParam = 0., bendingImpactParamErr = 0., bendingImpactParamErr2 = 0.;
Double_t bendingMomentum = 0., bendingMomentumErr = 0.;
Double_t bendingVertexDispersion2 = GetRecoParam()->GetBendingVertexDispersion() * GetRecoParam()->GetBendingVertexDispersion();
Double_t angleMCS2 = 0.; // maximum angular dispersion**2 due to MCS in chamber
Double_t impactMCS2 = 0.; // maximum impact parameter dispersion**2 due to MCS in chamber
for (Int_t iCh=0; iCh<=ch1; iCh++) {
angleMCS2 += fMaxMCSAngle2[iCh];
impactMCS2 += AliMUONConstants::DefaultChamberZ(iCh) * AliMUONConstants::DefaultChamberZ(iCh) * fMaxMCSAngle2[iCh];
}
Double_t sigmaCut = GetRecoParam()->GetSigmaCutForTracking();
// Create iterators to loop over clusters in both chambers
TIter nextInCh1(clusterStore.CreateChamberIterator(ch1,ch1));
TIter nextInCh2(clusterStore.CreateChamberIterator(ch2,ch2));
// list of segments
static TClonesArray *segments = new TClonesArray("AliMUONObjectPair", 100);
segments->Clear("C");
// Loop over clusters in the first chamber of the station
while ( ( cluster1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
z1 = cluster1->GetZ();
// reset cluster iterator of chamber 2
nextInCh2.Reset();
// Loop over clusters in the second chamber of the station
while ( ( cluster2 = static_cast<AliMUONVCluster*>(nextInCh2()) ) ) {
z2 = cluster2->GetZ();
dZ = z1 - z2;
// ------ track selection in non bending direction ------
nonBendingSlope = (cluster1->GetX() - cluster2->GetX()) / dZ;
if (GetRecoParam()->SelectOnTrackSlope()) {
// check if non bending slope is within tolerances
nonBendingSlopeErr = TMath::Sqrt((cluster1->GetErrX2() + cluster2->GetErrX2()) / dZ / dZ + angleMCS2);
if ((TMath::Abs(nonBendingSlope) - sigmaCut * nonBendingSlopeErr) > GetRecoParam()->GetMaxNonBendingSlope()) continue;
} else {
// or check if non bending impact parameter is within tolerances
nonBendingImpactParam = TMath::Abs(cluster1->GetX() - cluster1->GetZ() * nonBendingSlope);
nonBendingImpactParamErr = TMath::Sqrt((z1 * z1 * cluster2->GetErrX2() + z2 * z2 * cluster1->GetErrX2()) / dZ / dZ + impactMCS2);
if ((nonBendingImpactParam - sigmaCut * nonBendingImpactParamErr) > (3. * GetRecoParam()->GetNonBendingVertexDispersion())) continue;
}
// ------ track selection in bending direction ------
bendingSlope = (cluster1->GetY() - cluster2->GetY()) / dZ;
if (AliMUONTrackExtrap::IsFieldON()) { // depending whether the field is ON or OFF
// check if bending momentum is within tolerances
bendingImpactParam = cluster1->GetY() - cluster1->GetZ() * bendingSlope;
bendingImpactParamErr2 = (z1 * z1 * cluster2->GetErrY2() + z2 * z2 * cluster1->GetErrY2()) / dZ / dZ + impactMCS2;
bendingMomentum = TMath::Abs(AliMUONTrackExtrap::GetBendingMomentumFromImpactParam(bendingImpactParam));
bendingMomentumErr = TMath::Sqrt((bendingVertexDispersion2 + bendingImpactParamErr2) /
bendingImpactParam / bendingImpactParam + 0.01) * bendingMomentum;
if ((bendingMomentum + 3. * bendingMomentumErr) < GetRecoParam()->GetMinBendingMomentum()) continue;
} else {
if (GetRecoParam()->SelectOnTrackSlope()) {
// check if bending slope is within tolerances
bendingSlopeErr = TMath::Sqrt((cluster1->GetErrY2() + cluster2->GetErrY2()) / dZ / dZ + angleMCS2);
if ((TMath::Abs(bendingSlope) - sigmaCut * bendingSlopeErr) > GetRecoParam()->GetMaxBendingSlope()) continue;
} else {
// or check if bending impact parameter is within tolerances
bendingImpactParam = TMath::Abs(cluster1->GetY() - cluster1->GetZ() * bendingSlope);
bendingImpactParamErr = TMath::Sqrt((z1 * z1 * cluster2->GetErrY2() + z2 * z2 * cluster1->GetErrY2()) / dZ / dZ + impactMCS2);
if ((bendingImpactParam - sigmaCut * bendingImpactParamErr) > (3. * GetRecoParam()->GetBendingVertexDispersion())) continue;
}
}
// make new segment
segment = new ((*segments)[segments->GetLast()+1]) AliMUONObjectPair(cluster1, cluster2, kFALSE, kFALSE);
// Printout for debug
if (AliLog::GetGlobalDebugLevel() > 1) {
cout << "segmentIndex(0...): " << segments->GetLast() << endl;
segment->Dump();
cout << "Cluster in first chamber" << endl;
cluster1->Print();
cout << "Cluster in second chamber" << endl;
cluster2->Print();
}
}
}
// Printout for debug
AliDebug(1,Form("chambers%d-%d: NSegments = %d ", ch1+1, ch2+1, segments->GetEntriesFast()));
return segments;
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::RemoveUsedSegments(TClonesArray& segments)
{
/// To remove pairs of clusters already attached to a track
AliDebug(1,"Enter RemoveUsedSegments");
Int_t nSegments = segments.GetEntriesFast();
Int_t nTracks = fRecTracksPtr->GetEntriesFast();
AliMUONObjectPair *segment;
AliMUONTrack *track;
AliMUONVCluster *cluster, *cluster1, *cluster2;
Bool_t foundCluster1, foundCluster2, removeSegment;
// Loop over segments
for (Int_t iSegment=0; iSegment<nSegments; iSegment++) {
segment = (AliMUONObjectPair*) segments.UncheckedAt(iSegment);
cluster1 = (AliMUONVCluster*) segment->First();
cluster2 = (AliMUONVCluster*) segment->Second();
removeSegment = kFALSE;
// Loop over tracks
for (Int_t iTrack = 0; iTrack < nTracks; iTrack++) {
track = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack);
// skip empty slot
if (!track) continue;
foundCluster1 = kFALSE;
foundCluster2 = kFALSE;
// Loop over clusters
Int_t nClusters = track->GetNClusters();
for (Int_t iCluster = 0; iCluster < nClusters; iCluster++) {
cluster = ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->UncheckedAt(iCluster))->GetClusterPtr();
// check if both clusters are in that track
if (cluster == cluster1) foundCluster1 = kTRUE;
else if (cluster == cluster2) foundCluster2 = kTRUE;
if (foundCluster1 && foundCluster2) {
removeSegment = kTRUE;
break;
}
}
if (removeSegment) break;
}
if (removeSegment) segments.RemoveAt(iSegment);
}
segments.Compress();
// Printout for debug
AliDebug(1,Form("NSegments = %d ", segments.GetEntriesFast()));
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::RemoveIdenticalTracks()
{
/// To remove identical tracks:
/// Tracks are considered identical if they have all their clusters in common.
/// One keeps the track with the larger number of clusters if need be
AliMUONTrack *track1, *track2;
Int_t nTracks = fRecTracksPtr->GetEntriesFast();
Int_t clustersInCommon, nClusters1, nClusters2;
// Loop over first track of the pair
for (Int_t iTrack1 = 0; iTrack1 < nTracks; iTrack1++) {
track1 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack1);
// skip empty slot
if (!track1) continue;
nClusters1 = track1->GetNClusters();
// Loop over second track of the pair
for (Int_t iTrack2 = iTrack1+1; iTrack2 < nTracks; iTrack2++) {
track2 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack2);
// skip empty slot
if (!track2) continue;
nClusters2 = track2->GetNClusters();
// number of clusters in common between two tracks
clustersInCommon = track1->ClustersInCommon(track2);
// check for identical tracks
if ((clustersInCommon == nClusters1) || (clustersInCommon == nClusters2)) {
// decide which track to remove
if (nClusters2 > nClusters1) {
// remove track1 and continue the first loop with the track next to track1
fRecTracksPtr->RemoveAt(iTrack1);
fNRecTracks--;
break;
} else {
// remove track2 and continue the second loop with the track next to track2
fRecTracksPtr->RemoveAt(iTrack2);
fNRecTracks--;
}
}
} // track2
} // track1
fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::RemoveDoubleTracks()
{
/// To remove double tracks:
/// Tracks are considered identical if more than half of the clusters of the track
/// which has the smaller number of clusters are in common with the other track.
/// Among two identical tracks, one keeps the track with the larger number of clusters
/// or, if these numbers are equal, the track with the minimum chi2.
AliMUONTrack *track1, *track2;
Int_t nTracks = fRecTracksPtr->GetEntriesFast();
Int_t clustersInCommon2, nClusters1, nClusters2;
// Loop over first track of the pair
for (Int_t iTrack1 = 0; iTrack1 < nTracks; iTrack1++) {
track1 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack1);
// skip empty slot
if (!track1) continue;
nClusters1 = track1->GetNClusters();
// Loop over second track of the pair
for (Int_t iTrack2 = iTrack1+1; iTrack2 < nTracks; iTrack2++) {
track2 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack2);
// skip empty slot
if (!track2) continue;
nClusters2 = track2->GetNClusters();
// number of clusters in common between two tracks
clustersInCommon2 = 2 * track1->ClustersInCommon(track2);
// check for identical tracks
if (clustersInCommon2 > nClusters1 || clustersInCommon2 > nClusters2) {
// decide which track to remove
if ((nClusters1 > nClusters2) || ((nClusters1 == nClusters2) && (track1->GetGlobalChi2() <= track2->GetGlobalChi2()))) {
// remove track2 and continue the second loop with the track next to track2
fRecTracksPtr->RemoveAt(iTrack2);
fNRecTracks--;
} else {
// else remove track1 and continue the first loop with the track next to track1
fRecTracksPtr->RemoveAt(iTrack1);
fNRecTracks--;
break;
}
}
} // track2
} // track1
fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::RemoveBadTracks()
{
/// Remove tracks for which a problem occured somewhere during the tracking
AliMUONTrack *track, *nextTrack;
Bool_t trackRemoved = kFALSE;
track = (AliMUONTrack*) fRecTracksPtr->First();
while (track) {
nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
if (track->GetGlobalChi2() >= AliMUONTrack::MaxChi2()) {
AliWarning("problem occured somewhere during the tracking --> discard track");
fRecTracksPtr->Remove(track);
fNRecTracks--;
trackRemoved = kTRUE;
}
track = nextTrack;
}
// compress array of tracks if needed
if (trackRemoved) fRecTracksPtr->Compress();
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::RemoveConnectedTracks(Int_t stMin, Int_t stMax, Bool_t all)
{
/// Find and remove tracks sharing 1 cluster or more in station(s) [stMin, stMax].
/// For each couple of connected tracks, one removes the one with the smallest
/// number of clusters or with the highest chi2 value in case of equality.
/// If all=kTRUE: both tracks are removed.
// tag the tracks to be removed
TagConnectedTracks(stMin, stMax, all);
// remove them
Int_t nTracks = fRecTracksPtr->GetEntriesFast();
for (Int_t i = 0; i < nTracks; i++) {
if (((AliMUONTrack*) fRecTracksPtr->UncheckedAt(i))->IsConnected()) {
fRecTracksPtr->RemoveAt(i);
fNRecTracks--;
}
}
// remove holes in the array if any
fRecTracksPtr->Compress();
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::TagConnectedTracks(Int_t stMin, Int_t stMax, Bool_t all)
{
/// Find and tag tracks sharing 1 cluster or more in station(s) [stMin, stMax].
/// For each couple of connected tracks, one tags the one with the smallest
/// number of clusters or with the highest chi2 value in case of equality.
/// If all=kTRUE: both tracks are tagged.
AliMUONTrack *track1, *track2;
Int_t nClusters1, nClusters2;
Int_t nTracks = fRecTracksPtr->GetEntriesFast();
// reset the tags
for (Int_t i = 0; i < nTracks; i++) ((AliMUONTrack*) fRecTracksPtr->UncheckedAt(i))->Connected(kFALSE);
// Loop over first track of the pair
for (Int_t iTrack1 = 0; iTrack1 < nTracks; iTrack1++) {
track1 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack1);
// Loop over second track of the pair
for (Int_t iTrack2 = iTrack1+1; iTrack2 < nTracks; iTrack2++) {
track2 = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iTrack2);
// check for connected tracks and tag them
if (track1->ClustersInCommon(track2, stMin, stMax) > 0) {
if (all) {
// tag both tracks
track1->Connected();
track2->Connected();
} else {
// tag only the worst track
nClusters1 = track1->GetNClusters();
nClusters2 = track2->GetNClusters();
if ((nClusters1 > nClusters2) || ((nClusters1 == nClusters2) && (track1->GetGlobalChi2() <= track2->GetGlobalChi2()))) {
track2->Connected();
} else {
track1->Connected();
}
}
}
}
}
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::AskForNewClustersInChamber(const AliMUONTrackParam &trackParam,
AliMUONVClusterStore& clusterStore, Int_t chamber)
{
/// Ask the clustering to reconstruct new clusters around the track candidate position
// check if the current chamber is useable
if (!fClusterServer || !GetRecoParam()->UseChamber(chamber)) return;
// maximum distance between the center of the chamber and a detection element
// (accounting for the inclination of the chamber)
static const Double_t kMaxDZ = 15.; // 15 cm
// extrapolate track parameters to the chamber
AliMUONTrackParam extrapTrackParam(trackParam);
if (!AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParam, AliMUONConstants::DefaultChamberZ(chamber))) return;
// build the searching area using the track and chamber resolutions and the maximum-distance-to-track value
const TMatrixD& kParamCov = extrapTrackParam.GetCovariances();
Double_t errX2 = kParamCov(0,0) + kMaxDZ * kMaxDZ * kParamCov(1,1) + 2. * kMaxDZ * TMath::Abs(kParamCov(0,1)) +
GetRecoParam()->GetDefaultNonBendingReso(chamber) * GetRecoParam()->GetDefaultNonBendingReso(chamber);
Double_t errY2 = kParamCov(2,2) + kMaxDZ * kMaxDZ * kParamCov(3,3) + 2. * kMaxDZ * TMath::Abs(kParamCov(2,3)) +
GetRecoParam()->GetDefaultBendingReso(chamber) * GetRecoParam()->GetDefaultBendingReso(chamber);
Double_t dX = TMath::Abs(trackParam.GetNonBendingSlope()) * kMaxDZ +
GetRecoParam()->GetMaxNonBendingDistanceToTrack() +
GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errX2);
Double_t dY = TMath::Abs(trackParam.GetBendingSlope()) * kMaxDZ +
GetRecoParam()->GetMaxBendingDistanceToTrack() +
GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errY2);
AliMpArea area(extrapTrackParam.GetNonBendingCoor(),
extrapTrackParam.GetBendingCoor(),
dX, dY);
// ask to cluterize in the given area of the given chamber
fClusterServer->Clusterize(chamber, clusterStore, area, GetRecoParam());
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::AskForNewClustersInStation(const AliMUONTrackParam &trackParam,
AliMUONVClusterStore& clusterStore, Int_t station)
{
/// Ask the clustering to reconstruct new clusters around the track candidate position
/// in the 2 chambers of the given station
AskForNewClustersInChamber(trackParam, clusterStore, 2*station+1);
AskForNewClustersInChamber(trackParam, clusterStore, 2*station);
}
//__________________________________________________________________________
Double_t AliMUONVTrackReconstructor::TryOneCluster(const AliMUONTrackParam &trackParam, AliMUONVCluster* cluster,
AliMUONTrackParam &trackParamAtCluster, Bool_t updatePropagator)
{
/// Test the compatibility between the track and the cluster (using trackParam's covariance matrix):
/// return the corresponding Chi2
/// return trackParamAtCluster
// extrapolate track parameters and covariances at the z position of the tested cluster
// and set pointer to cluster into trackParamAtCluster
trackParamAtCluster = trackParam;
trackParamAtCluster.SetClusterPtr(cluster);
if (!AliMUONTrackExtrap::ExtrapToZCov(&trackParamAtCluster, cluster->GetZ(), updatePropagator))
return 2.*AliMUONTrack::MaxChi2();
// Set differences between trackParam and cluster in the bending and non bending directions
Double_t dX = cluster->GetX() - trackParamAtCluster.GetNonBendingCoor();
Double_t dY = cluster->GetY() - trackParamAtCluster.GetBendingCoor();
// Calculate errors and covariances
const TMatrixD& kParamCov = trackParamAtCluster.GetCovariances();
Double_t sigmaX2 = kParamCov(0,0) + cluster->GetErrX2();
Double_t sigmaY2 = kParamCov(2,2) + cluster->GetErrY2();
Double_t covXY = kParamCov(0,2);
Double_t det = sigmaX2 * sigmaY2 - covXY * covXY;
// Compute chi2
if (det == 0.) return 2.*AliMUONTrack::MaxChi2();
return (dX * dX * sigmaY2 + dY * dY * sigmaX2 - 2. * dX * dY * covXY) / det;
}
//__________________________________________________________________________
Bool_t AliMUONVTrackReconstructor::TryOneClusterFast(const AliMUONTrackParam &trackParam, const AliMUONVCluster* cluster)
{
/// Test the compatibility between the track and the cluster
/// given the track and cluster resolutions + the maximum-distance-to-track value
/// and assuming linear propagation of the track:
/// return kTRUE if they are compatibles
Double_t dZ = cluster->GetZ() - trackParam.GetZ();
Double_t dX = cluster->GetX() - (trackParam.GetNonBendingCoor() + trackParam.GetNonBendingSlope() * dZ);
Double_t dY = cluster->GetY() - (trackParam.GetBendingCoor() + trackParam.GetBendingSlope() * dZ);
const TMatrixD& kParamCov = trackParam.GetCovariances();
Double_t errX2 = kParamCov(0,0) + dZ * dZ * kParamCov(1,1) + 2. * dZ * kParamCov(0,1) + cluster->GetErrX2();
Double_t errY2 = kParamCov(2,2) + dZ * dZ * kParamCov(3,3) + 2. * dZ * kParamCov(2,3) + cluster->GetErrY2();
Double_t dXmax = GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errX2) +
GetRecoParam()->GetMaxNonBendingDistanceToTrack();
Double_t dYmax = GetRecoParam()->GetSigmaCutForTracking() * TMath::Sqrt(2. * errY2) +
GetRecoParam()->GetMaxBendingDistanceToTrack();
if (TMath::Abs(dX) > dXmax || TMath::Abs(dY) > dYmax) return kFALSE;
return kTRUE;
}
//__________________________________________________________________________
Double_t AliMUONVTrackReconstructor::TryTwoClustersFast(const AliMUONTrackParam &trackParamAtCluster1, AliMUONVCluster* cluster2,
AliMUONTrackParam &trackParamAtCluster2)
{
/// Test the compatibility between the track and the 2 clusters together (using trackParam's covariance matrix)
/// assuming linear propagation between the two clusters:
/// return the corresponding Chi2 accounting for covariances between the 2 clusters
/// return trackParamAtCluster2
// extrapolate linearly track parameters and covariances at the z position of the second cluster
trackParamAtCluster2 = trackParamAtCluster1;
AliMUONTrackExtrap::LinearExtrapToZCov(&trackParamAtCluster2, cluster2->GetZ());
// set pointer to cluster2 into trackParamAtCluster2
trackParamAtCluster2.SetClusterPtr(cluster2);
// Set differences between track and clusters in the bending and non bending directions
AliMUONVCluster* cluster1 = trackParamAtCluster1.GetClusterPtr();
Double_t dX1 = cluster1->GetX() - trackParamAtCluster1.GetNonBendingCoor();
Double_t dX2 = cluster2->GetX() - trackParamAtCluster2.GetNonBendingCoor();
Double_t dY1 = cluster1->GetY() - trackParamAtCluster1.GetBendingCoor();
Double_t dY2 = cluster2->GetY() - trackParamAtCluster2.GetBendingCoor();
// Calculate errors and covariances
const TMatrixD& kParamCov1 = trackParamAtCluster1.GetCovariances();
const TMatrixD& kParamCov2 = trackParamAtCluster2.GetCovariances();
Double_t dZ = trackParamAtCluster2.GetZ() - trackParamAtCluster1.GetZ();
Double_t sigma2X1 = kParamCov1(0,0) + cluster1->GetErrX2();
Double_t sigma2X2 = kParamCov2(0,0) + cluster2->GetErrX2();
Double_t covX1X2 = kParamCov1(0,0) + dZ * kParamCov1(0,1);
Double_t sigma2Y1 = kParamCov1(2,2) + cluster1->GetErrY2();
Double_t sigma2Y2 = kParamCov2(2,2) + cluster2->GetErrY2();
Double_t covY1Y2 = kParamCov1(2,2) + dZ * kParamCov1(2,3);
// Compute chi2
Double_t detX = sigma2X1 * sigma2X2 - covX1X2 * covX1X2;
Double_t detY = sigma2Y1 * sigma2Y2 - covY1Y2 * covY1Y2;
if (detX == 0. || detY == 0.) return 2.*AliMUONTrack::MaxChi2();
return (dX1 * dX1 * sigma2X2 + dX2 * dX2 * sigma2X1 - 2. * dX1 * dX2 * covX1X2) / detX
+ (dY1 * dY1 * sigma2Y2 + dY2 * dY2 * sigma2Y1 - 2. * dY1 * dY2 * covY1Y2) / detY;
}
//__________________________________________________________________________
Bool_t AliMUONVTrackReconstructor::FollowLinearTrackInChamber(AliMUONTrack &trackCandidate, const AliMUONVClusterStore& clusterStore,
Int_t nextChamber)
{
/// Follow trackCandidate in chamber(0..) nextChamber assuming linear propagation, and search for compatible cluster(s)
/// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
/// kTRUE: duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
/// fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
/// Remove the obsolete "trackCandidate" at the end.
/// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
/// return kTRUE if new cluster(s) have been found (otherwise return kFALSE)
AliDebug(1,Form("Enter FollowLinearTrackInChamber(1..) %d", nextChamber+1));
Double_t chi2WithOneCluster = AliMUONTrack::MaxChi2();
Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
Bool_t foundOneCluster = kFALSE;
AliMUONTrack *newTrack = 0x0;
AliMUONVCluster *cluster;
AliMUONTrackParam trackParam;
AliMUONTrackParam extrapTrackParamAtCluster;
AliMUONTrackParam bestTrackParamAtCluster;
// Get track parameters according to the propagation direction
if (nextChamber > 7) trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
else trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
trackParam.GetParameters().Print();
trackParam.GetCovariances().Print();
}
// Add MCS effect
AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(trackParam.GetClusterPtr()->GetChamberId()),-1.);
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInChamber: look for cluster in chamber(1..): " << nextChamber+1 << endl;
}
// Create iterators to loop over clusters in chamber
TIter next(clusterStore.CreateChamberIterator(nextChamber,nextChamber));
// look for candidates in chamber
while ( ( cluster = static_cast<AliMUONVCluster*>(next()) ) ) {
// try to add the current cluster fast
if (!TryOneClusterFast(trackParam, cluster)) continue;
// try to add the current cluster accuratly
extrapTrackParamAtCluster = trackParam;
AliMUONTrackExtrap::LinearExtrapToZCov(&extrapTrackParamAtCluster, cluster->GetZ());
chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCluster, cluster, extrapTrackParamAtCluster);
// if good chi2 then consider to add cluster
if (chi2WithOneCluster < maxChi2WithOneCluster) {
foundOneCluster = kTRUE;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInChamber: found one cluster in chamber(1..): " << nextChamber+1
<< " (Chi2 = " << chi2WithOneCluster << ")" << endl;
cluster->Print();
}
if (GetRecoParam()->TrackAllTracks()) {
// copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
if (GetRecoParam()->RequestStation(nextChamber/2))
extrapTrackParamAtCluster.SetRemovable(kFALSE);
else extrapTrackParamAtCluster.SetRemovable(kTRUE);
newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster,*cluster);
newTrack->SetGlobalChi2(trackCandidate.GetGlobalChi2()+chi2WithOneCluster);
fNRecTracks++;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInChamber: added one cluster in chamber(1..): " << nextChamber+1 << endl;
if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
}
} else if (chi2WithOneCluster < bestChi2WithOneCluster) {
// keep track of the best cluster
bestChi2WithOneCluster = chi2WithOneCluster;
bestTrackParamAtCluster = extrapTrackParamAtCluster;
}
}
}
// fill out the best track if required else clean up the fRecTracksPtr array
if (!GetRecoParam()->TrackAllTracks()) {
if (foundOneCluster) {
if (GetRecoParam()->RequestStation(nextChamber/2))
bestTrackParamAtCluster.SetRemovable(kFALSE);
else bestTrackParamAtCluster.SetRemovable(kTRUE);
trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster,*(bestTrackParamAtCluster.GetClusterPtr()));
trackCandidate.SetGlobalChi2(trackCandidate.GetGlobalChi2()+bestChi2WithOneCluster);
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInChamber: added the best cluster in chamber(1..): " << bestTrackParamAtCluster.GetClusterPtr()->GetChamberId()+1 << endl;
if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
}
} else return kFALSE;
} else if (foundOneCluster) {
// remove obsolete track
fRecTracksPtr->Remove(&trackCandidate);
fNRecTracks--;
} else return kFALSE;
return kTRUE;
}
//__________________________________________________________________________
Bool_t AliMUONVTrackReconstructor::FollowLinearTrackInStation(AliMUONTrack &trackCandidate, const AliMUONVClusterStore& clusterStore,
Int_t nextStation)
{
/// Follow trackCandidate in station(0..) nextStation assuming linear propagation, and search for compatible cluster(s)
/// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
/// kTRUE: duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
/// fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
/// Remove the obsolete "trackCandidate" at the end.
/// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
/// return kTRUE if new cluster(s) have been found (otherwise return kFALSE)
AliDebug(1,Form("Enter FollowLinearTrackInStation(1..) %d", nextStation+1));
// Order the chamber according to the propagation direction (tracking starts with chamber 2):
// - nextStation == station(1...) 5 => forward propagation
// - nextStation < station(1...) 5 => backward propagation
Int_t ch1, ch2;
if (nextStation==4) {
ch1 = 2*nextStation+1;
ch2 = 2*nextStation;
} else {
ch1 = 2*nextStation;
ch2 = 2*nextStation+1;
}
Double_t chi2WithOneCluster = AliMUONTrack::MaxChi2();
Double_t chi2WithTwoClusters = AliMUONTrack::MaxChi2();
Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
Double_t maxChi2WithTwoClusters = 4. * GetRecoParam()->GetSigmaCutForTracking() *
GetRecoParam()->GetSigmaCutForTracking(); // 4 because 4 quantities in chi2
Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
Double_t bestChi2WithTwoClusters = maxChi2WithTwoClusters;
Bool_t foundOneCluster = kFALSE;
Bool_t foundTwoClusters = kFALSE;
AliMUONTrack *newTrack = 0x0;
AliMUONVCluster *clusterCh1, *clusterCh2;
AliMUONTrackParam trackParam;
AliMUONTrackParam extrapTrackParamAtCluster1;
AliMUONTrackParam extrapTrackParamAtCluster2;
AliMUONTrackParam bestTrackParamAtCluster1;
AliMUONTrackParam bestTrackParamAtCluster2;
Int_t nClusters = clusterStore.GetSize();
Bool_t *clusterCh1Used = new Bool_t[nClusters];
for (Int_t i = 0; i < nClusters; i++) clusterCh1Used[i] = kFALSE;
Int_t iCluster1;
// Get track parameters according to the propagation direction
if (nextStation==4) trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
else trackParam = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
trackParam.GetParameters().Print();
trackParam.GetCovariances().Print();
}
// Add MCS effect
AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(trackParam.GetClusterPtr()->GetChamberId()),-1.);
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: look for clusters in chamber(1..): " << ch2+1 << endl;
}
// Create iterators to loop over clusters in both chambers
TIter nextInCh1(clusterStore.CreateChamberIterator(ch1,ch1));
TIter nextInCh2(clusterStore.CreateChamberIterator(ch2,ch2));
// look for candidates in chamber 2
while ( ( clusterCh2 = static_cast<AliMUONVCluster*>(nextInCh2()) ) ) {
// try to add the current cluster fast
if (!TryOneClusterFast(trackParam, clusterCh2)) continue;
// try to add the current cluster accuratly
extrapTrackParamAtCluster2 = trackParam;
AliMUONTrackExtrap::LinearExtrapToZCov(&extrapTrackParamAtCluster2, clusterCh2->GetZ());
chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCluster2, clusterCh2, extrapTrackParamAtCluster2);
// if good chi2 then try to attach a cluster in the other chamber too
if (chi2WithOneCluster < maxChi2WithOneCluster) {
Bool_t foundSecondCluster = kFALSE;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: found one cluster in chamber(1..): " << ch2+1
<< " (Chi2 = " << chi2WithOneCluster << ")" << endl;
clusterCh2->Print();
cout << " look for second clusters in chamber(1..): " << ch1+1 << " ..." << endl;
}
// add MCS effect
AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCluster2,AliMUONConstants::ChamberThicknessInX0(ch2),-1.);
// reset cluster iterator of chamber 1
nextInCh1.Reset();
iCluster1 = -1;
// look for second candidates in chamber 1
while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
iCluster1++;
// try to add the current cluster fast
if (!TryOneClusterFast(extrapTrackParamAtCluster2, clusterCh1)) continue;
// try to add the current cluster in addition to the one found in the previous chamber
chi2WithTwoClusters = TryTwoClustersFast(extrapTrackParamAtCluster2, clusterCh1, extrapTrackParamAtCluster1);
// if good chi2 then consider to add the 2 clusters to the "trackCandidate"
if (chi2WithTwoClusters < maxChi2WithTwoClusters) {
foundSecondCluster = kTRUE;
foundTwoClusters = kTRUE;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: found one cluster in chamber(1..): " << ch1+1
<< " (Chi2 = " << chi2WithTwoClusters << ")" << endl;
clusterCh1->Print();
}
if (GetRecoParam()->TrackAllTracks()) {
// copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new clusters
newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
extrapTrackParamAtCluster1.SetRemovable(kTRUE);
newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster1,*clusterCh1);
extrapTrackParamAtCluster2.SetRemovable(kTRUE);
newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster2,*clusterCh2);
newTrack->SetGlobalChi2(newTrack->GetGlobalChi2()+chi2WithTwoClusters);
fNRecTracks++;
// Tag clusterCh1 as used
clusterCh1Used[iCluster1] = kTRUE;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: added two clusters in station(1..): " << nextStation+1 << endl;
if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
}
} else if (chi2WithTwoClusters < bestChi2WithTwoClusters) {
// keep track of the best couple of clusters
bestChi2WithTwoClusters = chi2WithTwoClusters;
bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
bestTrackParamAtCluster2 = extrapTrackParamAtCluster2;
}
}
}
// if no cluster found in chamber1 then consider to add clusterCh2 only
if (!foundSecondCluster) {
foundOneCluster = kTRUE;
if (GetRecoParam()->TrackAllTracks()) {
// copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
if (GetRecoParam()->RequestStation(nextStation))
extrapTrackParamAtCluster2.SetRemovable(kFALSE);
else extrapTrackParamAtCluster2.SetRemovable(kTRUE);
newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster2,*clusterCh2);
newTrack->SetGlobalChi2(newTrack->GetGlobalChi2()+chi2WithOneCluster);
fNRecTracks++;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: added one cluster in chamber(1..): " << ch2+1 << endl;
if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
}
} else if (!foundTwoClusters && chi2WithOneCluster < bestChi2WithOneCluster) {
// keep track of the best cluster except if a couple of clusters has already been found
bestChi2WithOneCluster = chi2WithOneCluster;
bestTrackParamAtCluster1 = extrapTrackParamAtCluster2;
}
}
}
}
// look for candidates in chamber 1 not already attached to a track
// if we want to keep all possible tracks or if no good couple of clusters has been found
if (GetRecoParam()->TrackAllTracks() || !foundTwoClusters) {
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: look for single cluster in chamber(1..): " << ch1+1 << endl;
}
//Extrapolate trackCandidate to chamber "ch2"
AliMUONTrackExtrap::LinearExtrapToZCov(&trackParam, AliMUONConstants::DefaultChamberZ(ch2));
// add MCS effect for next step
AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(ch2),-1.);
// reset cluster iterator of chamber 1
nextInCh1.Reset();
iCluster1 = -1;
// look for second candidates in chamber 1
while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
iCluster1++;
if (clusterCh1Used[iCluster1]) continue; // Skip clusters already used
// try to add the current cluster fast
if (!TryOneClusterFast(trackParam, clusterCh1)) continue;
// try to add the current cluster accuratly
extrapTrackParamAtCluster1 = trackParam;
AliMUONTrackExtrap::LinearExtrapToZCov(&extrapTrackParamAtCluster1, clusterCh1->GetZ());
chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCluster1, clusterCh1, extrapTrackParamAtCluster1);
// if good chi2 then consider to add clusterCh1
// We do not try to attach a cluster in the other chamber too since it has already been done above
if (chi2WithOneCluster < maxChi2WithOneCluster) {
foundOneCluster = kTRUE;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: found one cluster in chamber(1..): " << ch1+1
<< " (Chi2 = " << chi2WithOneCluster << ")" << endl;
clusterCh1->Print();
}
if (GetRecoParam()->TrackAllTracks()) {
// copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
if (GetRecoParam()->RequestStation(nextStation))
extrapTrackParamAtCluster1.SetRemovable(kFALSE);
else extrapTrackParamAtCluster1.SetRemovable(kTRUE);
newTrack->AddTrackParamAtCluster(extrapTrackParamAtCluster1,*clusterCh1);
newTrack->SetGlobalChi2(newTrack->GetGlobalChi2()+chi2WithOneCluster);
fNRecTracks++;
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: added one cluster in chamber(1..): " << ch1+1 << endl;
if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
}
} else if (chi2WithOneCluster < bestChi2WithOneCluster) {
// keep track of the best cluster except if a couple of clusters has already been found
bestChi2WithOneCluster = chi2WithOneCluster;
bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
}
}
}
}
// fill out the best track if required else clean up the fRecTracksPtr array
if (!GetRecoParam()->TrackAllTracks()) {
if (foundTwoClusters) {
bestTrackParamAtCluster1.SetRemovable(kTRUE);
trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster1,*(bestTrackParamAtCluster1.GetClusterPtr()));
bestTrackParamAtCluster2.SetRemovable(kTRUE);
trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster2,*(bestTrackParamAtCluster2.GetClusterPtr()));
trackCandidate.SetGlobalChi2(trackCandidate.GetGlobalChi2()+bestChi2WithTwoClusters);
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: added the two best clusters in station(1..): " << nextStation+1 << endl;
if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
}
} else if (foundOneCluster) {
if (GetRecoParam()->RequestStation(nextStation))
bestTrackParamAtCluster1.SetRemovable(kFALSE);
else bestTrackParamAtCluster1.SetRemovable(kTRUE);
trackCandidate.AddTrackParamAtCluster(bestTrackParamAtCluster1,*(bestTrackParamAtCluster1.GetClusterPtr()));
trackCandidate.SetGlobalChi2(trackCandidate.GetGlobalChi2()+bestChi2WithOneCluster);
// Printout for debuging
if ((AliLog::GetDebugLevel("MUON","AliMUONVTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
cout << "FollowLinearTrackInStation: added the best cluster in chamber(1..): " << bestTrackParamAtCluster1.GetClusterPtr()->GetChamberId()+1 << endl;
if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
}
} else {
delete [] clusterCh1Used;
return kFALSE;
}
} else if (foundOneCluster || foundTwoClusters) {
// remove obsolete track
fRecTracksPtr->Remove(&trackCandidate);
fNRecTracks--;
} else {
delete [] clusterCh1Used;
return kFALSE;
}
delete [] clusterCh1Used;
return kTRUE;
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::ImproveTracks()
{
/// Improve tracks by removing clusters with local chi2 highter than the defined cut
/// Recompute track parameters and covariances at the remaining clusters
AliDebug(1,"Enter ImproveTracks");
AliMUONTrack *track, *nextTrack;
track = (AliMUONTrack*) fRecTracksPtr->First();
while (track) {
// prepare next track in case the actual track is suppressed
nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
ImproveTrack(*track);
// remove track if improvement failed
if (!track->IsImproved()) {
fRecTracksPtr->Remove(track);
fNRecTracks--;
}
track = nextTrack;
}
// compress the array in case of some tracks have been removed
fRecTracksPtr->Compress();
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::Finalize()
{
/// Recompute track parameters and covariances at each attached cluster
/// Set the label pointing to the corresponding MC track
/// Remove the track if finalization failed
AliMUONTrack *track, *nextTrack;
Bool_t trackRemoved = kFALSE;
track = (AliMUONTrack*) fRecTracksPtr->First();
while (track) {
nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
if (FinalizeTrack(*track)) track->FindMCLabel();
else {
fRecTracksPtr->Remove(track);
fNRecTracks--;
trackRemoved = kTRUE;
}
track = nextTrack;
}
// compress array of tracks if needed
if (trackRemoved) fRecTracksPtr->Compress();
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::DiscardMonoCathodClusters()
{
/// Assign a different resolution to the mono-cathod clusters
/// in the direction of the missing plane and refit the track
/// Remove the track in case of failure
if (!fkTransformer) AliFatal("missing geometry transformer");
AliMUONTrack *track, *nextTrack;
Bool_t trackRemoved = kFALSE;
track = (AliMUONTrack*) fRecTracksPtr->First();
while (track) {
nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
ChangeMonoCathodClusterRes(*track);
if (!RefitTrack(*track) || (GetRecoParam()->ImproveTracks() && !track->IsImproved())) {
fRecTracksPtr->Remove(track);
fNRecTracks--;
trackRemoved = kTRUE;
}
track = nextTrack;
}
// compress array of tracks if needed
if (trackRemoved) fRecTracksPtr->Compress();
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::ChangeMonoCathodClusterRes(AliMUONTrack &track)
{
/// Assign a different resolution to the mono-cathod clusters
/// in the direction of the missing plane and refit the track
// Loop over clusters
AliMUONVCluster *cluster;
Int_t nClusters = track.GetNClusters();
for (Int_t iCluster = 0; iCluster < nClusters; iCluster++) {
cluster = ((AliMUONTrackParam*) track.GetTrackParamAtCluster()->UncheckedAt(iCluster))->GetClusterPtr();
// do it only for stations 3, 4 & 5
if (cluster->GetChamberId() < 4) continue;
// get the cathod corresponding to the bending/non-bending plane
Int_t deId = cluster->GetDetElemId();
AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(deId, kFALSE);
if (!de) continue;
AliMp::CathodType cath1 = de->GetCathodType(AliMp::kBendingPlane);
AliMp::CathodType cath2 = de->GetCathodType(AliMp::kNonBendingPlane);
// get the corresponding segmentation
const AliMpVSegmentation* seg1 = AliMpSegmentation::Instance()->GetMpSegmentation(deId, cath1);
const AliMpVSegmentation* seg2 = AliMpSegmentation::Instance()->GetMpSegmentation(deId, cath2);
if (!seg1 || !seg2) continue;
// get local coordinate of the cluster
Double_t lX,lY,lZ;
Double_t gX = cluster->GetX();
Double_t gY = cluster->GetY();
Double_t gZ = cluster->GetZ();
fkTransformer->Global2Local(deId,gX,gY,gZ,lX,lY,lZ);
// find pads below the cluster
AliMpPad pad1 = seg1->PadByPosition(lX, lY, kFALSE);
AliMpPad pad2 = seg2->PadByPosition(lX, lY, kFALSE);
// build their ID if pads are valid
UInt_t padId1 = (pad1.IsValid()) ? AliMUONVDigit::BuildUniqueID(deId, pad1.GetManuId(), pad1.GetManuChannel(), cath1) : 0;
UInt_t padId2 = (pad2.IsValid()) ? AliMUONVDigit::BuildUniqueID(deId, pad2.GetManuId(), pad2.GetManuChannel(), cath2) : 0;
// check if the cluster contains these pads
Bool_t hasNonBending = kFALSE;
Bool_t hasBending = kFALSE;
for (Int_t iDigit = 0; iDigit < cluster->GetNDigits(); iDigit++) {
UInt_t digitId = cluster->GetDigitId(iDigit);
if (digitId == padId1) {
hasBending = kTRUE;
if (hasNonBending) break;
} else if (digitId == padId2) {
hasNonBending = kTRUE;
if (hasBending) break;
}
}
// modify the cluster resolution if needed
if (!hasNonBending) cluster->SetErrXY(GetRecoParam()->GetMonoCathodClNonBendingRes(), cluster->GetErrY());
if (!hasBending) cluster->SetErrXY(cluster->GetErrX(), GetRecoParam()->GetMonoCathodClBendingRes());
}
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::ValidateTracksWithTrigger(AliMUONVTrackStore& trackStore,
const AliMUONVTriggerTrackStore& triggerTrackStore,
const AliMUONVTriggerStore& triggerStore,
const AliMUONTrackHitPattern& trackHitPattern)
{
/// Try to match track from tracking system with trigger track
AliCodeTimerAuto("",0);
trackHitPattern.ExecuteValidation(trackStore, triggerTrackStore, triggerStore);
}
//__________________________________________________________________________
void AliMUONVTrackReconstructor::EventReconstructTrigger(const AliMUONTriggerCircuit& circuit,
const AliMUONVTriggerStore& triggerStore,
AliMUONVTriggerTrackStore& triggerTrackStore)
{
/// Fill trigger track store from local trigger
AliDebug(1, "");
AliCodeTimerAuto("",0);
AliMUONGlobalTrigger* globalTrigger = triggerStore.Global();
UChar_t gloTrigPat = 0;
if (globalTrigger)
{
gloTrigPat = globalTrigger->GetGlobalResponse();
}
AliMUONTriggerTrack triggerTrack;
TIter next(triggerStore.CreateIterator());
AliMUONLocalTrigger* locTrg(0x0);
while ( ( locTrg = static_cast<AliMUONLocalTrigger*>(next()) ) )
{
if ( locTrg->IsTrigX() && locTrg->IsTrigY() )
{ // make Trigger Track if trigger in X and Y
if (TriggerToTrack(circuit, *locTrg, triggerTrack, gloTrigPat))
triggerTrackStore.Add(triggerTrack);
} // board is fired
} // end of loop on Local Trigger
}
//__________________________________________________________________________
Bool_t AliMUONVTrackReconstructor::TriggerToTrack(const AliMUONTriggerCircuit& circuit,
const AliMUONLocalTrigger& locTrg,
AliMUONTriggerTrack& triggerTrack,
UChar_t globalTriggerPattern)
{
/// To make the trigger tracks from Local Trigger
const Double_t kTrigNonBendReso = AliMUONConstants::TriggerNonBendingReso();
const Double_t kTrigBendReso = AliMUONConstants::TriggerBendingReso();
const Double_t kSqrt12 = TMath::Sqrt(12.);
TMatrixD trigCov(3,3);
Int_t localBoardId = locTrg.LoCircuit();
Float_t y11 = circuit.GetY11Pos(localBoardId, locTrg.LoStripX());
Float_t z11 = circuit.GetZ11Pos(localBoardId, locTrg.LoStripX());
// need first to convert deviation to [0-30]
// (see AliMUONLocalTriggerBoard::LocalTrigger)
Int_t deviation = locTrg.GetDeviation();
Int_t stripX21 = locTrg.LoStripX()+deviation+1;
Float_t y21 = circuit.GetY21Pos(localBoardId, stripX21);
Float_t z21 = circuit.GetZ21Pos(localBoardId, stripX21);
Float_t x11 = circuit.GetX11Pos(localBoardId, locTrg.LoStripY());
AliDebug(1, Form(" MakeTriggerTrack %3d %2d %2d %2d (%f %f %f) (%f %f)\n",locTrg.LoCircuit(),
locTrg.LoStripX(),locTrg.LoStripX()+deviation+1,locTrg.LoStripY(),x11, y11, z11, y21, z21));
if (TMath::Abs(z11) < 0.00001) return kFALSE;
Double_t deltaZ = z11 - z21;
Float_t slopeX = x11/z11;
Float_t slopeY = (y11-y21) / deltaZ;
Float_t sigmaX = circuit.GetX11Width(localBoardId, locTrg.LoStripY()) / kSqrt12;
Float_t sigmaY = circuit.GetY11Width(localBoardId, locTrg.LoStripX()) / kSqrt12;
Float_t sigmaY21 = circuit.GetY21Width(localBoardId, locTrg.LoStripX()) / kSqrt12;
trigCov.Zero();
trigCov(0,0) = kTrigNonBendReso * kTrigNonBendReso + sigmaX * sigmaX;
trigCov(1,1) = kTrigBendReso * kTrigBendReso + sigmaY * sigmaY;
trigCov(2,2) =
(2. * kTrigBendReso * kTrigBendReso + sigmaY * sigmaY + sigmaY21 * sigmaY21 ) / deltaZ / deltaZ;
trigCov(1,2) = trigCov(2,1) = trigCov(1,1) / deltaZ;
triggerTrack.SetX11(x11);
triggerTrack.SetY11(y11);
triggerTrack.SetZ11(z11);
triggerTrack.SetZ21(z21);
triggerTrack.SetSlopeX(slopeX);
triggerTrack.SetSlopeY(slopeY);
triggerTrack.SetGTPattern(globalTriggerPattern);
triggerTrack.SetLoTrgNum(localBoardId);
triggerTrack.SetCovariances(trigCov);
triggerTrack.SetUniqueID(locTrg.GetUniqueID());
return kTRUE;
}
| 42.454365 | 157 | 0.705987 | [
"geometry",
"object",
"3d"
] |
114c33ec68a82cf188fa19e779b1556a5383b860 | 5,093 | cpp | C++ | libs2eplugins/src/s2e/Plugins/Lua/LuaS2EExecutionStateMemory.cpp | sebastianpoeplau/s2e | 995cac6126e7d80337e8c4a72bfa9a87eea7eb68 | [
"MIT"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | libs2eplugins/src/s2e/Plugins/Lua/LuaS2EExecutionStateMemory.cpp | Moirai7/s2e | 5a321f76d1a862c3898b9d24de621109b0c12b7d | [
"MIT"
] | 2 | 2020-11-02T08:01:00.000Z | 2022-03-27T02:59:18.000Z | libs2eplugins/src/s2e/Plugins/Lua/LuaS2EExecutionStateMemory.cpp | Moirai7/s2e | 5a321f76d1a862c3898b9d24de621109b0c12b7d | [
"MIT"
] | 11 | 2020-08-06T03:59:45.000Z | 2022-02-25T02:31:59.000Z | ///
/// Copyright (C) 2014-2015, Cyberhaven
///
/// 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 <vector>
#include <s2e/S2E.h>
#include <s2e/S2EExecutionState.h>
#include <s2e/Utils.h>
#include "LuaExpression.h"
#include "LuaS2EExecutionStateMemory.h"
namespace s2e {
namespace plugins {
const char LuaS2EExecutionStateMemory::className[] = "LuaS2EExecutionStateMemory";
Lunar<LuaS2EExecutionStateMemory>::RegType LuaS2EExecutionStateMemory::methods[] = {
LUNAR_DECLARE_METHOD(LuaS2EExecutionStateMemory, readPointer),
LUNAR_DECLARE_METHOD(LuaS2EExecutionStateMemory, readBytes),
LUNAR_DECLARE_METHOD(LuaS2EExecutionStateMemory, write),
LUNAR_DECLARE_METHOD(LuaS2EExecutionStateMemory, makeSymbolic),
{0, 0}};
int LuaS2EExecutionStateMemory::readPointer(lua_State *L) {
long address = (long) luaL_checkinteger(L, 1);
uint64_t pointerSize = m_state->getPointerSize();
if (pointerSize == 4) {
uint32_t data = 0;
if (!m_state->mem()->read(address, &data, sizeof(data))) {
g_s2e->getWarningsStream(m_state) << "Could not read address " << hexval(address) << "\n";
return 0;
}
lua_pushinteger(L, data);
} else {
uint64_t data = 0;
if (!m_state->mem()->read(address, &data, sizeof(data))) {
g_s2e->getWarningsStream(m_state) << "Could not read address " << hexval(address) << "\n";
return 0;
}
lua_pushinteger(L, data);
}
return 1;
}
int LuaS2EExecutionStateMemory::readBytes(lua_State *L) {
long address = (long) luaL_checkinteger(L, 1);
long size = (long) luaL_checkinteger(L, 2);
std::vector<uint8_t> bytes(size);
if (!m_state->mem()->read(address, bytes.data(), size * sizeof(uint8_t))) {
return 0;
}
luaL_Buffer buff;
luaL_buffinit(L, &buff);
luaL_addlstring(&buff, (char *) bytes.data(), size * sizeof(uint8_t));
luaL_pushresult(&buff);
return 1;
}
int LuaS2EExecutionStateMemory::write(lua_State *L) {
long address = (long) luaL_checkinteger(L, 1);
if (lua_isuserdata(L, 2)) {
void *expr = luaL_checkudata(L, 2, "LuaExpression");
LuaExpression *value = *static_cast<LuaExpression **>(expr);
g_s2e->getDebugStream(m_state) << "Writing " << value->get() << "\n";
m_state->mem()->write(address, value->get());
} else if (lua_isnumber(L, 2)) {
long value = (long) luaL_checkinteger(L, 2);
long size = (long) luaL_checkinteger(L, 3);
g_s2e->getDebugStream(m_state) << "Writing " << value << " of size " << size << "\n";
switch (size) {
case 1:
m_state->mem()->write<uint8_t>(address, value);
break;
case 2:
m_state->mem()->write<uint16_t>(address, value);
break;
case 4:
m_state->mem()->write<uint32_t>(address, value);
break;
case 8:
m_state->mem()->write<uint64_t>(address, value);
break;
default:
g_s2e->getDebugStream(m_state)
<< "LuaS2EExecutionStateRegisters::write: Incorrect size " << size << "\n";
break;
}
}
return 1;
}
int LuaS2EExecutionStateMemory::makeSymbolic(lua_State *L) {
long address = (long) luaL_checkinteger(L, 1);
long size = (long) luaL_checkinteger(L, 2);
std::string name = luaL_checkstring(L, 3);
std::vector<uint8_t> concreteData(size);
if (!m_state->mem()->read(address, concreteData.data(), size * sizeof(uint8_t))) {
lua_pushinteger(L, 0);
return 1;
}
std::vector<klee::ref<klee::Expr>> symb = m_state->createSymbolicArray(name, size, concreteData);
for (unsigned i = 0; i < size; ++i) {
if (!m_state->mem()->write(address + i, symb[i])) {
lua_pushinteger(L, 0);
return 1;
}
}
lua_pushinteger(L, 1);
return 1;
}
} // namespace plugins
} // namespace s2e
| 35.124138 | 102 | 0.634007 | [
"vector"
] |
114c48514670296495b1cd7430d8d681201f8c1f | 3,698 | cpp | C++ | 731. My Calendar II.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | 1 | 2020-10-11T08:10:53.000Z | 2020-10-11T08:10:53.000Z | 731. My Calendar II.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | null | null | null | 731. My Calendar II.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | null | null | null | //
// Created by Yuyang Huang on 6/18/20.
//
#include "LeetCodeLib.h"
/*
* @lc app=leetcode id=731 lang=cpp
*
* [731] My Calendar II
*
* https://leetcode.com/problems/my-calendar-ii/description/
*
* algorithms
* Medium (46.45%)
* Likes: 581
* Dislikes: 80
* Total Accepted: 39.9K
* Total Submissions: 81.7K
* Testcase Example: '["MyCalendarTwo","book","book","book","book","book","book"]\n' +
'[[],[10,20],[50,60],[10,40],[5,15],[5,10],[25,55]]'
*
* Implement a MyCalendarTwo class to store your events. A new event can be
* added if adding the event will not cause a triple booking.
*
* Your class will have one method, book(int start, int end). Formally, this
* represents a booking on the half open interval [start, end), the range of
* real numbers x such that start <= x < end.
*
* A triple booking happens when three events have some non-empty intersection
* (ie., there is some time that is common to all 3 events.)
*
* For each call to the method MyCalendar.book, return true if the event can be
* added to the calendar successfully without causing a triple booking.
* Otherwise, return false and do not add the event to the calendar.
* Your class will be called like this: MyCalendar cal = new MyCalendar();
* MyCalendar.book(start, end)
*
* Example 1:
*
*
* MyCalendar();
* MyCalendar.book(10, 20); // returns true
* MyCalendar.book(50, 60); // returns true
* MyCalendar.book(10, 40); // returns true
* MyCalendar.book(5, 15); // returns false
* MyCalendar.book(5, 10); // returns true
* MyCalendar.book(25, 55); // returns true
* Explanation:
* The first two events can be booked. The third event can be double booked.
* The fourth event (5, 15) can't be booked, because it would result in a
* triple booking.
* The fifth event (5, 10) can be booked, as it does not use time 10 which is
* already double booked.
* The sixth event (25, 55) can be booked, as the time in [25, 40) will be
* double booked with the third event;
* the time [40, 50) will be single booked, and the time [50, 55) will be
* double booked with the second event.
*
*
*
*
* Note:
*
*
* The number of calls to MyCalendar.book per test case will be at most
* 1000.
* In calls to MyCalendar.book(start, end), start and end are integers in the
* range [0, 10^9].
*
*
*
*/
// @lc code=start
/*
* Time complexity: O(n*n)
* brute force
* can be optimized with suffix tree to O(n)
*/
class MyCalendarTwo {
public:
MyCalendarTwo() {}
bool book(int start, int end) {
// for already duplicate time, return false
for (auto &event : duplicateEvents) {
if (event.second > start && event.first < end) {
return false;
}
}
for (auto &event : noDuplicateEvents) {
if (event.second > start && event.first < end) {
auto overlap = make_pair(max(event.first, start), min(event.second, end));
duplicateEvents.emplace_back(overlap);
}
}
noDuplicateEvents.emplace_back(make_pair(start, end));
return true;
}
private:
vector<pair<int, int>> noDuplicateEvents;
vector<pair<int, int>> duplicateEvents;
};
/**
* Your MyCalendarTwo object will be instantiated and called as such:
* MyCalendarTwo* obj = new MyCalendarTwo();
* bool param_1 = obj->book(start,end);
*/
// @lc code=end
int main() {
MyCalendarTwo MyCalendarTwo;
PrintSingleResult(MyCalendarTwo.book(10, 20)); // returns true
PrintSingleResult(MyCalendarTwo.book(50, 60)); // returns true
PrintSingleResult(MyCalendarTwo.book(10, 40)); // returns true
PrintSingleResult(MyCalendarTwo.book(5, 15)); // returns false
PrintSingleResult(MyCalendarTwo.book(5, 10)); // returns true
PrintSingleResult(MyCalendarTwo.book(25, 55)); // returns true
}
| 29.822581 | 87 | 0.683072 | [
"object",
"vector"
] |
1151ff11461b3a344a4f3ea9d89acebb718c0f55 | 3,801 | hpp | C++ | benchtest/test.hpp | AE9RB/fftbench | 9eb4bbcaac24351a4878c4c71e8d652970b0c6eb | [
"MIT"
] | 2 | 2017-02-22T13:56:32.000Z | 2017-04-02T21:55:11.000Z | benchtest/test.hpp | AE9RB/fftbench | 9eb4bbcaac24351a4878c4c71e8d652970b0c6eb | [
"MIT"
] | null | null | null | benchtest/test.hpp | AE9RB/fftbench | 9eb4bbcaac24351a4878c4c71e8d652970b0c6eb | [
"MIT"
] | null | null | null | // benchtest - A benchmarking and unit testing framework.
// Copyright (C) 2014 David Turnbull
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
namespace testing {
class Test {
friend class Runner;
virtual Info* TestInfo() = 0;
virtual void TestBody() {};
// Helper for common typos.
struct Setup_should_be_spelled_SetUp {};
virtual Setup_should_be_spelled_SetUp* Setup() {
return nullptr;
}
virtual Setup_should_be_spelled_SetUp* SetupTestCase() {
return nullptr;
}
// Benchmark info
std::chrono::high_resolution_clock::time_point start_time;
::std::vector<double> results;
unsigned long count = 0;
unsigned long size = 0;
bool keep_running = true;
protected:
Test() {}
static void SetUpTestCase() {}
static void TearDownTestCase() {}
virtual void SetUp() {}
virtual void TearDown() {}
bool Benchmark(unsigned long max = 100) {
auto end_time = ::std::chrono::high_resolution_clock::now();
double this_time = ::std::chrono::duration<double, std::micro>(end_time - start_time).count();
if (!keep_running) return false;
if (!size) {
size = max / 5;
if (size < 10) size = 10;
}
if (count) {
if (results.size() < size) {
auto it=results.begin();
for (; it!=results.end(); ++it) {
if (*it > this_time) {
results.insert(it, this_time);
break;
}
}
if (it==results.end()) {
results.push_back(this_time);
}
}
else {
keep_running = false;
for (auto it=results.begin(); it!=results.end(); ++it) {
if (*it > this_time) {
results.pop_back();
results.insert(it, this_time);
keep_running = true;
break;
}
}
}
}
++count;
if (count > max) keep_running = false;
if (!keep_running) {
double mean = 0;
unsigned long trim = results.size() / 5;
for (auto i = trim; i < results.size() - trim; ++i) {
mean += results[i];
}
mean /= results.size() - trim*2;
reporter()->Bench(count-1, mean);
}
start_time = ::std::chrono::high_resolution_clock::now();
return keep_running;
}
public:
virtual bool HasFatalFailure() {
return TestInfo()->HasFatalFailure();
}
virtual bool HasNonfatalFailure() {
return TestInfo()->HasNonfatalFailure();
}
virtual bool HasFailure() {
return TestInfo()->HasFailure();
}
};
}
| 36.548077 | 106 | 0.502762 | [
"vector"
] |
115307c7612cbb8963de10864c2d53f4e5d39da7 | 5,008 | cpp | C++ | nucleusSegmentation/src/lib/mask2polygon/src/polygonedit/BoundaryFixFunction.cpp | SBU-BMI/pathomics_analysis_restore | 595df78e3c46ea6e5d43c3c2faa016b9a9395ffa | [
"BSD-3-Clause"
] | null | null | null | nucleusSegmentation/src/lib/mask2polygon/src/polygonedit/BoundaryFixFunction.cpp | SBU-BMI/pathomics_analysis_restore | 595df78e3c46ea6e5d43c3c2faa016b9a9395ffa | [
"BSD-3-Clause"
] | 8 | 2016-12-28T14:33:35.000Z | 2018-08-02T01:00:23.000Z | nucleusSegmentation/src/lib/mask2polygon/src/polygonedit/BoundaryFixFunction.cpp | SBU-BMI/pathomics_analysis_restore | 595df78e3c46ea6e5d43c3c2faa016b9a9395ffa | [
"BSD-3-Clause"
] | 4 | 2017-03-20T16:25:56.000Z | 2020-10-14T14:32:49.000Z | //============================================================================
// Name : BoundaryFix.cpp
// Author : bkatigb
// Version :
// Copyright :
// Description :
//============================================================================
#include "clipper.h"
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <stdio.h>
#include <ios>
#include <map>
#include <fstream>
#include <vector>
#include <list>
#include <set>
#include <fts.h>
#include <sstream>
#include <boost/assign.hpp>
#include <boost/geometry/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
#include <boost/geometry/geometries/linestring.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include "BoundaryFix.h"
BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian)
using namespace std;
using namespace ClipperLib;
using namespace boost::geometry;
void processBoundaryFixing(stringstream &instream, stringstream &outstream)
{
vector<points> coord;
/*data id*/
string rec_id;
int orig_item_cnt,item_out_cnt;
string str,xp,yp,sv_rec_id, file_id ;
using boost::assign::tuple_list_of;
using boost::make_tuple;
using boost::geometry::append;
typedef boost::geometry::model::polygon<boost::tuple<int, int> > polygon;
typedef boost::geometry::model::polygon
<
boost::tuple<int, int>
> clockwise_closed_polygon;
clockwise_closed_polygon cwcp,cwcp_in;
double area_after;
double area_before;
typedef boost::geometry::model::d2::point_xy<double> xy;
boost::geometry::model::linestring<xy> line;
boost::geometry::model::linestring<xy> simplified;
typedef boost::geometry::model::d2::point_xy<double> P;
boost::geometry::model::linestring<P> line1, line2;
int pos1,pos2,eol_ch;
bool f1st=true;
typedef boost::geometry::model::d2::point_xy<double> point_type;
typedef boost::geometry::model::polygon<point_type> polygon_type;
point_type p(4, 1);
IntPoint XY;
Polygon poly_in;
Polygons poly_out1;
Polygons poly_out;
polygon poly;
points pt;
f1st = true;
int ctr0=0;
int ctr1=0;
int ctr2=0;
int ln_ctr=0;
bool b = false;
bool proc = false;
cwcp.clear();
while (instream.good())
{
instream >> str;
if (f1st)
{
pos1 = str.find(';');
if (pos1 > 0)
{
sv_rec_id = str;
}
// f1st = false;
ctr0 = 0;
}
pos1 = str.find(',');
pos2 = str.size() - 1;
eol_ch = instream.peek();
if (f1st)
{
f1st = false;
}
else
{
if (pos1 != pos2 && pos1>0)
{
xp = str.substr(0,pos1);
yp = str.substr(pos1+1,pos2-pos1);
pt.x = strtod(xp.c_str(),NULL);
pt.y = strtod(yp.c_str(),NULL);
coord.push_back(pt);
ctr0 = coord.size();
}
}
if (eol_ch==10 || eol_ch==13)
{
rec_id = sv_rec_id;
//file_id = instreamname.c_str();
ctr0 = coord.size();
if (ctr0 >= 4)
{
proc = true;
}
else
{
proc = false;
}
if (proc)
{
/*remove collinear*/
boost::geometry::clear(line1);
boost::geometry::clear(line2);
for (int i=0;i!=ctr0;i++)
{
append(line1, make_tuple(coord[i].x, coord[i].y));
}
if (ctr0 > 500)
{
boost::geometry::simplify(line1, line2, 0.1);
}
else if (ctr0 > 200)
{
boost::geometry::simplify(line1, line2, 0.25);
}
else if (ctr0 < 50)
{
boost::geometry::simplify(line1, line2, 2.0);
// boost::geometry::simplify(line1, line2, 0.0);
}
else
{
boost::geometry::simplify(line1, line2, 1.75);
}
ctr0 = line2.size();
if (ctr0 >= 4)
{
proc = true;
}
else
{
proc = false;
}
}
if (proc)
{
poly_in.clear();
poly_out.clear();
/*splits up in the event of self-intersect*/
for (int i = 0;i!=ctr0;i++)
{
XY.X = line2.at(i).get<0>();
XY.Y = line2.at(i).get<1>();
poly_in.push_back(XY);
// cout << XY.X << "," << XY.Y << " ";
}
SimplifyPolygon(poly_in,poly_out1);
// cout << endl << "poly_out1.size()" << poly_out1.size() << endl;
if (poly_out1.size() <= 1)
{
poly_out = poly_out1;
}
else
{
SimplifyPolygons(poly_out1,poly_out);
poly_out = poly_out1;
}
ctr1 = poly_out.size();
// cout << "ctr1: " << ctr1 << endl;
for (int i=0;i<ctr1;i++)
{
// cout << "# " << i << " output size " << poly_out[i].size() << endl;
if (poly_out[i].size()>=3)
{
ctr2 = poly_out[i].size();
boost::geometry::clear(cwcp);
for (int j=0;j!=ctr2;j++)
{
boost::geometry::exterior_ring(cwcp).push_back(make_tuple(poly_out[i][j].X,poly_out[i][j].Y));
}
boost::geometry::correct(cwcp);
outstream << rec_id;
outstream << dsv(cwcp,","," ","","","","") << endl;
}
}
}
f1st = true;
coord.clear();
} /*eol*/
} /*while good*/
outstream.clear();
coord.clear();
}
| 20.694215 | 102 | 0.580272 | [
"geometry",
"vector",
"model"
] |
115a1d421fc2da0e838348797320646761bf0d57 | 13,559 | cpp | C++ | NiVek/Software/GroundStation/NiVek.D3D/D2DWrapper.cpp | bytemaster-0xff/DroneTek | 9b88b30e7d442833b8bab3302d93dc6463d67619 | [
"MIT"
] | null | null | null | NiVek/Software/GroundStation/NiVek.D3D/D2DWrapper.cpp | bytemaster-0xff/DroneTek | 9b88b30e7d442833b8bab3302d93dc6463d67619 | [
"MIT"
] | null | null | null | NiVek/Software/GroundStation/NiVek.D3D/D2DWrapper.cpp | bytemaster-0xff/DroneTek | 9b88b30e7d442833b8bab3302d93dc6463d67619 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "D2DWrapper.h"
using namespace NiVek;
using namespace Platform;
using namespace Microsoft::WRL;
using namespace Windows::UI::Core;
using namespace Windows::Foundation;
using namespace D2D1;
using namespace Windows::Storage;
using namespace Platform;
using namespace Concurrency;
using namespace Microsoft::WRL;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
using namespace Windows::Storage;
using namespace Windows::System;
using namespace Windows::UI::Core;
using namespace Windows::UI::ViewManagement;
using namespace Windows::Storage::Streams;
void NiVek::D2DWrapper::Initialize( Windows::UI::Core::CoreWindow^ window )
{
m_window = window;
m_displayInfo = Windows::Graphics::Display::DisplayInformation::GetForCurrentView();
m_dpi = static_cast<float>(m_displayInfo->LogicalDpi);
m_renderTargetBitmap = nullptr;
CreateDeviceIndependentResources();
CreateDeviceResources();
CreateWindowSizeDependentResources();
}
void NiVek::D2DWrapper::CreateDeviceIndependentResources()
{
D2D1_FACTORY_OPTIONS options;
ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
#if defined(_DEBUG)
// If the project is in a debug build, enable Direct2D debugging via SDK Layers.
options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION;
#endif
DX::ThrowIfFailed(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, __uuidof(ID2D1Factory1), &options, &m_d2dFactory));
DX::ThrowIfFailed(DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), &m_dwriteFactory ) );
DX::ThrowIfFailed(CoCreateInstance( CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_wicFactory)));
}
void NiVek::D2DWrapper::CreateDeviceResources()
{
// This flag adds support for surfaces with a different color channel ordering than the API default.
// It is recommended usage, and is required for compatibility with Direct2D.
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#if defined(_DEBUG)
// If the project is in a debug build, enable debugging via SDK Layers with this flag.
creationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
// This array defines the set of DirectX hardware feature levels this app will support.
// Note the ordering should be preserved.
// Don't forget to declare your application's minimum required feature level in its
// description. All applications are assumed to support 9.1 unless otherwise stated.
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1
};
// Create the DX11 API device object, and get a corresponding context.
ComPtr<ID3D11Device> d3dDevice;
ComPtr<ID3D11DeviceContext> d3dContext;
DX::ThrowIfFailed(
D3D11CreateDevice(
nullptr, // specify null to use the default adapter
D3D_DRIVER_TYPE_HARDWARE,
nullptr, // leave as nullptr unless software device
creationFlags, // optionally set debug and Direct2D compatibility flags
featureLevels, // list of feature levels this app can support
ARRAYSIZE(featureLevels), // number of entries in above list
D3D11_SDK_VERSION, // always set this to D3D11_SDK_VERSION for modern
&d3dDevice, // returns the Direct3D device created
&m_featureLevel, // returns feature level of device created
&d3dContext // returns the device immediate context
)
);
// Get the DirectX11.1 device by QI off the DirectX11 one.
DX::ThrowIfFailed(
d3dDevice.As(&m_d3dDevice)
);
// And get the corresponding device context in the same way.
DX::ThrowIfFailed(
d3dContext.As(&m_d3dContext)
);
// Obtain the underlying DXGI device of the Direct3D11.1 device.
ComPtr<IDXGIDevice> dxgiDevice;
DX::ThrowIfFailed(
m_d3dDevice.As(&dxgiDevice)
);
// Obtain the Direct2D device for 2D rendering.
DX::ThrowIfFailed(
m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice)
);
// And get its corresponding device context object.
DX::ThrowIfFailed(
m_d2dDevice->CreateDeviceContext(
D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
&m_d2dContext
)
);
DX::ThrowIfFailed(
m_dwriteFactory->CreateTextFormat(
L"Segoe UI",
nullptr,
DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
58.0f,
L"en-US",
&nameTextFormat
)
);
DX::ThrowIfFailed(
nameTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)
);
DX::ThrowIfFailed(
nameTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
);
// Release the swap chain (if it exists) as it will be incompatible with
// the new device.
m_swapChain = nullptr;
}
void NiVek::D2DWrapper::CreateWindowSizeDependentResources()
{
// Store the window bounds so the next time we get a SizeChanged event we can
// avoid rebuilding everything if the size is identical.
m_windowBounds = m_window->Bounds;
// If the swap chain already exists, resize it.
if(m_swapChain != nullptr)
{
DX::ThrowIfFailed(
m_swapChain->ResizeBuffers(2, 0, 0, DXGI_FORMAT_B8G8R8A8_UNORM, 0)
);
}
// Otherwise, create a new one.
else
{
// Create a descriptor for the swap chain.
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0};
swapChainDesc.Width = 0; // use automatic sizing
swapChainDesc.Height = 0;
swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // this is the most common swapchain format
swapChainDesc.Stereo = false;
swapChainDesc.SampleDesc.Count = 1; // don't use multi-sampling
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = 2; // use double buffering to enable flip
swapChainDesc.Scaling = DXGI_SCALING_NONE;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // we recommend using this swap effect for all applications
swapChainDesc.Flags = 0;
// Once the desired swap chain description is configured, it must be created on the same adapter as our D3D Device
// First, retrieve the underlying DXGI Device from the D3D Device.
ComPtr<IDXGIDevice1> dxgiDevice;
DX::ThrowIfFailed(
m_d3dDevice.As(&dxgiDevice)
);
// Identify the physical adapter (GPU or card) this device is running on.
ComPtr<IDXGIAdapter> dxgiAdapter;
DX::ThrowIfFailed(
dxgiDevice->GetAdapter(&dxgiAdapter)
);
// And obtain the factory object that created it.
ComPtr<IDXGIFactory2> dxgiFactory;
DX::ThrowIfFailed(
dxgiAdapter->GetParent(
__uuidof(IDXGIFactory2),
&dxgiFactory
)
);
// Create a swap chain for this window from the DXGI factory.
DX::ThrowIfFailed(
dxgiFactory->CreateSwapChainForCoreWindow(
m_d3dDevice.Get(),
reinterpret_cast<IUnknown*>(m_window),
&swapChainDesc,
nullptr, // allow on all displays
&m_swapChain
)
);
// Ensure that DXGI does not queue more than one frame at a time. This both reduces
// latency and ensures that the application will only render after each VSync, minimizing
// power consumption.
DX::ThrowIfFailed(
dxgiDevice->SetMaximumFrameLatency(1)
);
}
// Obtain the backbuffer for this window which will be the final 3D rendertarget.
ComPtr<ID3D11Texture2D> backBuffer;
DX::ThrowIfFailed(
m_swapChain->GetBuffer(
0,
__uuidof(ID3D11Texture2D),
&backBuffer
)
);
// Create a view interface on the rendertarget to use on bind.
DX::ThrowIfFailed(
m_d3dDevice->CreateRenderTargetView(
backBuffer.Get(),
nullptr,
&m_renderTargetView
)
);
// Cache the rendertarget dimensions in our helper class for convenient use.
D3D11_TEXTURE2D_DESC backBufferDesc = {0};
backBuffer->GetDesc(&backBufferDesc);
m_renderTargetSize.Width = static_cast<float>(backBufferDesc.Width);
m_renderTargetSize.Height = static_cast<float>(backBufferDesc.Height);
// Create a descriptor for the depth/stencil buffer.
CD3D11_TEXTURE2D_DESC depthStencilDesc(
DXGI_FORMAT_D24_UNORM_S8_UINT,
backBufferDesc.Width,
backBufferDesc.Height,
1,
1,
D3D11_BIND_DEPTH_STENCIL
);
// Allocate a 2-D surface as the depth/stencil buffer.
ComPtr<ID3D11Texture2D> depthStencil;
DX::ThrowIfFailed(
m_d3dDevice->CreateTexture2D(
&depthStencilDesc,
nullptr,
&depthStencil
)
);
// Create a DepthStencil view on this surface to use on bind.
DX::ThrowIfFailed(
m_d3dDevice->CreateDepthStencilView(
depthStencil.Get(),
&CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D),
&m_depthStencilView
)
);
// Create a viewport descriptor of the full window size.
CD3D11_VIEWPORT viewport(
0.0f,
0.0f,
static_cast<float>(backBufferDesc.Width),
static_cast<float>(backBufferDesc.Height)
);
// Set the current viewport using the descriptor.
m_d3dContext->RSSetViewports(1, &viewport);
// Now we set up the Direct2D render target bitmap linked to the swapchain.
// Whenever we render to this bitmap, it will be directly rendered to the
// swapchain associated with the window.
D2D1_BITMAP_PROPERTIES1 bitmapProperties =
BitmapProperties1(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
m_dpi,
m_dpi
);
// Direct2D needs the dxgi version of the backbuffer surface pointer.
ComPtr<IDXGISurface> dxgiBackBuffer;
DX::ThrowIfFailed(
m_swapChain->GetBuffer(
0,
__uuidof(IDXGISurface),
&dxgiBackBuffer
)
);
// Get a D2D surface from the DXGI back buffer to use as the D2D render target.
DX::ThrowIfFailed(
m_d2dContext->CreateBitmapFromDxgiSurface(
dxgiBackBuffer.Get(),
&bitmapProperties,
&m_d2dTargetBitmap
)
);
// So now we can set the Direct2D render target.
m_d2dContext->SetTarget(m_d2dTargetBitmap.Get());
// Set D2D text anti-alias mode to Grayscale to ensure proper rendering of text on intermediate surfaces.
m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
}
void NiVek::D2DWrapper::UpdateForWindowSizeChange()
{
}
/*void NiVek::D2DWrapper::SetDpi( float dpi )
{
}*/
void NiVek::D2DWrapper::SaveBitmapToFile()
{
}
void NiVek::D2DWrapper::SaveBitmapToStream( _In_ ComPtr<ID2D1Bitmap1> d2dBitmap,
_In_ ComPtr<IWICImagingFactory2> wicFactory2,
_In_ ComPtr<ID2D1DeviceContext> d2dContext,
_In_ REFGUID wicFormat,
_In_ IStream* stream ){
// Create and initialize WIC Bitmap Encoder.
ComPtr<IWICBitmapEncoder> wicBitmapEncoder;
DX::ThrowIfFailed(
wicFactory2->CreateEncoder(
wicFormat,
nullptr, // No preferred codec vendor.
&wicBitmapEncoder
)
);
DX::ThrowIfFailed(
wicBitmapEncoder->Initialize(
stream,
WICBitmapEncoderNoCache
)
);
// Create and initialize WIC Frame Encoder.
ComPtr<IWICBitmapFrameEncode> wicFrameEncode;
DX::ThrowIfFailed(
wicBitmapEncoder->CreateNewFrame(
&wicFrameEncode,
nullptr // No encoder options.
)
);
DX::ThrowIfFailed(
wicFrameEncode->Initialize(nullptr)
);
// Retrieve D2D Device.
ComPtr<ID2D1Device> d2dDevice;
d2dContext->GetDevice(&d2dDevice);
// Create IWICImageEncoder.
ComPtr<IWICImageEncoder> imageEncoder;
DX::ThrowIfFailed(
wicFactory2->CreateImageEncoder(
d2dDevice.Get(),
&imageEncoder
)
);
DX::ThrowIfFailed(
imageEncoder->WriteFrame(
d2dBitmap.Get(),
wicFrameEncode.Get(),
nullptr // Use default WICImageParameter options.
)
);
DX::ThrowIfFailed(
wicFrameEncode->Commit()
);
DX::ThrowIfFailed(
wicBitmapEncoder->Commit()
);
// Flush all memory buffers to the next-level storage object.
DX::ThrowIfFailed( stream->Commit(STGC_DEFAULT) );
}
void NiVek::D2DWrapper::BeginDrawChart(int width, int height){
if(m_renderTargetBitmap == nullptr){
D2D1_BITMAP_PROPERTIES1 bmpProps = D2D1::BitmapProperties1(D2D1_BITMAP_OPTIONS_TARGET,D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,D2D1_ALPHA_MODE_PREMULTIPLIED), 96, 96,0);
DX::ThrowIfFailed( m_d2dContext->CreateBitmap(D2D1::SizeU(width,height),nullptr,0, bmpProps, &m_renderTargetBitmap) );
m_d2dContext->SetTarget(m_renderTargetBitmap.Get());
}
m_d2dContext->BeginDraw();
ColorF brushColor = D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f);
m_d2dContext->Clear(brushColor);
m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
}
void NiVek::D2DWrapper::DrawLine(const Platform::Array<float>^ points, int pointCount, Windows::UI::Color color){
ID2D1SolidColorBrush *brush;
DX::ThrowIfFailed( m_d2dContext->CreateSolidColorBrush(DX::ConvertToColorF(color), &brush) );
for(int idx = 0; idx < pointCount - 2; idx += 2){
m_d2dContext->DrawLine(D2D1::Point2F(points[idx], points[idx+1]),
D2D1::Point2F(points[idx + 2], points[idx+3]),
brush, 2.0f, 0);
}
brush->Release();
}
void NiVek::D2DWrapper::EndDrawChart(){
m_d2dContext->EndDraw();
}
Windows::Storage::Streams::InMemoryRandomAccessStream^ NiVek::D2DWrapper::GetImageStream(){
GUID wicFormat = GUID_ContainerFormatBmp;
ComPtr<IStream> stream;
ComPtr<ISequentialStream> ss;
auto m_inMemStream = ref new InMemoryRandomAccessStream();
DX::ThrowIfFailed(CreateStreamOverRandomAccessStream(m_inMemStream ,IID_PPV_ARGS(&stream)));
SaveBitmapToStream(m_renderTargetBitmap, m_wicFactory, m_d2dContext, wicFormat, stream.Get());
return m_inMemStream;
}
| 29.412148 | 175 | 0.748728 | [
"render",
"object",
"3d"
] |
115ab77dc874132d61cfd5f70fd7d19a79dccf66 | 1,161 | hpp | C++ | src/level-file-loader.hpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | src/level-file-loader.hpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | src/level-file-loader.hpp | tilnewman/halloween | 7cea37e31b2e566be76707cd8dc48527cec95bc5 | [
"MIT"
] | null | null | null | #ifndef LEVEL_FILE_LOADER_HPP_INCLUDED
#define LEVEL_FILE_LOADER_HPP_INCLUDED
//
// level-file-loader.hpp
//
#include "json.hpp"
#include "tileset.hpp"
#include <string>
#include <vector>
#include <SFML/Graphics/Rect.hpp>
namespace halloween
{
struct Context;
struct Settings;
using Json = nlohmann::json;
//
class LevelFileLoader
{
public:
LevelFileLoader();
void load(Context & context, const std::size_t LEVEL_NUMBER);
private:
static void parseLevelDetails(Context & context, Json & json);
void parseLayers(Context & context, Json & json);
void parseTileLayer(Context & context, const TileImage IMAGE, Json & json);
static void
parseRectLayer(Context & context, Json & json, std::vector<sf::FloatRect> & rects);
static sf::FloatRect parseAndConvertRect(const Context & CONTEXT, Json & json);
void parseSpawnLayer(Context & context, Json & json);
static void parseCoinLayer(Context & context, Json & json);
private:
std::string m_path;
};
} // namespace halloween
#endif // LEVEL_FILE_LOADER_HPP_INCLUDED
| 22.764706 | 95 | 0.668389 | [
"vector"
] |
115c49d9ff86fdab11070220bb93bcee611f2b62 | 9,461 | cpp | C++ | storage/source/app/config/Config.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | storage/source/app/config/Config.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | storage/source/app/config/Config.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | #include <common/toolkit/StringTk.h>
#include <common/toolkit/UnitTk.h>
#include "Config.h"
#define CONFIG_DEFAULT_CFGFILENAME "/etc/congfs/congfs-storage.conf"
#define CONFIG_STORAGETARGETS_DELIMITER ','
Config::Config(int argc, char** argv) :
AbstractConfig(argc, argv)
{
initConfig(argc, argv, true);
}
/**
* Sets the default values for each configurable in the configMap.
*
* @param addDashes currently unused
*/
void Config::loadDefaults(bool addDashes)
{
AbstractConfig::loadDefaults();
// re-definitions
configMapRedefine("cfgFile", "");
// own definitions
configMapRedefine("connInterfacesFile", "");
configMapRedefine("connInterfacesList", "");
configMapRedefine("storeStorageDirectory", "");
configMapRedefine("storeAllowFirstRunInit", "true");
configMapRedefine("tuneNumStreamListeners", "1");
configMapRedefine("tuneNumWorkers", "8");
configMapRedefine("tuneWorkerBufSize", "4m");
configMapRedefine("tuneProcessFDLimit", "50000");
configMapRedefine("tuneWorkerNumaAffinity", "false");
configMapRedefine("tuneListenerNumaAffinity", "false");
configMapRedefine("tuneListenerPrioShift", "-1");
configMapRedefine("tuneBindToNumaZone", "");
configMapRedefine("tuneFileReadSize", "32k");
configMapRedefine("tuneFileReadAheadTriggerSize", "4m");
configMapRedefine("tuneFileReadAheadSize", "0");
configMapRedefine("tuneFileWriteSize", "64k");
configMapRedefine("tuneFileWriteSyncSize", "0");
configMapRedefine("tuneUsePerUserMsgQueues", "false");
configMapRedefine("tuneDirCacheLimit", "1024");
configMapRedefine("tuneEarlyStat", "false");
configMapRedefine("tuneNumResyncSlaves", "12");
configMapRedefine("tuneNumResyncGatherSlaves", "6");
configMapRedefine("tuneUseAggressiveStreamPoll", "false");
configMapRedefine("tuneUsePerTargetWorkers", "true");
configMapRedefine("quotaEnableEnforcement", "false");
configMapRedefine("quotaDisableZfsSupport", "false");
configMapRedefine("sysResyncSafetyThresholdMins", "10");
configMapRedefine("sysTargetOfflineTimeoutSecs", "180");
configMapRedefine("runDaemonized", "false");
configMapRedefine("pidFile", "");
}
/**
* @param addDashes currently usused
*/
void Config::applyConfigMap(bool enableException, bool addDashes)
{
AbstractConfig::applyConfigMap(false);
for (StringMapIter iter = configMap.begin(); iter != configMap.end();)
{
bool unknownElement = false;
if (iter->first == std::string("logType"))
{
if (iter->second == "syslog")
{
logType = LogType_SYSLOG;
}
else if (iter->second == "logfile")
{
logType = LogType_LOGFILE;
}
else
{
throw InvalidConfigException("The value of config argument logType is invalid.");
}
}
else if (iter->first == std::string("connInterfacesFile"))
connInterfacesFile = iter->second;
else if (iter->first == std::string("connInterfacesList"))
connInterfacesList = iter->second;
else if (iter->first == std::string("storeStorageDirectory"))
{
storageDirectories.clear();
std::list<std::string> split;
StringTk::explode(iter->second, CONFIG_STORAGETARGETS_DELIMITER, &split);
std::transform(
split.begin(), split.end(),
std::back_inserter(storageDirectories),
[] (const std::string& p) {
return Path(StringTk::trim(p));
});
storageDirectories.remove_if(std::mem_fn(&Path::empty));
}
else if (iter->first == std::string("storeAllowFirstRunInit"))
storeAllowFirstRunInit = StringTk::strToBool(iter->second);
else if (iter->first == std::string("tuneNumStreamListeners"))
tuneNumStreamListeners = StringTk::strToUInt(iter->second);
else if (iter->first == std::string("tuneNumWorkers"))
tuneNumWorkers = StringTk::strToUInt(iter->second);
else if (iter->first == std::string("tuneWorkerBufSize"))
tuneWorkerBufSize = UnitTk::strHumanToInt64(iter->second);
else if (iter->first == std::string("tuneProcessFDLimit"))
tuneProcessFDLimit = StringTk::strToUInt(iter->second);
else if (iter->first == std::string("tuneWorkerNumaAffinity"))
tuneWorkerNumaAffinity = StringTk::strToBool(iter->second);
else if (iter->first == std::string("tuneListenerNumaAffinity"))
tuneListenerNumaAffinity = StringTk::strToBool(iter->second);
else if (iter->first == std::string("tuneBindToNumaZone"))
{
if (iter->second.empty()) // not defined => disable
tuneBindToNumaZone = -1; // -1 means disable binding
else
tuneBindToNumaZone = StringTk::strToInt(iter->second);
}
else if (iter->first == std::string("tuneListenerPrioShift"))
tuneListenerPrioShift = StringTk::strToInt(iter->second);
else if (iter->first == std::string("tuneFileReadSize"))
tuneFileReadSize = UnitTk::strHumanToInt64(iter->second);
else if (iter->first == std::string("tuneFileReadAheadTriggerSize"))
tuneFileReadAheadTriggerSize = UnitTk::strHumanToInt64(iter->second);
else if (iter->first == std::string("tuneFileReadAheadSize"))
tuneFileReadAheadSize = UnitTk::strHumanToInt64(iter->second);
else if (iter->first == std::string("tuneFileWriteSize"))
tuneFileWriteSize = UnitTk::strHumanToInt64(iter->second);
else if (iter->first == std::string("tuneFileWriteSyncSize"))
tuneFileWriteSyncSize = UnitTk::strHumanToInt64(iter->second);
else if (iter->first == std::string("tuneUsePerUserMsgQueues"))
tuneUsePerUserMsgQueues = StringTk::strToBool(iter->second);
else if (iter->first == std::string("tuneDirCacheLimit"))
tuneDirCacheLimit = StringTk::strToUInt(iter->second);
else if (iter->first == std::string("tuneEarlyStat"))
this->tuneEarlyStat = StringTk::strToBool(iter->second);
else if (iter->first == std::string("tuneNumResyncGatherSlaves"))
this->tuneNumResyncGatherSlaves = StringTk::strToUInt(iter->second);
else if (iter->first == std::string("tuneNumResyncSlaves"))
this->tuneNumResyncSlaves = StringTk::strToUInt(iter->second);
else if (iter->first == std::string("tuneUseAggressiveStreamPoll"))
tuneUseAggressiveStreamPoll = StringTk::strToBool(iter->second);
else if (iter->first == std::string("tuneUsePerTargetWorkers"))
tuneUsePerTargetWorkers = StringTk::strToBool(iter->second);
else if (iter->first == std::string("quotaEnableEnforcement"))
quotaEnableEnforcement = StringTk::strToBool(iter->second);
else if (iter->first == std::string("quotaDisableZfsSupport"))
quotaDisableZfsSupport = StringTk::strToBool(iter->second);
else if (iter->first == std::string("sysResyncSafetyThresholdMins"))
sysResyncSafetyThresholdMins = StringTk::strToInt64(iter->second);
else if (iter->first == std::string("sysTargetOfflineTimeoutSecs"))
{
sysTargetOfflineTimeoutSecs = StringTk::strToUInt(iter->second);
if (sysTargetOfflineTimeoutSecs < 30)
{
throw InvalidConfigException("Invalid sysTargetOfflineTimeoutSecs value "
+ iter->second + " (must be at least 30)");
}
}
else if (iter->first == std::string("runDaemonized"))
runDaemonized = StringTk::strToBool(iter->second);
else if (iter->first == std::string("pidFile"))
pidFile = iter->second;
else
{
// unknown element occurred
unknownElement = true;
if (enableException)
{
throw InvalidConfigException("The config argument '" + iter->first + "' is invalid");
}
}
if (unknownElement)
{
// just skip the unknown element
iter++;
}
else
{
// remove this element from the map
iter = eraseFromConfigMap(iter);
}
}
}
void Config::initImplicitVals()
{
// tuneFileReadAheadTriggerSize (should be ">= tuneFileReadAheadSize")
if(tuneFileReadAheadTriggerSize < tuneFileReadAheadSize)
tuneFileReadAheadTriggerSize = tuneFileReadAheadSize;
// connInterfacesList(/File)
AbstractConfig::initInterfacesList(connInterfacesFile, connInterfacesList);
// check if sync_file_range was enabled on a distro that doesn't support it
#ifndef CONFIG_DISTRO_HAS_SYNC_FILE_RANGE
if(tuneFileWriteSyncSize)
{
throw InvalidConfigException(
"Config option is not supported for this distribution: 'tuneFileWriteSyncSize'");
}
#endif
// connAuthHash
AbstractConfig::initConnAuthHash(connAuthFile, &connAuthHash);
}
std::string Config::createDefaultCfgFilename() const
{
struct stat statBuf;
const int statRes = stat(CONFIG_DEFAULT_CFGFILENAME, &statBuf);
if(!statRes && S_ISREG(statBuf.st_mode) )
return CONFIG_DEFAULT_CFGFILENAME; // there appears to be a config file
return ""; // no default file otherwise
}
| 39.752101 | 97 | 0.648557 | [
"transform"
] |
115f73b5da7fbaf903dc93cca90eee84e134834e | 2,817 | cpp | C++ | ChampionshipLib/source/Championship.cpp | lucasguesserts/prisoners_dilemma | a786af699c95c99797b074b1b73a2a3f7ef68436 | [
"MIT"
] | null | null | null | ChampionshipLib/source/Championship.cpp | lucasguesserts/prisoners_dilemma | a786af699c95c99797b074b1b73a2a3f7ef68436 | [
"MIT"
] | null | null | null | ChampionshipLib/source/Championship.cpp | lucasguesserts/prisoners_dilemma | a786af699c95c99797b074b1b73a2a3f7ef68436 | [
"MIT"
] | null | null | null | #include <cstddef>
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include "Strategy.hpp"
#include "Player.hpp"
#include "Match.hpp"
#include "Championship.hpp"
using namespace PrisonersDilemma;
ChampionshipDescription::ChampionshipDescription(
const std::string & name,
const std::string & description,
const unsigned numberOfTurns)
: name(name),
description(description),
numberOfTurns(numberOfTurns)
{}
Championship::Championship(
const ChampionshipDescription & fullDescription,
const std::vector<const Strategy *> & strategies)
: ChampionshipDescription(fullDescription)
{
for(auto strategy: strategies)
this->players.emplace_back(*strategy);
return;
}
void Championship::compete(void)
{
for(auto leftPlayer=this->players.begin() ; leftPlayer!=this->players.end() ; ++leftPlayer)
for(auto rightPlayer=leftPlayer ; rightPlayer!=this->players.end() ; ++rightPlayer)
Match(*leftPlayer, *rightPlayer, this->numberOfTurns);
return;
}
void Championship::rank(void)
{
auto compare = [](Player& lhs, Player& rhs){ return lhs.score() < rhs.score(); };
std::sort(this->players.begin(), this->players.end(), compare);
return;
}
std::ostream& PrisonersDilemma::operator<<(std::ostream& os, const Championship& championship)
{
// This is how it is going to look like:
//
// Strategies rank:
// Place : Score : Strategy
// 0 : 1198 : Meta-Regulated Adaptative Tit For Tat
// 1 : 1201 : Gradual
// 2 : 1265 : Generous Tit For Tat
// 3 : 1283 : Adaptative Tit For Tat
using std::endl;
const std::string tab = "\t";
os << static_cast<ChampionshipDescription>(championship);
os << tab << "Strategies rank:" << endl;
auto divisor = " : ";
os << tab << tab << "Place" << divisor << " Score" << divisor << "Strategy" << endl;
os << tab << tab << "-----" << divisor << " -----" << divisor << "--------" << endl;
for(size_t place=0u ; place<championship.players.size() ; place++)
{
const Player& player = championship.players.at(place);
os << tab << tab << \
std::setw( 5) << std::right << place << divisor << \
std::setw( 6) << std::right << player.score() << divisor << \
std::setw(40) << std::left << player.strategy->name << \
endl;
}
os << endl;
return os;
}
std::ostream& PrisonersDilemma::operator<<(std::ostream& os, const ChampionshipDescription& championshipDescription)
{
using std::endl;
const std::string tab = "\t";
os << championshipDescription.name << " Championship" << endl;
os << "----------------------------------------" << endl;
os << tab << "Description: " << championshipDescription.description << endl;
os << tab << "Number of Turns: " << championshipDescription.numberOfTurns << endl;
return os;
}
| 31.651685 | 116 | 0.649982 | [
"vector"
] |
1164247d285bab6c05e2c803cb27d9159339996a | 26,956 | cpp | C++ | src/oatpp-swagger/Generator.cpp | oben01/oatpp-swagger | 8b70945f0e9bcf09e16b5cb4be08e752097b0288 | [
"Apache-2.0"
] | null | null | null | src/oatpp-swagger/Generator.cpp | oben01/oatpp-swagger | 8b70945f0e9bcf09e16b5cb4be08e752097b0288 | [
"Apache-2.0"
] | null | null | null | src/oatpp-swagger/Generator.cpp | oben01/oatpp-swagger | 8b70945f0e9bcf09e16b5cb4be08e752097b0288 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi, <lganzzzo@gmail.com>
*
* 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 "Generator.hpp"
#include "oatpp/core/utils/ConversionUtils.hpp"
#include "oatpp/core/data/stream/BufferStream.hpp"
#include <limits>
namespace oatpp { namespace swagger {
oatpp::String Generator::getEnumSchemaName(const Type* type) {
auto polymorphicDispatcher = static_cast<const data::mapping::type::__class::AbstractEnum::PolymorphicDispatcher*>(
type->polymorphicDispatcher
);
Type* interType = polymorphicDispatcher->getInterpretationType();
data::stream::BufferOutputStream stream;
stream << type->nameQualifier << "(" << interType->classId.name << ")";
return stream.toString();
}
oatpp::Object<oas3::Schema> Generator::generateSchemaForSimpleType(const Type* type, oatpp::BaseObject::Property* property, const oatpp::Void& defaultValue) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::generateSchemaForSimpleType()]: Error. Type should not be null.");
auto result = oas3::Schema::createShared();
auto classId = type->classId.id;
if(classId == oatpp::data::mapping::type::__class::String::CLASS_ID.id) {
result->type = "string";
if(property != nullptr && !property->info.pattern.empty()) {
result->pattern = property->info.pattern.c_str();
}
} else if(classId == oatpp::data::mapping::type::__class::Int8::CLASS_ID.id) {
result->type = "integer";
result->minimum = std::numeric_limits<v_int8>::min();
result->maximum = std::numeric_limits<v_int8>::max();
} else if(classId == oatpp::data::mapping::type::__class::UInt8::CLASS_ID.id) {
result->type = "integer";
result->minimum = std::numeric_limits<v_uint8>::min();
result->maximum = std::numeric_limits<v_uint8>::max();
} else if(classId == oatpp::data::mapping::type::__class::Int16::CLASS_ID.id) {
result->type = "integer";
result->minimum = std::numeric_limits<v_int16>::min();
result->maximum = std::numeric_limits<v_int16>::max();
} else if(classId == oatpp::data::mapping::type::__class::UInt16::CLASS_ID.id) {
result->type = "integer";
result->minimum = std::numeric_limits<v_uint16>::min();
result->maximum = std::numeric_limits<v_uint16>::max();
} else if(classId == oatpp::data::mapping::type::__class::Int32::CLASS_ID.id) {
result->type = "integer";
result->minimum = std::numeric_limits<v_int32>::min();
result->maximum = std::numeric_limits<v_int32>::max();
} else if(classId == oatpp::data::mapping::type::__class::UInt32::CLASS_ID.id) {
result->type = "integer";
result->minimum = std::numeric_limits<v_uint32>::min();
result->maximum = std::numeric_limits<v_uint32>::max();
} else if(classId == oatpp::data::mapping::type::__class::Int64::CLASS_ID.id) {
result->type = "integer";
result->format = "int64";
} else if(classId == oatpp::data::mapping::type::__class::UInt64::CLASS_ID.id) {
result->type = "integer";
} else if(classId == oatpp::data::mapping::type::__class::Float32::CLASS_ID.id) {
result->type = "number";
result->format = "float";
} else if(classId == oatpp::data::mapping::type::__class::Float64::CLASS_ID.id) {
result->type = "number";
result->format = "double";
} else if(classId == oatpp::data::mapping::type::__class::Boolean::CLASS_ID.id) {
result->type = "boolean";
} else {
return nullptr; // Unknown simple type;
}
return result;
}
oatpp::Object<oas3::Schema> Generator::generateSchemaForTypeObject(const Type* type, bool linkSchema, UsedTypes& usedTypes) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::generateSchemaForTypeObject()]: Error. Type should not be null.");
auto result = oas3::Schema::createShared();
if(linkSchema) {
result->ref = oatpp::String("#/components/schemas/") + type->nameQualifier;
usedTypes[type->nameQualifier] = type;
return result;
} else {
result->type = "object";
result->properties = {};
auto polymorphicDispatcher = static_cast<const oatpp::data::mapping::type::__class::AbstractObject::PolymorphicDispatcher*>(
type->polymorphicDispatcher
);
auto instance = polymorphicDispatcher->createObject();
auto properties = polymorphicDispatcher->getProperties();
for(auto* p : properties->getList()) {
const auto& defaultValue = p->get(static_cast<oatpp::BaseObject*>(instance.get()));
result->properties[p->name] = generateSchemaForType(p->type, true, usedTypes, p, defaultValue);
}
return result;
}
}
oatpp::Object<oas3::Schema> Generator::generateSchemaForCollection_1D(const Type* type, bool linkSchema, UsedTypes& usedTypes, bool uniqueItems) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::generateSchemaForCollection_1D()]: Error. Type should not be null.");
auto result = oas3::Schema::createShared();
result->type = "array";
result->items = generateSchemaForType(*type->params.begin(), linkSchema, usedTypes);
if(uniqueItems) {
result->uniqueItems = true;
}
return result;
}
oatpp::Object<oas3::Schema> Generator::generateSchemaForEnum(const Type* type, bool linkSchema, UsedTypes& usedTypes, oatpp::BaseObject::Property* property) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::generateSchemaForTypeObject()]: Error. Type should not be null.");
if(linkSchema) {
auto result = oas3::Schema::createShared();
result->ref = oatpp::String("#/components/schemas/") + getEnumSchemaName(type);
usedTypes[getEnumSchemaName(type)] = type;
return result;
}
auto polymorphicDispatcher = static_cast<const data::mapping::type::__class::AbstractEnum::PolymorphicDispatcher*>(
type->polymorphicDispatcher
);
Type* interType = polymorphicDispatcher->getInterpretationType();
auto result = generateSchemaForType(interType, linkSchema, usedTypes);
result->enumValues = oatpp::List<oatpp::Any>::createShared();
auto interEnum = polymorphicDispatcher->getInterpretedEnum();
for(auto& v : interEnum) {
result->enumValues->push_back(v);
}
return result;
}
oatpp::Object<oas3::Schema> Generator::generateSchemaForAbstractPairList(const Type* type, bool linkSchema, UsedTypes& usedTypes, oatpp::BaseObject::Property* property ) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::generateSchemaForAbstractPairList()]: Error. Type should not be null.");
auto result = oas3::Schema::createShared();
// A PairList<String, T> is a Fields<T> and a Fields<T> is a simple JSON object
if (type->params.front()->classId.id == oatpp::String::Class::CLASS_ID.id) {
result->type = "object";
result->additionalProperties = generateSchemaForType(type->params.back(), linkSchema, usedTypes);
}
return result;
}
oatpp::Object<oas3::Schema> Generator::generateSchemaForType(const Type* type, bool linkSchema, UsedTypes& usedTypes, oatpp::BaseObject::Property* property, const oatpp::Void& defaultValue) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::generateSchemaForType()]: Error. Type should not be null.");
oatpp::Object<oas3::Schema> result;
auto classId = type->classId.id;
if(classId == oatpp::data::mapping::type::__class::AbstractObject::CLASS_ID.id) {
result = generateSchemaForTypeObject(type, linkSchema, usedTypes);
} else if(classId == oatpp::data::mapping::type::__class::AbstractVector::CLASS_ID.id) {
result = generateSchemaForCollection_1D(type, linkSchema, usedTypes, false);
} else if(classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID.id) {
result = generateSchemaForCollection_1D(type, linkSchema, usedTypes, false);
} else if(classId == oatpp::data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID.id) {
result = generateSchemaForCollection_1D(type, linkSchema, usedTypes, true);
} else if(classId == oatpp::data::mapping::type::__class::AbstractPairList::CLASS_ID.id) {
result = generateSchemaForAbstractPairList(type, linkSchema, usedTypes, property);
} else if(classId == oatpp::data::mapping::type::__class::AbstractEnum::CLASS_ID.id) {
result = generateSchemaForEnum(type, linkSchema, usedTypes, property);
} else {
result = generateSchemaForSimpleType(type, property, defaultValue);
}
if(!result) {
auto interpretation = type->findInterpretation(m_config->enableInterpretations);
if(interpretation) {
result = generateSchemaForType(interpretation->getInterpretationType(), linkSchema, usedTypes);
}
}
if(!result) {
result = oas3::Schema::createShared();
result->type = type->classId.name;
if(type->nameQualifier) {
result->format = type->nameQualifier;
}
}
if(property != nullptr) {
if(!property->info.description.empty()) {
result->description = property->info.description.c_str();
}
if (defaultValue) {
result->defaultValue = defaultValue;
}
}
return result;
}
void Generator::addParamsToParametersList(const PathItemParameters& paramsList,
Endpoint::Info::Params& params,
const oatpp::String& inType,
UsedTypes& usedTypes)
{
for(auto& paramName : params.getOrder()) {
auto param = params[paramName];
auto parameter = oas3::PathItemParameter::createShared();
parameter->in = inType;
parameter->name = param.name;
parameter->description = param.description;
parameter->required = param.required;
parameter->deprecated = param.deprecated;
parameter->schema = generateSchemaForType(param.type, true, usedTypes);
for(auto& ex : param.examples) {
parameter->addExample(ex.first, ex.second);
}
paramsList->push_back(parameter);
}
}
oatpp::Object<oas3::RequestBody> Generator::generateRequestBody(const Endpoint::Info& endpointInfo, bool linkSchema, UsedTypes& usedTypes) {
if(endpointInfo.consumes.size() > 0) {
auto body = oas3::RequestBody::createShared();
body->description = endpointInfo.body.description;
body->required = endpointInfo.body.required;
body->content = body->content.createShared();
for(auto& hint : endpointInfo.consumes) {
auto mediaType = oas3::MediaTypeObject::createShared();
mediaType->schema = generateSchemaForType(hint.schema, linkSchema, usedTypes);
if(hint.examples.size() > 0) {
for(auto& ex : hint.examples) {
mediaType->addExample(ex.first, ex.second);
}
} else {
for(auto& ex : endpointInfo.body.examples) {
mediaType->addExample(ex.first, ex.second);
}
}
body->content[hint.contentType] = mediaType;
}
return body;
} else {
if(endpointInfo.body.name != nullptr && endpointInfo.body.type != nullptr) {
auto body = oas3::RequestBody::createShared();
body->description = endpointInfo.body.description;
body->required = endpointInfo.body.required;
auto mediaType = oas3::MediaTypeObject::createShared();
mediaType->schema = generateSchemaForType(endpointInfo.body.type, linkSchema, usedTypes);
for(auto& ex : endpointInfo.body.examples) {
mediaType->addExample(ex.first, ex.second);
}
body->content = body->content.createShared();
if(endpointInfo.bodyContentType != nullptr) {
body->content[endpointInfo.bodyContentType] = mediaType;
} else {
body->content["text/plain"] = mediaType;
}
return body;
}
}
return nullptr;
}
oatpp::Fields<Object<oas3::OperationResponse>> Generator::generateResponses(const Endpoint::Info& endpointInfo, bool linkSchema, UsedTypes& usedTypes) {
auto responses = Fields<Object<oas3::OperationResponse>>::createShared();
if(endpointInfo.responses.size() > 0) {
for(auto& hint : endpointInfo.responses) {
auto mediaType = oas3::MediaTypeObject::createShared();
mediaType->schema = generateSchemaForType(hint.second.schema, linkSchema, usedTypes);
for(auto& ex : hint.second.examples) {
mediaType->addExample(ex.first, ex.second);
}
auto response = oas3::OperationResponse::createShared();
response->description = hint.second.description.get() == nullptr ? hint.first.description : hint.second.description;
response->content = {};
response->content[hint.second.contentType] = mediaType;
responses[oatpp::utils::conversion::int32ToStr(hint.first.code)] = response;
}
} else {
auto mediaType = oas3::MediaTypeObject::createShared();
mediaType->schema = generateSchemaForType(oatpp::String::Class::getType(), linkSchema, usedTypes);
auto response = oas3::OperationResponse::createShared();
response->description = "success";
response->content = {};
response->content["text/plain"] = mediaType;
responses["200"] = response;
}
return responses;
}
void Generator::generatePathItemData(const std::shared_ptr<Endpoint>& endpoint, const oatpp::Object<oas3::PathItem>& pathItem, UsedTypes& usedTypes, UsedSecuritySchemes &usedSecuritySchemes) {
auto info = endpoint->info();
if(info) {
auto operation = oas3::PathItemOperation::createShared();
operation->operationId = info->name;
operation->summary = info->summary;
operation->description = info->description;
if(info->tags.size() > 0) {
operation->tags = oatpp::List<String>({});
for(auto& tag : info->tags) {
operation->tags->push_back(tag);
}
}
if(oatpp::base::StrBuffer::equalsCI("get", info->method->c_str(), info->method->getSize())) {
pathItem->operationGet = operation;
} else if(oatpp::base::StrBuffer::equalsCI("put", info->method->c_str(), info->method->getSize())) {
pathItem->operationPut = operation;
} else if(oatpp::base::StrBuffer::equalsCI("post", info->method->c_str(), info->method->getSize())) {
pathItem->operationPost = operation;
} else if(oatpp::base::StrBuffer::equalsCI("delete", info->method->c_str(), info->method->getSize())) {
pathItem->operationDelete = operation;
} else if(oatpp::base::StrBuffer::equalsCI("options", info->method->c_str(), info->method->getSize())) {
pathItem->operationOptions = operation;
} else if(oatpp::base::StrBuffer::equalsCI("head", info->method->c_str(), info->method->getSize())) {
pathItem->operationHead = operation;
} else if(oatpp::base::StrBuffer::equalsCI("patch", info->method->c_str(), info->method->getSize())) {
pathItem->operationPatch = operation;
} else if(oatpp::base::StrBuffer::equalsCI("trace", info->method->c_str(), info->method->getSize())) {
pathItem->operationTrace = operation;
}
operation->responses = generateResponses(*info, true, usedTypes);
operation->requestBody = generateRequestBody(*info, true, usedTypes);
if(!operation->parameters) {
operation->parameters = {};
Endpoint::Info::Params filteredHeaders;
if(!info->headers.getOrder().empty()) {
for (const auto &header : info->headers.getOrder()) {
// We don't want the Authorization header listed as Parameter. This should be done in ENDPOINT_INFO() { info->addSecurityRequirement( /* SecurityScheme-Name */ ); }
if (header != oatpp::web::protocol::http::Header::AUTHORIZATION) {
filteredHeaders[header] = info->headers[header];
}
}
}
addParamsToParametersList(operation->parameters, filteredHeaders, "header", usedTypes);
addParamsToParametersList(operation->parameters, info->pathParams, "path", usedTypes);
addParamsToParametersList(operation->parameters, info->queryParams, "query", usedTypes);
}
if(!info->securityRequirements.empty()) {
OATPP_ASSERT(info->authorization && "[oatpp-swagger::oas3::Generator::generatePathItemData()]: Error. Endpoint has security requirement but is no authorized endpoint.");
}
if(info->authorization) {
OATPP_ASSERT(!info->securityRequirements.empty() && "[oatpp-swagger::oas3::Generator::generatePathItemData()]: Error. Authorized endpoint with no security requirements (info->addSecurityRequirement()) set.");
if (!info->securityRequirements.empty()) {
operation->security = oatpp::List<Fields<List<String>>>({});
for (const auto &sec : info->securityRequirements) {
usedSecuritySchemes[sec.first] = true;
if (sec.second == nullptr) {
// who ever came up to define "security" as an array of objects of array of strings
auto fields = Fields<oatpp::List<String>>({});
fields[sec.first] = oatpp::List<String>({});
operation->security->push_back(fields);
} else {
auto fields = Fields<List<String>>::createShared();
auto sro = List<String>::createShared();
for (const auto &sr : *sec.second) {
sro->push_back(sr);
}
fields[sec.first] = sro;
operation->security->push_back(fields);
}
}
}
}
}
}
Generator::Paths Generator::generatePaths(const std::shared_ptr<Endpoints>& endpoints, UsedTypes& usedTypes, UsedSecuritySchemes &usedSecuritySchemes) {
auto result = Paths::createShared();
auto curr = endpoints->getFirstNode();
while (curr != nullptr) {
auto endpoint = curr->getData();
if(endpoint->info() && !endpoint->info()->hide) {
oatpp::String path = endpoint->info()->path;
if(path->getSize() == 0) {
continue;
}
if(path->getData()[0] != '/') {
path = "/" + path;
}
auto& pathItem = result[path];
if(!pathItem) {
pathItem = oas3::PathItem::createShared();
}
generatePathItemData(endpoint, pathItem, usedTypes, usedSecuritySchemes);
}
curr = curr->getNext();
}
return result;
}
void Generator::decomposeObject(const Type* type, UsedTypes& decomposedTypes) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::decomposeObject()]: Error. Type should not be null.");
auto schemaIt = decomposedTypes.find(type->nameQualifier);
if(schemaIt != decomposedTypes.end()) {
return;
}
decomposedTypes[type->nameQualifier] = type;
auto polymorphicDispatcher = static_cast<const oatpp::data::mapping::type::__class::AbstractObject::PolymorphicDispatcher*>(
type->polymorphicDispatcher
);
auto properties = polymorphicDispatcher->getProperties();
for(auto* p : properties->getList()) {
decomposeType(p->type, decomposedTypes);
}
}
void Generator::decomposeCollection_1D(const Type* type, UsedTypes& decomposedTypes) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::Collection_1D()]: Error. Type should not be null.");
decomposeType(*type->params.begin(), decomposedTypes);
}
void Generator::decomposeMap(const Type* type, UsedTypes& decomposedTypes) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::decomposeMap()]: Error. Type should not be null.");
// The only possible JSON representation of a PairList<A, B> is A being a String, even if an numeric one
if (type->params.front()->classId.id == oatpp::data::mapping::type::__class::String::CLASS_ID.id) {
decomposeType(type->params.back(), decomposedTypes);
}
// TODO - more advanced cases with complex key types
}
void Generator::decomposeEnum(const Type* type, UsedTypes& decomposedTypes) {
auto schemaIt = decomposedTypes.find(getEnumSchemaName(type));
if(schemaIt != decomposedTypes.end()) {
return;
}
decomposedTypes[getEnumSchemaName(type)] = type;
}
void Generator::decomposeType(const Type* type, UsedTypes& decomposedTypes) {
OATPP_ASSERT(type && "[oatpp-swagger::oas3::Generator::decomposeType()]: Error. Type should not be null.");
auto classId = type->classId.id;
if(classId == oatpp::data::mapping::type::__class::AbstractObject::CLASS_ID.id){
decomposeObject(type, decomposedTypes);
} else if(classId == oatpp::data::mapping::type::__class::AbstractVector::CLASS_ID.id){
decomposeCollection_1D(type, decomposedTypes);
} else if(classId == oatpp::data::mapping::type::__class::AbstractList::CLASS_ID.id){
decomposeCollection_1D(type, decomposedTypes);
} else if(classId == oatpp::data::mapping::type::__class::AbstractUnorderedSet::CLASS_ID.id){
decomposeCollection_1D(type, decomposedTypes);
} else if(classId == oatpp::data::mapping::type::__class::AbstractPairList::CLASS_ID.id){
decomposeMap(type, decomposedTypes);
} else if(classId == oatpp::data::mapping::type::__class::AbstractEnum::CLASS_ID.id){
decomposeEnum(type, decomposedTypes);
}
}
Generator::UsedTypes Generator::decomposeTypes(UsedTypes& usedTypes) {
UsedTypes result; // decomposed schemas
auto it = usedTypes.begin();
while (it != usedTypes.end()) {
decomposeType(it->second, result);
result[it->first] = it->second;
it ++;
}
return result;
}
oatpp::Object<oas3::Components> Generator::generateComponents(const UsedTypes &decomposedTypes,
const std::shared_ptr<std::unordered_map<oatpp::String,std::shared_ptr<oatpp::swagger::SecurityScheme>>> &securitySchemes,
UsedSecuritySchemes &usedSecuritySchemes) {
auto result = oas3::Components::createShared();
result->schemas = {};
auto it = decomposedTypes.begin();
while (it != decomposedTypes.end()) {
UsedTypes schemas; ///< dummy
result->schemas[it->first] = generateSchemaForType(it->second, false, schemas);
it ++;
}
if(securitySchemes) {
result->securitySchemes = {};
for (const auto &ss : usedSecuritySchemes) {
OATPP_ASSERT(securitySchemes->find(ss.first) != securitySchemes->end() && "[oatpp-swagger::oas3::Generator::generateComponents()]: Error. Requested unknown security requirement.");
result->securitySchemes[ss.first] = generateSecurityScheme(securitySchemes->at(ss.first));
}
}
return result;
}
oatpp::Object<oas3::SecurityScheme> Generator::generateSecurityScheme(const std::shared_ptr<oatpp::swagger::SecurityScheme> &ss) {
auto oasSS = oatpp::swagger::oas3::SecurityScheme::createShared();
oasSS->type = ss->type;
oasSS->description = ss->description;
oasSS->openIdConnectUrl = ss->openIdConnectUrl;
oasSS->in = ss->in;
oasSS->bearerFormat = ss->bearerFormat;
oasSS->name = ss->name;
oasSS->scheme = ss->scheme;
if(ss->flows) {
oasSS->flows = oasSS->flows->createShared();
if(ss->flows->implicit) {
oasSS->flows->implicit = oas3::OAuthFlow::createShared();
oasSS->flows->implicit->tokenUrl = ss->flows->implicit->tokenUrl;
oasSS->flows->implicit->refreshUrl = ss->flows->implicit->refreshUrl;
oasSS->flows->implicit->authorizationUrl = ss->flows->implicit->authorizationUrl;
if(ss->flows->implicit->scopes) {
oasSS->flows->implicit->scopes = oatpp::Fields<String>({});
for(const auto &scope : *ss->flows->implicit->scopes) {
oasSS->flows->implicit->scopes[scope.first] = scope.second;
}
}
}
if(ss->flows->password) {
oasSS->flows->password = oas3::OAuthFlow::createShared();
oasSS->flows->password->tokenUrl = ss->flows->password->tokenUrl;
oasSS->flows->password->refreshUrl = ss->flows->password->refreshUrl;
oasSS->flows->password->authorizationUrl = ss->flows->password->authorizationUrl;
if(ss->flows->password->scopes) {
oasSS->flows->password->scopes = oatpp::Fields<String>({});
for(const auto &scope : *ss->flows->password->scopes) {
oasSS->flows->password->scopes[scope.first] = scope.second;
}
}
}
if(ss->flows->clientCredentials) {
oasSS->flows->clientCredentials = oas3::OAuthFlow::createShared();
oasSS->flows->clientCredentials->tokenUrl = ss->flows->clientCredentials->tokenUrl;
oasSS->flows->clientCredentials->refreshUrl = ss->flows->clientCredentials->refreshUrl;
oasSS->flows->clientCredentials->authorizationUrl = ss->flows->clientCredentials->authorizationUrl;
if(ss->flows->clientCredentials->scopes) {
oasSS->flows->clientCredentials->scopes = oatpp::Fields<String>({});
for(const auto &scope : *ss->flows->clientCredentials->scopes) {
oasSS->flows->clientCredentials->scopes[scope.first] = scope.second;
}
}
}
if(ss->flows->authorizationCode) {
oasSS->flows->authorizationCode = oas3::OAuthFlow::createShared();
oasSS->flows->authorizationCode->tokenUrl = ss->flows->authorizationCode->tokenUrl;
oasSS->flows->authorizationCode->refreshUrl = ss->flows->authorizationCode->refreshUrl;
oasSS->flows->authorizationCode->authorizationUrl = ss->flows->authorizationCode->authorizationUrl;
if(ss->flows->authorizationCode->scopes) {
oasSS->flows->authorizationCode->scopes = oatpp::Fields<String>({});
for(const auto &scope : *ss->flows->authorizationCode->scopes) {
oasSS->flows->authorizationCode->scopes[scope.first] = scope.second;
}
}
}
}
return oasSS;
}
Generator::Generator(const std::shared_ptr<Config>& config)
: m_config(config)
{}
oatpp::Object<oas3::Document> Generator::generateDocument(const std::shared_ptr<oatpp::swagger::DocumentInfo>& docInfo, const std::shared_ptr<Endpoints>& endpoints) {
auto document = oas3::Document::createShared();
document->info = oas3::Info::createFromBaseModel(docInfo->header);
if(docInfo->servers) {
document->servers = {};
for(const auto &it : *docInfo->servers) {
document->servers->push_back(oas3::Server::createFromBaseModel(it));
}
}
UsedTypes usedTypes;
UsedSecuritySchemes usedSecuritySchemes;
document->paths = generatePaths(endpoints, usedTypes, usedSecuritySchemes);
auto decomposedTypes = decomposeTypes(usedTypes);
document->components = generateComponents(decomposedTypes, docInfo->securitySchemes, usedSecuritySchemes);
return document;
}
}}
| 38.674319 | 214 | 0.673134 | [
"object"
] |
1166136df1823892fd8fd8bd80d8331a235a5094 | 4,256 | hpp | C++ | Engine/Color/RGB.hpp | seb776/Tricible | fb1b7c7e027231c158a1945d3568777c4092ca6d | [
"Apache-2.0"
] | 2 | 2017-09-08T04:52:01.000Z | 2018-10-13T14:30:52.000Z | Engine/Color/RGB.hpp | seb776/Tricible | fb1b7c7e027231c158a1945d3568777c4092ca6d | [
"Apache-2.0"
] | 2 | 2018-10-24T12:48:00.000Z | 2018-11-02T16:15:21.000Z | Engine/Color/RGB.hpp | seb776/Tricible | fb1b7c7e027231c158a1945d3568777c4092ca6d | [
"Apache-2.0"
] | 1 | 2018-03-17T23:45:21.000Z | 2018-03-17T23:45:21.000Z | #pragma once
// Standard library header
#include <stdint.h>
#include "../Tools/Tools.hpp"
namespace Tricible
{
namespace Color
{
class RGB
{
private:
// TODO public + no getter ? or inline ?
uint8_t _red; // Value of the red channel.
uint8_t _green; // Value of the green channel.
uint8_t _blue; // Value of the blue channel.
public:
// ----------------------------------------------------------------
// Section : Constructor + Destructor
// ----------------------------------------------------------------
// TODO : rvalue ?
// Default constructor
RGB() : _red(0U), _green(0U), _blue(0U)
{
// nothing
}
// Copy constructor taking a const ref
RGB(const RGB & obj)
: _red(obj._red), _green(obj._green), _blue(obj._blue)
{
// nothing
}
// Constructor with parameters.
// @param r Value of the red channel.
// @param g Value of the green channel.
// @param b Value of the blue channel.
RGB(uint8_t r, uint8_t g, uint8_t b)
: _red(r), _green(g), _blue(b)
{
// nothing
}
// Assignment operator
RGB & operator=(const RGB & obj)
{
if (this != &obj)
{
_red = obj._red;
_green = obj._green;
_blue = obj._blue;
}
return (*this);
}
// Creates a modifiable clone. Making deep copies of this object's values.
void Clone(RGB * colorOut)
{
*colorOut = *this;
}
void Clear()
{
_red = 0;
_green = 0;
_blue = 0;
}
// Destructor [almost always virtual]
virtual ~RGB()
{
// nothing
}
// ----------------------------------------------------------------
// Section : Getter + Setter
// ----------------------------------------------------------------
// get red
const uint8_t Red() const
{
return (_red);
}
// set red
void Red(const uint8_t red)
{
_red = red;
}
// get green
const uint8_t Green() const
{
return (_green);
}
// set green
void Green(const uint8_t green)
{
_green = green;
}
// get blue
const uint8_t Blue() const
{
return (_blue);
}
// set blue
void Blue(const uint8_t blue)
{
_blue = blue;
}
// ----------------------------------------------------------------
// Section : Comparison operators
// ----------------------------------------------------------------
bool operator == (const RGB & rightValue) const
{
return (_red == rightValue._red && _green == rightValue._green && _blue && rightValue._blue);
}
bool operator != (const RGB & rightValue) const
{
return !(*this == rightValue);
}
RGB operator*(float rightValue) const
{
RGB copy = *this;
copy._red = (uint32_t)(Clamp((float)copy._red * rightValue, 0.0f, 255.0f));
copy._green = (uint32_t)(Clamp((float)copy._green * rightValue, 0.0f, 255.0f));
copy._blue = (uint32_t)(Clamp((float)copy._blue * rightValue, 0.0f, 255.0f));
return copy;
}
const RGB& operator+=(const RGB& rightValue)
{
this->_red = Clamp((uint32_t)this->_red + (uint32_t)rightValue._red, 0U, 255U);
this->_green = Clamp((uint32_t)this->_green + (uint32_t)rightValue._green, 0U, 255U);
this->_blue = Clamp((uint32_t)this->_blue + (uint32_t)rightValue._blue, 0U, 255U);
return *this;
}
RGB operator+(const RGB& rightValue)
{
Color::RGB col;
col._red = Clamp((uint32_t)this->_red + (uint32_t)rightValue._red, 0U, 255U);
col._green = Clamp((uint32_t)this->_green + (uint32_t)rightValue._green, 0U, 255U);
col._blue = Clamp((uint32_t)this->_blue + (uint32_t)rightValue._blue, 0U, 255U);
return col;
}
// TODO Rename to ToUint32_t
uint32_t ToInt()
{
//return (_red << 24) + (_green << 16) + (_blue << 8) + 0xFF;
return 0xFF000000 + _red + (_green << 8) + (_blue << 16);
}
};
class HDRARGB
{
public:
float A;
float R;
float G;
float B;
HDRARGB() :
HDRARGB(1.0f,0.0f,0.0f, 0.0f)
{}
HDRARGB(float a, float r, float g, float b) :
A(a),
R(r),
G(g),
B(b)
{}
operator RGB() const {
return RGB(static_cast<int8_t>(R * 255.f), static_cast<int8_t>(G * 255.f), static_cast<int8_t>(B * 255.f));
}
};
}
}
// END
| 21.386935 | 111 | 0.526316 | [
"object"
] |
11677944d1ff10df1899d7cefe5f572844f5a63a | 8,056 | cpp | C++ | ROS/trimble/src/SX10_driver.cpp | nicholasAWwright/UWB-Thesis-MSME-UIUC | eac8c77e29d6d054125b71b0038912f630b6ec48 | [
"MIT"
] | 1 | 2021-07-26T09:33:26.000Z | 2021-07-26T09:33:26.000Z | ROS/trimble/src/SX10_driver.cpp | nicholasAWwright/UWB-Thesis-MSME-UIUC | eac8c77e29d6d054125b71b0038912f630b6ec48 | [
"MIT"
] | null | null | null | ROS/trimble/src/SX10_driver.cpp | nicholasAWwright/UWB-Thesis-MSME-UIUC | eac8c77e29d6d054125b71b0038912f630b6ec48 | [
"MIT"
] | 1 | 2022-01-03T19:32:52.000Z | 2022-01-03T19:32:52.000Z | #include "ros/ros.h"
#include "ros/package.h"
#include "std_msgs/Header.h"
#include "geometry_msgs/PoseStamped.h"
#include "geometry_msgs/PointStamped.h"
#include "serial/serial.h"
#define SPEED 115200 //serial baud rate
#define TOF_REPORT_LEN (65) // \r and \n add 2 to length of visible 63
#define TOF_REPORT_ARGS (12)
std::string port, tag_id, frame_id; //ROS params
ros::Publisher trimbleData_pub; //cartesian data
ros::Publisher trimbleDataRaw_pub; //raw spherical data
void pub_poseStamped(const float x, const float y, const float z, const ros::Time timeStamp0)
{
geometry_msgs::PoseStamped pose_msg;
pose_msg.header.seq = 0;
pose_msg.header.stamp = timeStamp0;
pose_msg.header.frame_id = frame_id;
pose_msg.pose.position.x = x;
pose_msg.pose.position.y = y;
pose_msg.pose.position.z = z;
// https://quaternions.online/ <-- quaternion calculator
pose_msg.pose.orientation.x = 0.0; // this quaternion points along positive x-axis
pose_msg.pose.orientation.y = 0.0;
pose_msg.pose.orientation.z = 0.0;
pose_msg.pose.orientation.w = 1.0;
// pose_msg.pose.covariance = {10, 0, 0, 0, 0, 0,
// 0, 10, 0, 0, 0, 0,
// 0, 0, 1e6, 0, 0, 0,
// 0, 0, 0, 1e6, 0, 0,
// 0, 0, 0, 0, 1e6, 0,
// 0, 0, 0, 0, 0, 1e6};
trimbleData_pub.publish(pose_msg);
}
void pub_pointStamped(const float x, const float y, const float z, const ros::Time timeStamp0)
{
geometry_msgs::PointStamped point_msg;
point_msg.header.seq = 0;
point_msg.header.stamp = timeStamp0;
point_msg.header.frame_id = frame_id;
point_msg.point.x = x;
point_msg.point.y = y;
point_msg.point.z = z;
//// https://quaternions.online/ <-- quaternion calculator
// pose_msg.pose.orientation.x = 0.0; // this quaternion points along positive x-axis
// pose_msg.pose.orientation.y = 0.0;
// pose_msg.pose.orientation.z = 0.0;
// pose_msg.pose.orientation.w = 1.0;
// pose_msg.pose.covariance = {10, 0, 0, 0, 0, 0,
// 0, 10, 0, 0, 0, 0,
// 0, 0, 1e6, 0, 0, 0,
// 0, 0, 0, 1e6, 0, 0,
// 0, 0, 0, 0, 1e6, 0,
// 0, 0, 0, 0, 0, 1e6};
trimbleDataRaw_pub.publish(point_msg);
}
int main(int argc, char *argv[])
{
ros::init(argc, argv, "trimble");
ros::NodeHandle nh("~");
nh.param<std::string>("device_port", port, "/dev/ttyUSB0");
nh.param<std::string>("frame_id", frame_id, "trimble");
trimbleData_pub = nh.advertise<geometry_msgs::PoseStamped>("data", 1);
trimbleDataRaw_pub = nh.advertise<geometry_msgs::PointStamped>("dataRaw", 1);
serial::Serial trimbleSerial(port, SPEED, serial::Timeout::simpleTimeout(100));
ROS_INFO("serial opened");
int bytes_avail = 0;
float tol = 0.001; //tolerance from zero [m]
float maxSpeed = 10; //maximum speed for vehicle [m/s]
float x_old = 0.0;
float y_old = 0.0;
float z_old = 0.0;
float dist_old = 0.0;
ros::Time time_old = ros::Time::now();
double timeStep = 0.0;
float speed = 0.0;
ros::Rate loop_rate(10000);
while(ros::ok())
{
//* *************** *
//* Get Serial Data *
//* *************** *
bytes_avail = trimbleSerial.available();
if(bytes_avail > 0)
{
ros::Time timeStamp0 = ros::Time::now(); //stamp the serial message as soon as it arrives, before parsing
std::vector<std::string> report_cpp = trimbleSerial.readlines(); //read entire serial buffer until timeout
int lines = report_cpp.size();
// ROS_INFO("serial lines = %d",lines);
float HVr[3]; //total station coordinates (horizontal angle, vertical angle, slope distance)
//* ***************** *
//* Parse Serial Data *
//* ***************** *
for (int i = 0; i < lines; i++)
{
int line1_size = report_cpp[1].length();
int line2_size = report_cpp[2].length();
int line3_size = report_cpp[3].length();
char report_c1[line1_size]; //c string
char report_c2[line2_size]; //c string
char report_c3[line3_size]; //c string
// std::cout << report_cpp[i] << std::endl; //print serial output
switch(i)
{
case 0: //"0/n/n"
break;
case 1: //horz angle
strcpy(report_c1,report_cpp[i].c_str()); //change c++ string to c string
sscanf(report_c1,"7=%f/n", &HVr[0]);
break;
case 2: //vert angle
strcpy(report_c2,report_cpp[i].c_str()); //change c++ string to c string
sscanf(report_c2,"8=%f/n", &HVr[1]);
break;
case 3: //slope dist
strcpy(report_c3,report_cpp[i].c_str()); //change c++ string to c string
sscanf(report_c3,"9=%f/n", &HVr[2]);
break;
case 4: //">/n"
// ROS_INFO("horz=%f | vert=%f | dist=%f",HVr[0],HVr[1],HVr[2]); //spherical data
break;
}
}
//* ********************** *
//* Spherical -> Cartesian *
//* ********************** *
if (HVr[2] < tol) {HVr[2] = dist_old;} //use previous total station laser measurement if current is zero
//MATLAB standard spherical variables in standard units
float r = HVr[2]; // [m]
float azimuth = (-HVr[0])*M_PI/180.0; // [rad] (axis flipped)
float elevation = (-HVr[1] + 90)*M_PI/180.0; // [rad] (axis flipped and straight up was zero)
//spherical to cartesian transformation (https://www.mathworks.com/help/matlab/ref/sph2cart.html)
float x = r * cos(elevation) * cos(azimuth);
float y = r * cos(elevation) * sin(azimuth);
float z = r * sin(elevation);
// ROS_INFO("x=%f | y=%f | z=%f",x,y,z); //cartesian data
//* ******* *
//* Publish *
//* ******* *
// //Check how long it took to go from new serial data through calculations
// ros::Time timeStamp1 = ros::Time::now(); //stamp the message after calcs
// ros::Duration serial2pub_dur = timeStamp1 - timeStamp0; //delay from data to publish
// float serial2pub_sec = serial2pub_dur.toSec();
// ROS_INFO("Time from serial data to publish: %fs", serial2pub_sec);
pub_pointStamped(HVr[0], HVr[1], HVr[2], timeStamp0); //publish raw data always
timeStep = (timeStamp0 - time_old).toSec();
speed = sqrt(pow((x - x_old),2) + pow((y - y_old),2) + pow((z - z_old),2) )/timeStep;
// ROS_INFO("speed = %.2f",speed);
if( (abs(x) < tol) && (abs(y) < tol) && (abs(z) < tol) ) //Don't publish zeros
{
ROS_INFO("zeros");
}
else if (speed > maxSpeed) //don't publish sensor jumps
{
ROS_INFO("jump");
}
else
{
pub_poseStamped(x,y,z,timeStamp0);
x_old = x; y_old = y; z_old = z; //store data for comparison next message
time_old = timeStamp0;
dist_old = HVr[2]; //store slope distance in case it doesn't measure correctly next iteration
}
}
else
{
ros::spinOnce();
loop_rate.sleep();
}
}
trimbleSerial.close();
std::cout << "Closed serial port" << std::endl;
return 0;
}
| 38.361905 | 118 | 0.516509 | [
"vector"
] |
116e8683af4eca3444b6d7eb81ed7e46d22cc628 | 2,582 | cpp | C++ | Tek2/PSU/Zappy/client/src/Vision.cpp | PhilippeDeSousa/EpitechBundle | 5981d424c7dd25a5fbae79172e6a14db27ba985d | [
"MIT"
] | 1 | 2019-03-14T19:05:58.000Z | 2019-03-14T19:05:58.000Z | Tek2/PSU/Zappy/client/src/Vision.cpp | PhilippeDeSousa/EpitechBundle | 5981d424c7dd25a5fbae79172e6a14db27ba985d | [
"MIT"
] | null | null | null | Tek2/PSU/Zappy/client/src/Vision.cpp | PhilippeDeSousa/EpitechBundle | 5981d424c7dd25a5fbae79172e6a14db27ba985d | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2018
** Project description
** File description:
** Description here
*/
#include "Vision.hpp"
zappy::Vision::Vision()
: _cells(1)
{
}
zappy::Vision::Vision(std::string str)
: _cells(1)
{
std::string delimiter = ",";
std::string strCell;
std::vector<Inventory> list;
size_t last = 0;
size_t next = 0;
int i = 0;
while ((next = str.find(delimiter, last)) != std::string::npos) {
strCell = std::string(str.substr(last, next - last));
if (i < _cells)
list.push_back(splitPerCell(strCell));
else {
_vision.push_back(list);
list = std::vector<Inventory>();
i = 0;
list.push_back(splitPerCell(strCell));
_cells += 2;
}
last = next + 1;
i += 1;
}
strCell = std::string(str.substr(last));
list.push_back(splitPerCell(strCell));
_vision.push_back(list);
}
bool zappy::Vision::empty()
{
if (_vision.empty())
return (true);
else
return (false);
}
zappy::Inventory zappy::Vision::updateInv(Inventory tile, std::string match)
{
if (match == "player")
tile.setPlayers();
else if (match == "food")
tile.setFood();
else
tile.setStones(match);
return (tile);
}
zappy::Inventory zappy::Vision::findMatches(Inventory tile, std::string str,
std::string strRegex)
{
std::regex reg(strRegex);
std::sregex_iterator it(str.begin(), str.end(), reg);
std::sregex_iterator end;
while(it != end) {
for (std::size_t i = 0; i < it->size(); ++i) {
tile = updateInv(tile, (*it)[i]);
}
it++;
}
return (tile);
}
zappy::Inventory zappy::Vision::splitPerCell(std::string str)
{
zappy::Inventory tile;
tile = findMatches(tile, str, "food");
tile = findMatches(tile, str, "player");
tile = findMatches(tile, str, "linemate");
tile = findMatches(tile, str, "deraumere");
tile = findMatches(tile, str, "sibur");
tile = findMatches(tile, str, "mendiane");
tile = findMatches(tile, str, "phiras");
tile = findMatches(tile, str, "thystame");
return (tile);
}
int zappy::Vision::lookForFood()
{
return (0);
}
std::size_t zappy::Vision::howManyTiles(std::string str)
{
std::size_t n = std::count(str.begin(), str.end(), ',') + 1;
return (n);
}
std::vector<std::vector<zappy::Inventory>> zappy::Vision::getVision()
{
return (this->_vision);
}
zappy::Inventory zappy::Vision::getHere()
{
if (_vision.empty())
std::cout << "empty vector !" << std::endl;
return (_vision[0][0]);
}
zappy::Inventory zappy::Vision::getLeft()
{
return (_vision[1][0]);
}
zappy::Inventory zappy::Vision::getFront()
{
return (_vision[1][1]);
}
zappy::Inventory zappy::Vision::getRight()
{
return (_vision[1][2]);
}
| 19.560606 | 76 | 0.646398 | [
"vector"
] |
1174d001253876b57ee21475a237c1352f2c783f | 4,801 | cxx | C++ | larcv/core/DataFormat/Voxel3D.cxx | kvtsang/larcv2 | b2804b3390ea4d9f8bdf2c3ab5c82216fa532adf | [
"MIT"
] | 14 | 2017-10-19T15:08:29.000Z | 2021-03-31T21:21:07.000Z | larcv/core/DataFormat/Voxel3D.cxx | kvtsang/larcv2 | b2804b3390ea4d9f8bdf2c3ab5c82216fa532adf | [
"MIT"
] | 32 | 2017-10-25T22:54:06.000Z | 2019-10-01T13:57:15.000Z | larcv/core/DataFormat/Voxel3D.cxx | kvtsang/larcv2 | b2804b3390ea4d9f8bdf2c3ab5c82216fa532adf | [
"MIT"
] | 16 | 2017-12-07T12:04:40.000Z | 2021-11-15T00:53:31.000Z | #ifndef __LARCV_VOXEL3D_CXX__
#define __LARCV_VOXEL3D_CXX__
#include "Voxel3D.h"
#include <iostream>
#include <algorithm>
namespace larcv {
SparseTensor3D::SparseTensor3D(VoxelSet&& vs, Voxel3DMeta meta)
: VoxelSet(std::move(vs))
{ this->meta(meta); }
void SparseTensor3D::meta(const larcv::Voxel3DMeta& meta)
{
for (auto const& vox : this->as_vector()) {
if (vox.id() < meta.size()) continue;
std::cerr << "VoxelSet contains ID " << vox.id()
<< " which cannot exists in Voxel3DMeta with size " << meta.size()
<< std::endl;
throw std::exception();
}
_meta = meta;
}
void SparseTensor3D::emplace(const double x, const double y, const double z,
const float val, const bool add)
{
auto id = _meta.id(x, y, z);
if (id != kINVALID_VOXELID) VoxelSet::emplace(id, val, add);
}
const Voxel& SparseTensor3D::close(VoxelID_t id, double distance) const
{
const std::vector<larcv::Voxel>& voxel_v = this->as_vector();
if(voxel_v.empty())
return kINVALID_VOXEL;
const Point3D pt = _meta.position(id);
int threshold = (int) std::ceil(distance);
VoxelID_t max = _meta.id(std::min(pt.x + threshold, _meta.max_x()), std::min(pt.y + threshold, _meta.max_y()), std::min(pt.z + threshold, _meta.max_z()));
VoxelID_t min = _meta.id(std::max(pt.x - threshold, _meta.min_x()), std::max(pt.y - threshold, _meta.min_y()), std::max(pt.z - threshold, _meta.min_z()));
Voxel vox_max(max,0.);
Voxel vox_min(min,0.);
auto iter_max = std::lower_bound(voxel_v.begin(), voxel_v.end(), vox_max);
auto iter_min = std::lower_bound(voxel_v.begin(), voxel_v.end(), vox_min);
double min_distance = distance;
VoxelID_t final_vox = kINVALID_VOXELID;
//std::cout << kINVALID_VOXEL << std::endl;
for (auto& i = iter_min; i != iter_max; ++i) {
const Point3D current_point = _meta.position((*i).id());
double d = pt.distance(current_point);
if (d < min_distance) {
min_distance = d;
final_vox = (*i).id();
}
}
return this->find(final_vox);
}
bool SparseTensor3D::within(VoxelID_t id, double distance) const {
const std::vector<larcv::Voxel>& voxel_v = this->as_vector();
if(voxel_v.empty())
return false;
const Point3D pt = _meta.position(id);
int threshold = (int) std::ceil(distance);
VoxelID_t max = _meta.id(std::min(pt.x + threshold, _meta.max_x()), std::min(pt.y + threshold, _meta.max_y()), std::min(pt.z + threshold, _meta.max_z()));
VoxelID_t min = _meta.id(std::max(pt.x - threshold, _meta.min_x()), std::max(pt.y - threshold, _meta.min_y()), std::max(pt.z - threshold, _meta.min_z()));
Voxel vox_max(max,0.);
Voxel vox_min(min,0.);
auto iter_max = std::lower_bound(voxel_v.begin(), voxel_v.end(), vox_max);
auto iter_min = std::lower_bound(voxel_v.begin(), voxel_v.end(), vox_min);
for (auto& i = iter_min; i != iter_max; ++i) {
const Point3D current_point = _meta.position((*i).id());
double d = pt.distance(current_point);
if (d < distance) {
return true;
}
}
return false;
}
Point3D SparseTensor3D::pca() const {
size_t npts = this->size();
//float coords[npts][3];
double ** coords = (double**) malloc(npts * sizeof(double*));
for (size_t i = 0; i < npts; ++i) {
coords[i] = (double*) malloc(3 * sizeof(double));
Voxel v = this->as_vector()[i];
Point3D p = this->meta().position(v.id());
coords[i][0] = p.x;
coords[i][1] = p.y;
coords[i][2] = p.z;
}
double output[3];
compute_pca(coords, npts, output);
// coords: free me please!
for (size_t i = 0; i < npts; ++i) free(coords[i]);
free(coords);
return Point3D(output[0], output[1], output[2]);
}
PCA_3D SparseTensor3D::fit_pca(bool store_spread, bool use_true_coord)
{
PCA_3D::Points_t points(this->size());
// fill (x,y,z) from voxel id or xyz
for (size_t i = 0; i < points.size; ++i) {
Voxel v = this->as_vector()[i];
if (use_true_coord) {
Point3D p = this->meta().position(v.id());
points.xyz[i][0] = p.x;
points.xyz[i][1] = p.y;
points.xyz[i][2] = p.z;
}
else {
size_t ix, iy, iz;
this->meta().id_to_xyz_index(v.id(), ix, iy, iz);
points.xyz[i][0] = ix;
points.xyz[i][1] = iy;
points.xyz[i][2] = iz;
}
}
return PCA_3D(points, store_spread);
}
void ClusterVoxel3D::meta(const larcv::Voxel3DMeta& meta)
{
for (auto const& vs : this->as_vector()) {
for (auto const& vox : vs.as_vector()) {
if (vox.id() < meta.size()) continue;
std::cerr << "VoxelSet contains ID " << vox.id()
<< " which cannot exists in Voxel3DMeta with size " << meta.size()
<< std::endl;
throw std::exception();
}
}
_meta = meta;
}
}
#endif
| 32.221477 | 158 | 0.614247 | [
"vector"
] |
117699a62813517b28f1ed9846c8883ebace7cd0 | 6,705 | cpp | C++ | debug/moc_mainwindow.cpp | henrytsui000/HESPICE | 05d5285b1dbf85efab658f37287204f57f6b4824 | [
"MIT"
] | 3 | 2022-01-09T10:29:33.000Z | 2022-03-24T15:35:08.000Z | debug/moc_mainwindow.cpp | henrytsui000/HESPICE | 05d5285b1dbf85efab658f37287204f57f6b4824 | [
"MIT"
] | null | null | null | debug/moc_mainwindow.cpp | henrytsui000/HESPICE | 05d5285b1dbf85efab658f37287204f57f6b4824 | [
"MIT"
] | null | null | null | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 68 (Qt 6.1.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../Test/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 68
#error "This file was generated using the moc from 6.1.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
const uint offsetsAndSize[30];
char stringdata0[315];
};
#define QT_MOC_LITERAL(ofs, len) \
uint(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs), len
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 10), // "MainWindow"
QT_MOC_LITERAL(11, 20), // "on_actionR_triggered"
QT_MOC_LITERAL(32, 0), // ""
QT_MOC_LITERAL(33, 20), // "on_actionL_triggered"
QT_MOC_LITERAL(54, 20), // "on_actionC_triggered"
QT_MOC_LITERAL(75, 20), // "on_actionV_triggered"
QT_MOC_LITERAL(96, 20), // "on_actionI_triggered"
QT_MOC_LITERAL(117, 22), // "on_actionGND_triggered"
QT_MOC_LITERAL(140, 22), // "on_actionCUT_triggered"
QT_MOC_LITERAL(163, 23), // "on_actionMOVE_triggered"
QT_MOC_LITERAL(187, 23), // "on_actionWIRE_triggered"
QT_MOC_LITERAL(211, 24), // "on_actionBUILD_triggered"
QT_MOC_LITERAL(236, 23), // "on_actionWAVE_triggered"
QT_MOC_LITERAL(260, 26), // "on_actionZOOM_IN_triggered"
QT_MOC_LITERAL(287, 27) // "on_actionZOOM_OUT_triggered"
},
"MainWindow\0on_actionR_triggered\0\0"
"on_actionL_triggered\0on_actionC_triggered\0"
"on_actionV_triggered\0on_actionI_triggered\0"
"on_actionGND_triggered\0on_actionCUT_triggered\0"
"on_actionMOVE_triggered\0on_actionWIRE_triggered\0"
"on_actionBUILD_triggered\0"
"on_actionWAVE_triggered\0"
"on_actionZOOM_IN_triggered\0"
"on_actionZOOM_OUT_triggered"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
9, // revision
0, // classname
0, 0, // classinfo
13, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags, initial metatype offsets
1, 0, 92, 2, 0x08, 0 /* Private */,
3, 0, 93, 2, 0x08, 1 /* Private */,
4, 0, 94, 2, 0x08, 2 /* Private */,
5, 0, 95, 2, 0x08, 3 /* Private */,
6, 0, 96, 2, 0x08, 4 /* Private */,
7, 0, 97, 2, 0x08, 5 /* Private */,
8, 0, 98, 2, 0x08, 6 /* Private */,
9, 0, 99, 2, 0x08, 7 /* Private */,
10, 0, 100, 2, 0x08, 8 /* Private */,
11, 0, 101, 2, 0x08, 9 /* Private */,
12, 0, 102, 2, 0x08, 10 /* Private */,
13, 0, 103, 2, 0x08, 11 /* Private */,
14, 0, 104, 2, 0x08, 12 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<MainWindow *>(_o);
(void)_t;
switch (_id) {
case 0: _t->on_actionR_triggered(); break;
case 1: _t->on_actionL_triggered(); break;
case 2: _t->on_actionC_triggered(); break;
case 3: _t->on_actionV_triggered(); break;
case 4: _t->on_actionI_triggered(); break;
case 5: _t->on_actionGND_triggered(); break;
case 6: _t->on_actionCUT_triggered(); break;
case 7: _t->on_actionMOVE_triggered(); break;
case 8: _t->on_actionWIRE_triggered(); break;
case 9: _t->on_actionBUILD_triggered(); break;
case 10: _t->on_actionWAVE_triggered(); break;
case 11: _t->on_actionZOOM_IN_triggered(); break;
case 12: _t->on_actionZOOM_OUT_triggered(); break;
default: ;
}
}
(void)_a;
}
const QMetaObject MainWindow::staticMetaObject = { {
QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(),
qt_meta_stringdata_MainWindow.offsetsAndSize,
qt_meta_data_MainWindow,
qt_static_metacall,
nullptr,
qt_incomplete_metaTypeArray<qt_meta_stringdata_MainWindow_t
, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>, QtPrivate::TypeAndForceComplete<void, std::false_type>
>,
nullptr
} };
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 13)
qt_static_metacall(this, _c, _id, _a);
_id -= 13;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 13)
*reinterpret_cast<QMetaType *>(_a[0]) = QMetaType();
_id -= 13;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 37.458101 | 728 | 0.646682 | [
"object"
] |
117cb52cf249e6eec6b5082a1e47c8ccd7bec76f | 1,455 | cpp | C++ | src/mmlib/library/libpath.cpp | JonnyWideFoot/pd.arcus | a6197a5a2a18c0e3f752e15aa982d1e44d052730 | [
"BSD-4-Clause-UC"
] | null | null | null | src/mmlib/library/libpath.cpp | JonnyWideFoot/pd.arcus | a6197a5a2a18c0e3f752e15aa982d1e44d052730 | [
"BSD-4-Clause-UC"
] | null | null | null | src/mmlib/library/libpath.cpp | JonnyWideFoot/pd.arcus | a6197a5a2a18c0e3f752e15aa982d1e44d052730 | [
"BSD-4-Clause-UC"
] | null | null | null | #include "global.h"
#include "tools/io.h"
#include "library/libpath.h"
LibraryPathStore* LibraryPathStore::getSingleton()
{
static LibraryPathStore inst;
return &inst;
}
LibraryPathStore::LibraryPathStore()
{
parseEnvironmentVariable();
}
// Parses the environment variable PD_PARAM_PATH into search paths to look for
// library files. The order of searching is: local directory, lib path,
void LibraryPathStore::parseEnvironmentVariable()
{
m_LibraryPath.clear();
m_LibraryPath.push_back(".");
char *c_env = getenv("PD_PARAM_PATH");
// if the return value of getenv is NULL the variable is undefined.
if(c_env == NULL)
{
printf("Library Paths: PD_PARAM_PATH undefined\n");
return;
}
std::string env_PD_PARAM_PATH = "";
env_PD_PARAM_PATH = c_env;
std::vector <std::string> temp_m_LibraryPath = chopstr(env_PD_PARAM_PATH, ";:, \t\12\15" );
for(size_t i=0;i<temp_m_LibraryPath.size();i++)
{
m_LibraryPath.push_back( temp_m_LibraryPath[i] );
}
printf("Library Paths: \n");
for(size_t i=0;i<m_LibraryPath.size();i++)
{
printf(" %s/\n",m_LibraryPath[i].c_str());
}
}
std::string LibraryPathStore::findFullFilename(const std::string &filename)
{
for(int i=0;i<m_LibraryPath.size();i++)
{
std::string composite;
composite = m_LibraryPath[i] + "/" + filename;
if(IO::fileExists(composite))
{
return composite;
};
}
return filename; // return filename evwen if it fails such that error messages are fine
}
| 23.467742 | 92 | 0.714777 | [
"vector"
] |
11808130f9d610a15e3b0bff5d23a4be8aee0450 | 17,155 | cpp | C++ | src/bvals/bvals_cc.cpp | luminoctum/athena-crm | 525ad5d1c442f9f6d66f2307eed88cd6fb723810 | [
"BSD-3-Clause"
] | null | null | null | src/bvals/bvals_cc.cpp | luminoctum/athena-crm | 525ad5d1c442f9f6d66f2307eed88cd6fb723810 | [
"BSD-3-Clause"
] | null | null | null | src/bvals/bvals_cc.cpp | luminoctum/athena-crm | 525ad5d1c442f9f6d66f2307eed88cd6fb723810 | [
"BSD-3-Clause"
] | null | null | null | //========================================================================================
// Athena++ astrophysical MHD code
// Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors
// Licensed under the 3-clause BSD License, see LICENSE file for details
//========================================================================================
//! \file bvals_cc.cpp
// \brief functions that apply BCs for CELL_CENTERED variables
// C++ headers
#include <iostream> // endl
#include <iomanip>
#include <sstream> // stringstream
#include <stdexcept> // runtime_error
#include <string> // c_str()
#include <cstring> // memcpy
#include <cstdlib>
#include <cmath>
// Athena++ classes headers
#include "bvals.hpp"
#include "../athena.hpp"
#include "../globals.hpp"
#include "../athena_arrays.hpp"
#include "../mesh/mesh.hpp"
#include "../hydro/hydro.hpp"
#include "../eos/eos.hpp"
#include "../field/field.hpp"
#include "../coordinates/coordinates.hpp"
#include "../parameter_input.hpp"
#include "../utils/buffer_utils.hpp"
// MPI header
#ifdef MPI_PARALLEL
#include <mpi.h>
#endif
//----------------------------------------------------------------------------------------
//! \fn int BoundaryValues::LoadHydroBoundaryBufferSameLevel(AthenaArray<Real> &src,
// Real *buf, const NeighborBlock& nb)
// \brief Set hydro boundary buffers for sending to a block on the same level
int BoundaryValues::LoadHydroBoundaryBufferSameLevel(AthenaArray<Real> &src, Real *buf,
const NeighborBlock& nb)
{
MeshBlock *pmb=pmy_block_;
int si, sj, sk, ei, ej, ek;
si=(nb.ox1>0)?(pmb->ie-NGHOST+1):pmb->is;
ei=(nb.ox1<0)?(pmb->is+NGHOST-1):pmb->ie;
sj=(nb.ox2>0)?(pmb->je-NGHOST+1):pmb->js;
ej=(nb.ox2<0)?(pmb->js+NGHOST-1):pmb->je;
sk=(nb.ox3>0)?(pmb->ke-NGHOST+1):pmb->ks;
ek=(nb.ox3<0)?(pmb->ks+NGHOST-1):pmb->ke;
int p=0;
BufferUtility::Pack4DData(src, buf, 0, NHYDRO-1, si, ei, sj, ej, sk, ek, p);
return p;
}
//----------------------------------------------------------------------------------------
//! \fn int BoundaryValues::LoadHydroBoundaryBufferToCoarser(AthenaArray<Real> &src,
// Real *buf, const NeighborBlock& nb,
// bool conserved_values)
// \brief Set hydro boundary buffers for sending to a block on the coarser level
int BoundaryValues::LoadHydroBoundaryBufferToCoarser(AthenaArray<Real> &src, Real *buf,
const NeighborBlock& nb,
bool conserved_values)
{
MeshBlock *pmb=pmy_block_;
MeshRefinement *pmr=pmb->pmr;
int si, sj, sk, ei, ej, ek;
int cn=pmb->cnghost-1;
si=(nb.ox1>0)?(pmb->cie-cn):pmb->cis;
ei=(nb.ox1<0)?(pmb->cis+cn):pmb->cie;
sj=(nb.ox2>0)?(pmb->cje-cn):pmb->cjs;
ej=(nb.ox2<0)?(pmb->cjs+cn):pmb->cje;
sk=(nb.ox3>0)?(pmb->cke-cn):pmb->cks;
ek=(nb.ox3<0)?(pmb->cks+cn):pmb->cke;
int p=0;
if (conserved_values) { // normal case
pmr->RestrictCellCenteredValues(src, pmr->coarse_cons_, 0, NHYDRO-1,
si, ei, sj, ej, sk, ek);
BufferUtility::Pack4DData(pmr->coarse_cons_, buf, 0, NHYDRO-1,
si, ei, sj, ej, sk, ek, p);
}
else { // must be initialization of boundary primitives
pmr->RestrictCellCenteredValues(src, pmr->coarse_prim_, 0, NHYDRO-1,
si, ei, sj, ej, sk, ek);
BufferUtility::Pack4DData(pmr->coarse_prim_, buf, 0, NHYDRO-1,
si, ei, sj, ej, sk, ek, p);
}
return p;
}
//----------------------------------------------------------------------------------------
//! \fn int BoundaryValues::LoadHydroBoundaryBufferToFiner(AthenaArray<Real> &src,
// Real *buf, const NeighborBlock& nb)
// \brief Set hydro boundary buffers for sending to a block on the finer level
int BoundaryValues::LoadHydroBoundaryBufferToFiner(AthenaArray<Real> &src, Real *buf,
const NeighborBlock& nb)
{
MeshBlock *pmb=pmy_block_;
int si, sj, sk, ei, ej, ek;
int cn=pmb->cnghost-1;
si=(nb.ox1>0)?(pmb->ie-cn):pmb->is;
ei=(nb.ox1<0)?(pmb->is+cn):pmb->ie;
sj=(nb.ox2>0)?(pmb->je-cn):pmb->js;
ej=(nb.ox2<0)?(pmb->js+cn):pmb->je;
sk=(nb.ox3>0)?(pmb->ke-cn):pmb->ks;
ek=(nb.ox3<0)?(pmb->ks+cn):pmb->ke;
// send the data first and later prolongate on the target block
// need to add edges for faces, add corners for edges
if(nb.ox1==0) {
if(nb.fi1==1) si+=pmb->block_size.nx1/2-pmb->cnghost;
else ei-=pmb->block_size.nx1/2-pmb->cnghost;
}
if(nb.ox2==0 && pmb->block_size.nx2 > 1) {
if(nb.ox1!=0) {
if(nb.fi1==1) sj+=pmb->block_size.nx2/2-pmb->cnghost;
else ej-=pmb->block_size.nx2/2-pmb->cnghost;
}
else {
if(nb.fi2==1) sj+=pmb->block_size.nx2/2-pmb->cnghost;
else ej-=pmb->block_size.nx2/2-pmb->cnghost;
}
}
if(nb.ox3==0 && pmb->block_size.nx3 > 1) {
if(nb.ox1!=0 && nb.ox2!=0) {
if(nb.fi1==1) sk+=pmb->block_size.nx3/2-pmb->cnghost;
else ek-=pmb->block_size.nx3/2-pmb->cnghost;
}
else {
if(nb.fi2==1) sk+=pmb->block_size.nx3/2-pmb->cnghost;
else ek-=pmb->block_size.nx3/2-pmb->cnghost;
}
}
int p=0;
BufferUtility::Pack4DData(src, buf, 0, NHYDRO-1, si, ei, sj, ej, sk, ek, p);
return p;
}
//----------------------------------------------------------------------------------------
//! \fn void BoundaryValues::SendHydroBoundaryBuffers(AthenaArray<Real> &src,
// bool conserved_values)
// \brief Send boundary buffers
void BoundaryValues::SendHydroBoundaryBuffers(AthenaArray<Real> &src,
bool conserved_values)
{
MeshBlock *pmb=pmy_block_;
int mylevel=pmb->loc.level;
for(int n=0; n<pmb->nneighbor; n++) {
NeighborBlock& nb = pmb->neighbor[n];
int ssize;
if(nb.level==mylevel)
ssize=LoadHydroBoundaryBufferSameLevel(src, hydro_send_[nb.bufid],nb);
else if(nb.level<mylevel)
ssize=LoadHydroBoundaryBufferToCoarser(src, hydro_send_[nb.bufid], nb,
conserved_values);
else
ssize=LoadHydroBoundaryBufferToFiner(src, hydro_send_[nb.bufid], nb);
if(nb.rank == Globals::my_rank) { // on the same process
MeshBlock *pbl=pmb->pmy_mesh->FindMeshBlock(nb.gid);
std::memcpy(pbl->pbval->hydro_recv_[nb.targetid],
hydro_send_[nb.bufid], ssize*sizeof(Real));
pbl->pbval->hydro_flag_[nb.targetid]=BNDRY_ARRIVED;
}
#ifdef MPI_PARALLEL
else // MPI
MPI_Start(&req_hydro_send_[nb.bufid]);
#endif
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn void BoundaryValues::SetHydroBoundarySameLevel(AthenaArray<Real> &dst,
// Real *buf, const NeighborBlock& nb)
// \brief Set hydro boundary received from a block on the same level
void BoundaryValues::SetHydroBoundarySameLevel(AthenaArray<Real> &dst, Real *buf,
const NeighborBlock& nb)
{
MeshBlock *pmb=pmy_block_;
int si, sj, sk, ei, ej, ek;
if(nb.ox1==0) si=pmb->is, ei=pmb->ie;
else if(nb.ox1>0) si=pmb->ie+1, ei=pmb->ie+NGHOST;
else si=pmb->is-NGHOST, ei=pmb->is-1;
if(nb.ox2==0) sj=pmb->js, ej=pmb->je;
else if(nb.ox2>0) sj=pmb->je+1, ej=pmb->je+NGHOST;
else sj=pmb->js-NGHOST, ej=pmb->js-1;
if(nb.ox3==0) sk=pmb->ks, ek=pmb->ke;
else if(nb.ox3>0) sk=pmb->ke+1, ek=pmb->ke+NGHOST;
else sk=pmb->ks-NGHOST, ek=pmb->ks-1;
int p=0;
if (nb.polar) {
for (int n=0; n<(NHYDRO); ++n) {
Real sign = flip_across_pole_hydro[n] ? -1.0 : 1.0;
for (int k=sk; k<=ek; ++k) {
for (int j=ej; j>=sj; --j) {
#pragma simd
for (int i=si; i<=ei; ++i)
dst(n,k,j,i) = sign * buf[p++];
}
}
}
}
else
BufferUtility::Unpack4DData(buf, dst, 0, NHYDRO-1, si, ei, sj, ej, sk, ek, p);
return;
}
//----------------------------------------------------------------------------------------
//! \fn void BoundaryValues::SetHydroBoundaryFromCoarser(Real *buf,
// const NeighborBlock& nb,
// bool conserved_values)
// \brief Set hydro prolongation buffer received from a block on a coarser level
void BoundaryValues::SetHydroBoundaryFromCoarser(Real *buf, const NeighborBlock& nb,
bool conserved_values)
{
MeshBlock *pmb=pmy_block_;
MeshRefinement *pmr=pmb->pmr;
int si, sj, sk, ei, ej, ek;
int cng=pmb->cnghost;
if(nb.ox1==0) {
si=pmb->cis, ei=pmb->cie;
if((pmb->loc.lx1&1L)==0L) ei+=cng;
else si-=cng;
}
else if(nb.ox1>0) si=pmb->cie+1, ei=pmb->cie+cng;
else si=pmb->cis-cng, ei=pmb->cis-1;
if(nb.ox2==0) {
sj=pmb->cjs, ej=pmb->cje;
if(pmb->block_size.nx2 > 1) {
if((pmb->loc.lx2&1L)==0L) ej+=cng;
else sj-=cng;
}
}
else if(nb.ox2>0) sj=pmb->cje+1, ej=pmb->cje+cng;
else sj=pmb->cjs-cng, ej=pmb->cjs-1;
if(nb.ox3==0) {
sk=pmb->cks, ek=pmb->cke;
if(pmb->block_size.nx3 > 1) {
if((pmb->loc.lx3&1L)==0L) ek+=cng;
else sk-=cng;
}
}
else if(nb.ox3>0) sk=pmb->cke+1, ek=pmb->cke+cng;
else sk=pmb->cks-cng, ek=pmb->cks-1;
int p=0;
if (nb.polar) {
for (int n=0; n<(NHYDRO); ++n) {
Real sign = flip_across_pole_hydro[n] ? -1.0 : 1.0;
for (int k=sk; k<=ek; ++k) {
for (int j=ej; j>=sj; --j) {
#pragma simd
for (int i=si; i<=ei; ++i) {
if (conserved_values)
pmr->coarse_cons_(n,k,j,i) = sign * buf[p++];
else
pmr->coarse_prim_(n,k,j,i) = sign * buf[p++];
}
}
}
}
}
else {
if (conserved_values)
BufferUtility::Unpack4DData(buf, pmr->coarse_cons_, 0, NHYDRO-1,
si, ei, sj, ej, sk, ek, p);
else
BufferUtility::Unpack4DData(buf, pmr->coarse_prim_, 0, NHYDRO-1,
si, ei, sj, ej, sk, ek, p);
}
return;
}
//----------------------------------------------------------------------------------------
//! \fn void BoundaryValues::SetHydroBoundaryFromFiner(AthenaArray<Real> &dst,
// Real *buf, const NeighborBlock& nb)
// \brief Set hydro boundary received from a block on a finer level
void BoundaryValues::SetHydroBoundaryFromFiner(AthenaArray<Real> &dst, Real *buf,
const NeighborBlock& nb)
{
MeshBlock *pmb=pmy_block_;
// receive already restricted data
int si, sj, sk, ei, ej, ek;
if(nb.ox1==0) {
si=pmb->is, ei=pmb->ie;
if(nb.fi1==1) si+=pmb->block_size.nx1/2;
else ei-=pmb->block_size.nx1/2;
}
else if(nb.ox1>0) si=pmb->ie+1, ei=pmb->ie+NGHOST;
else si=pmb->is-NGHOST, ei=pmb->is-1;
if(nb.ox2==0) {
sj=pmb->js, ej=pmb->je;
if(pmb->block_size.nx2 > 1) {
if(nb.ox1!=0) {
if(nb.fi1==1) sj+=pmb->block_size.nx2/2;
else ej-=pmb->block_size.nx2/2;
}
else {
if(nb.fi2==1) sj+=pmb->block_size.nx2/2;
else ej-=pmb->block_size.nx2/2;
}
}
}
else if(nb.ox2>0) sj=pmb->je+1, ej=pmb->je+NGHOST;
else sj=pmb->js-NGHOST, ej=pmb->js-1;
if(nb.ox3==0) {
sk=pmb->ks, ek=pmb->ke;
if(pmb->block_size.nx3 > 1) {
if(nb.ox1!=0 && nb.ox2!=0) {
if(nb.fi1==1) sk+=pmb->block_size.nx3/2;
else ek-=pmb->block_size.nx3/2;
}
else {
if(nb.fi2==1) sk+=pmb->block_size.nx3/2;
else ek-=pmb->block_size.nx3/2;
}
}
}
else if(nb.ox3>0) sk=pmb->ke+1, ek=pmb->ke+NGHOST;
else sk=pmb->ks-NGHOST, ek=pmb->ks-1;
int p=0;
if (nb.polar) {
for (int n=0; n<(NHYDRO); ++n) {
Real sign = flip_across_pole_hydro[n] ? -1.0 : 1.0;
for (int k=sk; k<=ek; ++k) {
for (int j=sj; j<=ej; ++j) {
#pragma simd
for (int i=si; i<=ei; ++i)
dst(n,k,j,i) = sign * buf[p++];
}
}
}
}
else
BufferUtility::Unpack4DData(buf, dst, 0, NHYDRO-1, si, ei, sj, ej, sk, ek, p);
return;
}
//----------------------------------------------------------------------------------------
//! \fn bool BoundaryValues::ReceiveHydroBoundaryBuffers(AthenaArray<Real> &dst)
// \brief receive the boundary data
bool BoundaryValues::ReceiveHydroBoundaryBuffers(AthenaArray<Real> &dst)
{
MeshBlock *pmb=pmy_block_;
bool flag=true;
for(int n=0; n<pmb->nneighbor; n++) {
NeighborBlock& nb = pmb->neighbor[n];
if(hydro_flag_[nb.bufid]==BNDRY_COMPLETED) continue;
if(hydro_flag_[nb.bufid]==BNDRY_WAITING) {
if(nb.rank==Globals::my_rank) {// on the same process
flag=false;
continue;
}
#ifdef MPI_PARALLEL
else { // MPI boundary
int test;
MPI_Iprobe(MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&test,MPI_STATUS_IGNORE);
MPI_Test(&req_hydro_recv_[nb.bufid],&test,MPI_STATUS_IGNORE);
if(test==false) {
flag=false;
continue;
}
hydro_flag_[nb.bufid] = BNDRY_ARRIVED;
}
#endif
}
if(nb.level==pmb->loc.level)
SetHydroBoundarySameLevel(dst, hydro_recv_[nb.bufid], nb);
else if(nb.level<pmb->loc.level) // this set only the prolongation buffer
SetHydroBoundaryFromCoarser(hydro_recv_[nb.bufid], nb, true);
else
SetHydroBoundaryFromFiner(dst, hydro_recv_[nb.bufid], nb);
hydro_flag_[nb.bufid] = BNDRY_COMPLETED; // completed
}
if(flag&& (pmb->block_bcs[INNER_X2]==POLAR_BNDRY
|| pmb->block_bcs[OUTER_X2]==POLAR_BNDRY))
PolarSingleHydro(dst);
return flag;
}
//----------------------------------------------------------------------------------------
//! \fn void BoundaryValues::ReceiveHydroBoundaryBuffersWithWait(AthenaArray<Real> &dst,
// bool conserved_values)
// \brief receive the boundary data for initialization
void BoundaryValues::ReceiveHydroBoundaryBuffersWithWait(AthenaArray<Real> &dst,
bool conserved_values)
{
MeshBlock *pmb=pmy_block_;
for(int n=0; n<pmb->nneighbor; n++) {
NeighborBlock& nb = pmb->neighbor[n];
#ifdef MPI_PARALLEL
if(nb.rank!=Globals::my_rank)
MPI_Wait(&req_hydro_recv_[nb.bufid],MPI_STATUS_IGNORE);
#endif
if(nb.level==pmb->loc.level)
SetHydroBoundarySameLevel(dst, hydro_recv_[nb.bufid], nb);
else if(nb.level<pmb->loc.level)
SetHydroBoundaryFromCoarser(hydro_recv_[nb.bufid], nb, conserved_values);
else
SetHydroBoundaryFromFiner(dst, hydro_recv_[nb.bufid], nb);
hydro_flag_[nb.bufid] = BNDRY_COMPLETED; // completed
}
if (pmb->block_bcs[INNER_X2]==POLAR_BNDRY||pmb->block_bcs[OUTER_X2]==POLAR_BNDRY)
PolarSingleHydro(dst);
return;
}
//----------------------------------------------------------------------------------------
//! \fn void BoundaryValues::PolarSingleHydro(AthenaArray<Real> &dst)
//
// \brief single CPU in the azimuthal direction for the polar boundary
void BoundaryValues::PolarSingleHydro(AthenaArray<Real> &dst)
{
MeshBlock *pmb=pmy_block_;
if(pmb->loc.level == pmb->pmy_mesh->root_level && pmb->pmy_mesh->nrbx3 == 1){
if(pmb->block_bcs[INNER_X2]==POLAR_BNDRY){
int nx3_half = (pmb->ke - pmb->ks + 1) / 2;
for (int n=0; n<(NHYDRO); ++n) {
for (int j=pmb->js-NGHOST; j<=pmb->js-1; ++j) {
for (int i=pmb->is-NGHOST; i<=pmb->ie+NGHOST; ++i){
for (int k=pmb->ks-NGHOST; k<=pmb->ke+NGHOST; ++k) {
exc_(k)=dst(n,k,j,i);
}
for (int k=pmb->ks-NGHOST; k<=pmb->ke+NGHOST; ++k) {
int k_shift = k;
k_shift += (k < (nx3_half+NGHOST) ? 1 : -1) * nx3_half;
dst(n,k,j,i)=exc_(k_shift);
}
}
}
}
}
if(pmb->block_bcs[OUTER_X2]==POLAR_BNDRY){
int nx3_half = (pmb->ke - pmb->ks + 1) / 2;
for (int n=0; n<(NHYDRO); ++n) {
for (int j=pmb->je+1; j<=pmb->je+NGHOST; ++j) {
for (int i=pmb->is-NGHOST; i<=pmb->ie+NGHOST; ++i){
for (int k=pmb->ks-NGHOST; k<=pmb->ke+NGHOST; ++k) {
exc_(k)=dst(n,k,j,i);
}
for (int k=pmb->ks-NGHOST; k<=pmb->ke+NGHOST; ++k) {
int k_shift = k;
k_shift += (k < (nx3_half+NGHOST) ? 1 : -1) * nx3_half;
dst(n,k,j,i)=exc_(k_shift);
}
}
}
}
}
}
return;
}
| 35.371134 | 90 | 0.526843 | [
"mesh"
] |
1180fca6cf3bb5d61dd582265754623f2e4b7c84 | 1,038 | cc | C++ | chrome/browser/ui/gtk/instant_overlay_controller_gtk.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | chrome/browser/ui/gtk/instant_overlay_controller_gtk.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/gtk/instant_overlay_controller_gtk.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright 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 "chrome/browser/ui/gtk/instant_overlay_controller_gtk.h"
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#include "chrome/browser/ui/gtk/tab_contents_container_gtk.h"
#include "chrome/browser/ui/search/instant_overlay_model.h"
InstantOverlayControllerGtk::InstantOverlayControllerGtk(
BrowserWindowGtk* window,
TabContentsContainerGtk* contents)
: InstantOverlayController(window->browser()),
window_(window),
contents_(contents) {
}
InstantOverlayControllerGtk::~InstantOverlayControllerGtk() {
}
void InstantOverlayControllerGtk::OverlayStateChanged(
const InstantOverlayModel& model) {
if (model.mode().is_search_suggestions()) {
// TODO(jered): Support non-100% height.
contents_->SetOverlay(model.GetOverlayContents());
} else {
contents_->SetOverlay(NULL);
}
window_->MaybeShowBookmarkBar(false);
}
| 32.4375 | 73 | 0.765896 | [
"model"
] |
1187b10764e42e9a1d85817841c0f71c3b157ec1 | 30,874 | cpp | C++ | src/Render/DX12/PipelineCommonUtils.cpp | Ubpa/DustEngine | 4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0 | [
"MIT"
] | 9 | 2020-08-03T02:11:07.000Z | 2020-09-29T09:12:45.000Z | src/Render/DX12/PipelineCommonUtils.cpp | Ubpa/DustEngine | 4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0 | [
"MIT"
] | null | null | null | src/Render/DX12/PipelineCommonUtils.cpp | Ubpa/DustEngine | 4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0 | [
"MIT"
] | 1 | 2020-08-10T03:34:52.000Z | 2020-08-10T03:34:52.000Z | #include <Utopia/Render/DX12/PipelineCommonUtils.h>
#include <Utopia/Render/DX12/ShaderCBMngr.h>
#include <Utopia/Render/DX12/GPURsrcMngrDX12.h>
#include <Utopia/Render/DX12/MeshLayoutMngr.h>
#include <Utopia/Render/Material.h>
#include <Utopia/Render/Shader.h>
#include <Utopia/Render/ShaderMngr.h>
#include <Utopia/Render/Components/Camera.h>
#include <Utopia/Render/Components/MeshFilter.h>
#include <Utopia/Render/Components/MeshRenderer.h>
#include <Utopia/Render/Components/Skybox.h>
#include <Utopia/Render/Components/Light.h>
#include <Utopia/Core/Components/LocalToWorld.h>
#include <Utopia/Core/Components/Translation.h>
#include <Utopia/Core/Components/WorldToLocal.h>
#include <Utopia/Core/Components/PrevLocalToWorld.h>
#include <Utopia/Core/AssetMngr.h>
#include <Utopia/Core/GameTimer.h>
#include <UECS/UECS.hpp>
#include "../_deps/LTCTex.h"
using namespace Ubpa;
using namespace Ubpa::Utopia;
using namespace Ubpa::UECS;
MaterialCBDesc Utopia::RegisterMaterialCB(UDX12::DynamicUploadVector& buffer, const Material& material) {
const Shader& shader = *material.shader;
MaterialCBDesc rst;
rst.beginOffset = buffer.Size();
auto CalculateSize = [&](ID3D12ShaderReflection* refl) {
D3D12_SHADER_DESC shaderDesc;
ThrowIfFailed(refl->GetDesc(&shaderDesc));
for (UINT i = 0; i < shaderDesc.ConstantBuffers; i++) {
auto cb = refl->GetConstantBufferByIndex(i);
D3D12_SHADER_BUFFER_DESC cbDesc;
ThrowIfFailed(cb->GetDesc(&cbDesc));
if (PipelineCommonResourceMngr::GetInstance().IsCommonCB(cbDesc.Name))
continue;
D3D12_SHADER_INPUT_BIND_DESC rsrcDesc;
refl->GetResourceBindingDescByName(cbDesc.Name, &rsrcDesc);
auto target = rst.registerIdx2LocalOffset.find(rsrcDesc.BindPoint);
if (target != rst.registerIdx2LocalOffset.end())
continue;
rst.registerIdx2LocalOffset.emplace(std::pair{ rsrcDesc.BindPoint, rst.size });
rst.size += UDX12::Util::CalcConstantBufferByteSize(cbDesc.Size);
}
};
for (size_t i = 0; i < shader.passes.size(); i++) {
CalculateSize(GPURsrcMngrDX12::Instance().GetShaderRefl_vs(shader, i));
CalculateSize(GPURsrcMngrDX12::Instance().GetShaderRefl_ps(shader, i));
}
buffer.Resize(buffer.Size() + rst.size);
auto UpdateShaderCBsForRefl = [&](std::set<size_t>& flags, const Material& material, ID3D12ShaderReflection* refl) {
D3D12_SHADER_DESC shaderDesc;
ThrowIfFailed(refl->GetDesc(&shaderDesc));
for (UINT i = 0; i < shaderDesc.ConstantBuffers; i++) {
auto cb = refl->GetConstantBufferByIndex(i);
D3D12_SHADER_BUFFER_DESC cbDesc;
ThrowIfFailed(cb->GetDesc(&cbDesc));
D3D12_SHADER_INPUT_BIND_DESC rsrcDesc;
refl->GetResourceBindingDescByName(cbDesc.Name, &rsrcDesc);
if (rst.registerIdx2LocalOffset.find(rsrcDesc.BindPoint) == rst.registerIdx2LocalOffset.end())
continue;
if (flags.find(rsrcDesc.BindPoint) != flags.end())
continue;
flags.insert(rsrcDesc.BindPoint);
size_t offset = rst.beginOffset + rst.registerIdx2LocalOffset.at(rsrcDesc.BindPoint);
for (UINT j = 0; j < cbDesc.Variables; j++) {
auto var = cb->GetVariableByIndex(j);
D3D12_SHADER_VARIABLE_DESC varDesc;
ThrowIfFailed(var->GetDesc(&varDesc));
auto target = material.properties.find(varDesc.Name);
if (target == material.properties.end())
continue;
std::visit([&](const auto& value) {
using Value = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<Value, bool>) {
auto v = static_cast<unsigned int>(value);
assert(varDesc.Size == sizeof(unsigned int));
buffer.Set(offset + varDesc.StartOffset, &v, sizeof(unsigned int));
}
else if constexpr (std::is_same_v<Value, SharedVar<Texture2D>> || std::is_same_v<Value, SharedVar<TextureCube>>)
assert(false);
else {
assert(varDesc.Size == sizeof(Value));
buffer.Set(offset + varDesc.StartOffset, &value, varDesc.Size);
}
}, target->second.value);
}
}
};
std::set<size_t> flags;
for (size_t i = 0; i < shader.passes.size(); i++) {
UpdateShaderCBsForRefl(flags, material, GPURsrcMngrDX12::Instance().GetShaderRefl_vs(shader, i));
UpdateShaderCBsForRefl(flags, material, GPURsrcMngrDX12::Instance().GetShaderRefl_ps(shader, i));
}
return rst;
}
PipelineCommonResourceMngr::PipelineCommonResourceMngr()
: defaultSkyboxGpuHandle{ 0 }
{}
PipelineCommonResourceMngr& PipelineCommonResourceMngr::GetInstance() {
static PipelineCommonResourceMngr instance;
return instance;
}
void PipelineCommonResourceMngr::Init(ID3D12Device* device) {
errorMat = AssetMngr::Instance().LoadAsset<Material>(LR"(_internal\materials\error.mat)");
directionalShadowMat = AssetMngr::Instance().LoadAsset<Material>(LR"(_internal\materials\directionalShadow.mat)");
blackTex2D = AssetMngr::Instance().LoadAsset<Texture2D>(LR"(_internal\textures\black.png)");
whiteTex2D = AssetMngr::Instance().LoadAsset<Texture2D>(LR"(_internal\textures\white.png)");
errorTex2D = AssetMngr::Instance().LoadAsset<Texture2D>(LR"(_internal\textures\error.png)");
normalTex2D = AssetMngr::Instance().LoadAsset<Texture2D>(LR"(_internal\textures\normal.png)");
brdfLutTex2D = AssetMngr::Instance().LoadAsset<Texture2D>(LR"(_internal\textures\BRDFLUT.png)");
ltcTex2Ds[0] = std::make_shared<Texture2D>();
ltcTex2Ds[1] = std::make_shared<Texture2D>();
ltcTex2Ds[0]->image = Image(LTCTex::SIZE, LTCTex::SIZE, 4, LTCTex::data1);
ltcTex2Ds[1]->image = Image(LTCTex::SIZE, LTCTex::SIZE, 4, LTCTex::data2);
GPURsrcMngrDX12::Instance().RegisterTexture2D(*ltcTex2Ds[0]);
GPURsrcMngrDX12::Instance().RegisterTexture2D(*ltcTex2Ds[1]);
ltcSrvDHA = UDX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->Allocate(2);
auto ltc0 = GPURsrcMngrDX12::Instance().GetTexture2DResource(*ltcTex2Ds[0]);
auto ltc1 = GPURsrcMngrDX12::Instance().GetTexture2DResource(*ltcTex2Ds[1]);
const auto ltc0SRVDesc = UDX12::Desc::SRV::Tex2D(ltc0->GetDesc().Format);
const auto ltc1SRVDesc = UDX12::Desc::SRV::Tex2D(ltc1->GetDesc().Format);
device->CreateShaderResourceView(
ltc0,
<c0SRVDesc,
ltcSrvDHA.GetCpuHandle(static_cast<uint32_t>(0))
);
device->CreateShaderResourceView(
ltc1,
<c1SRVDesc,
ltcSrvDHA.GetCpuHandle(static_cast<uint32_t>(1))
);
blackTexCube = AssetMngr::Instance().LoadAsset<TextureCube>(LR"(_internal\textures\blackCube.png)");
whiteTexCube = AssetMngr::Instance().LoadAsset<TextureCube>(LR"(_internal\textures\whiteCube.png)");
auto blackRsrc = GPURsrcMngrDX12::Instance().GetTexture2DResource(*blackTex2D);
auto blackTexCubeRsrc = GPURsrcMngrDX12::Instance().GetTextureCubeResource(*blackTexCube);
defaultSkyboxGpuHandle = GPURsrcMngrDX12::Instance().GetTextureCubeSrvGpuHandle(*blackTexCube);
defaultIBLSrvDHA = UDX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->Allocate(3);
auto cubeDesc = UDX12::Desc::SRV::TexCube(DXGI_FORMAT_R32G32B32A32_FLOAT);
auto lutDesc = UDX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32B32A32_FLOAT);
device->CreateShaderResourceView(blackTexCubeRsrc, &cubeDesc, defaultIBLSrvDHA.GetCpuHandle(0));
device->CreateShaderResourceView(blackTexCubeRsrc, &cubeDesc, defaultIBLSrvDHA.GetCpuHandle(1));
device->CreateShaderResourceView(blackRsrc, &lutDesc, defaultIBLSrvDHA.GetCpuHandle(2));
commonCBs = {
"StdPipeline_cbPerObject",
"StdPipeline_cbPerCamera",
"StdPipeline_cbLightArray",
"StdPipeline_cbDirectionalShadow",
};
const vecf3 origin[6] = {
{ 1,-1, 1}, // +x right
{-1,-1,-1}, // -x left
{-1, 1, 1}, // +y top
{-1,-1,-1}, // -y buttom
{-1,-1, 1}, // +z front
{ 1,-1,-1}, // -z back
};
const vecf3 right[6] = {
{ 0, 0,-2}, // +x
{ 0, 0, 2}, // -x
{ 2, 0, 0}, // +y
{ 2, 0, 0}, // -y
{ 2, 0, 0}, // +z
{-2, 0, 0}, // -z
};
const vecf3 up[6] = {
{ 0, 2, 0}, // +x
{ 0, 2, 0}, // -x
{ 0, 0,-2}, // +y
{ 0, 0, 2}, // -y
{ 0, 2, 0}, // +z
{ 0, 2, 0}, // -z
};
constexpr auto quadPositionsSize = UDX12::Util::CalcConstantBufferByteSize(sizeof(QuadPositionLs));
constexpr auto mipInfoSize = UDX12::Util::CalcConstantBufferByteSize(sizeof(MipInfo));
constexpr auto atrousConfigSize = UDX12::Util::CalcConstantBufferByteSize(sizeof(ATrousConfig));
constexpr auto persistentCBBufferSize = 6 * quadPositionsSize
+ IBLData::PreFilterMapMipLevels * mipInfoSize
+ UINT(ATrousN) * atrousConfigSize;
persistentCBBuffer.emplace(device, persistentCBBufferSize);
for (size_t i = 0; i < 6; i++) {
QuadPositionLs positionLs;
auto p0 = origin[i];
auto p1 = origin[i] + right[i];
auto p2 = origin[i] + right[i] + up[i];
auto p3 = origin[i] + up[i];
positionLs.positionL4x = { p0[0], p1[0], p2[0], p3[0] };
positionLs.positionL4y = { p0[1], p1[1], p2[1], p3[1] };
positionLs.positionL4z = { p0[2], p1[2], p2[2], p3[2] };
persistentCBBuffer->Set(i * quadPositionsSize, &positionLs, sizeof(QuadPositionLs));
}
size_t size = IBLData::PreFilterMapSize;
for (UINT i = 0; i < IBLData::PreFilterMapMipLevels; i++) {
MipInfo info;
info.roughness = i / float(IBLData::PreFilterMapMipLevels - 1);
info.resolution = (float)size;
persistentCBBuffer->Set(6 * quadPositionsSize + i * mipInfoSize, &info, sizeof(MipInfo));
size /= 2;
}
for (size_t i = 0; i < ATrousN; i++) {
ATrousConfig config;
config.gKernelStep = (int)(i + 1);
persistentCBBuffer->Set(
6 * quadPositionsSize + IBLData::PreFilterMapMipLevels * mipInfoSize + i * atrousConfigSize,
&config,
sizeof(ATrousConfig));
}
}
void PipelineCommonResourceMngr::Release() {
blackTex2D = nullptr;
whiteTex2D = nullptr;
errorTex2D = nullptr;
normalTex2D = nullptr;
brdfLutTex2D = nullptr;
ltcTex2Ds[0] = nullptr;
ltcTex2Ds[1] = nullptr;
UDX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->Free(std::move(ltcSrvDHA));
blackTexCube = nullptr;
whiteTexCube = nullptr;
errorMat = nullptr;
directionalShadowMat = nullptr;
defaultSkyboxGpuHandle.ptr = 0;
UDX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->Free(std::move(defaultIBLSrvDHA));
commonCBs.clear();
persistentCBBuffer.reset();
}
std::shared_ptr<Material> PipelineCommonResourceMngr::GetErrorMaterial() const { return errorMat; }
std::shared_ptr<Material> PipelineCommonResourceMngr::GetDirectionalShadowMaterial() const { return directionalShadowMat; }
D3D12_GPU_DESCRIPTOR_HANDLE PipelineCommonResourceMngr::GetDefaultSkyboxGpuHandle() const { return defaultSkyboxGpuHandle; }
bool PipelineCommonResourceMngr::IsCommonCB(std::string_view cbDescName) const {
return commonCBs.contains(cbDescName);
}
const UDX12::DescriptorHeapAllocation& PipelineCommonResourceMngr::GetDefaultIBLSrvDHA() const {
return defaultIBLSrvDHA;
}
std::shared_ptr<Texture2D> PipelineCommonResourceMngr::GetErrorTex2D() const {
return errorTex2D;
}
std::shared_ptr<Texture2D> PipelineCommonResourceMngr::GetWhiteTex2D() const {
return whiteTex2D;
}
std::shared_ptr<Texture2D> PipelineCommonResourceMngr::GetBlackTex2D() const {
return blackTex2D;
}
std::shared_ptr<Texture2D> PipelineCommonResourceMngr::GetNormalTex2D() const {
return normalTex2D;
}
std::shared_ptr<Texture2D> PipelineCommonResourceMngr::GetBrdfLutTex2D() const {
return brdfLutTex2D;
}
std::shared_ptr<Texture2D> PipelineCommonResourceMngr::GetLtcTex2D(size_t idx) const {
assert(idx == 0 || idx == 1);
return ltcTex2Ds[idx];
}
const UDX12::DescriptorHeapAllocation& PipelineCommonResourceMngr::GetLtcSrvDHA() const {
return ltcSrvDHA;
}
std::shared_ptr<TextureCube> PipelineCommonResourceMngr::GetBlackTexCube() const {
return blackTexCube;
}
std::shared_ptr<TextureCube> PipelineCommonResourceMngr::GetWhiteTexCube() const {
return whiteTexCube;
}
D3D12_GPU_VIRTUAL_ADDRESS PipelineCommonResourceMngr::GetQuadPositionLocalGpuAddress(size_t idx) const {
assert(idx < 6);
return persistentCBBuffer->GetResource()->GetGPUVirtualAddress()
+ idx * UDX12::Util::CalcConstantBufferByteSize(sizeof(QuadPositionLs));
}
D3D12_GPU_VIRTUAL_ADDRESS PipelineCommonResourceMngr::GetMipInfoGpuAddress(size_t idx) const {
assert(idx < IBLData::PreFilterMapMipLevels);
return persistentCBBuffer->GetResource()->GetGPUVirtualAddress()
+ 6 * UDX12::Util::CalcConstantBufferByteSize(sizeof(QuadPositionLs))
+ idx * UDX12::Util::CalcConstantBufferByteSize(sizeof(MipInfo));
}
D3D12_GPU_VIRTUAL_ADDRESS PipelineCommonResourceMngr::GetATrousConfigGpuAddress(size_t idx) const {
assert(idx < ATrousN);
return persistentCBBuffer->GetResource()->GetGPUVirtualAddress()
+ 6 * UDX12::Util::CalcConstantBufferByteSize(sizeof(QuadPositionLs))
+ IBLData::PreFilterMapMipLevels * UDX12::Util::CalcConstantBufferByteSize(sizeof(MipInfo))
+ idx * UDX12::Util::CalcConstantBufferByteSize(sizeof(ATrousConfig));
}
IBLData::~IBLData() {
if (!RTVsDH.IsNull())
UDX12::DescriptorHeapMngr::Instance().GetRTVCpuDH()->Free(std::move(RTVsDH));
if (!SRVDH.IsNull())
UDX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->Free(std::move(SRVDH));
}
void IBLData::Init(ID3D12Device* device) {
D3D12_CLEAR_VALUE clearColor;
clearColor.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
clearColor.Color[0] = 0.f;
clearColor.Color[1] = 0.f;
clearColor.Color[2] = 0.f;
clearColor.Color[3] = 1.f;
RTVsDH = UDX12::DescriptorHeapMngr::Instance().GetRTVCpuDH()->Allocate(6 * (1 + IBLData::PreFilterMapMipLevels));
SRVDH = UDX12::DescriptorHeapMngr::Instance().GetCSUGpuDH()->Allocate(3);
{ // irradiance
auto rsrcDesc = UDX12::Desc::RSRC::TextureCube(
IBLData::IrradianceMapSize, IBLData::IrradianceMapSize,
1, DXGI_FORMAT_R32G32B32A32_FLOAT
);
const auto defaultHeapProp = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
device->CreateCommittedResource(
&defaultHeapProp,
D3D12_HEAP_FLAG_NONE,
&rsrcDesc,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
&clearColor,
IID_PPV_ARGS(&irradianceMapResource)
);
for (UINT i = 0; i < 6; i++) {
auto rtvDesc = UDX12::Desc::RTV::Tex2DofTexCube(DXGI_FORMAT_R32G32B32A32_FLOAT, i);
device->CreateRenderTargetView(irradianceMapResource.Get(), &rtvDesc, RTVsDH.GetCpuHandle(i));
}
auto srvDesc = UDX12::Desc::SRV::TexCube(DXGI_FORMAT_R32G32B32A32_FLOAT);
device->CreateShaderResourceView(irradianceMapResource.Get(), &srvDesc, SRVDH.GetCpuHandle(0));
}
{ // prefilter
auto rsrcDesc = UDX12::Desc::RSRC::TextureCube(
IBLData::PreFilterMapSize, IBLData::PreFilterMapSize,
IBLData::PreFilterMapMipLevels, DXGI_FORMAT_R32G32B32A32_FLOAT
);
const auto defaultHeapProp = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
device->CreateCommittedResource(
&defaultHeapProp,
D3D12_HEAP_FLAG_NONE,
&rsrcDesc,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE,
&clearColor,
IID_PPV_ARGS(&prefilterMapResource)
);
for (UINT mip = 0; mip < IBLData::PreFilterMapMipLevels; mip++) {
for (UINT i = 0; i < 6; i++) {
auto rtvDesc = UDX12::Desc::RTV::Tex2DofTexCube(DXGI_FORMAT_R32G32B32A32_FLOAT, i, mip);
device->CreateRenderTargetView(
prefilterMapResource.Get(),
&rtvDesc,
RTVsDH.GetCpuHandle(6 * (1 + mip) + i)
);
}
}
auto srvDesc = UDX12::Desc::SRV::TexCube(DXGI_FORMAT_R32G32B32A32_FLOAT, IBLData::PreFilterMapMipLevels);
device->CreateShaderResourceView(prefilterMapResource.Get(), &srvDesc, SRVDH.GetCpuHandle(1));
}
{// BRDF LUT
auto brdfLUTTex2D = PipelineCommonResourceMngr::GetInstance().GetBrdfLutTex2D();
auto brdfLUTTex2DRsrc = GPURsrcMngrDX12::Instance().GetTexture2DResource(*brdfLUTTex2D);
auto desc = UDX12::Desc::SRV::Tex2D(DXGI_FORMAT_R32G32_FLOAT);
device->CreateShaderResourceView(brdfLUTTex2DRsrc, &desc, SRVDH.GetCpuHandle(2));
}
}
RenderContext Ubpa::Utopia::GenerateRenderContext(size_t ID, std::span<const UECS::World* const> worlds)
{
auto errorMat = PipelineCommonResourceMngr::GetInstance().GetErrorMaterial();
auto defaultSkyboxGpuHandle = PipelineCommonResourceMngr::GetInstance().GetDefaultSkyboxGpuHandle();
RenderContext ctx;
ctx.ID = ID;
{ // object
for (auto world : worlds) {
world->RunChunkJob(
[&](ChunkView chunk) {
auto meshFilters = chunk->GetCmptArray<MeshFilter>();
auto meshRenderers = chunk->GetCmptArray<MeshRenderer>();
auto L2Ws = chunk->GetCmptArray<LocalToWorld>();
auto W2Ls = chunk->GetCmptArray<WorldToLocal>();
auto prevL2Ws = chunk->GetCmptArray<PrevLocalToWorld>();
auto entities = chunk->GetEntityArray();
size_t N = chunk->EntityNum();
for (size_t i = 0; i < N; i++) {
auto meshFilter = meshFilters[i];
auto meshRenderer = meshRenderers[i];
if (!meshFilter.mesh)
return;
RenderObject obj;
obj.mesh = meshFilter.mesh;
obj.entity = entities[i];
size_t M = obj.mesh->GetSubMeshes().size();// std::min(meshRenderer.materials.size(), obj.mesh->GetSubMeshes().size());
if (M == 0)
continue;
bool isDraw = false;
for (size_t j = 0; j < M; j++) {
auto material = j < meshRenderer.materials.size() ? meshRenderer.materials[j] : nullptr;
if (!material || !material->shader)
obj.material = errorMat;
else {
if (material->shader->passes.empty())
continue;
obj.material = material;
}
obj.translation = L2Ws[i].value.decompose_translation();
obj.submeshIdx = j;
for (size_t k = 0; k < obj.material->shader->passes.size(); k++) {
obj.passIdx = k;
ctx.renderQueue.Add(obj);
}
isDraw = true;
}
if (!isDraw)
continue;
auto target = ctx.entity2data.find(obj.entity.index);
if (target != ctx.entity2data.end())
continue;
RenderContext::EntityData data;
data.l2w = L2Ws[i].value;
data.w2l = !W2Ls.empty() ? W2Ls[i].value : L2Ws[i].value.inverse();
data.prevl2w = !prevL2Ws.empty() ? prevL2Ws[i].value : L2Ws[i].value;
data.mesh = meshFilter.mesh;
data.materials = meshRenderer.materials;
ctx.entity2data.emplace_hint(target, std::pair{ obj.entity.index, data });
bboxf3 boungdingBoxWS = L2Ws[i].value * data.mesh->GetBoundingBox();
ctx.boundingBox.combine_to_self(boungdingBoxWS);
}
},
{ // ArchetypeFilter
.all = {
AccessTypeID_of<Latest<MeshFilter>>,
AccessTypeID_of<Latest<MeshRenderer>>,
AccessTypeID_of<Latest<LocalToWorld>>,
}
},
false
);
}
}
{ // light
std::array<ShaderLight, LightArray::size> dirLights;
std::array<ShaderLight, LightArray::size> pointLights;
std::array<ShaderLight, LightArray::size> spotLights;
std::array<ShaderLight, LightArray::size> rectLights;
std::array<ShaderLight, LightArray::size> diskLights;
ctx.lightArray.diectionalLightNum = 0;
ctx.lightArray.pointLightNum = 0;
ctx.lightArray.spotLightNum = 0;
ctx.lightArray.rectLightNum = 0;
ctx.lightArray.diskLightNum = 0;
for (auto world : worlds) {
world->RunEntityJob(
[&](const Light* light) {
switch (light->mode)
{
case Light::Mode::Directional:
ctx.lightArray.diectionalLightNum++;
break;
case Light::Mode::Point:
ctx.lightArray.pointLightNum++;
break;
case Light::Mode::Spot:
ctx.lightArray.spotLightNum++;
break;
case Light::Mode::Rect:
ctx.lightArray.rectLightNum++;
break;
case Light::Mode::Disk:
ctx.lightArray.diskLightNum++;
break;
default:
assert("not support" && false);
break;
}
},
false,
{ // ArchetypeFilter
.all = { UECS::AccessTypeID_of<UECS::Latest<LocalToWorld>> }
}
);
}
size_t offset_diectionalLight = 0;
size_t offset_pointLight = offset_diectionalLight + ctx.lightArray.diectionalLightNum;
size_t offset_spotLight = offset_pointLight + ctx.lightArray.pointLightNum;
size_t offset_rectLight = offset_spotLight + ctx.lightArray.spotLightNum;
size_t offset_diskLight = offset_rectLight + ctx.lightArray.rectLightNum;
size_t cur_diectionalLight = 0;
size_t cur_pointLight = 0;
size_t cur_spotLight = 0;
size_t cur_rectLight = 0;
size_t cur_diskLight = 0;
for (auto world : worlds) {
world->RunEntityJob(
[&](const Light* light, const LocalToWorld* l2w) {
switch (light->mode)
{
case Light::Mode::Directional:
ctx.lightArray.lights[cur_diectionalLight].color = light->color * light->intensity;
ctx.lightArray.lights[cur_diectionalLight].dir = (l2w->value * vecf3{ 0,0,1 }).safe_normalize();
cur_diectionalLight++;
break;
case Light::Mode::Point:
ctx.lightArray.lights[cur_pointLight].color = light->color * light->intensity;
ctx.lightArray.lights[cur_pointLight].position = l2w->value * pointf3{ 0.f };
ctx.lightArray.lights[cur_pointLight].range = light->range;
cur_pointLight++;
break;
case Light::Mode::Spot:
ctx.lightArray.lights[cur_spotLight].color = light->color * light->intensity;
ctx.lightArray.lights[cur_spotLight].position = l2w->value * pointf3{ 0.f };
ctx.lightArray.lights[cur_spotLight].dir = (l2w->value * vecf3{ 0,1,0 }).safe_normalize();
ctx.lightArray.lights[cur_spotLight].range = light->range;
ctx.lightArray.lights[cur_spotLight].*
ShaderLight::Spot::pCosHalfInnerSpotAngle = std::cos(to_radian(light->innerSpotAngle) / 2.f);
ctx.lightArray.lights[cur_spotLight].*
ShaderLight::Spot::pCosHalfOuterSpotAngle = std::cos(to_radian(light->outerSpotAngle) / 2.f);
cur_spotLight++;
break;
case Light::Mode::Rect:
ctx.lightArray.lights[cur_rectLight].color = light->color * light->intensity;
ctx.lightArray.lights[cur_rectLight].position = l2w->value * pointf3{ 0.f };
ctx.lightArray.lights[cur_rectLight].dir = (l2w->value * vecf3{ 0,1,0 }).safe_normalize();
ctx.lightArray.lights[cur_rectLight].horizontal = (l2w->value * vecf3{ 1,0,0 }).safe_normalize();
ctx.lightArray.lights[cur_rectLight].range = light->range;
ctx.lightArray.lights[cur_rectLight].*
ShaderLight::Rect::pWidth = light->width;
ctx.lightArray.lights[cur_rectLight].*
ShaderLight::Rect::pHeight = light->height;
cur_rectLight++;
break;
case Light::Mode::Disk:
ctx.lightArray.lights[cur_diskLight].color = light->color * light->intensity;
ctx.lightArray.lights[cur_diskLight].position = l2w->value * pointf3{ 0.f };
ctx.lightArray.lights[cur_diskLight].dir = (l2w->value * vecf3{ 0,1,0 }).safe_normalize();
ctx.lightArray.lights[cur_diskLight].horizontal = (l2w->value * vecf3{ 1,0,0 }).safe_normalize();
ctx.lightArray.lights[cur_diskLight].range = light->range;
ctx.lightArray.lights[cur_diskLight].*
ShaderLight::Disk::pWidth = light->width;
ctx.lightArray.lights[cur_diskLight].*
ShaderLight::Disk::pHeight = light->height;
cur_diskLight++;
break;
default:
break;
}
},
false
);
}
}
{ // directional shadow
bool foundDirectionalLight = false;
for (auto world : worlds) {
if (foundDirectionalLight)
break;
world->RunEntityJob(
[&](const Light* light, const LocalToWorld* l2w) {
if (foundDirectionalLight)
return;
if (light->mode != Light::Mode::Directional)
return;
transformf w2l = l2w->value.inverse();
bboxf3 boundingBox = w2l * ctx.boundingBox;
vecf3 diagonal = boundingBox.diagonal();
vecf3 dir{ 0,0,1 };
transformf translate(vecf3(0, 0, 0) - (boundingBox.center().as<vecf3>() - dir * diagonal.z * 0.5));
transformf rotate(quatf::rotate_with<Axis::Y>(to_radian(180.f)));
ctx.directionalShadow.DirectionalShadowViewProj =
transformf::orthographic(diagonal.x, diagonal.y, 0, diagonal.z) * rotate * translate * w2l;
},
false
);
}
}
// use first skybox in the world vector
ctx.skyboxSrvGpuHandle = defaultSkyboxGpuHandle;
for (auto world : worlds) {
if (auto ptr = world->entityMngr.ReadSingleton<Skybox>(); ptr && ptr->material) {
auto target = ptr->material->properties.find("gSkybox");
if (target != ptr->material->properties.end() && std::holds_alternative<SharedVar<TextureCube>>(target->second.value)) {
auto texcube = std::get<SharedVar<TextureCube>>(target->second.value);
ctx.skyboxSrvGpuHandle = GPURsrcMngrDX12::Instance().GetTextureCubeSrvGpuHandle(*texcube);
break;
}
}
}
return ctx;
}
void Ubpa::Utopia::DrawObjects(
const ShaderCBMngr& shaderCBMngr,
const RenderContext& ctx,
ID3D12GraphicsCommandList* cmdList,
std::string_view lightMode,
size_t rtNum,
DXGI_FORMAT rtFormat,
DXGI_FORMAT dsvFormat,
D3D12_GPU_VIRTUAL_ADDRESS cameraCBAddress,
D3D12_GPU_DESCRIPTOR_HANDLE iblDataSrvGpuHandle,
const Material* defaultMaterial)
{
D3D12_GPU_DESCRIPTOR_HANDLE ibl;
if (ctx.skyboxSrvGpuHandle.ptr == PipelineCommonResourceMngr::GetInstance().GetDefaultSkyboxGpuHandle().ptr)
ibl = PipelineCommonResourceMngr::GetInstance().GetDefaultIBLSrvDHA().GetGpuHandle();
else
ibl = iblDataSrvGpuHandle;
if (defaultMaterial)
cmdList->SetGraphicsRootSignature(GPURsrcMngrDX12::Instance().GetShaderRootSignature(*defaultMaterial->shader));
const Shader* currRootSignatureShader = defaultMaterial ? defaultMaterial->shader.get() : nullptr;
auto Draw = [&](const RenderObject& obj) {
const Material* material = defaultMaterial ? defaultMaterial : obj.material.get();
const Shader* shader = material->shader.get();
// TODO: default pass index
size_t passIdx = defaultMaterial ? 0 : obj.passIdx;
const auto& pass = shader->passes[passIdx];
if (auto target = pass.tags.find("LightMode"); target == pass.tags.end() || target->second != lightMode)
return;
if (currRootSignatureShader != shader) {
currRootSignatureShader = shader;
cmdList->SetGraphicsRootSignature(GPURsrcMngrDX12::Instance().GetShaderRootSignature(*currRootSignatureShader));
}
D3D12_GPU_VIRTUAL_ADDRESS objCBAddress = shaderCBMngr.GetObjectCBAddress(ctx.ID, obj.entity.index);
auto lightCBAddress = shaderCBMngr.GetLightCBAddress(ctx.ID);
auto directionalShadowCBAddress = shaderCBMngr.GetDirectionalShadowCBAddress(ctx.ID);
shaderCBMngr.SetGraphicsRoot_CBV_SRV(
cmdList,
ctx.ID,
*material,
{
{StdPipeline_cbPerObject, objCBAddress},
{StdPipeline_cbPerCamera, cameraCBAddress},
{StdPipeline_cbLightArray, lightCBAddress},
{StdPipeline_cbDirectionalShadow, directionalShadowCBAddress}
},
{
{StdPipeline_srvIBL, ibl},
{StdPipeline_srvLTC, PipelineCommonResourceMngr::GetInstance().GetLtcSrvDHA().GetGpuHandle()}
}
);
auto& meshGPUBuffer = GPURsrcMngrDX12::Instance().GetMeshGPUBuffer(*obj.mesh);
const auto& submesh = obj.mesh->GetSubMeshes().at(obj.submeshIdx);
const auto meshVBView = meshGPUBuffer.VertexBufferView();
const auto meshIBView = meshGPUBuffer.IndexBufferView();
cmdList->IASetVertexBuffers(0, 1, &meshVBView);
cmdList->IASetIndexBuffer(&meshIBView);
// submesh.topology
D3D12_PRIMITIVE_TOPOLOGY d3d12Topology;
switch (submesh.topology)
{
case Ubpa::Utopia::MeshTopology::Triangles:
d3d12Topology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
break;
case Ubpa::Utopia::MeshTopology::Lines:
d3d12Topology = D3D_PRIMITIVE_TOPOLOGY_LINELIST;
break;
case Ubpa::Utopia::MeshTopology::LineStrip:
d3d12Topology = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
break;
case Ubpa::Utopia::MeshTopology::Points:
d3d12Topology = D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
break;
default:
assert(false);
d3d12Topology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
break;
}
cmdList->IASetPrimitiveTopology(d3d12Topology);
if (pass.renderState.stencilState.enable)
cmdList->OMSetStencilRef(pass.renderState.stencilState.ref);
cmdList->SetPipelineState(GPURsrcMngrDX12::Instance().GetOrCreateShaderPSO(
*shader,
passIdx,
MeshLayoutMngr::Instance().GetMeshLayoutID(*obj.mesh),
rtNum,
rtFormat
));
cmdList->DrawIndexedInstanced((UINT)submesh.indexCount, 1, (UINT)submesh.indexStart, (INT)submesh.baseVertex, 0);
};
for (const auto& obj : ctx.renderQueue.GetOpaques())
Draw(obj);
for (const auto& obj : ctx.renderQueue.GetTransparents())
Draw(obj);
}
void Ubpa::Utopia::UpdateCrossFrameCameraResources(
CameraRsrcMngr& crossFrameCameraRsrcMngr,
std::span<const IPipeline::CameraData> cameras,
std::span<ID3D12Resource* const> defaultRTs)
{
crossFrameCameraRsrcMngr.Update(cameras);
for (size_t i = 0; i < cameras.size(); ++i) {
const auto& camera = cameras[i];
auto desc = defaultRTs[i]->GetDesc();
size_t defalut_width = desc.Width;
size_t defalut_height = desc.Height;
auto& cameraRsrcMap = crossFrameCameraRsrcMngr.Get(camera);
if (!cameraRsrcMap.Contains(key_CameraConstants))
cameraRsrcMap.Register(key_CameraConstants, CameraConstants{});
auto& cameraConstants = cameraRsrcMap.Get<CameraConstants>(key_CameraConstants);
if (!cameraRsrcMap.Contains(key_CameraJitterIndex))
cameraRsrcMap.Register(key_CameraJitterIndex, 0);
auto& cameraJitterIndex = cameraRsrcMap.Get<int>(key_CameraJitterIndex);
auto cmptCamera = camera.world->entityMngr.ReadComponent<Camera>(camera.entity);
auto cmptW2L = camera.world->entityMngr.ReadComponent<WorldToLocal>(camera.entity);
auto cmptTranslation = camera.world->entityMngr.ReadComponent<Translation>(camera.entity);
size_t rt_width = defalut_width, rt_height = defalut_height;
if (cmptCamera->renderTarget) {
rt_width = cmptCamera->renderTarget->image.GetWidth();
rt_height = cmptCamera->renderTarget->image.GetHeight();
}
float SampleX = HaltonSequence2[(cameraJitterIndex % 8)];
float SampleY = HaltonSequence3[(cameraJitterIndex % 8)];
cameraJitterIndex++;
float JitterX = (SampleX * 2.0f - 1.0f) / rt_width;
float JitterY = (SampleY * 2.0f - 1.0f) / rt_height;
transformf view = cmptW2L ? cmptW2L->value : transformf::eye();
transformf proj = cmptCamera->prjectionMatrix;
transformf unjitteredProj = proj;
proj[2][0] += JitterX;
proj[2][1] += JitterY;
cameraConstants.View = view;
cameraConstants.InvView = view.inverse();
cameraConstants.Proj = proj;
cameraConstants.InvProj = proj.inverse();
cameraConstants.PrevViewProj = cameraConstants.UnjitteredViewProj;
cameraConstants.ViewProj = proj * view;
cameraConstants.UnjitteredViewProj = unjitteredProj * view;
cameraConstants.InvViewProj = view.inverse() * proj.inverse();
cameraConstants.EyePosW = cmptTranslation ? cmptTranslation->value.as<pointf3>() : pointf3{ 0.f };
cameraConstants.FrameCount = cameraConstants.FrameCount + 1;
cameraConstants.RenderTargetSize = { rt_width, rt_height };
cameraConstants.InvRenderTargetSize = { 1.0f / rt_width, 1.0f / rt_height };
cameraConstants.NearZ = cmptCamera->clippingPlaneMin;
cameraConstants.FarZ = cmptCamera->clippingPlaneMax;
cameraConstants.TotalTime = GameTimer::Instance().TotalTime();
cameraConstants.DeltaTime = GameTimer::Instance().DeltaTime();
cameraConstants.Jitter.x = JitterX;
cameraConstants.Jitter.y = JitterY;
cameraConstants.padding0 = 0;
cameraConstants.padding1 = 0;
}
} | 37.152828 | 125 | 0.723813 | [
"mesh",
"render",
"object",
"vector"
] |
118bdb4981c01a0dd9fab9c5d268b5d519eaf4c1 | 7,379 | hpp | C++ | redfish-core/include/gzfile.hpp | HCLOpenBMC/bmcweb | 4028ff77ddebe603b009a8afaf6bc36bc5949612 | [
"Apache-2.0"
] | 7 | 2021-02-23T15:33:42.000Z | 2022-02-25T09:28:48.000Z | redfish-core/include/gzfile.hpp | HCLOpenBMC/bmcweb | 4028ff77ddebe603b009a8afaf6bc36bc5949612 | [
"Apache-2.0"
] | 221 | 2019-07-15T16:26:01.000Z | 2022-03-31T17:18:10.000Z | redfish-core/include/gzfile.hpp | HCLOpenBMC/bmcweb | 4028ff77ddebe603b009a8afaf6bc36bc5949612 | [
"Apache-2.0"
] | 82 | 2019-07-11T14:00:57.000Z | 2022-03-31T15:26:01.000Z | #pragma once
#include <zlib.h>
#include <array>
#include <filesystem>
#include <vector>
class GzFileReader
{
public:
bool gzGetLines(const std::string& filename, uint64_t& skip, uint64_t& top,
std::vector<std::string>& logEntries, size_t& logCount)
{
gzFile logStream = gzopen(filename.c_str(), "r");
if (!logStream)
{
BMCWEB_LOG_ERROR << "Can't open gz file: " << filename << '\n';
return false;
}
if (!readFile(logStream, skip, top, logEntries, logCount))
{
gzclose(logStream);
return false;
}
gzclose(logStream);
return true;
}
std::string getLastMessage()
{
return lastMessage;
}
private:
std::string lastMessage;
std::string lastDelimiter;
size_t totalFilesSize = 0;
void printErrorMessage(gzFile logStream)
{
int errNum = 0;
const char* errMsg = gzerror(logStream, &errNum);
BMCWEB_LOG_ERROR << "Error reading gz compressed data.\n"
<< "Error Message: " << errMsg << '\n'
<< "Error Number: " << errNum;
}
bool readFile(gzFile logStream, uint64_t& skip, uint64_t& top,
std::vector<std::string>& logEntries, size_t& logCount)
{
constexpr int bufferLimitSize = 1024;
do
{
std::string bufferStr;
bufferStr.resize(bufferLimitSize);
int bytesRead = gzread(logStream, bufferStr.data(),
static_cast<unsigned int>(bufferStr.size()));
// On errors, gzread() shall return a value less than 0.
if (bytesRead < 0)
{
printErrorMessage(logStream);
return false;
}
bufferStr.resize(static_cast<size_t>(bytesRead));
if (!hostLogEntryParser(bufferStr, skip, top, logEntries, logCount))
{
BMCWEB_LOG_ERROR << "Error occurs during parsing host log.\n";
return false;
}
} while (!gzeof(logStream));
return true;
}
bool hostLogEntryParser(const std::string& bufferStr, uint64_t& skip,
uint64_t& top, std::vector<std::string>& logEntries,
size_t& logCount)
{
// Assume we have 8 files, and the max size of each file is
// 16k, so define the max size as 256kb (double of 8 files *
// 16kb)
constexpr size_t maxTotalFilesSize = 262144;
// It may contain several log entry in one line, and
// the end of each log entry will be '\r\n' or '\r'.
// So we need to go through and split string by '\n' and '\r'
size_t pos = bufferStr.find_first_of("\n\r");
size_t initialPos = 0;
std::string newLastMessage;
while (pos != std::string::npos)
{
std::string logEntry =
bufferStr.substr(initialPos, pos - initialPos);
// Since there might be consecutive delimiters like "\r\n", we need
// to filter empty strings.
if (!logEntry.empty())
{
logCount++;
if (!lastMessage.empty())
{
logEntry.insert(0, lastMessage);
lastMessage.clear();
}
if (logCount > skip && logCount <= (skip + top))
{
totalFilesSize += logEntry.size();
if (totalFilesSize > maxTotalFilesSize)
{
BMCWEB_LOG_ERROR
<< "File size exceeds maximum allowed size of "
<< maxTotalFilesSize;
return false;
}
logEntries.push_back(logEntry);
}
}
else
{
// Handle consecutive delimiter. '\r\n' act as a single
// delimiter, the other case like '\n\n', '\n\r' or '\r\r' will
// push back a "\n" as a log.
std::string delimiters;
if (pos > 0)
{
delimiters = bufferStr.substr(pos - 1, 2);
}
// Handle consecutive delimiter but spilt between two files.
if (pos == 0 && !(lastDelimiter.empty()))
{
delimiters = lastDelimiter + bufferStr.substr(0, 1);
}
if (delimiters != "\r\n")
{
logCount++;
if (logCount > skip && logCount <= (skip + top))
{
totalFilesSize++;
if (totalFilesSize > maxTotalFilesSize)
{
BMCWEB_LOG_ERROR
<< "File size exceeds maximum allowed size of "
<< maxTotalFilesSize;
return false;
}
logEntries.emplace_back("\n");
}
}
}
initialPos = pos + 1;
pos = bufferStr.find_first_of("\n\r", initialPos);
}
// Store the last message
if (initialPos < bufferStr.size())
{
newLastMessage = bufferStr.substr(initialPos);
}
// If consecutive delimiter spilt by buffer or file, the last character
// must be the delimiter.
else if (initialPos == bufferStr.size())
{
lastDelimiter = std::string(1, bufferStr.back());
}
// If file doesn't contain any "\r" or "\n", initialPos should be zero
if (initialPos == 0)
{
// Solved an edge case that the log doesn't in skip and top range,
// but consecutive files don't contain a single delimiter, this
// lastMessage becomes unnecessarily large. Since last message will
// prepend to next log, logCount need to plus 1
if ((logCount + 1) > skip && (logCount + 1) <= (skip + top))
{
lastMessage.insert(
lastMessage.end(),
std::make_move_iterator(newLastMessage.begin()),
std::make_move_iterator(newLastMessage.end()));
// Following the previous question, protect lastMessage don't
// larger than max total files size
size_t tmpMessageSize = totalFilesSize + lastMessage.size();
if (tmpMessageSize > maxTotalFilesSize)
{
BMCWEB_LOG_ERROR
<< "File size exceeds maximum allowed size of "
<< maxTotalFilesSize;
return false;
}
}
}
else
{
if (!newLastMessage.empty())
{
lastMessage = std::move(newLastMessage);
}
}
return true;
}
public:
GzFileReader() = default;
~GzFileReader() = default;
GzFileReader(const GzFileReader&) = delete;
GzFileReader& operator=(const GzFileReader&) = delete;
};
| 34.971564 | 80 | 0.484483 | [
"vector"
] |
118cf529ccb31c9424de662ce5c57f54e528278f | 1,852 | cpp | C++ | src/Geometry/SurfaceInteraction.cpp | Jerry-Shen0527/SimpleRayTracer | a016c33ad456dcbd2dde633e616874bf9e5ee19a | [
"Apache-2.0"
] | null | null | null | src/Geometry/SurfaceInteraction.cpp | Jerry-Shen0527/SimpleRayTracer | a016c33ad456dcbd2dde633e616874bf9e5ee19a | [
"Apache-2.0"
] | null | null | null | src/Geometry/SurfaceInteraction.cpp | Jerry-Shen0527/SimpleRayTracer | a016c33ad456dcbd2dde633e616874bf9e5ee19a | [
"Apache-2.0"
] | null | null | null | #include "Geometry/Interaction.h"
#include "Geometry/Primitive.h"
#include "Geometry/Shape.h"
Spectrum SurfaceInteraction::Le(const Vector3f& w) const
{
const AreaLight* area = primitive->GetAreaLight();
return area ? area->L(*this, w) : Spectrum(0.f);
}
Ray Interaction::SpawnRayTo(const Interaction& it) const
{
Point3f origin = OffsetRayOrigin(p, pError, n, it.p - p);
Point3f target = OffsetRayOrigin(it.p, it.pError, it.n, origin - it.p);
Vector3f d = target - origin;
return Ray(origin, d, 1 - ShadowEpsilon, time, GetMedium(d));
}
Ray Interaction::SpawnRay(const Vector3f& d) const
{
Point3f o = OffsetRayOrigin(p, pError, n, d);
return Ray(o, d, Infinity, time, GetMedium(d));
}
Ray Interaction::SpawnRayTo(const Point3f& p2) const
{
Point3f origin = OffsetRayOrigin(p, pError, n, p2 - p);
Vector3f d = p2 - p;
return Ray(origin, d, 1 - ShadowEpsilon, time, GetMedium(d));
}
void SurfaceInteraction::set_face_normal(const Vector3f& r_in, const Normal3f& outward_normal)
{
front_face = Dot(r_in, outward_normal) < 0;
n = front_face ? outward_normal : -outward_normal;
}
SurfaceInteraction::SurfaceInteraction(
const Point3f& p, const Vector3f& pError, const Point2f& uv,
const Vector3f& wo, const Vector3f& dpdu, const Vector3f& dpdv,
const Normal3f& dndu, const Normal3f& dndv, Float time, const Shape* shape)
: Interaction(p, Normal3f(Normalize(Cross(dpdu, dpdv))), pError, wo, time,
nullptr),
uv(uv),
dpdu(dpdu),
dpdv(dpdv),
dndu(dndu),
dndv(dndv),
shape(shape),
faceIndex(faceIndex) {
// Initialize shading geometry from true geometry
shading.n = n;
shading.dpdu = dpdu;
shading.dpdv = dpdv;
shading.dndu = dndu;
shading.dndv = dndv;
// Adjust normal based on orientation and handedness
if (shape && (shape->reverseOrientation ^ shape->transformSwapsHandedness)) {
n *= -1;
shading.n *= -1;
}
} | 28.9375 | 94 | 0.715443 | [
"geometry",
"shape"
] |
118d2485bc300dfa05c781f9e5ed3d54590790d9 | 5,344 | hpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/OSPF_TRAP_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/OSPF_TRAP_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/OSPF_TRAP_MIB.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _OSPF_TRAP_MIB_
#define _OSPF_TRAP_MIB_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xe {
namespace OSPF_TRAP_MIB {
class OSPFTRAPMIB : public ydk::Entity
{
public:
OSPFTRAPMIB();
~OSPFTRAPMIB();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class OspfTrapControl; //type: OSPFTRAPMIB::OspfTrapControl
std::shared_ptr<cisco_ios_xe::OSPF_TRAP_MIB::OSPFTRAPMIB::OspfTrapControl> ospftrapcontrol;
}; // OSPFTRAPMIB
class OSPFTRAPMIB::OspfTrapControl : public ydk::Entity
{
public:
OspfTrapControl();
~OspfTrapControl();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf ospfsettrap; //type: binary
ydk::YLeaf ospfconfigerrortype; //type: OspfConfigErrorType
ydk::YLeaf ospfpackettype; //type: OspfPacketType
ydk::YLeaf ospfpacketsrc; //type: string
class OspfConfigErrorType;
class OspfPacketType;
}; // OSPFTRAPMIB::OspfTrapControl
class OSPFTRAPMIB::OspfTrapControl::OspfConfigErrorType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf badVersion;
static const ydk::Enum::YLeaf areaMismatch;
static const ydk::Enum::YLeaf unknownNbmaNbr;
static const ydk::Enum::YLeaf unknownVirtualNbr;
static const ydk::Enum::YLeaf authTypeMismatch;
static const ydk::Enum::YLeaf authFailure;
static const ydk::Enum::YLeaf netMaskMismatch;
static const ydk::Enum::YLeaf helloIntervalMismatch;
static const ydk::Enum::YLeaf deadIntervalMismatch;
static const ydk::Enum::YLeaf optionMismatch;
static const ydk::Enum::YLeaf mtuMismatch;
static const ydk::Enum::YLeaf duplicateRouterId;
static const ydk::Enum::YLeaf noError;
static int get_enum_value(const std::string & name) {
if (name == "badVersion") return 1;
if (name == "areaMismatch") return 2;
if (name == "unknownNbmaNbr") return 3;
if (name == "unknownVirtualNbr") return 4;
if (name == "authTypeMismatch") return 5;
if (name == "authFailure") return 6;
if (name == "netMaskMismatch") return 7;
if (name == "helloIntervalMismatch") return 8;
if (name == "deadIntervalMismatch") return 9;
if (name == "optionMismatch") return 10;
if (name == "mtuMismatch") return 11;
if (name == "duplicateRouterId") return 12;
if (name == "noError") return 13;
return -1;
}
};
class OSPFTRAPMIB::OspfTrapControl::OspfPacketType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf hello;
static const ydk::Enum::YLeaf dbDescript;
static const ydk::Enum::YLeaf lsReq;
static const ydk::Enum::YLeaf lsUpdate;
static const ydk::Enum::YLeaf lsAck;
static const ydk::Enum::YLeaf nullPacket;
static int get_enum_value(const std::string & name) {
if (name == "hello") return 1;
if (name == "dbDescript") return 2;
if (name == "lsReq") return 3;
if (name == "lsUpdate") return 4;
if (name == "lsAck") return 5;
if (name == "nullPacket") return 6;
return -1;
}
};
}
}
#endif /* _OSPF_TRAP_MIB_ */
| 41.426357 | 162 | 0.65625 | [
"vector"
] |
118e26b0b8d91af4f9a63734a2a747d889b259e5 | 974 | cc | C++ | tests/clang_src2src/pragma_sst_null_vector.cc | minyee/sst-macro | fd2c52b3872b9c49af77f5f82b3177cc7bbe403c | [
"BSD-Source-Code"
] | null | null | null | tests/clang_src2src/pragma_sst_null_vector.cc | minyee/sst-macro | fd2c52b3872b9c49af77f5f82b3177cc7bbe403c | [
"BSD-Source-Code"
] | null | null | null | tests/clang_src2src/pragma_sst_null_vector.cc | minyee/sst-macro | fd2c52b3872b9c49af77f5f82b3177cc7bbe403c | [
"BSD-Source-Code"
] | 1 | 2018-02-21T11:39:08.000Z | 2018-02-21T11:39:08.000Z | /**
namespace sstmac {
class vector {
public:
void resize(size_t sz){
size_ = sz;
}
size_t size() const {
return size_;
}
template <class... Args>
void push_back(Args... args){
++size_;
}
template <class... Args>
void emplace_back(Args... args){
++size_;
}
bool empty() const {
return size_ == 0;
}
private:
size_t size_;
};
}
*/
template <class T>
struct vector {
vector() : size_(0), storage_(nullptr){}
void resize(int size){
if (size != size_){
delete[] storage_;
storage_ = new T[size];
size_ = size;
}
}
int size() const {
return size_;
}
void null_fxn() {
}
T& operator[](int idx){
return storage_[idx];
}
T* storage_;
int size_;
};
int fxn()
{
#pragma sst null_type sstmac::vector size resize
vector<double> vec;
vec.resize(100);
vec.null_fxn();
int n = vec.size();
#pragma sst compute
for (int i=0; i < vec.size(); ++i){
vec[i] = 5;
}
return 0;
}
| 12.175 | 48 | 0.574949 | [
"vector"
] |
11968be2a94c7d7d95dc2eed26b74589081ac42d | 64,757 | hpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_infra_rsi_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_infra_rsi_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_infra_rsi_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _CISCO_IOS_XR_INFRA_RSI_OPER_
#define _CISCO_IOS_XR_INFRA_RSI_OPER_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_infra_rsi_oper {
class VrfGroup : public ydk::Entity
{
public:
VrfGroup();
~VrfGroup();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class Nodes; //type: VrfGroup::Nodes
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::VrfGroup::Nodes> nodes;
}; // VrfGroup
class VrfGroup::Nodes : public ydk::Entity
{
public:
Nodes();
~Nodes();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Node; //type: VrfGroup::Nodes::Node
ydk::YList node;
}; // VrfGroup::Nodes
class VrfGroup::Nodes::Node : public ydk::Entity
{
public:
Node();
~Node();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf node_name; //type: string
class Groups; //type: VrfGroup::Nodes::Node::Groups
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::VrfGroup::Nodes::Node::Groups> groups;
}; // VrfGroup::Nodes::Node
class VrfGroup::Nodes::Node::Groups : public ydk::Entity
{
public:
Groups();
~Groups();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Group; //type: VrfGroup::Nodes::Node::Groups::Group
ydk::YList group;
}; // VrfGroup::Nodes::Node::Groups
class VrfGroup::Nodes::Node::Groups::Group : public ydk::Entity
{
public:
Group();
~Group();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf group_name; //type: string
ydk::YLeaf vr_fs; //type: uint32
ydk::YLeaf forward_reference; //type: boolean
class Vrf; //type: VrfGroup::Nodes::Node::Groups::Group::Vrf
ydk::YList vrf;
}; // VrfGroup::Nodes::Node::Groups::Group
class VrfGroup::Nodes::Node::Groups::Group::Vrf : public ydk::Entity
{
public:
Vrf();
~Vrf();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf vrf_name; //type: string
}; // VrfGroup::Nodes::Node::Groups::Group::Vrf
class Srlg : public ydk::Entity
{
public:
Srlg();
~Srlg();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class Groups; //type: Srlg::Groups
class Interfaces; //type: Srlg::Interfaces
class Rsips; //type: Srlg::Rsips
class SrlgMaps; //type: Srlg::SrlgMaps
class Nodes; //type: Srlg::Nodes
class InterfaceSrlgNames; //type: Srlg::InterfaceSrlgNames
class InheritNodes; //type: Srlg::InheritNodes
class SrlgValues; //type: Srlg::SrlgValues
class InterfaceDetails; //type: Srlg::InterfaceDetails
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Groups> groups;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Interfaces> interfaces;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Rsips> rsips;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::SrlgMaps> srlg_maps;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes> nodes;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::InterfaceSrlgNames> interface_srlg_names;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::InheritNodes> inherit_nodes;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::SrlgValues> srlg_values;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::InterfaceDetails> interface_details;
}; // Srlg
class Srlg::Groups : public ydk::Entity
{
public:
Groups();
~Groups();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Group; //type: Srlg::Groups::Group
ydk::YList group;
}; // Srlg::Groups
class Srlg::Groups::Group : public ydk::Entity
{
public:
Group();
~Group();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf group_name; //type: string
ydk::YLeaf group_name_xr; //type: string
ydk::YLeaf group_values; //type: uint32
class SrlgAttribute; //type: Srlg::Groups::Group::SrlgAttribute
ydk::YList srlg_attribute;
}; // Srlg::Groups::Group
class Srlg::Groups::Group::SrlgAttribute : public ydk::Entity
{
public:
SrlgAttribute();
~SrlgAttribute();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf priority; //type: Priority
ydk::YLeaf srlg_index; //type: uint16
}; // Srlg::Groups::Group::SrlgAttribute
class Srlg::Interfaces : public ydk::Entity
{
public:
Interfaces();
~Interfaces();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Interface; //type: Srlg::Interfaces::Interface
ydk::YList interface;
}; // Srlg::Interfaces
class Srlg::Interfaces::Interface : public ydk::Entity
{
public:
Interface();
~Interface();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf interface_name; //type: string
ydk::YLeaf interface_name_xr; //type: string
ydk::YLeaf value_count; //type: uint32
ydk::YLeaf registrations; //type: uint32
ydk::YLeafList srlg_value; //type: list of uint32
}; // Srlg::Interfaces::Interface
class Srlg::Rsips : public ydk::Entity
{
public:
Rsips();
~Rsips();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Rsip; //type: Srlg::Rsips::Rsip
ydk::YList rsip;
}; // Srlg::Rsips
class Srlg::Rsips::Rsip : public ydk::Entity
{
public:
Rsip();
~Rsip();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf rsip_name; //type: string
ydk::YLeaf optical_layer_interface_name; //type: string
ydk::YLeaf registrations; //type: uint32
ydk::YLeaf interface_values; //type: uint32
class SrlgAttribute; //type: Srlg::Rsips::Rsip::SrlgAttribute
ydk::YList srlg_attribute;
}; // Srlg::Rsips::Rsip
class Srlg::Rsips::Rsip::SrlgAttribute : public ydk::Entity
{
public:
SrlgAttribute();
~SrlgAttribute();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf priority; //type: Priority
ydk::YLeaf srlg_index; //type: uint16
}; // Srlg::Rsips::Rsip::SrlgAttribute
class Srlg::SrlgMaps : public ydk::Entity
{
public:
SrlgMaps();
~SrlgMaps();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class SrlgMap; //type: Srlg::SrlgMaps::SrlgMap
ydk::YList srlg_map;
}; // Srlg::SrlgMaps
class Srlg::SrlgMaps::SrlgMap : public ydk::Entity
{
public:
SrlgMap();
~SrlgMap();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf srlg_name; //type: string
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf srlg_name_xr; //type: string
}; // Srlg::SrlgMaps::SrlgMap
class Srlg::Nodes : public ydk::Entity
{
public:
Nodes();
~Nodes();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class Node; //type: Srlg::Nodes::Node
ydk::YList node;
}; // Srlg::Nodes
class Srlg::Nodes::Node : public ydk::Entity
{
public:
Node();
~Node();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf node_name; //type: string
class SrlgMaps; //type: Srlg::Nodes::Node::SrlgMaps
class Groups; //type: Srlg::Nodes::Node::Groups
class InheritNodes; //type: Srlg::Nodes::Node::InheritNodes
class Interfaces; //type: Srlg::Nodes::Node::Interfaces
class InterfaceDetails; //type: Srlg::Nodes::Node::InterfaceDetails
class SrlgValues; //type: Srlg::Nodes::Node::SrlgValues
class InterfaceSrlgNames; //type: Srlg::Nodes::Node::InterfaceSrlgNames
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::SrlgMaps> srlg_maps;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::Groups> groups;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::InheritNodes> inherit_nodes;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::Interfaces> interfaces;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::InterfaceDetails> interface_details;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::SrlgValues> srlg_values;
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::InterfaceSrlgNames> interface_srlg_names;
}; // Srlg::Nodes::Node
class Srlg::Nodes::Node::SrlgMaps : public ydk::Entity
{
public:
SrlgMaps();
~SrlgMaps();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class SrlgMap; //type: Srlg::Nodes::Node::SrlgMaps::SrlgMap
ydk::YList srlg_map;
}; // Srlg::Nodes::Node::SrlgMaps
class Srlg::Nodes::Node::SrlgMaps::SrlgMap : public ydk::Entity
{
public:
SrlgMap();
~SrlgMap();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_name; //type: string
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf srlg_name_xr; //type: string
}; // Srlg::Nodes::Node::SrlgMaps::SrlgMap
class Srlg::Nodes::Node::Groups : public ydk::Entity
{
public:
Groups();
~Groups();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Group; //type: Srlg::Nodes::Node::Groups::Group
ydk::YList group;
}; // Srlg::Nodes::Node::Groups
class Srlg::Nodes::Node::Groups::Group : public ydk::Entity
{
public:
Group();
~Group();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf group_name; //type: string
ydk::YLeaf group_name_xr; //type: string
ydk::YLeaf group_values; //type: uint32
class SrlgAttribute; //type: Srlg::Nodes::Node::Groups::Group::SrlgAttribute
ydk::YList srlg_attribute;
}; // Srlg::Nodes::Node::Groups::Group
class Srlg::Nodes::Node::Groups::Group::SrlgAttribute : public ydk::Entity
{
public:
SrlgAttribute();
~SrlgAttribute();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf priority; //type: Priority
ydk::YLeaf srlg_index; //type: uint16
}; // Srlg::Nodes::Node::Groups::Group::SrlgAttribute
class Srlg::Nodes::Node::InheritNodes : public ydk::Entity
{
public:
InheritNodes();
~InheritNodes();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class InheritNode; //type: Srlg::Nodes::Node::InheritNodes::InheritNode
ydk::YList inherit_node;
}; // Srlg::Nodes::Node::InheritNodes
class Srlg::Nodes::Node::InheritNodes::InheritNode : public ydk::Entity
{
public:
InheritNode();
~InheritNode();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf inherit_node_name; //type: string
ydk::YLeaf node_name; //type: string
ydk::YLeaf node_values; //type: uint32
class SrlgAttribute; //type: Srlg::Nodes::Node::InheritNodes::InheritNode::SrlgAttribute
ydk::YList srlg_attribute;
}; // Srlg::Nodes::Node::InheritNodes::InheritNode
class Srlg::Nodes::Node::InheritNodes::InheritNode::SrlgAttribute : public ydk::Entity
{
public:
SrlgAttribute();
~SrlgAttribute();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf priority; //type: Priority
ydk::YLeaf srlg_index; //type: uint16
}; // Srlg::Nodes::Node::InheritNodes::InheritNode::SrlgAttribute
class Srlg::Nodes::Node::Interfaces : public ydk::Entity
{
public:
Interfaces();
~Interfaces();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class Interface; //type: Srlg::Nodes::Node::Interfaces::Interface
ydk::YList interface;
}; // Srlg::Nodes::Node::Interfaces
class Srlg::Nodes::Node::Interfaces::Interface : public ydk::Entity
{
public:
Interface();
~Interface();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf interface_name; //type: string
ydk::YLeaf interface_name_xr; //type: string
ydk::YLeaf value_count; //type: uint32
ydk::YLeaf registrations; //type: uint32
ydk::YLeafList srlg_value; //type: list of uint32
}; // Srlg::Nodes::Node::Interfaces::Interface
class Srlg::Nodes::Node::InterfaceDetails : public ydk::Entity
{
public:
InterfaceDetails();
~InterfaceDetails();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class InterfaceDetail; //type: Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail
ydk::YList interface_detail;
}; // Srlg::Nodes::Node::InterfaceDetails
class Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail : public ydk::Entity
{
public:
InterfaceDetail();
~InterfaceDetail();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf interface_name; //type: string
ydk::YLeaf groups; //type: uint32
ydk::YLeaf nodes; //type: uint32
class SrlgAttribute; //type: Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail::SrlgAttribute
class Rsip; //type: Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail::Rsip
ydk::YList srlg_attribute;
ydk::YList rsip;
}; // Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail
class Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail::SrlgAttribute : public ydk::Entity
{
public:
SrlgAttribute();
~SrlgAttribute();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf priority; //type: Priority
ydk::YLeaf source; //type: Source
ydk::YLeaf source_name; //type: string
ydk::YLeaf srlg_index; //type: uint16
}; // Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail::SrlgAttribute
class Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail::Rsip : public ydk::Entity
{
public:
Rsip();
~Rsip();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf rsip_name; //type: string
}; // Srlg::Nodes::Node::InterfaceDetails::InterfaceDetail::Rsip
class Srlg::Nodes::Node::SrlgValues : public ydk::Entity
{
public:
SrlgValues();
~SrlgValues();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class SrlgValue; //type: Srlg::Nodes::Node::SrlgValues::SrlgValue
ydk::YList srlg_value;
}; // Srlg::Nodes::Node::SrlgValues
class Srlg::Nodes::Node::SrlgValues::SrlgValue : public ydk::Entity
{
public:
SrlgValue();
~SrlgValue();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf value_; //type: uint32
ydk::YLeafList interface_name; //type: list of string
}; // Srlg::Nodes::Node::SrlgValues::SrlgValue
class Srlg::Nodes::Node::InterfaceSrlgNames : public ydk::Entity
{
public:
InterfaceSrlgNames();
~InterfaceSrlgNames();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
class InterfaceSrlgName; //type: Srlg::Nodes::Node::InterfaceSrlgNames::InterfaceSrlgName
ydk::YList interface_srlg_name;
}; // Srlg::Nodes::Node::InterfaceSrlgNames
class Srlg::Nodes::Node::InterfaceSrlgNames::InterfaceSrlgName : public ydk::Entity
{
public:
InterfaceSrlgName();
~InterfaceSrlgName();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_name; //type: string
ydk::YLeaf srlg_name_xr; //type: string
ydk::YLeaf srlg_value; //type: uint32
class Interfaces; //type: Srlg::Nodes::Node::InterfaceSrlgNames::InterfaceSrlgName::Interfaces
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::Nodes::Node::InterfaceSrlgNames::InterfaceSrlgName::Interfaces> interfaces;
}; // Srlg::Nodes::Node::InterfaceSrlgNames::InterfaceSrlgName
class Srlg::Nodes::Node::InterfaceSrlgNames::InterfaceSrlgName::Interfaces : public ydk::Entity
{
public:
Interfaces();
~Interfaces();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList interface_name; //type: list of string
}; // Srlg::Nodes::Node::InterfaceSrlgNames::InterfaceSrlgName::Interfaces
class Srlg::InterfaceSrlgNames : public ydk::Entity
{
public:
InterfaceSrlgNames();
~InterfaceSrlgNames();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class InterfaceSrlgName; //type: Srlg::InterfaceSrlgNames::InterfaceSrlgName
ydk::YList interface_srlg_name;
}; // Srlg::InterfaceSrlgNames
class Srlg::InterfaceSrlgNames::InterfaceSrlgName : public ydk::Entity
{
public:
InterfaceSrlgName();
~InterfaceSrlgName();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf srlg_name; //type: string
ydk::YLeaf srlg_name_xr; //type: string
ydk::YLeaf srlg_value; //type: uint32
class Interfaces; //type: Srlg::InterfaceSrlgNames::InterfaceSrlgName::Interfaces
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::Srlg::InterfaceSrlgNames::InterfaceSrlgName::Interfaces> interfaces;
}; // Srlg::InterfaceSrlgNames::InterfaceSrlgName
class Srlg::InterfaceSrlgNames::InterfaceSrlgName::Interfaces : public ydk::Entity
{
public:
Interfaces();
~Interfaces();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeafList interface_name; //type: list of string
}; // Srlg::InterfaceSrlgNames::InterfaceSrlgName::Interfaces
class Srlg::InheritNodes : public ydk::Entity
{
public:
InheritNodes();
~InheritNodes();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class InheritNode; //type: Srlg::InheritNodes::InheritNode
ydk::YList inherit_node;
}; // Srlg::InheritNodes
class Srlg::InheritNodes::InheritNode : public ydk::Entity
{
public:
InheritNode();
~InheritNode();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf inherit_node_name; //type: string
ydk::YLeaf node_name; //type: string
ydk::YLeaf node_values; //type: uint32
class SrlgAttribute; //type: Srlg::InheritNodes::InheritNode::SrlgAttribute
ydk::YList srlg_attribute;
}; // Srlg::InheritNodes::InheritNode
class Srlg::InheritNodes::InheritNode::SrlgAttribute : public ydk::Entity
{
public:
SrlgAttribute();
~SrlgAttribute();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf priority; //type: Priority
ydk::YLeaf srlg_index; //type: uint16
}; // Srlg::InheritNodes::InheritNode::SrlgAttribute
class Srlg::SrlgValues : public ydk::Entity
{
public:
SrlgValues();
~SrlgValues();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class SrlgValue; //type: Srlg::SrlgValues::SrlgValue
ydk::YList srlg_value;
}; // Srlg::SrlgValues
class Srlg::SrlgValues::SrlgValue : public ydk::Entity
{
public:
SrlgValue();
~SrlgValue();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf value_; //type: uint32
ydk::YLeafList interface_name; //type: list of string
}; // Srlg::SrlgValues::SrlgValue
class Srlg::InterfaceDetails : public ydk::Entity
{
public:
InterfaceDetails();
~InterfaceDetails();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
class InterfaceDetail; //type: Srlg::InterfaceDetails::InterfaceDetail
ydk::YList interface_detail;
}; // Srlg::InterfaceDetails
class Srlg::InterfaceDetails::InterfaceDetail : public ydk::Entity
{
public:
InterfaceDetail();
~InterfaceDetail();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf interface_name; //type: string
ydk::YLeaf groups; //type: uint32
ydk::YLeaf nodes; //type: uint32
class SrlgAttribute; //type: Srlg::InterfaceDetails::InterfaceDetail::SrlgAttribute
class Rsip; //type: Srlg::InterfaceDetails::InterfaceDetail::Rsip
ydk::YList srlg_attribute;
ydk::YList rsip;
}; // Srlg::InterfaceDetails::InterfaceDetail
class Srlg::InterfaceDetails::InterfaceDetail::SrlgAttribute : public ydk::Entity
{
public:
SrlgAttribute();
~SrlgAttribute();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf srlg_value; //type: uint32
ydk::YLeaf priority; //type: Priority
ydk::YLeaf source; //type: Source
ydk::YLeaf source_name; //type: string
ydk::YLeaf srlg_index; //type: uint16
}; // Srlg::InterfaceDetails::InterfaceDetail::SrlgAttribute
class Srlg::InterfaceDetails::InterfaceDetail::Rsip : public ydk::Entity
{
public:
Rsip();
~Rsip();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf rsip_name; //type: string
}; // Srlg::InterfaceDetails::InterfaceDetail::Rsip
class SelectiveVrfDownload : public ydk::Entity
{
public:
SelectiveVrfDownload();
~SelectiveVrfDownload();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class State; //type: SelectiveVrfDownload::State
std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_infra_rsi_oper::SelectiveVrfDownload::State> state;
}; // SelectiveVrfDownload
class SelectiveVrfDownload::State : public ydk::Entity
{
public:
State();
~State();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf is_svd_enabled; //type: boolean
ydk::YLeaf is_svd_enabled_cfg; //type: boolean
}; // SelectiveVrfDownload::State
class Priority : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf critical;
static const ydk::Enum::YLeaf high;
static const ydk::Enum::YLeaf medium;
static const ydk::Enum::YLeaf low;
static const ydk::Enum::YLeaf very_low;
static const ydk::Enum::YLeaf invald;
static int get_enum_value(const std::string & name) {
if (name == "critical") return 0;
if (name == "high") return 1;
if (name == "medium") return 2;
if (name == "low") return 3;
if (name == "very-low") return 4;
if (name == "invald") return 5;
return -1;
}
};
class Source : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf configured;
static const ydk::Enum::YLeaf from_group;
static const ydk::Enum::YLeaf inherited;
static const ydk::Enum::YLeaf from_optical;
static const ydk::Enum::YLeaf configured_and_notified;
static const ydk::Enum::YLeaf from_group_and_notified;
static const ydk::Enum::YLeaf inherited_and_notified;
static const ydk::Enum::YLeaf from_optical_and_notified;
static int get_enum_value(const std::string & name) {
if (name == "configured") return 1;
if (name == "from-group") return 2;
if (name == "inherited") return 4;
if (name == "from-optical") return 8;
if (name == "configured-and-notified") return 17;
if (name == "from-group-and-notified") return 18;
if (name == "inherited-and-notified") return 20;
if (name == "from-optical-and-notified") return 24;
return -1;
}
};
}
}
#endif /* _CISCO_IOS_XR_INFRA_RSI_OPER_ */
| 47.82644 | 162 | 0.683864 | [
"vector"
] |
119743aa00de23c96c0fb9cc5c22e67c92f4b1fa | 11,786 | cpp | C++ | src/arch/x86/SMBIOS.cpp | arthurmco/annOS | 0e8d275c6e2869f7b96a873edaeb4857fc485b24 | [
"MIT"
] | 6 | 2018-01-26T05:44:29.000Z | 2022-02-13T21:59:20.000Z | src/arch/x86/SMBIOS.cpp | arthurmco/annOS | 0e8d275c6e2869f7b96a873edaeb4857fc485b24 | [
"MIT"
] | 9 | 2018-01-17T12:23:21.000Z | 2018-01-25T18:22:13.000Z | src/arch/x86/SMBIOS.cpp | arthurmco/annOS | 0e8d275c6e2869f7b96a873edaeb4857fc485b24 | [
"MIT"
] | null | null | null | #include <arch/x86/SMBIOS.hpp>
#include <libk/stdio.h> // TODO: move strlen it to string.h
#include <libk/stdlib.h>
#include <libk/panic.h>
#include <arch/x86/VMM.hpp>
#include <Log.hpp>
using namespace annos;
using namespace annos::x86;
bool CheckIfChecksumValid(SMBiosEntry* e)
{
char* smb_bytes = (char*)e;
unsigned char chksum_total = 0;
for (unsigned i = 0; i < e->length; i++) {
chksum_total += smb_bytes[i];
}
Log::Write(Debug, "smbios", "Checksum is %d, should be %d at 0x%x",
chksum_total, 0, e);
return (chksum_total == 0);
}
bool SMBios::Detect()
{
/* Check if we find the SMBIOS entry point
It's composed by the characters '_SM_', and it lies in a 16-byte
boundary (aka address ended with 0), between physical addresses
0xf0000 to 0xfffff.
*/
uintptr_t smbios_addr = 0xc00f0000;
const char* entry_magic = "_SM_";
const char* interm_magic = "_DMI_";
while (smbios_addr < 0xc0100000) {
if (!memcmp(entry_magic, (void*)smbios_addr, 4)) {
if (!memcmp(interm_magic, (void*)(smbios_addr+0x10), 5)) {
if (!CheckIfChecksumValid((SMBiosEntry*) smbios_addr)) {
smbios_addr += 0x10;
// TODO: Unmap
continue;
}
smbios_addr -= 0xc0000000;
Log::Write(Info, "smbios", "SMBIOS entry point found at 0x%x",
smbios_addr);
this->_smbios_entry_addr = smbios_addr + 0xc0000000;
return true;
}
}
smbios_addr += 0x10;
}
Log::Write(Warning, "smbios", "No SMBIOS entry point found");
return false;
}
/* Gets the string index 'idx' after the smbios table 'tbl' */
const char* SMBios::GetSMBiosString(SMBiosStrHeader* hdr, unsigned idx)
{
uintptr_t start = ((uintptr_t)hdr) + hdr->length;
unsigned str_idx = 1; // actual string index
unsigned str_off = 0;
// Detect if we have a table with no strings;
// If so, return.
// It should start right at the end of the current table
const char* sch = ((const char*)(start + str_off));
if (sch[0] == '\0' && sch[1] == '\0')
return NULL;
// Process strings until we reach the maximum size possible: the table length
SMBiosEntry* sb = (SMBiosEntry*)this->_smbios_entry_addr;
while ((hdr->length + str_off) < sb->smbios_struct_len) {
if (idx == str_idx)
return ((const char*)(start + str_off));
str_off++;
const char* ch = ((const char*)(start + str_off));
// We found a zero termination
// Next string is another string
if (ch[0] == '\0') {
// We found another one
// End of string table
if (ch[1] == '\0' && ch[2] != '\0')
break;
str_idx++;
str_off++;
} else if (ch[0] <= 31 || ch[0] >= 127) {
// Did some shit, got in a place where it shouldn't
return NULL;
}
}
return NULL;
}
void SMBios::ParseBiosInformation(SMBiosStrHeader* hdr)
{
SMBios_BiosInfo* binfo = (SMBios_BiosInfo*)hdr;
const char* vendor = this->GetSMBiosString(hdr, binfo->vendor_strptr);
const char* version = this->GetSMBiosString(hdr, binfo->version_strptr);
const char* rdate = this->GetSMBiosString(hdr, binfo->releasedate_strptr);
Log::Write(Info, "smbios", "BIOS vendor: %s",
(vendor) ? vendor : "<null>");
Log::Write(Info, "smbios", "BIOS version: %s",
(version) ? version : "<null>");
Log::Write(Info, "smbios", "BIOS release date: %s",
(rdate) ? rdate : "<null>");
Log::Write(Info, "smbios", "BIOS starting segment: %04x",
binfo->starting_segment);
Log::Write(Info, "smbios", "BIOS ROM size: %d kB",
64 * (binfo->rom_size+1));
}
/* Parse SMBIOS board information header */
void SMBios::ParseBoardInformation(SMBiosStrHeader* hdr)
{
SMBios_Baseboard* binfo = (SMBios_Baseboard*)hdr;
const char* manufacturer = this->GetSMBiosString(hdr, binfo->manufacturer_sp);
const char* product = this->GetSMBiosString(hdr, binfo->prodname_sp);
const char* version = this->GetSMBiosString(hdr, binfo->version_sp);
const char* serialnum = this->GetSMBiosString(hdr, binfo->serialnumber_sp);
static const char* boardtype_str[] =
{"", "Unknown", "Other", "Server Blade", "Connectivity Switch",
"System Management Module", "Processor Module", "I/O Module",
"Memory Module", "Daughterboard", "Motherboard",
"Processor/Memory Module", "Processor/IO Module",
"Interconnect board"};
Log::Write(Info, "smbios", "Board type: %s (%x)",
boardtype_str[binfo->board_type], binfo->board_type);
Log::Write(Info, "smbios", "Board Manufacturer: %s", manufacturer);
Log::Write(Info, "smbios", "Board Product: %s", product);
Log::Write(Info, "smbios", "Board Version: %s", version);
Log::Write(Info, "smbios", "Board Serial number: %s",
(serialnum) ? serialnum : "<null>");
}
/* Parse SMBIOS system information header */
void SMBios::ParseSysInformation(SMBiosStrHeader* hdr)
{
SMBios_SysInfo* sinfo = (SMBios_SysInfo*)hdr;
const char* manufacturer = this->GetSMBiosString(hdr, sinfo->manufacturer_sp);
const char* product = this->GetSMBiosString(hdr, sinfo->prodname_sp);
const char* version = this->GetSMBiosString(hdr, sinfo->version_sp);
const char* serialnum = this->GetSMBiosString(hdr, sinfo->serialnumber_sp);
const char* sku = this->GetSMBiosString(hdr, sinfo->serialnumber_sp);
const char* model = this->GetSMBiosString(hdr, sinfo->serialnumber_sp);
Log::Write(Info, "smbios", "Manufacturer: %s",
(manufacturer) ? manufacturer : "<null>");
Log::Write(Info, "smbios", "Product: %s",
(product) ? product : "<null>");
Log::Write(Info, "smbios", "Version: %s",
(version) ? version : "<null>");
Log::Write(Info, "smbios", "Serial number: %s",
(serialnum) ? serialnum : "<null>");
static const char* wake_event_str[] =
{"Reserved", "Other", "Unknown", "APM Timer", "Modem Ring",
"LAN Remote", "Power Switch", "PCI PME#", "AC Power Restored"};
Log::Write(Info, "smbios", "Wake up Type: %s (0x%x)",
wake_event_str[sinfo->wakeup_event], sinfo->wakeup_event);
Log::Write(Info, "smbios", "SKU: %s",
(sku) ? sku : "<null>");
Log::Write(Info, "smbios", "Model: %s",
(model) ? model : "<null>");
}
/* Parse memory device header */
void SMBios::ParseMemDevice(SMBiosStrHeader* hdr)
{
SMBios_MemDevice* minfo = (SMBios_MemDevice*)hdr;
const char* manufacturer = this->GetSMBiosString(hdr, minfo->manufacturer_sp);
const char* serialnum = this->GetSMBiosString(hdr, minfo->serialnumber_sp);
const char* asset_tag = this->GetSMBiosString(hdr, minfo->asset_tag_sp);
const char* part_number = this->GetSMBiosString(hdr, minfo->part_number_sp);
const char* dev_location = this->GetSMBiosString(hdr, minfo->device_location_sp);
const char* bank_location = this->GetSMBiosString(hdr, minfo->bank_location_sp);
Log::Write(Info, "smbios", "Memory located at array handle %04x",
minfo->memarray_handle);
Log::Write(Info, "smbios", "\tLocated at bank %s device %s",
(bank_location) ? bank_location : "<null>",
(dev_location) ? dev_location : "<null>");
unsigned size_kb = 0;
if (minfo->size == 0x7fff)
size_kb = minfo->extended_size * 1024;
else if (minfo->size & 0x8000)
size_kb = minfo->size & 0x7fff;
else
size_kb = minfo->size * 1024;
Log::Write(Info, "smbios", "\tSize: %d MB, %d MHz", size_kb/1024,
minfo->speed_mhz);
Log::Write(Info, "smbios", "\tManufacturer: %s",
(manufacturer) ? manufacturer : "<null>");
Log::Write(Info, "smbios", "\tSerial number: %s",
(serialnum) ? serialnum : "<null>");
Log::Write(Info, "smbios", "\tAsset Tag: %s",
(asset_tag) ? asset_tag : "<null>");
Log::Write(Info, "smbios", "\tPart number: %s",
(part_number) ? part_number : "<null>");
}
/* Parse SMBIOS processor header */
void SMBios::ParseSysProcessor(SMBiosStrHeader* hdr)
{
SMBios_Processor* smproc = (SMBios_Processor*)hdr;
const char* socket = this->GetSMBiosString(hdr, smproc->socket_sp);
const char* proc_manufacturer = this->GetSMBiosString(
hdr, smproc->proc_manufacturer_sp);
const char* proc_version = this->GetSMBiosString(
hdr, smproc->proc_version_sp);
static const char* sproc_type[] =
{"", "Other", "Unknown", "Central Processor", "Math Processor",
"DSP Processor", "Video Processor"};
Log::Write(Info, "smbios", "Processor Socket: %s", socket);
Log::Write(Info, "smbios", "Processor Type: %s (%x)",
sproc_type[smproc->proc_type], smproc->proc_type);
Log::Write(Info, "smbios", "Processor Family: %x", smproc->proc_family);
Log::Write(Info, "smbios", "Processor ID: %08x %08x",
((uint32_t)(smproc->proc_id >> 32)),
((uint32_t)(smproc->proc_id & 0xffffffff)));
Log::Write(Info, "smbios", "Processor Manufacturer: %s",
(proc_manufacturer) ? proc_manufacturer : "<null>");
Log::Write(Info, "smbios", "Processor Version: %s",
(proc_version) ? proc_version : "<null>");
Log::Write(Info, "smbios", "Bus Clock: %d MHz", smproc->clock_mhz);
Log::Write(Info, "smbios", "Processor Max Clock: %d MHz",
smproc->max_speed_mhz);
Log::Write(Info, "smbios", "Processor Current Clock: %d MHz",
smproc->curr_speed_mhz);
}
void SMBios::Initialize()
{
if (!this->_smbios_entry_addr)
if (!this->Detect())
return;
volatile SMBiosEntry* sm_entry = ( SMBiosEntry* )this->_smbios_entry_addr;
Log::Write(Info, "smbios", "entry point: len 0x%x, version %d.%d",
sm_entry->length, sm_entry->major, sm_entry->minor);
Log::Write(Info, "smbios", " maxstructsize %d, ep_revision %02x",
sm_entry->max_structure_size, sm_entry->entry_point_revision);
Log::Write(Info, "smbios", " smbios_addr %x, len %d, count %d",
sm_entry->smbios_struct_addr, sm_entry->smbios_struct_len,
sm_entry->smbios_struct_count);
/* Map 2 pages for guarding agains the smbios_struct_addr being near the end
* of a page.
* The MapPhysicalAddress starts mapping in the start, so you wouldn't even
* use a page properly before it ends
*/
uintptr_t smbios_ptr = sm_entry->smbios_struct_addr;
if (smbios_ptr > 0xf0000)
smbios_ptr = VMM::MapPhysicalAddress(sm_entry->smbios_struct_addr,
(sm_entry->smbios_struct_len/VMM_PAGE_SIZE)+2);
for (int i = 0; i < sm_entry->smbios_struct_count; i++) {
SMBiosStrHeader* smheader = (SMBiosStrHeader*)smbios_ptr;
Log::Write(Debug, "smbios", "struct %d is type %02d len %d handle %04x "
"address 0x%08x",
(i+1), smheader->type, smheader->length, smheader->handle,
smbios_ptr);
switch (smheader->type) {
case 0: this->ParseBiosInformation(smheader); break;
case 1: this->ParseSysInformation(smheader); break;
case 2: this->ParseBoardInformation(smheader); break;
case 4: this->ParseSysProcessor(smheader); break;
case 17: this->ParseMemDevice(smheader); break;
}
// The string table isn't considered in the smbios length field
// Why? i don't know.
// So we need to traverse it to determine the correct pointer to
// the next one
// The formula is:
// length_of_all_strings + idx + 1
// idx is for all zeros of the zero-terminated strings
// +1 is for the last \0
int max_idx = 1;
int strlength = 0;
const char* smstr = this->GetSMBiosString(smheader, max_idx);
while (smstr != NULL) {
// Log::Write(Debug, "smbios", "Found string: %s", smstr);
strlength += strlen(smstr)+1;
max_idx++;
smstr = this->GetSMBiosString(smheader, max_idx);
}
if (strlength > 0)
strlength += 1;
else
strlength += 2;
smbios_ptr += (smheader->length + strlength);
}
}
| 33.674286 | 85 | 0.644748 | [
"model"
] |
11995ce1970799a9075d0bd7fbe1ce0e4e380559 | 2,938 | cpp | C++ | src/Core/Validation/TransactionValidator.cpp | Paouky/GrinPlusPlus | b24e656547b45d39bc9dddc3e7dd7ee04f6c8798 | [
"MIT"
] | null | null | null | src/Core/Validation/TransactionValidator.cpp | Paouky/GrinPlusPlus | b24e656547b45d39bc9dddc3e7dd7ee04f6c8798 | [
"MIT"
] | null | null | null | src/Core/Validation/TransactionValidator.cpp | Paouky/GrinPlusPlus | b24e656547b45d39bc9dddc3e7dd7ee04f6c8798 | [
"MIT"
] | null | null | null | #include <Core/Validation/TransactionValidator.h>
#include <Core/Validation/TransactionBodyValidator.h>
#include <Consensus.h>
#include <Common/Util/HexUtil.h>
#include <Core/Validation/KernelSumValidator.h>
#include <Common/Logger.h>
#include <algorithm>
#include <numeric>
// See: https://github.com/mimblewimble/docs/wiki/Validation-logic
void TransactionValidator::Validate(const Transaction& transaction, const uint64_t block_height) const
{
// Verify the transaction does not exceed the max weight
ValidateWeight(transaction.GetBody(), block_height);
// Validate the "transaction body"
TransactionBodyValidator().Validate(transaction.GetBody());
// Verify no output or kernel includes invalid features (coinbase)
ValidateFeatures(transaction.GetBody());
// Verify the big "sum": all inputs plus reward+fee, all output commitments, all kernels plus the kernel excess
ValidateKernelSums(transaction);
}
void TransactionValidator::ValidateWeight(const TransactionBody& body, const uint64_t block_height) const
{
uint64_t weight = body.CalcWeight(block_height);
// Reserve enough space for a coinbase output and kernel
uint64_t reserve_weight = (Consensus::OUTPUT_WEIGHT + Consensus::KERNEL_WEIGHT);
if ((weight + reserve_weight) > Consensus::MAX_BLOCK_WEIGHT) {
throw BAD_DATA_EXCEPTION("Transaction exceeds maximum weight");
}
}
void TransactionValidator::ValidateFeatures(const TransactionBody& transactionBody) const
{
// Verify no output features.
const bool hasCoinbaseOutputs = std::any_of(
transactionBody.GetOutputs().cbegin(),
transactionBody.GetOutputs().cend(),
[](const TransactionOutput& output) { return output.IsCoinbase(); }
);
if (hasCoinbaseOutputs)
{
throw BAD_DATA_EXCEPTION("Transaction contains coinbase outputs.");
}
// Verify no kernel features.
const bool hasCoinbaseKernels = std::any_of(
transactionBody.GetKernels().cbegin(),
transactionBody.GetKernels().cend(),
[](const TransactionKernel& kernel) { return kernel.IsCoinbase(); }
);
if (hasCoinbaseKernels)
{
throw BAD_DATA_EXCEPTION("Transaction contains coinbase kernels.");
}
}
// Verify the sum of the kernel excesses equals the sum of the outputs, taking into account both the kernel_offset and overage.
void TransactionValidator::ValidateKernelSums(const Transaction& transaction) const
{
// Calculate overage
const std::vector<TransactionKernel>& blockKernels = transaction.GetKernels();
const int64_t overage = std::accumulate(
blockKernels.cbegin(),
blockKernels.cend(),
(int64_t)0,
[](int64_t overage, const TransactionKernel& kernel) { return overage + (int64_t)kernel.GetFee(); }
);
try
{
KernelSumValidator::ValidateKernelSums(transaction.GetBody(), overage, transaction.GetOffset(), std::nullopt);
}
catch (std::exception& e)
{
LOG_WARNING_F("Kernel sum validation failed with error: {}", e.what());
throw BAD_DATA_EXCEPTION("Kernel sum validation failed.");
}
} | 34.564706 | 127 | 0.76855 | [
"vector"
] |
11aaf30aae503cda93f0d2aeb9d0135912f064ce | 515 | hpp | C++ | ReceiverModule/environment_checker.hpp | Engin-Boot/environment-case-s1b12 | c7687cf9cdd927442ba4bd43cad573ce6f01e98b | [
"MIT"
] | null | null | null | ReceiverModule/environment_checker.hpp | Engin-Boot/environment-case-s1b12 | c7687cf9cdd927442ba4bd43cad573ce6f01e98b | [
"MIT"
] | null | null | null | ReceiverModule/environment_checker.hpp | Engin-Boot/environment-case-s1b12 | c7687cf9cdd927442ba4bd43cad573ce6f01e98b | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "Logger.hpp"
using namespace std;
extern void checkwhetherhigtemp(double temp, Logger& log);
extern void checkwhetherveryhightemp(double temp, Logger& log);
extern void checkwhetherlowtemp(double temp, Logger& log);
extern void checkwhetherverylowtemp(double temp, Logger& log);
extern void checkwhetherhighhumidity(double hum, Logger& log);
extern void checkwhetherveryhighhumidity(double hum, Logger& log);
extern void check_environment(vector<double> & v, Logger& log); | 39.615385 | 66 | 0.803883 | [
"vector"
] |
11aee68dd321ae7214f7bcd127dce8f823d96eef | 1,153 | cpp | C++ | code/src/cpp/helpers/solution.cpp | vdm370/partii-proj | bf07f6c8682666c069e06187e2fd762d938d3070 | [
"MIT"
] | null | null | null | code/src/cpp/helpers/solution.cpp | vdm370/partii-proj | bf07f6c8682666c069e06187e2fd762d938d3070 | [
"MIT"
] | null | null | null | code/src/cpp/helpers/solution.cpp | vdm370/partii-proj | bf07f6c8682666c069e06187e2fd762d938d3070 | [
"MIT"
] | null | null | null | #include "solution.h"
#include "graph_dist.h"
#include <unordered_set>
#include <float.h>
const double EPS = 1e-8;
solution::solution() {
value = DBL_MAX;
}
solution::solution(double val, vector<int> ind) {
value = val;
order = ind;
}
bool solution::operator<(const solution &other) const {
return value < other.value;
}
bool solution::sane(graph_dist &g) {
puts("------ Checking sanity --------");
print(true);
int n = g.nodes;
unordered_set<int> act;
for(auto &x : order) {
if(x < 0 || x >= n) return false;
act.insert(x);
}
printf("total nodes: %d\n", n);
printf("different nodes: %d\n", (int)act.size());
if((int)act.size() != n) return false;
puts("all nodes are correct");
double cost = 0;
for(int i = 0; i + 1 < n; i++) {
cost += g.dist[order[i]][order[i + 1]];
}
cost += g.dist[order.back()][order[0]];
printf("%.3f %.3f\n", cost, value);
return abs(cost - value) < EPS;
}
void solution::print(bool path) {
if(path) {
for(int i = 0; i < (int)order.size(); i++) {
if(i + 1 == (int)order.size()) printf("%d\n", order[i]);
else printf("%d ", order[i]);
}
}
printf("Solved the TSP with: %.2f\n", value);
}
| 24.531915 | 59 | 0.597572 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.