hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
08977ddae548d0bfbf421be88bd8b7a67d5dfde7 | 1,753 | hpp | C++ | src/MeshEdge.hpp | Loic-Corenthy/miniGL | 47976ea80e253e115eafae5934ec3ebdd2275d16 | [
"MIT"
] | 1 | 2021-08-18T03:54:22.000Z | 2021-08-18T03:54:22.000Z | src/MeshEdge.hpp | Loic-Corenthy/miniGL | 47976ea80e253e115eafae5934ec3ebdd2275d16 | [
"MIT"
] | null | null | null | src/MeshEdge.hpp | Loic-Corenthy/miniGL | 47976ea80e253e115eafae5934ec3ebdd2275d16 | [
"MIT"
] | null | null | null | //===============================================================================================//
/*!
* \file MeshEdge.hpp
* \author Loïc Corenthy
* \version 1.0
*/
//===============================================================================================//
#pragma once
#include <iostream>
namespace miniGL
{
/*!
* \brief Helper class to store a simple edge
* \details Stores an edge by its vertices and forces a specific order between them
*/
class MeshEdge
{
public:
/*!
* \brief Constructor with vertices
* @param pA is the index of the first vertex
* @param pB is the index of the second vertex
*/
MeshEdge(unsigned int pA, unsigned int pB);
/*!
* \brief Display the indices
*/
void display(void) const;
/*!
* \brief Set the index associated to the first vertex
* @param pIndex is the index associated to vertex "a"
*/
void a(unsigned int pIndex) noexcept;
/*!
* \brief Set the index associated to the second vertex
* @param pIndex is the index associated to vertex "b"
*/
void b(unsigned int pIndex) noexcept;
/*!
* \brief Get the index associated to the first vertex
* @return the index associated to vertex "a"
*/
unsigned int a(void) const noexcept;
/*!
* \brief Get the index associated to the second vertex
* @return the index associated to vertex "b"
*/
unsigned int b(void) const noexcept;
private:
unsigned int mA;
unsigned int mB;
}; // class MeshEdge
} // namespace miniGL
| 26.969231 | 99 | 0.494581 | Loic-Corenthy |
0899ccf06636c1042c59495e100b31d6e944693b | 1,211 | cc | C++ | src/solvers/wg/WGPreconditioner.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/solvers/wg/WGPreconditioner.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/solvers/wg/WGPreconditioner.cc | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*----------------------------------//
/**
* @file WGPreconditioner.cc
* @brief WGPreconditioner
* @author Jeremy Roberts
* @date Nov 11, 2012
*/
//---------------------------------------------------------------------------//
#include "WGPreconditioner.hh"
namespace detran
{
//---------------------------------------------------------------------------//
WGPreconditioner::WGPreconditioner(SP_input input,
SP_material material,
SP_mesh mesh,
std::string name)
: Base(name)
, d_input(input)
, d_material(material)
, d_mesh(mesh)
{
// Preconditions
Require(d_input);
Require(d_material);
Require(d_mesh);
// Number of groups
d_number_groups = d_material->number_groups();
// Size the solver and operator vectors
d_solver.resize(d_number_groups);
d_operator.resize(d_number_groups);
}
} // end namespace detran
//---------------------------------------------------------------------------//
// end of file WGPreconditioner.cc
//---------------------------------------------------------------------------//
| 27.522727 | 79 | 0.410405 | RLReed |
089c3d4542c573977e03099c1eab3ab89245371d | 2,040 | hpp | C++ | include/octargs/subparser_argument.hpp | KOLANICH/octargs | e2dfb9715a676c6a7a49b7dac7b2b71bfd9143ef | [
"MIT"
] | 4 | 2020-03-23T16:30:11.000Z | 2021-12-21T10:07:38.000Z | include/octargs/subparser_argument.hpp | KOLANICH/octargs | e2dfb9715a676c6a7a49b7dac7b2b71bfd9143ef | [
"MIT"
] | 32 | 2020-01-28T22:29:59.000Z | 2021-12-21T10:05:36.000Z | include/octargs/subparser_argument.hpp | KOLANICH/octargs | e2dfb9715a676c6a7a49b7dac7b2b71bfd9143ef | [
"MIT"
] | 1 | 2021-07-22T16:50:08.000Z | 2021-07-22T16:50:08.000Z | #ifndef OCTARGS_SUBPARSER_ARGUMENT_HPP_
#define OCTARGS_SUBPARSER_ARGUMENT_HPP_
#include "argument_base.hpp"
#include "internal/subparser_argument_impl.hpp"
namespace oct
{
namespace args
{
template <typename char_T, typename values_storage_T>
class basic_parser;
/// \brief Subparser argument
///
/// Subparser argument is a 'virtual' argument that allows registering
/// subparsers so it is possible to implement a command based user interface
/// (e.g. like the one provided by "git" command).
///
/// \tparam char_T char type (as in std::basic_string)
/// \tparam values_storage_T type of class uses as a storage for parsed values
/// \tparam data_T argument value data type
template <typename char_T, typename values_storage_T, typename data_T = void>
class basic_subparser_argument : public basic_argument_base<basic_subparser_argument,
internal::basic_subparser_argument_impl, char_T, values_storage_T, data_T>
{
public:
using char_type = char_T;
using values_storage_type = values_storage_T;
using data_type = data_T;
using base_type = basic_argument_base<oct::args::basic_subparser_argument, internal::basic_subparser_argument_impl,
char_T, values_storage_T, data_T>;
using parser_type = basic_parser<char_type, values_storage_type>;
using string_type = typename base_type::string_type;
using argument_ptr_type = typename base_type::argument_ptr_type;
explicit basic_subparser_argument(const argument_ptr_type& argument_ptr)
: base_type(argument_ptr)
{
// noop
}
template <typename handler_ptr_T>
explicit basic_subparser_argument(const argument_ptr_type& argument_ptr, const handler_ptr_T& handler_ptr)
: base_type(argument_ptr, handler_ptr)
{
// noop
}
parser_type add_parser(const string_type& name)
{
return this->get_argument().add_parser(name);
}
};
} // namespace args
} // namespace oct
#endif // OCTARGS_SUBPARSER_ARGUMENT_HPP_
| 31.875 | 119 | 0.734314 | KOLANICH |
089de3af826a5dd0b157e1514fad6dd002c5fec5 | 9,079 | cpp | C++ | src/main/resources/main/c++/World.cpp | yildiz-online/module-physics-bullet | f40d947686a7d9073bdfc213a9fb898924a93e90 | [
"MIT"
] | null | null | null | src/main/resources/main/c++/World.cpp | yildiz-online/module-physics-bullet | f40d947686a7d9073bdfc213a9fb898924a93e90 | [
"MIT"
] | 10 | 2018-11-19T20:36:02.000Z | 2021-12-03T03:03:52.000Z | src/main/resources/main/c++/World.cpp | yildiz-online/module-physics-bullet | f40d947686a7d9073bdfc213a9fb898924a93e90 | [
"MIT"
] | null | null | null | /*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* 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 "../includes/World.hpp"
#include "../includes/KinematicMotionState.hpp"
#include "../includes/DynamicMotionState.hpp"
#include <algorithm>
/**
* @author Grégory Van den Borre
*/
yz::World::World() {
this->ghostPairCallback = new btGhostPairCallback();
this->broadphase = new btDbvtBroadphase();
this->broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(
this->ghostPairCallback);
this->collisionConfiguration = new btDefaultCollisionConfiguration();
this->dispatcher = new btCollisionDispatcher(collisionConfiguration);
this->solver = new btSequentialImpulseConstraintSolver;
this->world = new btDiscreteDynamicsWorld(this->dispatcher,
this->broadphase, this->solver, this->collisionConfiguration);
}
yz::World::~World() {
for (int i = this->world->getNumCollisionObjects() - 1; i >= 0; i--) {
btCollisionObject* obj = this->world->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState()) {
delete body->getMotionState();
}
this->world->removeCollisionObject(obj);
delete obj;
}
delete this->world;
delete this->solver;
delete this->dispatcher;
delete this->collisionConfiguration;
delete this->broadphase;
delete this->ghostPairCallback;
}
yz::RigidBody* yz::World::createStaticBody(
btCollisionShape* shape,
const btVector3& position,
const btVector3& direction,
const long id) {
btScalar mass = 0;
btVector3 inertia(0, 0, 0);
btTransform trans;
trans.setIdentity();
trans.setOrigin(position);
yz::RigidBody* body = new yz::RigidBody(mass, new btDefaultMotionState(trans),
shape, inertia, new yz::NativeMovable());
body->setCollisionFlags(
body->getCollisionFlags() | btCollisionObject::CF_STATIC_OBJECT);
body->setActivationState(ISLAND_SLEEPING);
this->ids[body] = id;
world->addRigidBody(body);
return body;
}
yz::RigidBody* yz::World::createKinematicBody(
btCollisionShape* shape,
const long id,
const float x,
const float y,
const float z) {
btScalar mass = 0;
btVector3 inertia(0, 0, 0);
btTransform transform;
transform.setOrigin(btVector3(x, y, z));
yz::RigidBody* body = new yz::RigidBody(mass, new KinematicMotionState(transform), shape, inertia,
new yz::NativeMovable());
body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
body->setActivationState(DISABLE_DEACTIVATION);
world->addRigidBody(body,
body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT,
btCollisionObject::CF_KINEMATIC_OBJECT
| btCollisionObject::CO_GHOST_OBJECT);
this->ids[body] = id;
return body;
}
yz::RigidBody* yz::World::createDynamicBody(
btCollisionShape* shape,
const long id,
const float x,
const float y,
const float z,
const float mass) {
btVector3 inertia(0, 0, 0);
shape->calculateLocalInertia(mass, inertia);
btTransform transform;
transform.setOrigin(btVector3(x, y, z));
yz::DynamicMotionState* s = new yz::DynamicMotionState(transform);
yz::RigidBody* body = new yz::RigidBody(mass, s, shape, inertia, s->getMovable());
world->addRigidBody(body);
this->ids[body] = id;
return body;
}
btGhostObject* yz::World::createGhostObject(btCollisionShape* shape, const long id, const float x, const float y,
const float z) {
btGhostObject* ghostObject = new btGhostObject();
ghostObject->setCollisionShape(shape);
ghostObject->setWorldTransform(btTransform(btQuaternion(0, 0, 0, 1), btVector3(x, y, z)));
this->world->addCollisionObject(ghostObject, btCollisionObject::CO_GHOST_OBJECT,
btCollisionObject::CF_KINEMATIC_OBJECT);
this->ghostIds[ghostObject] = id;
return ghostObject;
}
void yz::World::removeGhost(btGhostObject* ghost) {
ghost->activate(false);
this->world->removeCollisionObject(ghost);
long id = this->ghostIds[ghost];
this->ghostCollisionResult.erase(
std::remove(this->ghostCollisionResult.begin(),
this->ghostCollisionResult.end(), id),
this->ghostCollisionResult.end());
this->ghostIds.erase(ghost);
delete ghost;
}
std::vector<jlong> yz::World::update(const long time) {
this->world->stepSimulation(time / 1000.0f, 7);
this->ghostCollisionResult.clear();
btCollisionObjectArray& collisionObjects = this->world->getCollisionObjectArray();
for (int i = 0; i < this->world->getNumCollisionObjects(); i++) {
btGhostObject* ghost = btGhostObject::upcast(collisionObjects.at(i));
if (ghost) {
btAlignedObjectArray<btCollisionObject*> objsInsidePairCachingGhostObject;
objsInsidePairCachingGhostObject.resize(0);
for (int j = 0; j < ghost->getNumOverlappingObjects(); j++) {
btCollisionObject* co = ghost->getOverlappingObject(j);
if (co) {
btRigidBody *pRigidBody = btRigidBody::upcast(co);
if (pRigidBody) {
jlong g = this->ghostIds[ghost];
jlong b = this->ids[pRigidBody];
if (b != g) {
this->ghostCollisionResult.push_back(g);
this->ghostCollisionResult.push_back(b);
}
}
}
}
}
}
//Retrieve rigid to rigid collisions.
int numManifolds = this->world->getDispatcher()->getNumManifolds();
std::vector<jlong> collisionList;
for (int i = 0; i < numManifolds; i++) {
btPersistentManifold* contactManifold = this->world->getDispatcher()->getManifoldByIndexInternal(i);
int numContacts = contactManifold->getNumContacts();
if (numContacts > 0) {
const btCollisionObject* firstCo = contactManifold->getBody0();
const btCollisionObject* secondCo = contactManifold->getBody1();
if (btRigidBody::upcast(firstCo) && btRigidBody::upcast(secondCo)) {
jlong firstId = this->ids[firstCo];
jlong secondId = this->ids[secondCo];
if (firstId && secondId) {
collisionList.push_back(firstId);
collisionList.push_back(secondId);
}
}
}
}
return collisionList;
}
long yz::World::rayCast(const btVector3& origin, const btVector3& end) const {
btCollisionWorld::ClosestRayResultCallback result(origin, end);
this->world->getCollisionWorld()->rayTest(origin, end, result);
long id = this->ids.at(result.m_collisionObject);
return id == 0 ? -1L : id;
}
long yz::World::rayCast(
const btVector3& origin,
const btVector3& end,
btCollisionWorld::ClosestRayResultCallback& result) const {
this->world->getCollisionWorld()->rayTest(origin, end, result);
long id = this->ids.at(result.m_collisionObject);
return id == 0 ? -1L : id;
}
void yz::World::rayCastPoint(
const btVector3& origin,
const btVector3& end,
float* resultArray) const {
btCollisionWorld::ClosestRayResultCallback result(origin, end);
this->world->getCollisionWorld()->rayTest(origin, end, result);
if (!result.hasHit()) {
resultArray[0] = -1;
resultArray[1] = 0;
resultArray[2] = 0;
resultArray[3] = 0;
} else {
btVector3 contact = result.m_hitPointWorld;
resultArray[0] = this->ids.at(result.m_collisionObject);
resultArray[1] = contact.getX();
resultArray[2] = contact.getY();
resultArray[3] = contact.getZ();
}
}
| 38.799145 | 119 | 0.660645 | yildiz-online |
08a1dd5ae3585187cbce42bca114816e809d687c | 4,266 | cpp | C++ | Ikasesteka/Classes/Scenes/Win.cpp | irontec/Ikasesteka | e5c33445f7ed4aefae7cebbc4f60b00fc943c6eb | [
"MIT"
] | 2 | 2015-02-28T02:49:32.000Z | 2019-08-31T23:09:48.000Z | Ikasesteka/Classes/Scenes/Win.cpp | irontec/Ikasesteka | e5c33445f7ed4aefae7cebbc4f60b00fc943c6eb | [
"MIT"
] | null | null | null | Ikasesteka/Classes/Scenes/Win.cpp | irontec/Ikasesteka | e5c33445f7ed4aefae7cebbc4f60b00fc943c6eb | [
"MIT"
] | 1 | 2019-12-25T01:42:10.000Z | 2019-12-25T01:42:10.000Z | //
// Win.cpp
// IkasGame
//
// Created by Sergio Garcia on 11/2/15.
//
//
#include "Win.h"
#include "../Singletons/GameSettingsManager.h"
#include "../Singletons/SceneManager.h"
#include "../Singletons/SoundManager.h"
#include "../Singletons/AppManager.h"
#include "../Helpers/LanguageManager.h"
#include "../Helpers/ScreenSizeManager.h"
#include "../Helpers/ImageManager.h"
#include "../CustomGUI/SpriteButton.h"
Scene* Win::createScene()
{
SceneManager::getInstance()->saveCurrentScene();
auto *scene = Scene::create();
auto *layer = Win::create();
layer->setTag(2339);
scene->addChild(layer);
return scene;
}
bool Win::init()
{
if (!Layer::init())
{
return false;
}
Rect visibleRect = ScreenSizeManager::getVisibleRect();
auto background = Sprite::create(ImageManager::getImage("background"), visibleRect);
background->setPosition(ScreenSizeManager::getScreenPositionFromPercentage(50, 50));
background->setAnchorPoint(Point::ANCHOR_MIDDLE);
this->addChild(background);
auto buttonNextGamePlay = SpriteButton::create(ImageManager::getImage("play"), 1.0f, CC_CALLBACK_1(Win::loadNextGamePlay, this));
buttonNextGamePlay->setAnchorPoint(Point::ANCHOR_MIDDLE);
Vec2 positionButtonNextGamePlay = ScreenSizeManager::getScreenPositionFromPercentage(50, 50);
buttonNextGamePlay->setPosition(positionButtonNextGamePlay);
this->addChild(buttonNextGamePlay);
auto winTitle = Sprite::create(ImageManager::getImage("win-title"));
winTitle->setScale(0.75f);
Vec2 positionWinTitle = buttonNextGamePlay->getPosition();
positionWinTitle.y += buttonNextGamePlay->getBoundingBox().size.height / 2;
positionWinTitle.y += ScreenSizeManager::getHeightFromPercentage(2);
winTitle->setPosition(positionWinTitle);
winTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM);
this->addChild(winTitle);
auto labelResume = Label::createWithTTF(LanguageManager::getLocalizedText("Win", "resume"), MainRegularFont, 70);
labelResume->setAlignment(TextHAlignment::CENTER);
labelResume->setAnchorPoint(Point::ANCHOR_MIDDLE_TOP);
labelResume->setTextColor(IkasGrayDark);
Vec2 positionLabelResume = buttonNextGamePlay->getPosition();
positionLabelResume.y -= buttonNextGamePlay->getBoundingBox().size.height / 2;
positionLabelResume.y -= ScreenSizeManager::getHeightFromPercentage(1);
labelResume->setPosition(positionLabelResume);
this->addChild(labelResume);
auto buttonSoundSettings = SpriteButton::create(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage), 0.30f, CC_CALLBACK_1(Win::switchSoundSettings, this));
buttonSoundSettings->setAnchorPoint(Point::ANCHOR_MIDDLE);
Vec2 positionButtonSoundSettings = ScreenSizeManager::getScreenPositionFromPercentage(80, 15);
buttonSoundSettings->setPosition(positionButtonSoundSettings);
this->addChild(buttonSoundSettings);
auto buttonHome = SpriteButton::create(ImageManager::getImage("home"), 0.30f, CC_CALLBACK_1(Win::returnHome, this));
buttonHome->setAnchorPoint(Point::ANCHOR_MIDDLE);
Vec2 positionButtonHome = ScreenSizeManager::getScreenPositionFromPercentage(22, 15);
buttonHome->setPosition(positionButtonHome);
this->addChild(buttonHome);
return true;
}
void Win::loadNextGamePlay(Ref* sender)
{
SoundManager::getInstance()->sfxPlay("button");
SceneManager::getInstance()->loadSavedScene();
AppManager::getInstance()->loadNextGamePlay();
}
void Win::switchSoundSettings(Ref* sender)
{
SoundManager::getInstance()->sfxPlay("button");
GameSettingsManager::getInstance()->switchSFX();
GameSettingsManager::getInstance()->switchMusic();
SpriteButton *item = static_cast<SpriteButton*>(sender);
item->setTexture(ImageManager::getImage(GameSettingsManager::getInstance()->getIsSFXOn() ? SoundEnableImage : SoundDisableImage));
}
void Win::returnHome(Ref* sender)
{
SoundManager::getInstance()->sfxPlay("button");
AppManager::getInstance()->setGamePlayDelegate(NULL);
SceneManager::getInstance()->runSceneWithType(SceneType::MAIN);
SceneManager::getInstance()->removeSavedScene();
} | 39.137615 | 219 | 0.7391 | irontec |
08a4f58321af313b9087d71f731a466cc776acf1 | 2,668 | cpp | C++ | third-party/Empirical/demos/utils/data/Histogram.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/demos/utils/data/Histogram.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/demos/utils/data/Histogram.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | #include "../../../include/emp/base/vector.hpp"
#include "../../../include/emp/config/command_line.hpp"
#include "../../../include/emp/config/SettingConfig.hpp"
#include "../../../include/emp/data/DataLog.hpp"
#include "../../../include/emp/io/File.hpp"
#include "../../../include/emp/datastructs/vector_utils.hpp"
#include "../../../include/emp/math/stats.hpp"
int main(int argc, char* argv[])
{
emp::SettingConfig config;
size_t num_bins = 40;
config.AddSetting("num_bins", "How many bins in histogram?", 'b', num_bins) = 40;
config.ProcessOptions(argc, argv);
auto unused_args = config.GetUnusedArgs();
if (unused_args.size() != 1) {
std::cout << "Must include a single filename for data." << std::endl;
exit(1);
}
emp::File file(unused_args[0]);
file.RemoveWhitespace(); // Clear out all whitespace in file.
file.RemoveEmpty(); // Remove all now-empty lines from file.
if (file.GetNumLines() == 0) {
std::cout << "No data found. Exiting." << std::endl;
exit(2);
}
std::cout << "Found data for " << file.GetNumLines() << " histograms." << std::endl;
auto data = file.ToData<double>();
// Analyze base data.
double min_val = data[0][0];
double max_val = min_val;
double total_val = 0.0;
size_t num_vals = 0;
for (auto & row : data) {
for (double val : row) {
if (val < min_val) min_val = val;
if (val > max_val) max_val = val;
total_val += val;
num_vals++;
}
}
// Collect the full histogram.
double full_span = (max_val - min_val) * 1.00001;
double bin_width = full_span / (double) num_bins;
emp::vector<size_t> bin_counts(num_bins, 0);
for (auto & row : data) {
for (double val : row) {
size_t cur_bin = (size_t) ((val - min_val) / bin_width);
bin_counts[cur_bin]++;
}
}
size_t max_bin_count = 0;
for (size_t count : bin_counts) if (count > max_bin_count) max_bin_count = count;
while (file.GetNumLines()) {
emp::DataLog<double> row = file.ExtractRowAs<double>();
std::cout << "MIN_VAL: " << min_val << std::endl;
row.AsciiHistogram();
std::cout << "MAX_VAL: " << max_val << std::endl;
}
std::cout << "OVERALL COUNT: " << num_vals << std::endl;
std::cout << "OVERALL MIN: " << min_val << std::endl;
std::cout << "OVERALL MAX: " << max_val << std::endl;
std::cout << "OVERALL MEAN: " << (total_val/(double) num_vals) << std::endl;
emp::AsciiBarGraph(bin_counts);
double scale = ((double) max_bin_count) / 80.0;
if (scale < 1.0) scale = 1.0;
for (size_t count : bin_counts) {
for (size_t i = 0; i < (count/scale); i++) std::cout << "*";
std::cout << std::endl;
}
}
| 29.977528 | 86 | 0.609445 | koellingh |
08a5df737092834f14a7425440bd9084c8edd30c | 646 | cc | C++ | src/utils/toft_storage_sharding_fingerprint_sharding.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | 1 | 2021-01-11T14:19:51.000Z | 2021-01-11T14:19:51.000Z | src/utils/toft_storage_sharding_fingerprint_sharding.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | src/utils/toft_storage_sharding_fingerprint_sharding.cc | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013, The Toft Authors.
// All rights reserved.
//
// Author: Ye Shunping <yeshunping@gmail.com>
// toft/storage/sharding/fingerprint_sharding.cc
#include "utils/toft_storage_sharding_fingerprint_sharding.h"
#include "utils/toft_hash_fingerprint.h"
namespace bubblefs {
namespace mytoft {
FingerprintSharding::FingerprintSharding() {
}
FingerprintSharding::~FingerprintSharding() {
}
int FingerprintSharding::Shard(const std::string& key) {
int shard_id = Fingerprint64(key) % (shard_num_);
return shard_id;
}
MYTOFT_REGISTER_SHARDING_POLICY(FingerprintSharding);
} // namespace mytoft
} // namespace bubblefs
| 21.533333 | 61 | 0.764706 | pengdu |
08a5fb79be8d1ac00a44dc45b68db71184c74a7f | 672 | cpp | C++ | main.cpp | andrea993/SPR_Denoiser | 9b8f6bca9bb11922b7b6a257996d0b8f217851fd | [
"MIT"
] | null | null | null | main.cpp | andrea993/SPR_Denoiser | 9b8f6bca9bb11922b7b6a257996d0b8f217851fd | [
"MIT"
] | null | null | null | main.cpp | andrea993/SPR_Denoiser | 9b8f6bca9bb11922b7b6a257996d0b8f217851fd | [
"MIT"
] | 1 | 2020-05-19T17:49:14.000Z | 2020-05-19T17:49:14.000Z | #include <iostream>
#include <cstdlib>
#include "denoiser.hpp"
#include <eigen3/Eigen/Dense>
std::istream& operator>>(std::istream& is, Eigen::VectorXd& v) {
int size;
is >> size;
v.resize(size);
for(int i = 0; i < size; ++i) {
is >> v(i);
}
return is;
}
int main() {
Denoiser den;
while(true) {
Eigen::Vector2d in_sample;
std::cin >> in_sample(0) >> in_sample(1);
if(std::cin.fail()) {
break;
}
auto out_sample = den.GetSmp(in_sample);
std::cout << out_sample(0) << ' ' << out_sample(1) << '\n';
};
return EXIT_SUCCESS;
} | 19.764706 | 68 | 0.5 | andrea993 |
08a9a6b7b66b944152d462945f622cd5f94dd38a | 754 | cpp | C++ | tools/AppInsights/src/core/contracts/StackFrame.cpp | crossmob/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 6,717 | 2015-08-06T18:04:37.000Z | 2019-05-04T12:38:51.000Z | tools/AppInsights/src/core/contracts/StackFrame.cpp | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 2,711 | 2015-08-06T18:41:09.000Z | 2019-04-29T12:14:23.000Z | tools/AppInsights/src/core/contracts/StackFrame.cpp | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 1,021 | 2015-08-06T18:08:56.000Z | 2019-04-14T06:50:57.000Z | #include "StackFrame.h"
using namespace ApplicationInsights::core;
StackFrame::StackFrame()
{
}
StackFrame::~StackFrame()
{
}
void StackFrame::Serialize(Serializer& serializer) const
{
serializer.WritePropertyName(L"level");
serializer.WriteIntegerValue(m_level);
serializer.WritePropertyName(L"method");
serializer.WriteStringValue(m_method);
if (!m_assembly.empty())
{
serializer.WritePropertyName(L"assembly");
serializer.WriteStringValue(m_assembly);
}
if (!m_fileName.empty())
{
serializer.WritePropertyName(L"fileName");
serializer.WriteStringValue(m_fileName);
}
serializer.WritePropertyName(L"line");
serializer.WriteIntegerValue(m_line);
}
| 20.378378 | 56 | 0.690981 | crossmob |
08aafdc5403a07bfd757199e3374e2bd9c22579c | 2,938 | cpp | C++ | mainwindow.cpp | yeliudev/Navigator-plus-plus | 7f662a9bdc157bf15a172386d5a19185edca661c | [
"MIT"
] | null | null | null | mainwindow.cpp | yeliudev/Navigator-plus-plus | 7f662a9bdc157bf15a172386d5a19185edca661c | [
"MIT"
] | null | null | null | mainwindow.cpp | yeliudev/Navigator-plus-plus | 7f662a9bdc157bf15a172386d5a19185edca661c | [
"MIT"
] | null | null | null | #include <QFileDialog>
#include <QMessageBox>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog.h"
using namespace std;
/*************************************************
* @brief MainWindow 类的构造函数
*************************************************/
MainWindow::MainWindow() : ui(new Ui::MainWindow)
{
ui->setupUi(this);
elidfont = new QFontMetrics(ui->pathLabel->font());
}
/*************************************************
* @brief MainWindow 类的析构函数
*************************************************/
MainWindow::~MainWindow()
{
delete ui;
}
/*************************************************
* @brief 窗体大小改变事件
* @param size 指向 QResizeEvent 的指针(无用)
*************************************************/
void MainWindow::resizeEvent(QResizeEvent *size)
{
// 启用省略模式输出路径
ui->pathLabel->setText(elidfont->elidedText(path, Qt::ElideMiddle, ui->pathLabel->width()));
}
/*************************************************
* @brief 打开文件按钮点击事件
*************************************************/
void MainWindow::on_openFileButton_clicked()
{
// 打开模式对话框,选择文件
QString fileName = QFileDialog::getOpenFileName(this, "Open File", filePath, "*.e00");
// 保存上次打开的目录
filePath = fileName.section('/', -2);
// 文件格式校验
if (fileName.section('.', -1) == "e00")
{
// 建立信号和槽的连接
map = new QGeoMap(this);
connect(map, SIGNAL(pathUpdated(QString)), this, SLOT(on_pathUpdated(QString)));
// 读取文件并解码
if (map->loadMap(fileName.toStdString()))
{
// 更新标题栏文字
this->setWindowTitle(fileName.section('/', -1) + " - Navigator++");
// 清除路径
path.clear();
ui->pathLabel->setText("");
// 渲染图形
ui->mapWidget->setMap(map);
ui->mapWidget->resetOffset();
ui->mapWidget->update();
}
else
{
// 释放无用内存
delete map;
map = nullptr;
}
}
else if (fileName.length())
{
QMessageBox::critical(this, "Error", "Please choose a \".e00\" file", QMessageBox::Ok);
}
}
/*************************************************
* @brief 路径分析按钮点击事件
*************************************************/
void MainWindow::on_analyzeButton_clicked()
{
// 检查是否已打开地图文件
if (map != nullptr)
{
Dialog dialog(map);
dialog.exec();
}
else
{
QMessageBox::information(this, "Notice", "Please open a map first", QMessageBox::Ok);
}
}
/*************************************************
* @brief 路径更新事件
* @param path 更新之后的路径字符串
*************************************************/
void MainWindow::on_pathUpdated(QString path)
{
// 更新要输出的路径字符串
this->path = path;
// 启用省略模式输出路径字符串
ui->pathLabel->setText(elidfont->elidedText(path, Qt::ElideMiddle, ui->pathLabel->width()));
// 绘制路径
ui->mapWidget->update();
}
| 26 | 96 | 0.46256 | yeliudev |
08acfa4eba959e743cf71144e147a5a8de7987a9 | 661 | hpp | C++ | p3iv_types/include/p3iv_types/route_option.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 4 | 2021-07-27T06:56:22.000Z | 2022-03-22T11:21:30.000Z | p3iv_types/include/p3iv_types/route_option.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | null | null | null | p3iv_types/include/p3iv_types/route_option.hpp | fzi-forschungszentrum-informatik/P3IV | 51784e6dc03dcaa0ad58a5078475fa4daec774bd | [
"BSD-3-Clause"
] | 1 | 2021-10-10T01:56:44.000Z | 2021-10-10T01:56:44.000Z | #pragma once
#include <memory>
#include <vector>
#include "driving_corridor.hpp"
#include "traffic_rules.hpp"
#include "internal/point2d.hpp"
namespace p3iv_types {
struct Crossing {
double begin;
double end;
};
class RouteOption {
public:
RouteOption() = default;
RouteOption(const VectorPoint2d& right, const VectorPoint2d& center, const VectorPoint2d& left);
RouteOption(const DrivingCorridor& drivingCorridor);
void setDrivingCorridor(const DrivingCorridor& drivingCorridor);
protected:
std::string uuid;
DrivingCorridor corridor;
Crossing crossing;
TrafficRules trafficRules;
};
} // namespace p3iv_types | 18.361111 | 100 | 0.741301 | fzi-forschungszentrum-informatik |
08ad07d632934f68a5931ae4d3db330d740dffb1 | 4,849 | cpp | C++ | nanocv/trainers/batch.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | null | null | null | nanocv/trainers/batch.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | null | null | null | nanocv/trainers/batch.cpp | 0x0all/nanocv | dc58dea6b4eb7be2089b168d39c2b02aa2730741 | [
"MIT"
] | 1 | 2018-08-02T02:41:37.000Z | 2018-08-02T02:41:37.000Z | #include "batch.h"
#include "nanocv/timer.h"
#include "nanocv/logger.h"
#include "nanocv/sampler.h"
#include "nanocv/minimize.h"
#include "nanocv/accumulator.h"
#include "nanocv/log_search.hpp"
namespace ncv
{
namespace
{
opt_state_t train_batch(
trainer_data_t& data,
optim::batch_optimizer optimizer, size_t iterations, scalar_t epsilon,
timer_t& timer, trainer_result_t& result, bool verbose)
{
size_t iteration = 0;
// construct the optimization problem
auto fn_size = ncv::make_opsize(data);
auto fn_fval = ncv::make_opfval(data);
auto fn_grad = ncv::make_opgrad(data);
auto fn_wlog = verbose ? ncv::make_opwlog() : nullptr;
auto fn_elog = verbose ? ncv::make_opelog() : nullptr;
auto fn_ulog = [&] (const opt_state_t& state)
{
const scalar_t tvalue = data.m_gacc.value();
const scalar_t terror_avg = data.m_gacc.avg_error();
const scalar_t terror_var = data.m_gacc.var_error();
// validation samples: loss value
data.m_lacc.set_params(state.x);
data.m_lacc.update(data.m_task, data.m_vsampler.get(), data.m_loss);
const scalar_t vvalue = data.m_lacc.value();
const scalar_t verror_avg = data.m_lacc.avg_error();
const scalar_t verror_var = data.m_lacc.var_error();
// update the optimum state
const auto ret = result.update(
state.x, tvalue, terror_avg, terror_var, vvalue, verror_avg, verror_var,
++ iteration, scalars_t({ data.lambda() }));
if (verbose)
log_info()
<< "[train = " << tvalue << "/" << terror_avg
<< ", valid = " << vvalue << "/" << verror_avg
<< " (" << text::to_string(ret) << ")"
<< ", xnorm = " << state.x.lpNorm<Eigen::Infinity>()
<< ", gnorm = " << state.g.lpNorm<Eigen::Infinity>()
<< ", epoch = " << iteration
<< ", lambda = " << data.lambda()
<< ", calls = " << state.n_fval_calls() << "/" << state.n_grad_calls()
<< "] done in " << timer.elapsed() << ".";
return ret != trainer_result_return_t::overfitting;
};
// assembly optimization problem & optimize the model
return ncv::minimize(fn_size, fn_fval, fn_grad, fn_wlog, fn_elog, fn_ulog,
data.m_x0, optimizer, iterations, epsilon);
}
}
trainer_result_t batch_train(
const model_t& model, const task_t& task, const sampler_t& tsampler, const sampler_t& vsampler, size_t nthreads,
const loss_t& loss, const string_t& criterion,
optim::batch_optimizer optimizer, size_t iterations, scalar_t epsilon,
bool verbose)
{
vector_t x0;
model.save_params(x0);
// setup acumulators
accumulator_t lacc(model, nthreads, criterion, criterion_t::type::value);
accumulator_t gacc(model, nthreads, criterion, criterion_t::type::vgrad);
trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);
// tune the regularization factor (if needed)
const auto op = [&] (scalar_t lambda)
{
data.set_lambda(lambda);
trainer_result_t result;
timer_t timer;
train_batch(data, optimizer, iterations, epsilon, timer, result, verbose);
return result;
};
if (data.m_lacc.can_regularize())
{
return log10_min_search(op, -6.0, +0.0, 0.5, 4).first;
}
else
{
return op(0.0);
}
}
}
| 46.180952 | 128 | 0.43906 | 0x0all |
08adf963915b4c0fccd11bc473d005574ab834b0 | 30,923 | cc | C++ | src/vnsw/agent/uve/mock_generator.cc | kaweue/contrail-controller | 66a8f1d13e2c28ddae6b5a5be6f068a03bea94e3 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/uve/mock_generator.cc | kaweue/contrail-controller | 66a8f1d13e2c28ddae6b5a5be6f068a03bea94e3 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/uve/mock_generator.cc | kaweue/contrail-controller | 66a8f1d13e2c28ddae6b5a5be6f068a03bea94e3 | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
//
#include <sys/types.h>
#include <unistd.h>
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/program_options.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <io/event_manager.h>
#include <net/address.h>
#include <base/task.h>
#include <base/logging.h>
#include <base/timer.h>
#include <sandesh/common/vns_constants.h>
#include <sandesh/common/vns_types.h>
#include <sandesh/common/flow_types.h>
#include <ksync/ksync_types.h>
namespace opt = boost::program_options;
typedef std::map<SessionIpPortProtocol, SessionAggInfo> SessionAggMap;
class MockGenerator {
public:
const static int kNumVRouterErrorMessagesPerSec;
const static int kNumSessionSamplesPerSec;
const static int kNumSessionSamplesInMessage;
MockGenerator(std::string &hostname, std::string &module_name,
std::string &node_type_name,
std::string &instance_id,
int http_server_port, int start_vn, int end_vn, int other_vn,
int num_vns, int vm_iterations,
std::vector<std::string> &collectors,
std::vector<uint32_t> &ip_vns,
int ip_start_index,
int num_vrouter_error_messages_per_sec,
int num_sessions_per_vm,
int num_session_samples_per_sec,
int num_session_samples_in_message,
EventManager *evm) :
hostname_(hostname),
module_name_(module_name),
node_type_name_(node_type_name),
instance_id_(instance_id),
http_server_port_(http_server_port),
start_vn_(start_vn),
end_vn_(end_vn),
other_vn_(other_vn),
num_vns_(num_vns),
vm_iterations_(vm_iterations),
collectors_(collectors),
ip_vns_(ip_vns),
ip_start_index_(ip_start_index),
num_session_per_vm_(num_sessions_per_vm),
num_session_samples_per_sec_(num_session_samples_per_sec),
num_session_samples_in_message_(num_session_samples_in_message),
num_vrouter_error_messages_per_sec_(num_vrouter_error_messages_per_sec),
rgen_(std::time(0)),
u_rgen_(&rgen_),
evm_(evm) {
}
bool Run() {
// Initialize Sandesh
Sandesh::InitGenerator(module_name_, hostname_,
node_type_name_, instance_id_, evm_, http_server_port_,
collectors_, NULL);
TaskScheduler *scheduler = TaskScheduler::GetInstance();
if (num_session_samples_per_sec_) {
SendSessionTask *stask(new SendSessionTask(this,
scheduler->GetTaskId("mockgen::SendSessionTask"), -1));
scheduler->Enqueue(stask);
}
if (num_vrouter_error_messages_per_sec_) {
SendMessageTask *mtask(new SendMessageTask(this,
scheduler->GetTaskId("mockgen::SendMessageTask"), -1));
scheduler->Enqueue(mtask);
}
return true;
}
private:
class SendMessageTask : public Task {
public:
SendMessageTask(MockGenerator *mock_generator,
int task_id, int task_instance) :
Task(task_id, task_instance),
mgen_(mock_generator) {
}
void SendVRouterError() {
std::string str1("VRouter operation failed. Error <");
uint32_t error(2);
std::string str2(":");
std::string error_msg("Entry not pressent");
std::string str3(">. Object <");
std::string obj_str("Flow: 333333 with Source IP: "
"not present >. Object < Flow: 333333 with Source IP: "
"10.0.0.6 Source Port: 3333 Destination IP: 10.0.0.10 "
"Destination Port: 13333 Protocol 6");
std::string str4(">. Operation <");
std::string state_str("Change");
std::string str5(">. Message number :");
uint64_t msg_no(418940931);
V_ROUTER_ERROR_LOG("", SandeshLevel::SYS_DEBUG, str1, error,
str2, error_msg, str3, obj_str, str4, state_str, str5,
msg_no);
}
bool Run() {
uint64_t diff_time(0);
for (int i = 0; i < mgen_->num_vrouter_error_messages_per_sec_;
i++) {
uint64_t stime(UTCTimestampUsec());
SendVRouterError();
diff_time += UTCTimestampUsec() - stime;
if (diff_time >= 1000000) {
LOG(ERROR, "Sent: " << i + 1 << " in " <<
diff_time/1000000 << " seconds, NOT sending at " <<
mgen_->num_vrouter_error_messages_per_sec_ << " rate");
return false;
}
}
usleep(1000000 - diff_time);
return false;
}
std::string Description() const {
return "SendMessageTask";
}
private:
MockGenerator *mgen_;
};
class SendSessionTask : public Task {
public:
SendSessionTask(MockGenerator *mock_generator,
int task_id, int task_instance) :
Task(task_id, task_instance),
mgen_(mock_generator) {
}
bool Run() {
if (mgen_->sessions_.empty()) {
int other_vn = mgen_->other_vn_;
for (int vn = mgen_->start_vn_; vn < mgen_->end_vn_; vn++) {
for (int nvm = 0; nvm < mgen_->vm_iterations_; nvm++) {
for (int nsession = 0; nsession < mgen_->num_session_per_vm_;
nsession++) {
SessionEndpoint end_point;
end_point.set_vmi(to_string(mgen_->u_rgen_()));
end_point.set_vn(mgen_->kVnPrefix +
integerToString(vn));
end_point.set_remote_vn(mgen_->kVnPrefix +
integerToString(other_vn));
end_point.set_is_client_session(mgen_->dClientSession(
mgen_->rgen_));
end_point.set_deployment(
mgen_->kDeployment[mgen_->dTagIdx(mgen_->rgen_)]);
end_point.set_tier(mgen_->kTier[mgen_->dTagIdx(
mgen_->rgen_)]);
end_point.set_application(
mgen_->kApplication[mgen_->dTagIdx(mgen_->rgen_)]);
end_point.set_site(mgen_->kSite[mgen_->dTagIdx(
mgen_->rgen_)]);
end_point.set_remote_deployment(
mgen_->kDeployment[mgen_->dTagIdx(mgen_->rgen_)]);
end_point.set_remote_tier(
mgen_->kTier[mgen_->dTagIdx(mgen_->rgen_)]);
end_point.set_remote_application(
mgen_->kApplication[mgen_->dTagIdx(mgen_->rgen_)]);
end_point.set_remote_site(mgen_->kSite[mgen_->dTagIdx(
mgen_->rgen_)]);
end_point.set_is_si(mgen_->dClientSession(mgen_->rgen_));
std::vector<std::string> labels;
std::vector<std::string> remote_labels;
int nlabels(mgen_->dLabels(mgen_->rgen_));
int nremote_labels(mgen_->dLabels(mgen_->rgen_));
for (int i = 0; i < nlabels + 1; i++) {
labels.push_back(
mgen_->kLabels[mgen_->dLabels(mgen_->rgen_)]);
}
for (int i = 0; i < nremote_labels + 1; i++) {
remote_labels.push_back(
mgen_->kLabels[mgen_->dLabels(mgen_->rgen_)]);
}
end_point.set_labels(
std::set<string>(labels.begin(),labels.end()));
end_point.set_remote_labels(
std::set<string>(remote_labels.begin(),remote_labels.end()));
SessionAggMap sess_agg_map;
int nsport = mgen_->dNPorts(mgen_->rgen_);
for (int i = 0; i < nsport; i++) {
IpAddress ipaddr(Ip4Address(mgen_->ip_vns_[vn] +
mgen_->ip_start_index_ + nvm));
uint16_t protoIdx(mgen_->dProtocols(mgen_->rgen_));
uint16_t port = mgen_->kPorts[protoIdx];
uint16_t proto = mgen_->kProtocols[protoIdx];
SessionIpPortProtocol sess_ip_port_proto;
sess_ip_port_proto.set_local_ip(ipaddr);
sess_ip_port_proto.set_service_port(port);
sess_ip_port_proto.set_protocol(proto);
SessionAggInfo place_holder;
sess_agg_map[sess_ip_port_proto];
}
end_point.set_sess_agg_info(sess_agg_map);
mgen_->sessions_.push_back(end_point);
}
}
other_vn = (other_vn + 1) % mgen_->num_vns_;
}
}
int lsession_cnt = 0;
int last_lsession_cnt = 0;
uint64_t diff_time = 0;
std::vector<SessionEndpoint>::iterator begin(mgen_->sessions_.begin() +
mgen_->session_counter_);
for (std::vector<SessionEndpoint>::iterator it = begin;
it != mgen_->sessions_.end(); ++it) {
bool sent_message(false);
uint64_t stime = UTCTimestampUsec();
SessionEndpoint &end_point(*it);
SessionAggMap sess_agg_info_map;
for (SessionAggMap::const_iterator it2
= end_point.get_sess_agg_info().begin();
it2 != end_point.get_sess_agg_info().end(); ++it2) {
SessionAggInfo sess_agg_info;
std::map<SessionIpPort, SessionInfo> session_map;
int ncport = mgen_->dNPorts(mgen_->rgen_);
for (int i = 0; i < ncport; i++) {
uint16_t cport(mgen_->dPort(mgen_->rgen_));
int nips = mgen_->dIps(mgen_->rgen_);
for (int j = 0; j < nips; j++) {
int other_vn;
stringToInteger(end_point.get_remote_vn()
.substr(MockGenerator::kVnPrefix.length(),
std::string::npos), other_vn);
IpAddress ipaddr(Ip4Address(mgen_->ip_vns_[other_vn]
+ mgen_->ip_start_index_ + j));
SessionIpPort sess_ip_port;
sess_ip_port.set_port(cport);
sess_ip_port.set_ip(ipaddr);
std::map<SessionIpPort, SessionInfo>::iterator iter
= session_map.find(sess_ip_port);
if (iter != session_map.end()) {
continue;
}
SessionInfo session_val;
SessionFlowInfo forward_flow_info;
SessionFlowInfo reverse_flow_info;
uint64_t forward_pkts(mgen_->dFlowPktsPerSec(
mgen_->rgen_));
uint64_t reverse_pkts(mgen_->dFlowPktsPerSec(
mgen_->rgen_));
// Send once in every 5 message as a logged message
if (j % 5 !=0 ) {
forward_flow_info.set_sampled_pkts(forward_pkts);
forward_flow_info.set_sampled_bytes(forward_pkts *
mgen_->dBytesPerPacket(mgen_->rgen_));
reverse_flow_info.set_sampled_pkts(reverse_pkts);
reverse_flow_info.set_sampled_bytes(reverse_pkts *
mgen_->dBytesPerPacket(mgen_->rgen_));
sess_agg_info.set_sampled_forward_pkts(
sess_agg_info.get_sampled_forward_pkts() +
forward_pkts);
sess_agg_info.set_sampled_forward_bytes(
sess_agg_info.get_sampled_forward_bytes() +
forward_flow_info.get_sampled_bytes());
sess_agg_info.set_sampled_reverse_pkts(
sess_agg_info.get_sampled_reverse_pkts() +
reverse_pkts);
sess_agg_info.set_sampled_reverse_bytes(
sess_agg_info.get_sampled_reverse_bytes() +
reverse_flow_info.get_sampled_bytes());
} else {
forward_flow_info.set_logged_pkts(forward_pkts);
forward_flow_info.set_logged_bytes(forward_pkts *
mgen_->dBytesPerPacket(mgen_->rgen_));
reverse_flow_info.set_logged_pkts(reverse_pkts);
reverse_flow_info.set_logged_bytes(reverse_pkts *
mgen_->dBytesPerPacket(mgen_->rgen_));
sess_agg_info.set_logged_forward_pkts(
sess_agg_info.get_logged_forward_pkts() +
forward_pkts);
sess_agg_info.set_logged_forward_bytes(
sess_agg_info.get_logged_forward_bytes() +
forward_flow_info.get_logged_bytes());
sess_agg_info.set_logged_reverse_pkts(
sess_agg_info.get_logged_reverse_pkts() +
reverse_pkts);
sess_agg_info.set_logged_reverse_bytes(
sess_agg_info.get_logged_reverse_bytes() +
reverse_flow_info.get_logged_bytes());
}
session_val.set_forward_flow_info(forward_flow_info);
session_val.set_reverse_flow_info(reverse_flow_info);
session_map[sess_ip_port] = session_val;
}
}
sess_agg_info.set_sessionMap(session_map);
sess_agg_info_map[it2->first] = sess_agg_info;
}
end_point.set_sess_agg_info(sess_agg_info_map);
lsession_cnt++;
mgen_->session_counter_++;
SESSION_ENDPOINT_OBJECT_LOG("", SandeshLevel::SYS_NOTICE,
std::vector<SessionEndpoint>(begin+last_lsession_cnt, it + 1));
sent_message = true;
last_lsession_cnt = lsession_cnt;
if (lsession_cnt == mgen_->num_session_samples_per_sec_) {
if (!sent_message) {
SESSION_ENDPOINT_OBJECT_LOG("", SandeshLevel::SYS_NOTICE,
std::vector<SessionEndpoint>(begin+last_lsession_cnt, it + 1));
}
diff_time += UTCTimestampUsec() - stime;
usleep(1000000 - diff_time);
return false;
}
diff_time += UTCTimestampUsec() - stime;
if (diff_time >= 1000000) {
if (lsession_cnt < mgen_->num_session_samples_per_sec_) {
LOG(ERROR, "Sent: " << lsession_cnt << " in " <<
diff_time/1000000 << " seconds, NOT sending at " <<
mgen_->num_session_samples_per_sec_ << " rate");
return false;
}
}
}
mgen_->session_counter_ = 0;
return false;
}
std::string Description() const {
return "SendSessionTask";
}
private:
MockGenerator *mgen_;
};
const static std::string kVnPrefix;
const static std::string kVmPrefix;
const static int kBytesPerPacket = 1024;
const static int kOtherVnPktsPerSec = 1000;
const static int kUveMsgIntvlInSec = 10;
const static int kFlowMsgIntvlInSec = 1;
const static int kFlowPktsPerSec = 100;
const static int kMaxIps = 64;
const static int kMaxPorts = 5;
const static boost::random::uniform_int_distribution<>
dBytesPerPacket;
const static boost::random::uniform_int_distribution<>
dOtherVnPktsPerSec;
const static boost::random::uniform_int_distribution<>
dFlowPktsPerSec;
const static boost::random::uniform_int_distribution<>
dDirection;
const static boost::random::uniform_int_distribution<>
dClientSession;
const static boost::random::uniform_int_distribution<>
dPort;
const static boost::random::uniform_int_distribution<>
dIps;
const static boost::random::uniform_int_distribution<>
dNPorts;
const static boost::random::uniform_int_distribution<>
dLabels;
const static std::vector<int> kProtocols;
const static boost::random::uniform_int_distribution<>
dProtocols;
const static boost::random::uniform_int_distribution<>
dTagIdx;
const static std::vector<string> kLabels;
const static std::vector<std::string> kDeployment;
const static std::vector<std::string> kTier;
const static std::vector<std::string> kSite;
const static std::vector<std::string> kApplication;
const static std::vector<int> kPorts;
const std::string hostname_;
const std::string module_name_;
const std::string node_type_name_;
const std::string instance_id_;
const int http_server_port_;
const int start_vn_;
const int end_vn_;
const int other_vn_;
const int num_vns_;
const int vm_iterations_;
const std::vector<std::string> collectors_;
const std::vector<uint32_t> ip_vns_;
const int ip_start_index_;
const int num_session_per_vm_;
const int num_session_samples_per_sec_;
const int num_session_samples_in_message_;
const int num_vrouter_error_messages_per_sec_;
std::vector<SessionEndpoint> sessions_;
static int session_counter_;
boost::random::mt19937 rgen_;
boost::uuids::random_generator u_rgen_;
EventManager *evm_;
friend class SendMessageTask;
};
const std::string MockGenerator::kVnPrefix("default-domain:mock-gen-test:vn");
const std::string MockGenerator::kVmPrefix("vm");
const boost::random::uniform_int_distribution<>
MockGenerator::dBytesPerPacket(1, MockGenerator::kBytesPerPacket);
const boost::random::uniform_int_distribution<>
MockGenerator::dOtherVnPktsPerSec(1, MockGenerator::kOtherVnPktsPerSec);
const boost::random::uniform_int_distribution<>
MockGenerator::dFlowPktsPerSec(1, MockGenerator::kFlowPktsPerSec);
const boost::random::uniform_int_distribution<>
MockGenerator::dDirection(0, 1);
const boost::random::uniform_int_distribution<>
MockGenerator::dClientSession(0, 1);
const boost::random::uniform_int_distribution<>
MockGenerator::dPort(0, 65535);
const std::vector<int> MockGenerator::kProtocols = boost::assign::list_of
(6)(17)(1);
const boost::random::uniform_int_distribution<>
MockGenerator::dProtocols(0, MockGenerator::kProtocols.size() - 1);
const std::vector<int> MockGenerator::kPorts = boost::assign::list_of
(443)(8080)(22);
const std::vector<std::string> MockGenerator::kDeployment = boost::assign::list_of
("Dep1")("Dep2")("Dep3")("Dep4");
const std::vector<std::string> MockGenerator::kTier = boost::assign::list_of
("Tier1")("Tier2")("Tier3")("Tier4");
const std::vector<std::string> MockGenerator::kApplication = boost::assign::list_of
("App1")("App2")("App3")("App4");
const std::vector<std::string> MockGenerator::kSite = boost::assign::list_of
("Site1")("Site2")("Site3")("Site4");
const std::vector<std::string> MockGenerator::kLabels = boost::assign::list_of
("Label1")("Label2")("Label3")("Label4")("Label5");
const boost::random::uniform_int_distribution<>
MockGenerator::dTagIdx(0, MockGenerator::kDeployment.size() - 1);
const boost::random::uniform_int_distribution<>
MockGenerator::dIps(1, MockGenerator::kMaxIps);
const boost::random::uniform_int_distribution<>
MockGenerator::dNPorts(1, MockGenerator::kMaxPorts);
const boost::random::uniform_int_distribution<>
MockGenerator::dLabels(0, MockGenerator::kLabels.size() - 1);
int MockGenerator::session_counter_(0);
const int MockGenerator::kNumVRouterErrorMessagesPerSec(50);
const int MockGenerator::kNumSessionSamplesPerSec(0);
const int MockGenerator::kNumSessionSamplesInMessage(0);
int main(int argc, char *argv[]) {
bool log_local(false), use_syslog(false), log_flow(false);
std::string log_category;
opt::options_description desc("Command line options");
desc.add_options()
("help", "help message")
("collectors", opt::value<std::vector<std::string> >()->multitoken(
)->default_value(std::vector<std::string>(1, "127.0.0.1:8086"),
"127.0.0.1:8086"),
"List of Collectors addresses in ip:port format")
("num_instances_per_generator", opt::value<int>()->default_value(10),
"Number of instances (virtual machines) per generator")
("num_networks", opt::value<int>()->default_value(100),
"Number of virtual networks")
("num_sessions_per_instance", opt::value<int>()->default_value(10),
"Number of sessions per instance")
("start_ip_address",
opt::value<std::string>()->default_value("1.0.0.1"),
"Start IP address to be used for instances")
("http_server_port", opt::value<int>()->default_value(-1),
"HTTP server port")
("generator_id", opt::value<int>()->default_value(0),
"Generator Id")
("num_generators", opt::value<int>()->default_value(1),
"Number of generators")
("num_vrouter_errors_per_second", opt::value<int>()->default_value(
MockGenerator::kNumVRouterErrorMessagesPerSec),
"Number of VRouterErrror messages to send in one second")
("num_session_samples_per_second", opt::value<int>()->default_value(
MockGenerator::kNumSessionSamplesPerSec),
"Number of session messages to send in one second")
("num_session_samples_in_message", opt::value<int>()->default_value(
MockGenerator::kNumSessionSamplesInMessage),
"Number of session samples to send in one message")
("log_property_file", opt::value<std::string>()->default_value(""),
"log4cplus property file name")
("log_files_count", opt::value<int>()->default_value(10),
"Maximum log file roll over index")
("log_file_size",
opt::value<long>()->default_value(10*1024*1024),
"Maximum size of the log file")
("log_category",
opt::value<std::string>()->default_value(log_category),
"Category filter for local logging of sandesh messages")
("log_file", opt::value<std::string>()->default_value("<stdout>"),
"Filename for the logs to be written to")
("log_level", opt::value<std::string>()->default_value("SYS_NOTICE"),
"Severity level for local logging of sandesh messages")
("log_local", opt::bool_switch(&log_local),
"Enable local logging of sandesh messages")
("use_syslog", opt::bool_switch(&use_syslog),
"Enable logging to syslog")
("syslog_facility", opt::value<std::string>()->default_value(
"LOG_LOCAL0"), "Syslog facility to receive log lines")
("log_flow", opt::bool_switch(&log_flow),
"Enable local logging of flow sandesh messages")
("slo_destination", opt::value<std::vector<std::string> >()->multitoken(
)->default_value(std::vector<std::string>(1, "collector"),
"collector"),
"List of destinations. valid values are collector, file, syslog")
("sampled_destination", opt::value<std::vector<std::string> >()->multitoken(
)->default_value(std::vector<std::string>(1, "collector"),
"collector"),
"List of destinations. valid values are collector, file, syslog");
opt::variables_map var_map;
opt::store(opt::parse_command_line(argc, argv, desc), var_map);
opt::notify(var_map);
if (var_map.count("help")) {
std::cout << desc << std::endl;
exit(0);
}
Module::type module(Module::VROUTER_AGENT);
std::string moduleid(g_vns_constants.ModuleNames.find(module)->second);
std::string log_property_file(
var_map["log_property_file"].as<std::string>());
if (log_property_file.size()) {
LoggingInit(log_property_file);
} else {
LoggingInit(var_map["log_file"].as<std::string>(),
var_map["log_file_size"].as<long>(),
var_map["log_files_count"].as<int>(),
use_syslog,
var_map["syslog_facility"].as<std::string>(),
moduleid,
SandeshLevelTolog4Level(Sandesh::StringToLevel(
var_map["log_level"].as<std::string>())));
}
Sandesh::SetLoggingParams(log_local,
var_map["log_category"].as<std::string>(),
var_map["log_level"].as<std::string>(), false, log_flow);
std::vector<std::string> slo_destination(
var_map["slo_destination"].as<std::vector<std::string> >());
std::vector<std::string> sample_destination(
var_map["sampled_destination"].as<std::vector<std::string> >());
Sandesh::set_logger_appender(var_map["log_file"].as<std::string>(),
var_map["log_file_size"].as<long>(),
var_map["log_files_count"].as<int>(),
var_map["syslog_facility"].as<std::string>(),
slo_destination,
moduleid, false);
Sandesh::set_logger_appender(var_map["log_file"].as<std::string>(),
var_map["log_file_size"].as<long>(),
var_map["log_files_count"].as<int>(),
var_map["syslog_facility"].as<std::string>(),
sample_destination,
moduleid, true);
Sandesh::set_send_to_collector_flags(sample_destination, slo_destination);
int gen_id(var_map["generator_id"].as<int>());
int ngens(var_map["num_generators"].as<int>());
int pid(getpid());
int num_instances(var_map["num_instances_per_generator"].as<int>());
int num_networks(var_map["num_networks"].as<int>());
NodeType::type node_type(
g_vns_constants.Module2NodeType.find(module)->second);
std::string node_type_name(
g_vns_constants.NodeTypeNames.find(node_type)->second);
int http_server_port(var_map["http_server_port"].as<int>());
std::vector<std::string> collectors(
var_map["collectors"].as<std::vector<std::string> >());
boost::system::error_code ec;
std::string hostname(boost::asio::ip::host_name(ec));
if (ec) {
LOG(ERROR, "Hostname FAILED: " << ec);
exit(1);
}
hostname += "-" + integerToString(pid);
int gen_factor = num_networks / num_instances;
if (gen_factor == 0) {
LOG(ERROR, "Number of virtual networks(" << num_networks << ") should "
"be greater than number of instances per generator(" <<
num_instances << ")");
exit(1);
}
int start_vn((gen_id % gen_factor) * num_instances);
int end_vn(((gen_id % gen_factor) + 1) * num_instances);
int other_vn_adj(num_networks / 2);
int other_vn;
if (gen_id >= other_vn_adj) {
other_vn = gen_id - other_vn_adj;
} else {
other_vn = gen_id + other_vn_adj;
}
int instance_iterations((num_instances + num_networks - 1) / num_networks);
int num_ips_per_vn(((ngens * num_instances) + num_networks - 1) /
num_networks);
std::string start_ip(var_map["start_ip_address"].as<std::string>());
boost::asio::ip::address_v4 start_ip_address(
boost::asio::ip::address_v4::from_string(start_ip.c_str(), ec));
if (ec) {
LOG(ERROR, "IP Address (" << start_ip << ") FAILED: " << ec);
exit(1);
}
std::vector<uint32_t> ip_vns;
for (int num = 0; num < num_networks; num++) {
ip_vns.push_back(start_ip_address.to_ulong() +
num_ips_per_vn * num);
}
int start_ip_index(gen_id * num_instances / num_networks);
EventManager evm;
int num_sessions_per_instance(var_map["num_sessions_per_instance"].as<int>());
int num_session_samples_per_sec(
var_map["num_session_samples_per_second"].as<int>());
int num_session_samples_in_message(
var_map["num_session_samples_in_message"].as<int>());
int num_vrouter_error_messages_per_sec(
var_map["num_vrouter_errors_per_second"].as<int>());
std::string instance_id(integerToString(gen_id));
MockGenerator mock_generator(hostname, moduleid, node_type_name,
instance_id, http_server_port, start_vn, end_vn, other_vn,
num_networks, instance_iterations, collectors, ip_vns, start_ip_index,
num_vrouter_error_messages_per_sec,
num_sessions_per_instance, num_session_samples_per_sec,
num_session_samples_in_message, &evm);
mock_generator.Run();
evm.Run();
return 0;
}
| 47.794436 | 93 | 0.565081 | kaweue |
08af87c6a633f86296bab73254db3fc2f197f8cb | 3,316 | cpp | C++ | iree/compiler/Dialect/Flow/Transforms/TestPartitionableLoopsInterface.cpp | L-Net-1992/iree | a9ce2574f11ce811c07c21b49f679667d66f7798 | [
"Apache-2.0"
] | null | null | null | iree/compiler/Dialect/Flow/Transforms/TestPartitionableLoopsInterface.cpp | L-Net-1992/iree | a9ce2574f11ce811c07c21b49f679667d66f7798 | [
"Apache-2.0"
] | null | null | null | iree/compiler/Dialect/Flow/Transforms/TestPartitionableLoopsInterface.cpp | L-Net-1992/iree | a9ce2574f11ce811c07c21b49f679667d66f7798 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/Flow/IR/PartitionableLoopsInterface.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
static const char kAttributeName[] = "__test_interface__";
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
namespace {
/// For ops that implement the `PartitionableLoopsInterface` that have the
/// `__test_interface__` attribute set generates a `util.unfoldable_constant`
/// with a value of type `tensor<axindex>`, where `a` is the number of loops and
/// the value has zeros for non-partitionable loops and 1 for partitionable
/// loops.
struct TestPartitionableLoopsInterfacePattern
: public OpInterfaceRewritePattern<PartitionableLoopsInterface> {
using OpInterfaceRewritePattern<
PartitionableLoopsInterface>::OpInterfaceRewritePattern;
LogicalResult matchAndRewrite(PartitionableLoopsInterface interfaceOp,
PatternRewriter &rewriter) const {
if (!interfaceOp->hasAttr(kAttributeName)) {
return failure();
}
unsigned numLoops = interfaceOp.getNumLoops();
SmallVector<unsigned> partitionableLoops =
interfaceOp.getPartitionableLoops(3);
SmallVector<int64_t> loopInfo(numLoops, 0);
for (auto partitionableLoop : partitionableLoops) {
loopInfo[partitionableLoop] = 1;
}
auto type = RankedTensorType::get(numLoops, rewriter.getIndexType());
auto constantAttr = DenseIntElementsAttr::get(type, loopInfo);
rewriter.create<Util::UnfoldableConstantOp>(interfaceOp.getLoc(),
constantAttr);
rewriter.updateRootInPlace(
interfaceOp, [&] { interfaceOp->removeAttr(kAttributeName); });
return success();
}
};
struct TestPartitionableLoopsInterfacePass
: public PassWrapper<TestPartitionableLoopsInterfacePass,
OperationPass<void>> {
StringRef getArgument() const override {
return "iree-flow-test-partitionable-loops-interface";
}
StringRef getDescription() const override {
return "Test the PartitionableLoopsInterface using operations that "
"implement that interface.";
}
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<FlowDialect>();
}
void runOnOperation() override {
RewritePatternSet patterns(&getContext());
patterns.add<TestPartitionableLoopsInterfacePattern>(patterns.getContext());
if (failed(applyPatternsAndFoldGreedily(getOperation(),
std::move(patterns)))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<void>>
createTestPartitionableLoopsInterfacePass() {
return std::make_unique<TestPartitionableLoopsInterfacePass>();
}
static PassRegistration<TestPartitionableLoopsInterfacePass> pass;
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
| 35.655914 | 80 | 0.727081 | L-Net-1992 |
08b1219de4621cd2345956a8c8746dd7848ca4d1 | 1,770 | cpp | C++ | Sandbox/src/Cloud.cpp | conholo/GLU-GLUT-Sandbox | 09b3d9351a56aa8b47bbe20989e99c4c05e62e7f | [
"MIT"
] | null | null | null | Sandbox/src/Cloud.cpp | conholo/GLU-GLUT-Sandbox | 09b3d9351a56aa8b47bbe20989e99c4c05e62e7f | [
"MIT"
] | null | null | null | Sandbox/src/Cloud.cpp | conholo/GLU-GLUT-Sandbox | 09b3d9351a56aa8b47bbe20989e99c4c05e62e7f | [
"MIT"
] | null | null | null | #include "Cloud.h"
#include "glew.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include "glut.h"
#include <iostream>
#include <glm/gtx/compatibility.hpp>
#include "Core/Geometry/Vertex.h"
#include "Core/Random.h"
Cloud::Cloud(const glm::vec3& position, float radius, uint32_t count)
:m_Position(position), m_Radius(radius), m_BallCount(count)
{
Core::Geometry* sphere = Core::Geometry::Create(Core::PrimitiveType::Icosphere);
CloudDrawList = glGenLists(1);
glNewList(CloudDrawList, GL_COMPILE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
for (uint32_t i = 0; i < m_BallCount; i++)
{
glm::vec3 randomPositionInSphere = m_Position + glm::vec3(
Core::Random::RandomRange(-m_Radius, m_Radius),
Core::Random::RandomRange(-m_Radius, m_Radius),
Core::Random::RandomRange(-m_Radius, m_Radius));
const float distance = glm::length(m_Position - randomPositionInSphere);
// Bigger towards the center, lighter towards the center.
glm::vec3 randomScale = glm::lerp(glm::vec3(.5f), glm::vec3(3.0f), 1.5f - distance / m_Radius);
glm::vec3 randomColor = glm::lerp(m_DarkerColor, m_White, 1.0f - distance / m_Radius);
glPushMatrix();
glColor3f(randomColor.r, randomColor.g, randomColor.b);
glTranslatef(randomPositionInSphere.x, randomPositionInSphere.y, randomPositionInSphere.z);
glScalef(randomScale.x, randomScale.y, randomScale.z);
glBegin(GL_TRIANGLES);
for (auto index : sphere->GetIndices())
{
Core::Vertex vertex = sphere->GetVertices()[index];
glVertex3f(vertex.Position.x, vertex.Position.y, vertex.Position.z);
glNormal3f(vertex.Normal.x, vertex.Normal.y, vertex.Normal.z);
}
glEnd();
glPopMatrix();
}
glEndList();
delete sphere;
}
Cloud::~Cloud()
{
}
void Cloud::Draw()
{
glCallList(CloudDrawList);
}
| 26.818182 | 97 | 0.720339 | conholo |
08b183b55ccbab39c1415d327cde75f8bd52712c | 641 | cpp | C++ | C++ Programs/smallest-number-left.cpp | Chibi-Shem/Hacktoberfest2020-Expert | 324843464aec039e130e85a16e74b76d310f1497 | [
"MIT"
] | 77 | 2020-10-01T10:06:59.000Z | 2021-11-08T08:57:18.000Z | C++ Programs/smallest-number-left.cpp | Chibi-Shem/Hacktoberfest2020-Expert | 324843464aec039e130e85a16e74b76d310f1497 | [
"MIT"
] | 46 | 2020-09-27T04:55:36.000Z | 2021-05-14T18:49:06.000Z | C++ Programs/smallest-number-left.cpp | Chibi-Shem/Hacktoberfest2020-Expert | 324843464aec039e130e85a16e74b76d310f1497 | [
"MIT"
] | 327 | 2020-09-26T17:06:03.000Z | 2021-10-09T06:04:39.000Z | #include<bits/stdc++.h>
using namespace std;
void smallerleft(int array[], int n){
stack<int> s;
for(int i =0;i<n;i++){
while(!s.empty() && s.top() >= array[i]){
s.pop();
}
if(s.empty()) cout<<"-1"<<" ";
else cout<<s.top()<<" ";
s.push(array[i]);
}
cout<<endl;
}
int main()
{
int t; cin>>t;
while(t--){
int n; cin>>n;
int array[100000];
for(int i =0;i<n;i++){
cin>>array[i];
}
smallerleft(array, n);
}
return 0;
} | 15.634146 | 49 | 0.368175 | Chibi-Shem |
08b22b604ea13976ec6e6d32cf5b2e2813015650 | 574 | hpp | C++ | src/TimeStamp.hpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | src/TimeStamp.hpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | src/TimeStamp.hpp | vinthewrench/FooServer | 1e00a80df41235d29c6402cb8ae4d1f7bbbe07a6 | [
"MIT"
] | null | null | null | //
// TimeStamp.hpp
//
// Created by Vincent Moscaritolo on 5/6/21.
//
#ifndef TimeStamp_hpp
#define TimeStamp_hpp
#include <stdlib.h>
#include <time.h>
#include <string>
namespace timestamp {
class TimeStamp{
public:
TimeStamp(bool isGMT = true);
TimeStamp(std::string str);
TimeStamp(time_t time) { _time = time;};
inline time_t getTime() { return _time; };
std::string RFC1123String();
std::string ISO8601String();
std::string logFileString();
std::string ClockString(bool isGMT = true);
private:
time_t _time;
};
};
#endif /* TimeStamp_hpp */
| 14.717949 | 45 | 0.689895 | vinthewrench |
08b4a774e5fda8ddaed3ce0f057b09938d78b021 | 3,193 | cc | C++ | ess/src/model/RecordLifecycleActionHeartbeatRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | ess/src/model/RecordLifecycleActionHeartbeatRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | ess/src/model/RecordLifecycleActionHeartbeatRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/ess/model/RecordLifecycleActionHeartbeatRequest.h>
using AlibabaCloud::Ess::Model::RecordLifecycleActionHeartbeatRequest;
RecordLifecycleActionHeartbeatRequest::RecordLifecycleActionHeartbeatRequest() :
RpcServiceRequest("ess", "2014-08-28", "RecordLifecycleActionHeartbeat")
{
setMethod(HttpRequest::Method::Post);
}
RecordLifecycleActionHeartbeatRequest::~RecordLifecycleActionHeartbeatRequest()
{}
std::string RecordLifecycleActionHeartbeatRequest::getLifecycleActionToken()const
{
return lifecycleActionToken_;
}
void RecordLifecycleActionHeartbeatRequest::setLifecycleActionToken(const std::string& lifecycleActionToken)
{
lifecycleActionToken_ = lifecycleActionToken;
setParameter("LifecycleActionToken", lifecycleActionToken);
}
int RecordLifecycleActionHeartbeatRequest::getHeartbeatTimeout()const
{
return heartbeatTimeout_;
}
void RecordLifecycleActionHeartbeatRequest::setHeartbeatTimeout(int heartbeatTimeout)
{
heartbeatTimeout_ = heartbeatTimeout;
setParameter("HeartbeatTimeout", std::to_string(heartbeatTimeout));
}
std::string RecordLifecycleActionHeartbeatRequest::getAccessKeyId()const
{
return accessKeyId_;
}
void RecordLifecycleActionHeartbeatRequest::setAccessKeyId(const std::string& accessKeyId)
{
accessKeyId_ = accessKeyId;
setParameter("AccessKeyId", accessKeyId);
}
std::string RecordLifecycleActionHeartbeatRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void RecordLifecycleActionHeartbeatRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string RecordLifecycleActionHeartbeatRequest::getLifecycleHookId()const
{
return lifecycleHookId_;
}
void RecordLifecycleActionHeartbeatRequest::setLifecycleHookId(const std::string& lifecycleHookId)
{
lifecycleHookId_ = lifecycleHookId;
setParameter("LifecycleHookId", lifecycleHookId);
}
std::string RecordLifecycleActionHeartbeatRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void RecordLifecycleActionHeartbeatRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
long RecordLifecycleActionHeartbeatRequest::getOwnerId()const
{
return ownerId_;
}
void RecordLifecycleActionHeartbeatRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
| 29.841121 | 109 | 0.798309 | iamzken |
08b543ad9ce1855d889cc85e9daf88d02bdffeaa | 351 | cpp | C++ | ImperatorToCK3/Source/CK3Outputter/outDynasty.cpp | Idhrendur/ImperatorToCK3 | 49a183919f019bcd54c032d752172ffd2fb77f0b | [
"MIT"
] | 2 | 2021-04-01T14:56:47.000Z | 2021-07-31T18:37:15.000Z | ImperatorToCK3/Source/CK3Outputter/outDynasty.cpp | Idhrendur/ImperatorToCK3 | 49a183919f019bcd54c032d752172ffd2fb77f0b | [
"MIT"
] | null | null | null | ImperatorToCK3/Source/CK3Outputter/outDynasty.cpp | Idhrendur/ImperatorToCK3 | 49a183919f019bcd54c032d752172ffd2fb77f0b | [
"MIT"
] | null | null | null | #include "outDynasty.h"
#include "CK3/Dynasties/Dynasty.h"
std::ostream& CK3::operator<<(std::ostream& output, const Dynasty& dynasty) {
// output ID, name and culture
output << dynasty.ID << " = {\n";
output << "\tname = \"" << dynasty.name << "\"\n";
output << "\tculture = " << dynasty.culture << "\n";
output << "}\n";
return output;
}
| 23.4 | 77 | 0.598291 | Idhrendur |
08b60c3a9be640a736a489285d5108a4b33269ca | 1,116 | cpp | C++ | Algorithms & Data Structures/Sorting Algorithms Implementation/MergeSort.cpp | zementalist/Professional-Experience | 04fc2db56ea3dd2389577ae90e479028009724f5 | [
"Apache-2.0"
] | null | null | null | Algorithms & Data Structures/Sorting Algorithms Implementation/MergeSort.cpp | zementalist/Professional-Experience | 04fc2db56ea3dd2389577ae90e479028009724f5 | [
"Apache-2.0"
] | null | null | null | Algorithms & Data Structures/Sorting Algorithms Implementation/MergeSort.cpp | zementalist/Professional-Experience | 04fc2db56ea3dd2389577ae90e479028009724f5 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cmath>
using namespace std;
void print(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << "\t";
}
cout << endl;
}
void merge(int arr[], int l, int r, int mid) {
int leftSize = (int) ceil( (double) ((r - l + 1) / 2));
int rightSize = (r - l + 1) / 2;
int *leftCopy = new int[leftSize];
int *rightCopy = new int[rightSize];
int i = l, j = mid + 1;
for (int a = 0; a < leftSize; a++) {
leftCopy[a] = arr[i++];
}
for (int b = 0; b < rightSize; b++) {
rightCopy[b] = arr[j++];
}
i = l, j = mid + 1;
int a = 0, b = 0;
while (a < leftSize && b < leftSize) {
if (leftCopy[a] < rightCopy[b]) {
arr[i++] = leftCopy[a++];
}
else {
arr[j++] = rightCopy[b++];
}
}
while (a < leftSize) {
arr[i++] = leftCopy[a++];
}
while (b < rightSize) {
arr[j++] = rightCopy[b++];
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int mid = (r + l) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, r, mid);
}
}
int main() {
int array[5]{ 1,2,3,4,5 };
mergeSort(array, 0, 4);
print(array, 5);
} | 18.295082 | 56 | 0.515233 | zementalist |
08b709ddb700803cc34fbaf6c69103642f64a530 | 63,953 | cc | C++ | src/tim/vx/ops/conv2d_test.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | 118 | 2021-01-12T01:56:25.000Z | 2022-03-30T09:50:58.000Z | src/tim/vx/ops/conv2d_test.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | 114 | 2021-01-29T08:21:43.000Z | 2022-03-28T11:58:10.000Z | src/tim/vx/ops/conv2d_test.cc | onepick/TIM-VX | ac2e0585805e0dd65cc93829d68b29ec3d83ac4d | [
"MIT"
] | 56 | 2021-01-12T02:42:53.000Z | 2022-03-24T02:15:20.000Z | #include "tim/vx/ops/conv2d.h"
#include "gtest/gtest.h"
#include "test_utils.h"
#include "tim/vx/context.h"
#include "tim/vx/graph.h"
#include "tim/vx/types.h"
TEST(Conv2d, shape_4_2_1_1_float32_PaddingTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
1, 1, 1, 1, // row = 1
2, 2, 3, 2 // row = 2
};
// weight data oihw
std::vector<float> weight_data = {
1, 2, 3, 4, //first 2x2 filter
-1, 1, -1, 1, // second 2x2 filter
-1, -1, 1, 1, // third 2x2 filter
};
// bias data
std::vector<float> bias_data = {1, 2, 3};
// nchw
std::vector<float> golden = {// first channel
18, 22, 21, 8, 7, 9, 8, 3, 2, 3, 1, -1,
// second channel
2, 3, 1, 0, 5, 6, 6, 4, -1, -2, -2, 1};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_2_2_float32_PointwiseTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn
tim::vx::ShapeType weight_shape({1, 1, 2, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1,
0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2};
// weight data oihw
std::vector<float> weight_data = {
1, 2 // first filter
};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3,
1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_float32_SimpleTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
// First batch
1, 1, 1, 1, // row = 1
2, 2, 2, 2, // row = 2
// Second batch
1, 2, 3, 4, // row = 1
1, 2, 3, 4, // row = 2
};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {1, 2, 3};
// nchw
std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_2_2_float32_SimpleChannelsTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 2, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data
std::vector<float> input_data = {
0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1,
0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2};
// weight data
std::vector<float> weight_data = {1, 2, 3, 4, 1, 2, 3, 4, -1, 1, -1, 1,
-1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {1, 2, 3};
std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_6_3_1_1_float32_SimpleAnisotropicStridesTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {3, 2, 1, -1, -2, -3, 4, 3, 2,
-2, -3, -4, 5, 4, 3, -3, -4, -5};
// weight data oihw
std::vector<float> weight_data = {
1, 2, //
3, 4, //
};
// bias data
std::vector<float> bias_data = {-1};
// nchw
std::vector<float> golden = {
30, -24, //
40, -34, //
};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({3, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {105, 150, 183, 95, 235, 312,
357, 178, 187, 234, 261, 121};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedConstFilterTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {105, 150, 183, 95, 235, 312,
357, 178, 187, 234, 261, 121};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedBiasTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {10};
// nchw
std::vector<float> golden = {115, 160, 193, 105, 245, 322,
367, 188, 197, 244, 271, 131};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::SAME;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedValidTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
// weight data oihw
std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {312, 357};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_2_2_float32_DisabledPointwiseMultifilterTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn
tim::vx::ShapeType weight_shape({1, 1, 2, 2}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{4, 2, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1,
0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2};
// weight data oihw
std::vector<float> weight_data = {1, 2, 2, 3};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {
1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3, 2.5, 2.5, 2.5, 2.5, 5, 5, 5, 5,
1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6, 2.5, 5, 7.5, 10, 2.5, 5, 7.5, 10};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_9_9_1_1_float32_SimpleDilationTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{3, 3, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {5, 5, 5, 5, 5, 5, 5, 5, 5};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({3, 3});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_float32_StrideTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{3, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 3, 2,
1, 2, 3, 4, 1, 2, 4, 4};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {1, 2, 3};
// nchw
std::vector<float> golden = {18, 22, 21, 2, 3, 1, 5, 6, 6,
17, 31, 40, 4, 5, 3, 3, 4, 4};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_float32_InputAndFilterSameWidthHeightTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({4, 2, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{1, 1, weight_shape[3], input_shape[3]}); //whcn
tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape,
tim::vx::TensorAttribute::INPUT);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT);
tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape,
tim::vx::TensorAttribute::OUTPUT);
// Input data nchw
std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 2, 2,
1, 2, 3, 4, 1, 2, 3, 4};
// weight data oihw
std::vector<float> weight_data = {1, 2, 3, 4, -1, -1, 1, 1};
// bias data
std::vector<float> bias_data = {0};
// nchw
std::vector<float> golden = {10, 34};
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({0, 0});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<float> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest1) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64,
output_min = -127, output_max = 128;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2,
1, 2, 3, 4, 1, 2, 3, 4};
// weight data oihw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1,
-1, 1, -1, -1, 1, 1};
// bias data
// scale:0.25 Zp:0
std::vector<float> bias_data_float = {1, 2, 3};
// golden data
//min:-127 max:128 scale:1 Zp:-1
std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest2) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -128.5, input_max = 128, weight_min = -128.5, weight_max = 128,
output_min = -127, output_max = 128;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-128.5 max:128 scale:1.00588 Zp:0
std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2,
1, 2, 3, 4, 1, 2, 3, 4};
// weight data oihw
// min:-128.5 max:128 scale:1.00588 Zp:0
std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1,
-1, 1, -1, -1, 1, 1};
// bias data
// scale:1.0116 Zp:0
std::vector<float> bias_data_float = {1, 2, 3};
// golden data
// min:-127 max:128 scale:1 Zp:-1
std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_6_3_1_1_uint8_AnisotropicStridesQuantizedTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 2, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64,
output_min = -127, output_max = 128;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {3, 2, 1, -1, -2, -3, 4, 3, 2,
-2, -3, -4, 5, 4, 3, -3, -4, -5};
// weight data oihw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> weight_data_float = {1, 2, 3, 4};
// bias data
// scale:0.25 Zp:0
std::vector<float> bias_data_float = {-1};
// golden data
//min:-127 max:128 scale:1 Zp:-1
std::vector<float> golden_float = {30, -24, 40, -34};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({3, 1});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_9_9_1_1_uint8_DilationQuantizedTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn
tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{3, 3, weight_shape[3], input_shape[3]}); //whcn
float input_min = -128, input_max = 127, weight_min = -128, weight_max = 127,
output_min = 0, output_max = 255;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<u_int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<u_int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {scales_zp.first};
std::vector<int32_t> zero_point_weight = {scales_zp.second};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<u_int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-128 max:127 scale:1 Zp:0
std::vector<float> input_data_float = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1,
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// weight data oihw
// min:-128 max:127 scale:1 Zp:0
std::vector<float> weight_data_float = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// bias data
// scale:1 Zp:0
std::vector<float> bias_data_float = {0};
// golden data
// min:0 max:255 scale:1 Zp:-128
std::vector<float> golden_float = {5, 5, 5, 5, 5, 5, 5, 5, 5};
std::vector<u_int8_t> input_data =
Quantize<uint8_t>(input_data_float, scales_input[0], zero_point_input[0]);
std::vector<u_int8_t> weight_data =
Quantize<uint8_t>(weight_data_float, scales_weight[0], zero_point_input[0]);
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
std::vector<u_int8_t> golden =
Quantize<uint8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({3, 3});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<u_int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerTensorTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = -63.5, weight_max = 64,
output_min = -63.5, output_max = 64;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {1};
std::vector<int32_t> zero_point_weight = {0};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0]};
std::vector<int32_t> zero_point_bias = {0};
scales_zp = QuantizationParams<int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::ASYMMETRIC, 2,
scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::ASYMMETRIC, 2, scales_bias,
zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3,
2, -1, -3, 3, -2, -4};
std::vector<int8_t> input_data =
Quantize<int8_t>(input_data_float, scales_input[0], zero_point_input[0]);
// weight_float_data = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2};
std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6,
7, 5, 3, 1, 8, 6, 4, 2};
// bias data
std::vector<float> bias_data_float = {3, -2};
std::vector<int32_t> bias_data =
Quantize<int32_t>(bias_data_float, scales_bias[0], zero_point_bias[0]);
// golden_int8_data = {61, -115, 111, -89}
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> golden_float = {31, -57, 56, -44};
std::vector<int8_t> golden =
Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerChannelTest) {
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn
tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{2, 1, weight_shape[3], input_shape[3]}); //whcn
float input_min = -63.5, input_max = 64, weight_min = 0, weight_max = 0,
output_min = -63.5, output_max = 64;
std::pair<float, int32_t> scales_zp;
scales_zp = QuantizationParams<int8_t>(input_min, input_max);
std::vector<float> scales_input = {scales_zp.first};
std::vector<int32_t> zero_point_input = {scales_zp.second};
scales_zp = QuantizationParams<int8_t>(weight_min, weight_max);
std::vector<float> scales_weight = {1, 2};
std::vector<int32_t> zero_point_weight = {0, 0};
std::vector<float> scales_bias = {scales_input[0] * scales_weight[0],
scales_input[0] * scales_weight[1]};
std::vector<int32_t> zero_point_bias = {0, 0};
scales_zp = QuantizationParams<int8_t>(output_min, output_max);
std::vector<float> scales_output = {scales_zp.first};
std::vector<int32_t> zero_point_output = {scales_zp.second};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL,
3, scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0,
scales_bias, zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape,
tim::vx::TensorAttribute::INPUT, quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT, quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
// Input data nchw
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3,
2, -1, -3, 3, -2, -4};
std::vector<int8_t> input_data =
Quantize<int8_t>(input_data_float, scales_input[0], zero_point_input[0]);
// weight_data_float = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2};
std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6,
4, 3, 2, 1, 4, 3, 2, 1};
// bias_data_float ={3, -2};
std::vector<int32_t> bias_data = {6, -2};
// golden data
// min:-63.5 max:64 scale:0.5 Zp:-1
std::vector<float> golden_float = {31, -57, 64, -46};
std::vector<int8_t> golden =
Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({1, 1});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
TEST(Conv2d, shape_w_h_128_1_ksize_1_1_stride_2_int8_QuantizedPerChannelTest) {
std::map<uint32_t, std::vector<uint32_t>> input_shape_list;
input_shape_list[32] = {18, 20, 22, 26, 28, 30, 34, 36, 38,
42, 44, 46, 50, 52, 54, 58, 60, 62};
input_shape_list[63] = {18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62};
input_shape_list[95] = {18, 20, 22, 26, 28, 30, 34, 36, 38,
42, 44, 46, 50, 52, 54, 58, 60, 62};
input_shape_list[96] = {18, 20, 22, 26, 28, 30, 34, 36, 38,
42, 44, 46, 50, 52, 54, 58, 60, 62};
tim::vx::ShapeType input_shape({2, 2, 128, 1}); //whcn
tim::vx::ShapeType weight_shape({1, 1, 128, 256}); //whio
tim::vx::ShapeType bias_shape({weight_shape[3]});
tim::vx::ShapeType output_shape(
{1, 1, weight_shape[3], input_shape[3]}); //whcn
std::vector<float> scales_input = {0.5};
std::vector<int32_t> zero_point_input = {-1};
std::vector<float> scales_weight(weight_shape[3]);
std::vector<int32_t> zero_point_weight(weight_shape[3]);
for (unsigned int i = 0; i < weight_shape[3]; i++) {
scales_weight[i] = 1;
zero_point_weight[i] = 0;
}
int32_t sizeofweight = scales_weight.size();
std::vector<float> scales_bias(sizeofweight);
std::vector<int32_t> zero_point_bias(sizeofweight);
for (int i = 0; i < sizeofweight; i++) {
scales_bias[i] = scales_input[0] * scales_weight[i];
zero_point_bias[i] = 0;
}
std::vector<float> scales_output = {0.5};
std::vector<int32_t> zero_point_output = {-1};
tim::vx::Quantization quant_input(tim::vx::QuantType::ASYMMETRIC, 2,
scales_input, zero_point_input);
tim::vx::Quantization quant_weight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL,
3, scales_weight, zero_point_weight);
tim::vx::Quantization quant_bias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0,
scales_bias, zero_point_bias);
tim::vx::Quantization quant_output(tim::vx::QuantType::ASYMMETRIC, 2,
scales_output, zero_point_output);
uint32_t weight_size =
weight_shape[0] * weight_shape[1] * weight_shape[2] * weight_shape[3];
std::vector<float> weight_data_float(weight_size);
for (uint32_t i = 0; i < weight_size; i++) {
weight_data_float[i] = 1;
}
std::vector<int8_t> weight_data = Quantize<int8_t>(weight_data_float, 1, 0);
// bias_data
std::vector<int32_t> bias_data(weight_shape[3]);
for (uint32_t i = 0; i < weight_shape[3]; i++) {
bias_data[i] = 2;
}
for (std::map<uint32_t, std::vector<uint32_t>>::iterator iter =
input_shape_list.begin();
iter != input_shape_list.end(); iter++) {
for (uint32_t j = 0; j < iter->second.size(); j++) {
input_shape[0] = iter->first;
input_shape[1] = iter->second[j];
output_shape[0] = (input_shape[0] + 1) / 2;
output_shape[1] = (input_shape[1] + 1) / 2;
tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape,
tim::vx::TensorAttribute::INPUT,
quant_input);
tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_weight);
tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape,
tim::vx::TensorAttribute::CONSTANT,
quant_bias);
tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape,
tim::vx::TensorAttribute::OUTPUT,
quant_output);
uint32_t input_size =
input_shape[0] * input_shape[1] * input_shape[2] * input_shape[3];
std::vector<float> input_data_float(input_size);
for (uint32_t i = 0; i < input_size; i++) {
input_data_float[i] = 1;
}
std::vector<int8_t> input_data = Quantize<int8_t>(
input_data_float, scales_input[0], zero_point_input[0]);
uint32_t golden_size =
output_shape[0] * output_shape[1] * output_shape[2] * output_shape[3];
std::vector<float> golden_float(golden_size);
for (uint32_t i = 0; i < golden_size; i++) {
golden_float[i] = 129;
}
std::vector<int8_t> golden =
Quantize<int8_t>(golden_float, scales_output[0], zero_point_output[0]);
auto ctx = tim::vx::Context::Create();
auto graph = ctx->CreateGraph();
auto input_tensor = graph->CreateTensor(input_spec);
auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data());
auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data());
auto output_tensor = graph->CreateTensor(output_spec);
auto padding = tim::vx::PadType::VALID;
std::array<uint32_t, 2> stride({2, 2});
std::array<uint32_t, 2> dilation({1, 1});
auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>(
padding, stride, dilation);
(*conv2d)
.BindInput(input_tensor)
.BindInput(weight_tensor)
.BindInput(bias_tensor)
.BindOutput(output_tensor);
EXPECT_TRUE(graph->Compile());
input_tensor->CopyDataToTensor(input_data.data());
EXPECT_TRUE(graph->Run());
uint32_t output_size = 1;
for (auto i : output_tensor->GetShape()) {
output_size *= i;
}
std::vector<int8_t> output(output_size);
EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data()));
EXPECT_EQ(golden, output);
}
}
}
| 38.948234 | 83 | 0.623208 | onepick |
08bb772415dc12db3244ac534cbf01afcff0fb71 | 9,260 | cpp | C++ | src/BlankPanel8HP.cpp | DomiKamu/Ohmer | c1c62e0f8a766c25e4f1848c9e4f5d56253ef34a | [
"BSD-3-Clause"
] | 7 | 2019-07-29T19:07:01.000Z | 2021-10-01T14:21:29.000Z | src/BlankPanel8HP.cpp | DomiKamu/Ohmer | c1c62e0f8a766c25e4f1848c9e4f5d56253ef34a | [
"BSD-3-Clause"
] | 6 | 2019-07-26T20:54:12.000Z | 2021-12-14T01:22:31.000Z | src/BlankPanel8HP.cpp | DomiKamu/Ohmer | c1c62e0f8a766c25e4f1848c9e4f5d56253ef34a | [
"BSD-3-Clause"
] | 3 | 2020-09-20T00:37:47.000Z | 2021-12-14T07:31:18.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
////// Blank Panel 8 HP module /////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "Ohmer.hpp"
struct OhmerBlank8 : Module {
enum ParamIds {
NUM_PARAMS
};
enum InputIds {
NUM_INPUTS
};
enum OutputIds {
NUM_OUTPUTS
};
enum LightIds {
NUM_LIGHTS
};
// Current selected plate model (color).
int Theme = 0; // 0 = Classic (default), 1 = Stage Repro, 2 = Absolute Night, 3 = Dark Signature, 4 = Deepblue Signature, 5 = Carbon Signature.
// Panel color (default is "Classic" beige model).
NVGcolor panelBackgroundColor = nvgRGB(0xd2, 0xd2, 0xcd);
OhmerBlank8() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
}
void process(const ProcessArgs &args) override {
// DSP processing...
// Depending current model (theme), set the relevant background color for panel.
panelBackgroundColor = tblPanelBackgroundColor[Theme];
}
json_t *dataToJson() override {
json_t *rootJ = json_object();
json_object_set_new(rootJ, "Theme", json_integer(Theme));
return rootJ;
}
void dataFromJson(json_t *rootJ) override {
json_t *ThemeJ = json_object_get(rootJ, "Theme");
if (ThemeJ)
Theme = json_integer_value(ThemeJ);
}
};
///////////////////////////////////////////////////// CONTEXT-MENU //////////////////////////////////////////////////////
struct OhmerBlank8ClassicMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 0; // Model: default Classic (beige).
}
};
struct OhmerBlank8StageReproMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 1; // Model: Stage Repro.
}
};
struct OhmerBlank8AbsoluteNightMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 2; // Model: Absolute Night.
}
};
struct OhmerBlank8DarkSignatureMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 3; // Model: Dark Signature.
}
};
struct OhmerBlank8DeepblueSignatureMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 4; // Model: Deepblue Signature.
}
};
struct OhmerBlank8CarbonSignatureMenu : MenuItem {
OhmerBlank8 *module;
void onAction(const event::Action &e) override {
module->Theme = 5; // Model: Carbon Signature.
}
};
struct OhmerBlank8SubMenuItems : MenuItem {
OhmerBlank8 *module;
Menu *createChildMenu() override {
Menu *menu = new Menu;
OhmerBlank8ClassicMenu *ohmerblank8menuitem1 = new OhmerBlank8ClassicMenu;
ohmerblank8menuitem1->text = "Classic (default)";
ohmerblank8menuitem1->rightText = CHECKMARK(module->Theme == 0);
ohmerblank8menuitem1->module = module;
menu->addChild(ohmerblank8menuitem1);
OhmerBlank8StageReproMenu *ohmerblank8menuitem2 = new OhmerBlank8StageReproMenu;
ohmerblank8menuitem2->text = "Stage Repro";
ohmerblank8menuitem2->rightText = CHECKMARK(module->Theme == 1);
ohmerblank8menuitem2->module = module;
menu->addChild(ohmerblank8menuitem2);
OhmerBlank8AbsoluteNightMenu *ohmerblank8menuitem3 = new OhmerBlank8AbsoluteNightMenu;
ohmerblank8menuitem3->text = "Absolute Night";
ohmerblank8menuitem3->rightText = CHECKMARK(module->Theme == 2);
ohmerblank8menuitem3->module = module;
menu->addChild(ohmerblank8menuitem3);
OhmerBlank8DarkSignatureMenu *ohmerblank8menuitem4 = new OhmerBlank8DarkSignatureMenu;
ohmerblank8menuitem4->text = "Dark \"Signature\"";
ohmerblank8menuitem4->rightText = CHECKMARK(module->Theme == 3);
ohmerblank8menuitem4->module = module;
menu->addChild(ohmerblank8menuitem4);
OhmerBlank8DeepblueSignatureMenu *ohmerblank8menuitem5 = new OhmerBlank8DeepblueSignatureMenu;
ohmerblank8menuitem5->text = "Deepblue \"Signature\"";
ohmerblank8menuitem5->rightText = CHECKMARK(module->Theme == 4);
ohmerblank8menuitem5->module = module;
menu->addChild(ohmerblank8menuitem5);
OhmerBlank8CarbonSignatureMenu *ohmerblank8menuitem6 = new OhmerBlank8CarbonSignatureMenu;
ohmerblank8menuitem6->text = "Carbon \"Signature\"";
ohmerblank8menuitem6->rightText = CHECKMARK(module->Theme == 5);
ohmerblank8menuitem6->module = module;
menu->addChild(ohmerblank8menuitem6);
return menu;
}
};
///////////////////////////////////////////////// PANEL BACKGROUND COLOR /////////////////////////////////////////////////
struct OhmerBlank8Background : TransparentWidget {
OhmerBlank8 *module;
OhmerBlank8Background() {
}
void draw(const DrawArgs &args) override {
nvgBeginPath(args.vg);
nvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y);
if (module)
nvgFillColor(args.vg, module->panelBackgroundColor);
else nvgFillColor(args.vg, nvgRGB(0xd2, 0xd2, 0xcd));
nvgFill(args.vg);
}
};
///////////////////////////////////////////////// MODULE WIDGET SECTION /////////////////////////////////////////////////
struct OhmerBlank8Widget : ModuleWidget {
// Panel (transparent widget).
OhmerBlank8Background *blankPanel;
// Silver Torx screws.
SvgScrew *topLeftScrewSilver;
SvgScrew *topRightScrewSilver;
SvgScrew *bottomLeftScrewSilver;
SvgScrew *bottomRightScrewSilver;
// Gold Torx screws.
SvgScrew *topLeftScrewGold;
SvgScrew *topRightScrewGold;
SvgScrew *bottomLeftScrewGold;
SvgScrew *bottomRightScrewGold;
OhmerBlank8Widget(OhmerBlank8 *module) {
setModule(module);
// 8 HP module, no SVG panel loaded, but using transparent widget instead.
box.size = Vec(8 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT);
{
blankPanel = new OhmerBlank8Background();
blankPanel->box.size = box.size;
blankPanel->module = module;
addChild(blankPanel);
}
// This 8 HP module uses 4 screws (may are silver or gold).
// Top-left silver screw.
topLeftScrewSilver = createWidget<Torx_Silver>(Vec(RACK_GRID_WIDTH, 0));
addChild(topLeftScrewSilver);
// Top-right silver screw.
topRightScrewSilver = createWidget<Torx_Silver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0));
addChild(topRightScrewSilver);
// Bottom-left silver screw.
bottomLeftScrewSilver = createWidget<Torx_Silver>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomLeftScrewSilver);
// Bottom-right silver screw.
bottomRightScrewSilver = createWidget<Torx_Silver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomRightScrewSilver);
// Top-left gold screw.
topLeftScrewGold = createWidget<Torx_Gold>(Vec(RACK_GRID_WIDTH, 0));
addChild(topLeftScrewGold);
// Top-right gold screw.
topRightScrewGold = createWidget<Torx_Gold>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0));
addChild(topRightScrewGold);
// Bottom-left gold screw.
bottomLeftScrewGold = createWidget<Torx_Gold>(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomLeftScrewGold);
// Bottom-right gold screw.
bottomRightScrewGold = createWidget<Torx_Gold>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH));
addChild(bottomRightScrewGold);
}
void step() override {
OhmerBlank8 *module = dynamic_cast<OhmerBlank8*>(this->module);
if (module) {
// Torx screws metal (silver, gold) are visible or hidden, depending selected model (from module's context-menu).
// Silver Torx screws are visible only for non-"Signature" modules (Classic, Stage Repro or Absolute Night).
topLeftScrewSilver->visible = (module->Theme < 3);
topRightScrewSilver->visible = (module->Theme < 3);
bottomLeftScrewSilver->visible = (module->Theme < 3);
bottomRightScrewSilver->visible = (module->Theme < 3);
// Gold Torx screws are visible only for "Signature" modules (Dark Signature, Deepblue Signature or Carbon Signature).
topLeftScrewGold->visible = (module->Theme > 2);
topRightScrewGold->visible = (module->Theme > 2);
bottomLeftScrewGold->visible = (module->Theme > 2);
bottomRightScrewGold->visible = (module->Theme > 2);
}
else {
// Default panel theme is always "Classic" (beige, using silver screws, using silver button, LCD).
// Other panels are, of course, hidden.
// By default, silver screws are visible for default beige Classic panel...
topLeftScrewSilver->visible = true;
topRightScrewSilver->visible = true;
bottomLeftScrewSilver->visible = true;
bottomRightScrewSilver->visible = true;
// ...and, of course, golden screws are hidden.
topLeftScrewGold->visible = false;
topRightScrewGold->visible = false;
bottomLeftScrewGold->visible = false;
bottomRightScrewGold->visible = false;
}
ModuleWidget::step();
}
void appendContextMenu(Menu *menu) override {
OhmerBlank8 *module = dynamic_cast<OhmerBlank8*>(this->module);
menu->addChild(new MenuEntry);
OhmerBlank8SubMenuItems *ohmerblank8submenuitems = new OhmerBlank8SubMenuItems;
ohmerblank8submenuitems->text = "Model";
ohmerblank8submenuitems->rightText = RIGHT_ARROW;
ohmerblank8submenuitems->module = module;
menu->addChild(ohmerblank8submenuitems);
}
};
Model *modelBlankPanel8 = createModel<OhmerBlank8, OhmerBlank8Widget>("OhmerBlank8");
| 35.891473 | 144 | 0.699784 | DomiKamu |
08bc69b1c7a19d0fbdd8e3181f145677e1ee5b97 | 2,162 | cpp | C++ | Jelly/src/AudioManager.cpp | RikdeRooij/Hazel | 029fd852872be2be66f97f8bb9e4ee525751b18d | [
"Apache-2.0"
] | 1 | 2021-06-17T14:15:45.000Z | 2021-06-17T14:15:45.000Z | Jelly/src/AudioManager.cpp | RikdeRooij/Hazel | 029fd852872be2be66f97f8bb9e4ee525751b18d | [
"Apache-2.0"
] | null | null | null | Jelly/src/AudioManager.cpp | RikdeRooij/Hazel | 029fd852872be2be66f97f8bb9e4ee525751b18d | [
"Apache-2.0"
] | null | null | null |
#include "AudioManager.h"
#include "AudioPlayer.h"
#include "glm/detail/func_geometric.inl"
#include "Player.h"
void AudioManager::AddFile(Sounds::Type sndType, const char* filepath)
{
//filepaths[sndType] = filepath;
//auto ap = AudioPlayerFactory::createFromFile(filepath);
AudioPlayer* ap = new AudioPlayer(filepath);
if (ap == nullptr)
throw;
//ap->setFinishListener(this);
audioPlayers[sndType] = ap;
}
AudioManager::AudioManager()
{
instance = this;
AddFile(Jump1, "assets/Sounds/jump1.wav");
AddFile(Jump2, "assets/Sounds/jump2.wav");
AddFile(Jump3, "assets/Sounds/jump3.wav");
AddFile(PlayerDie, "assets/Sounds/laser6.wav");
AddFile(EnemyDie, "assets/Sounds/m_health.wav");
AddFile(Hit, "assets/Sounds/pl_pain6.wav");
AddFile(Shoot, "assets/Sounds/LaserZap04.wav");
AddFile(Ricochet, "assets/Sounds/bulletby02.wav");
AddFile(Ricochet2, "assets/Sounds/bulletby02.wav");
AddFile(Powerup, "assets/Sounds/powerUp8.wav");
AudioPlayer::Loaded();
}
AudioManager::~AudioManager()
{
//filepaths.clear();
instance = nullptr;
for (auto i = audioPlayers.begin(); i != audioPlayers.end();)
{
Sounds::Type sndtype = i->first;
AudioPlayer* ap = audioPlayers[sndtype];
i = audioPlayers.erase(i); // update iterator
delete ap;
}
}
void AudioManager::Run()
{
}
void Jelly::AudioManager::DoPlaySoundType3D(Sounds::Type sndType, float px, float py, float speed) const
{
if (sndType == Sounds::NONE)
return;
auto ppos = Player::instance->GetPosition();
auto pdiff = glm::vec2(ppos.x - px, ppos.y - py);
auto dist = glm::length(pdiff);
auto dx = (px - ppos.x);
auto lr = clamp(static_cast<int>(std::round(dx * 30)), -100, 100);
auto vol = clamp(static_cast<int>(std::round(100 - dist * 20)), 0, 100);
auto ap = audioPlayers.at(sndType);
ap->Play(vol * 0.01f, lr * 0.01f, speed);
}
void Jelly::AudioManager::DoPlaySoundType2D(Sounds::Type sndType, float speed) const
{
if (sndType == Sounds::NONE)
return;
auto ap = audioPlayers.at(sndType);
ap->Play(1, 0, speed);
}
| 27.367089 | 104 | 0.653099 | RikdeRooij |
08bd3a3cdea5f78aae131b1f54c482654d57607d | 2,388 | cpp | C++ | vm/capi/string19.cpp | godfat/rubinius | d6a7a3323af0348800118ccd0b13fdf80adbbcef | [
"BSD-3-Clause"
] | null | null | null | vm/capi/string19.cpp | godfat/rubinius | d6a7a3323af0348800118ccd0b13fdf80adbbcef | [
"BSD-3-Clause"
] | null | null | null | vm/capi/string19.cpp | godfat/rubinius | d6a7a3323af0348800118ccd0b13fdf80adbbcef | [
"BSD-3-Clause"
] | null | null | null | #include "vm/vm.hpp"
#include "capi/19/include/ruby/ruby.h"
#include "capi/19/include/ruby/encoding.h"
#include "builtin/bytearray.hpp"
#include "builtin/encoding.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/integer.hpp"
#include "builtin/nativemethod.hpp"
#include "builtin/object.hpp"
#include "builtin/string.hpp"
#include "capi/capi.hpp"
#include <string.h>
using namespace rubinius;
using namespace rubinius::capi;
namespace rubinius {
namespace capi {
}
}
extern "C" {
VALUE rb_enc_str_new(const char *ptr, long len, rb_encoding *enc)
{
VALUE str = rb_str_new(ptr, len);
rb_enc_associate(str, enc);
return str;
}
VALUE rb_usascii_str_new(const char* ptr, long len) {
return rb_enc_str_new(ptr, len, rb_usascii_encoding());
}
VALUE rb_usascii_str_new2(const char* ptr) {
return rb_enc_str_new(ptr, strlen(ptr), rb_usascii_encoding());
}
VALUE rb_external_str_new_with_enc(const char* string, long size, rb_encoding* encoding) {
NativeMethodEnvironment* env = NativeMethodEnvironment::get();
String* str = String::create(env->state(), string, size);
str->taint(env->state());
Encoding* enc = Encoding::find(env->state(), encoding->name);
if(enc == Encoding::usascii_encoding(env->state())
&& !CBOOL(str->ascii_only_p(env->state()))) {
str->encoding(env->state(), Encoding::ascii8bit_encoding(env->state()));
} else {
str->encoding(env->state(), enc);
}
// TODO: handle transcoding if necessary
return env->get_handle(str);
}
VALUE rb_external_str_new(const char* string, long size) {
return rb_external_str_new_with_enc(string, size, rb_default_external_encoding());
}
VALUE rb_external_str_new_cstr(const char* string) {
return rb_external_str_new_with_enc(string, strlen(string), rb_default_external_encoding());
}
int rb_enc_str_coderange(VALUE string) {
// TODO
return ENC_CODERANGE_7BIT;
}
VALUE rb_locale_str_new_cstr(const char *ptr) {
// TODO
return rb_str_new2(ptr);
}
VALUE rb_locale_str_new(const char* ptr, long len) {
// TODO
return rb_str_new(ptr, len);
}
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to) {
// TODO
return str;
}
VALUE rb_str_export_to_enc(VALUE str, rb_encoding *enc) {
// TODO
return rb_str_conv_enc(str, rb_enc_get(str), enc);
}
}
| 25.956522 | 96 | 0.697236 | godfat |
08bfc6deaab93e37ad4ace6629735eaaad365ed5 | 88,979 | cpp | C++ | UnoTransport.cpp | ashwin-nat/UnoTransport | a26f55fdfda4b1dbb82359800dcf6788b1945906 | [
"MIT"
] | null | null | null | UnoTransport.cpp | ashwin-nat/UnoTransport | a26f55fdfda4b1dbb82359800dcf6788b1945906 | [
"MIT"
] | null | null | null | UnoTransport.cpp | ashwin-nat/UnoTransport | a26f55fdfda4b1dbb82359800dcf6788b1945906 | [
"MIT"
] | null | null | null | /**
* @file UnoTransport.cpp
* @author Ashwin Natarajan
* @brief This file contains the implementation of the protocol and methods specified in UnoTransport.hpp
* @version 0.1
* @date 2020-08-30
*
* @copyright MIT License
Copyright (c) 2020 Ashwin N
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 "UnoTransport.hpp"
#include <unistd.h> //for close, socket, etc
#include <fcntl.h> //for fcntl to set sockets as non blocking
#include <poll.h> //for poll()
#include <assert.h> //for asserts
#include <arpa/inet.h> //for IPv4 related stuff
#include <vector> //std::vector
#include <stdio.h> //for fprintf, perror, etc
#include <sys/timerfd.h> //for timerfd
#ifdef UNO_TRANSPORT_DEBUG
#include <inttypes.h> //for format specifiers to fixed width integers
#endif
/**************************************************************************************************************************/
//debug specific macros
#ifdef UNO_TRANSPORT_DEBUG
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_RESET "\x1b[0m"
#define UNO_DBG_PREFIX ANSI_COLOR_RED "<====================>"
#define UNO_DBG_SUFFIX "<====================>" ANSI_COLOR_RESET "\n"
#endif
#ifndef UNO_TRANSPORT_DEBUG
#define NDEBUG //remove asserts if the debug macro is not set
#endif
/**************************************************************************************************************************/
//general purpose macros
#define UNO_CLEAR_BIT(x,n) ((x) & ~(1UL << n))
#define UNO_SET_BIT(x,n) ((x) | (1UL << n) )
#define UNO_IS_BIT_SET(x,n) ((x) & (1UL <<n))
#define UNO_SEC_TO_NS(x) ((x) * 1000 * 1000 * 1000)
#define UNO_MS_TO_NS(x) ((x) * 1000 * 1000)
#define UNO_MS_TO_SEC(x) ((x) / 1000)
#define UNO_NS_TO_SEC(x) ((x) / (1000 * 1000 * 1000))
/**************************************************************************************************************************/
//the version of this protocol
#define UNO_TRANSPORT_PROTO_VER 1
/**************************************************************************************************************************/
//header fields lengths
#define UNO_TRANSPORT_HDR_SEQ_LEN 2
#define UNO_TRANSPORT_HDR_RC_LEN 1
#define UNO_TRANSPORT_HDR_PROTO_VER_LEN 1
#define UNO_TRANSPORT_HDR_CMD_LEN 1
#define UNO_TRANSPORT_HDR_MSG_LEN_LEN 2
/**************************************************************************************************************************/
//header fields positions
#define UNO_TRANSPORT_HDR_SEQ_POS 0
#define UNO_TRANSPORT_HDR_RC_POS 2
#define UNO_TRANSPORT_HDR_PROTO_VER_POS 3
#define UNO_TRANSPORT_HDR_CMD_POS 4
#define UNO_TRANSPORT_HDR_MSG_LEN_POS 5
/**************************************************************************************************************************/
//general purpose header related macros
#define UNO_SEQ_ID_RESET 0
#define UNO_TRANSPORT_CTRL_MSG_MAX_SIZE (10)
/**************************************************************************************************************************/
//the below are the bits that are supported in the control flag, the number is their position
#define UNO_TRANSPORT_CMD_CONTROL_MSG (0)
#define UNO_TRANSPORT_CMD_RELIABLE_MSG (1)
#define UNO_TRANSPORT_CMD_ACK_MSG (2)
#define UNO_TRANSPORT_CMD_SPL_MSG (3) //a special msg is one that will be passed to the app layer without any header
//or connection validation, should be used for discovery, control msg flag must
//not be set
//In a control command, extra info will be placed on the data section of the message.
// the first byte will be the command ID, followed by data specific to that command.
// commands must be very simple
/**
* @brief The command ID for connection request. This command is used for both opening and
closing connections There will be one byte of additional data
byte 1 = mode
0 = conn open req
1 = conn close req by client
2 = conn close req by server (explicit, server wants the client gone)
3 = conn close req by server (timeout)
*
*/
#define UNO_TRANSPORT_CTRL_CONN_REQ (1)
#define UNO_TRANSPORT_CTRL_CONN_REQ_LEN (2)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN (0)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ (1)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL (2)
#define UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO (3)
/**
* @brief The command ID for connection response. Additional data for connection response (if successful)
There will be no additional data (msg len = 0) if the server is full
bytes 1,2 = port number (in nwk byte order)
bytes 3,4 = keepalive interval in ms (in nwk byte order)
*
*/
#define UNO_TRANSPORT_CTRL_CONN_RSP (2)
#define UNO_TRANSPORT_CTRL_CONN_RSP_LEN (5)
/**
* @brief The command ID for error status. Additional data:
byte = status code, depends on command, full list to be populated here
*
*/
#define UNO_TRANSPORT_CTRL_ERR_RSP (3)
#define UNO_TRANSPORT_CTRL_ERR_RSP_LEN (2)
/**
* @brief The command ID for connection keep alive. There is no additioanl data for this
*
*/
#define UNO_TRANSPORT_CTRL_KEEPALIVE (4)
#define UNO_TRANSPORT_CTRL_KEEPALIVE_LEN (1)
/**
* @brief The command ID for the connection closed command. This will only be sent by the server
There will be 1 byte of additional data
byte 1 = reason
0 = close requested by client
1 = timedout
2 = explicit close notified by server (the caller doesn't like this client)
*
*/
#define UNO_TRANSPORT_CTRL_CONN_CLOSED (5)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_LEN (2)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_REQ (0)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_TIMEDOUT (1)
#define UNO_TRANSPORT_CTRL_CONN_CLOSED_OPT_EXPL (2)
/**************************************************************************************************************************/
/* HEADER FORMAT - drawn using the awesome website http://asciiflow.com/
+--------------------------------+----------+-------------------------------------+
| seq id |retry |proto.| cmd | msg len | data |
| |count |Ver | | | |
+------------------------+-------+----------+-------------------------------------+
0 2 3 4 5 6
NOTE: all multibyte fields will be in nwk byte order
*/
/**************************************************************************************************************************/
/**
* @brief This struct will hold the header in an easily accessible form. also supports
serialisation and deserialisation
*
*/
struct uno_hdr {
public:
uint16_t seq_id; //sequence id
uint8_t rc; //retry count
uint8_t proto_ver; //protocol version
uint8_t cmd; //command flags
uint16_t msg_len; //message length
/**
* @brief Construct a new uno hdr object with everything set to 0
*
*/
uno_hdr (void) {
seq_id = 0;
rc = 0;
proto_ver = UNO_TRANSPORT_PROTO_VER;
cmd = 0;
msg_len = 0;
}
/**
* @brief Construct a new uno hdr object by deserialising the given flag buffer containing the header
*
* @param hdr pointer to the buffer containing the header
*/
uno_hdr (const uint8_t *hdr) {
deserialise (hdr);
}
/**
* @brief Construct a new uno hdr object using the given paramters
*
* @param seq_id
* @param cmd
* @param msg_len
*/
uno_hdr (uint16_t seq_id, uint8_t cmd, uint16_t msg_len) {
this->seq_id = seq_id;
this->cmd = cmd;
this->msg_len = msg_len;
this->rc = 0;
this->proto_ver = UNO_TRANSPORT_PROTO_VER;
}
/**
* @brief Construct a new uno hdr object. copy the values of x into this
*
* @param x the object to copy from
*/
uno_hdr (const uno_hdr &x) {
seq_id = x.seq_id;
rc = x.rc;
proto_ver = x.proto_ver;
cmd = x.cmd;
msg_len = x.msg_len;
}
/**
* @brief serialise this struct into the given buffer
*
* @param hdr the buffer to which the data is to be serialised, which is assumed
to be not nullptr and large enough
*/
void serialise (uint8_t *hdr) {
//2 bytes seq_id in nwk byte order
hdr[UNO_TRANSPORT_HDR_SEQ_POS+0] = (this->seq_id >> 8) & 0xFF;
hdr[UNO_TRANSPORT_HDR_SEQ_POS+1] = (this->seq_id >> 0) & 0xFF;
//1 byte reboot count
hdr[UNO_TRANSPORT_HDR_RC_POS] = this->rc;
//1 byte proto ver
hdr[UNO_TRANSPORT_HDR_PROTO_VER_POS]= UNO_TRANSPORT_PROTO_VER;
//1 byte cmd info
hdr[UNO_TRANSPORT_HDR_CMD_POS] = this->cmd;
//2 bytes msg len
hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+0]= (this->msg_len >> 8) & 0xFF;
hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+1]= (this->msg_len >> 0) & 0xFF;
}
/**
* @brief deserialise from the given buffer into this hdr struct
*
* @param hdr the buffer containing the header, which is assumed to be not nullptr and
large enough
*/
void deserialise (const uint8_t *hdr) {
//2 byte seq in nwk byte order
seq_id = 0;
seq_id |= hdr[UNO_TRANSPORT_HDR_SEQ_POS+0] << 8;
seq_id |= hdr[UNO_TRANSPORT_HDR_SEQ_POS+1] << 0;
//1 byte reboot count
rc = hdr[UNO_TRANSPORT_HDR_RC_POS];
//1 byte proto ver
proto_ver= hdr[UNO_TRANSPORT_HDR_PROTO_VER_POS];
//1 byte cmd info
cmd = hdr[UNO_TRANSPORT_HDR_CMD_POS];
//2 byte msg len - in nwk byte order
msg_len = 0;
msg_len |= hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+0] << 8;
msg_len |= hdr[UNO_TRANSPORT_HDR_MSG_LEN_POS+1] << 0;
}
/**
* @brief checks if this header is valid or out of order or duplicate
*
* @param exp_seq the expected sequence number
* @return ret returns true if valid
*/
bool is_valid (uint16_t exp_seq) {
return true;
}
};
/**
* @brief This struct is the wrapper for the timer that will be used in this code. Currently, it
uses the linux timerfd
*
*/
struct uno_timer {
public:
int fd;
bool is_armed;
struct itimerspec last_config;
/**
* @brief Construct a new uno timer object. Creates the fd and initialises the fields
*
*/
uno_timer (void) {
//create the fd
fd = timerfd_create (CLOCK_MONOTONIC, 0);
if(fd == UNO_TRANSPORT_ERR) {
//raise exception
;
}
is_armed = false;
memset (&last_config, 0, sizeof(last_config));
}
/**
* @brief Destroy the uno timer object. Closes the fd and clears the fields
*
*/
~uno_timer (void) {
is_armed = false;
memset (&last_config, 0, sizeof(last_config));
close(fd);
fd = UNO_TRANSPORT_ERR;
}
/**
* @brief - sets the timer of this object
*
* @param timer_val - the const struct timespec structure containing the timer delay value
* @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure
*/
int arm_non_recurring (const struct timespec &timer_val) {
assert (timer_val.tv_sec>0 && timer_val.tv_nsec>0);
struct itimerspec val = {{0,},};
val.it_value.tv_sec = timer_val.tv_sec;
val.it_value.tv_nsec = timer_val.tv_nsec;
//arm the timer with the given value
int ret = timerfd_settime (fd, 0, &val, NULL);
if(ret == UNO_TRANSPORT_ERR) {
perror("timerfd_settime");
}
else {
//update the fields of the struct
is_armed = true;
memcpy (&last_config, &val, sizeof(val));
}
return ret;
}
/**
* @brief - clears the timer of this object
*
* @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure
*/
int disarm (void) {
//just returned if not armed
if(is_armed == false) {
return 0;
}
struct itimerspec val = {{0,},};
//disarm the timer
int ret = timerfd_settime (fd, 0, &val, NULL);
if(ret == UNO_TRANSPORT_ERR) {
perror("timerfd_settime");
}
else {
//update the fields of the struct
is_armed = false;
memcpy (&last_config, &val, sizeof(val));
}
return ret;
}
};
/**
* @brief the enum class of the msg types in the cmd field of the header
*
*/
enum class _uno_msg_type {
UNO_MSG_CTRL,
UNO_MSG_ACK,
UNO_MSG_DATA,
UNO_MSG_SPL,
UNO_MSG_UNKNOWN,
};
/**************************************************************************************************************************/
//static function declarations - descriptions will be placed above the definitions
static int _uno_create_client_fd (int broadcast);
static int _uno_create_server_fd (uint16_t port);
static ssize_t _uno_send (int fd, uint8_t *hdr, const void *msg, size_t len, const struct sockaddr_in *dst, uint16_t *seq);
static ssize_t _uno_timed_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src, int to_ms);
static ssize_t _uno_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src);
static _uno_msg_type _uno_get_msg_type (uint8_t cmd);
static void _create_new_connection (int fd, std::list<UnoConnection> &client_list, const struct sockaddr_in &src,
uno_hdr &hdr, uint16_t ka_dur, uint8_t max_conn, const struct timespec &curr_time);
static int _uno_get_port_from_fd (int fd);
static int _uno_process_server_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes,
std::list<UnoConnection> &client_list, uint16_t ka_dur, const struct sockaddr_in &src,
uint8_t max_conn, const struct timespec &curr_time, bool &is_spl);
static int _uno_process_client_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list,
const struct sockaddr_in &src);
static int _uno_send_server_full_rsp (int fd, const struct sockaddr_in &src, uno_hdr &hdr);
static int _uno_send_conn_close (int fd, const struct sockaddr_in &dst, uint16_t *seq);
static void _uno_close_connection_requested (int fd, std::list<UnoConnection> &client_list);
static void _uno_close_connection_requested_iter (std::list<UnoConnection>::iterator iter, std::list<UnoConnection> &client_list);
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list,
const struct sockaddr_in &dst);
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, int fd);
static int _uno_client_process_recv_msg (uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, uint16_t &server_seq);
static int _uno_send_reliable (int fd, uint8_t *hdr_ser, const void *msg, size_t len,
const struct sockaddr_in &dst, uint16_t *seq, uint8_t max_retries, uint16_t retry_interval);
static bool _uno_is_reliable_msg (uint8_t cmd_flags);
static int _uno_send_ack (int fd, const struct sockaddr_in &dst, const uno_hdr &hdr);
static bool _is_seq_valid (int fd, uint16_t inc_seq, uint16_t &saved_seq);
static int _uno_send_conn_close_expl (int fd, const struct sockaddr_in &dst, uint16_t *seq);
static int _uno_send_conn_close_to (int fd, const struct sockaddr_in &dst, uint16_t *seq);
static std::list<UnoConnection>::iterator _uno_find_most_stale_connection (std::list<UnoConnection> &client_list);
static void _uno_compute_timer_value (const struct timespec &last_msg_time, uint16_t keepalive_dur,
const struct timespec &curr_time, struct timespec &_timer_val);
/**************************************************************************************************************************/
//code specific to UnoConnection
/**
* @brief Construct a new Uno Connection object
*
* @param fd The fd of the already created socket
* @param cli reference to the struct socakddr_in holding the client's IPv4 addr
* @param hdr reference to the structure containing the deserialised header
* @param ka_dur the keep alive interval
* @param curr_time const reference to the struct containing the curr time, this value is used
as the initial value for last_msg_time
*/
UnoConnection :: UnoConnection (int fd, const struct sockaddr_in &cli, uno_hdr &hdr, uint16_t ka_dur,
const struct timespec &curr_time)
{
this->fd = _uno_create_client_fd (false);
if(this->fd == UNO_TRANSPORT_ERR) {
;
//throw exception here
}
//get the self addr info from the fd
int temp = _uno_get_port_from_fd (this->fd);
if(temp == UNO_TRANSPORT_ERR) {
//throw exception here
}
self_port = (uint16_t) temp;
//update in structures
memcpy (&cli_addr, &cli, sizeof(cli_addr));
//send the new connection info to the client using the argument fd
this->connected = true;
this->send_connect_rsp (hdr, ka_dur);
this->client_seq = 0;
this->close_reason = _close_reason::CLOSE_REASON_UNKNOWN;
//set the last msg time as the provided curr time
memcpy (&(this->last_msg_time), &curr_time, sizeof(curr_time));
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created new connection fd=%d port=%" PRIu16
" tv_sec=%ld tv_nsec=%ld" UNO_DBG_SUFFIX, this->fd, self_port,
this->last_msg_time.tv_sec, this->last_msg_time.tv_nsec);
#endif
}
/**
* @brief Construct a new Uno Connection object by copying the given one
*
* @param the object from which this one is to be copied from
*/
UnoConnection :: UnoConnection (const UnoConnection &cpy)
{
this->fd = cpy.fd;
this->self_port = cpy.self_port;
memcpy (&(this->cli_addr), &(cpy.cli_addr), sizeof(cpy.cli_addr));
this->client_seq = 0;
memset(&(this->last_msg_time), 0, sizeof(this->last_msg_time));
this->connected = cpy.connected;
this->close_reason = cpy.close_reason;
}
/**
* @brief Destroy the Uno Connection object. Sends connection close req to the client if the
client is still connected
*
*/
UnoConnection :: ~UnoConnection (void)
{
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "in UnoConnection destructor for fd=%d: connected=%d" UNO_DBG_SUFFIX, fd, connected);
#endif
if(this->connected) {
assert (this->close_reason != _close_reason::CLOSE_REASON_UNKNOWN);
switch(this->close_reason) {
//no need to send anything if close was requested by client
case _close_reason::CLOSE_REASON_REQUESTED_BY_CLIENT:
break;
//send explicit connection closure message
case _close_reason::CLOSE_REASON_REQUESTED_BY_SERVER:
_uno_send_conn_close_expl (this->fd, this->cli_addr, nullptr);
break;
//send connection timedout message
case _close_reason::CLOSE_REASON_TIMEDOUT:
_uno_send_conn_close_to (this->fd, this->cli_addr, nullptr);
break;
case _close_reason::CLOSE_REASON_UNKNOWN:
assert (0);
break;
}
this->connected = false;
this->close_reason = _close_reason::CLOSE_REASON_UNKNOWN;
}
close (this->fd);
this->fd = UNO_TRANSPORT_ERR;
this->connected = false;
memset (&(this->self_port), 0, sizeof(this->self_port));
memset (&(this->cli_addr), 0, sizeof(this->cli_addr));
this->client_seq = 0;
memset(&(this->last_msg_time), 0, sizeof(this->last_msg_time));
}
/**
* @brief Sends a connection response to the device sending the connection request
*
* @param hdr info in the header struct
* @param ka_dur the keepalive duration
* @return int retuns number of bytes sent on success, UNO_TRANSPORT_ERR on failure
*/
int UnoConnection :: send_connect_rsp (uno_hdr &hdr, uint16_t ka_dur)
{
uint8_t data[UNO_TRANSPORT_CTRL_CONN_RSP_LEN] = {0,};
//cmd id
data[0] = UNO_TRANSPORT_CTRL_CONN_RSP;
//port number - in nwk byte order
data[1] = (self_port >> 8) & 0xFF;
data[2] = (self_port >> 0) & 0xFF;
//keep alive - in nwk byte order
data[3] = (ka_dur >> 8) & 0xFF;
data[4] = (ka_dur >> 0) & 0xFF;
hdr.msg_len = sizeof(data);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
hdr.serialise(hdr_ser);
return _uno_send (fd, hdr_ser, data, sizeof(data), &cli_addr, NULL);
}
/**
* @brief Set the close reason variable
*
* @param reason
*/
void UnoConnection :: set_close_reason (_close_reason reason)
{
this->close_reason = reason;
}
/**************************************************************************************************************************/
//code specific to UnoTransportClient
/**
* @brief The default constructor for the client class, creates a UDP socket at a random port
*
* @return UnoTransportClient
*/
UnoTransportClient :: UnoTransportClient (void)
{
fd = _uno_create_client_fd (0);
if(fd == UNO_TRANSPORT_ERR) {
//raise exception here
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created client with fd = %d broadcast = 0" UNO_DBG_SUFFIX, fd);
#endif
seq = 0;
memset (&addr, 0, sizeof(addr));
can_broadcast = false;
connected = false;
self_port = (uint16_t) _uno_get_port_from_fd (fd);
}
/**
* @brief Constructor with capability to create a broadcast socket.
*
* @param broadcast set this to true if you want the socket to be able to broadcast
* @return UnoTransportClient N/A
*/
UnoTransportClient :: UnoTransportClient (bool broadcast)
{
//create a socket with broadcast permissions
int opt = (broadcast==true) ? (1) : (0);
fd = _uno_create_client_fd (opt);
if(fd == -1) {
//raise exception here
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created client with fd = %d broadcast = %d" UNO_DBG_SUFFIX, fd, broadcast);
#endif
//initialise other fields
seq = 0;
memset (&addr, 0, sizeof(addr));
can_broadcast = broadcast;
connected = false;
self_port = (uint16_t) _uno_get_port_from_fd (fd);
}
/**
* @brief Destructor for the client class, will close the socket and reset all other fields
*
* @return UnoTransportClient N/A
*/
UnoTransportClient :: ~UnoTransportClient (void)
{
//if connected, disconnect
if(connected) {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "closing connection in client destructor. fd=%d conn_port=%" PRIu16 UNO_DBG_SUFFIX,
fd, ntohs(addr.sin_port));
#endif
_uno_send_conn_close (fd, addr, &seq);
}
//close the socket
if(fd != UNO_TRANSPORT_ERR) {
close (fd);
fd = UNO_TRANSPORT_ERR;
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "destroyed client" UNO_DBG_SUFFIX);
#endif
//clear other fields
seq = 0;
memset (&addr, 0, sizeof(addr));
can_broadcast = false;
connected = false;
self_port = 0;
}
/**
* @brief get the port number of the connection (on the server side) (TO BE REMOVED)
*
* @return uint16_t the port number value
*/
uint16_t UnoTransportClient :: _dbg_get_port (void)
{
return ntohs(this->addr.sin_port);
}
/**
* @brief get the port number of the client side socket (TO BE REMOVED)
*
* @return uint16_t the port number
*/
uint16_t UnoTransportClient :: _dbg_get_self_port (void)
{
return self_port;
}
/**
* @brief Connect to the specified server
*
* @param dst - reference to the struct sockaddr_in instance containing the server's IPv4 address
* @param to_ms - the timeout in milliseconds
* @return int - 0 if successful, UNO_TRANSPORT_ERR if failed
*/
int UnoTransportClient :: connect (const struct sockaddr_in &dst, int to_ms)
{
struct sockaddr_in src;
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (this->fd, hdr_ser, data, sizeof(data), &dst, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent connection req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret,
this->fd, ntohs(dst.sin_port));
#endif
//todo - check source address, and continue waiting if interrupted by other message
if(ret != UNO_TRANSPORT_ERR) {
memset (&src, 0, sizeof(src));
memset (hdr_ser, 0, sizeof(hdr_ser));
uint8_t data[UNO_TRANSPORT_CTRL_MSG_MAX_SIZE] = {0,};
ret = _uno_timed_recv (this->fd, hdr_ser, data, sizeof(data), MSG_WAITALL, &src, to_ms);
hdr.deserialise (hdr_ser);
//process connection response
if(_uno_get_msg_type(hdr.cmd) == _uno_msg_type::UNO_MSG_CTRL &&
data[0] == UNO_TRANSPORT_CTRL_CONN_RSP) {
//if msg len is 1, then the server is full/connection refused
if(hdr.msg_len == 1) {
ret = UNO_TRANSPORT_CONN_REFUSED;
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "received conn refused" UNO_DBG_SUFFIX);
#endif
}
else {
//save the connection details
memcpy (&(this->addr), &src, sizeof(src));
//2 byte port in nwk byte order, save port in nwk byte order
memcpy (&(this->addr.sin_port), data+1, 2);
//2 byte keepalive duration in nwk byte order
this->keepalive_dur = 0;
this->keepalive_dur |= (data[3] << 8);
this->keepalive_dur |= (data[4] << 0);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "received connection rsp %d bytes fd=%d port=%" PRIu16
" ka=%" PRIu16 UNO_DBG_SUFFIX, ret, this->fd, ntohs(this->addr.sin_port), this->keepalive_dur);
#endif
ret = 0;
connected = true;
}
}
}
return ret;
}
/**
* @brief Send a mesage to the server that this client is connected to
*
* @param msg - void pointer to the mesage
* @param len - length of the message
* @return int - returns UNO_TRANSPORT_ERR on failure, or number of bytes sent on success
*/
int UnoTransportClient :: send_msg (const void *msg, size_t len)
{
assert (msg!=nullptr);
assert (len<=UNO_TRANSPORT_MTU);
if(msg==nullptr || len > UNO_TRANSPORT_MTU) {
return UNO_TRANSPORT_ERR;
}
if(this->connected==false) {
return UNO_TRANSPORT_ERR;
}
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
// uint8_t cmd_flags = 0;
uno_hdr hdr (seq, 0, len);
hdr.serialise (hdr_ser);
int ret = _uno_send (this->fd, hdr_ser, msg, len, &addr, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "send message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, this->fd, ret);
#endif
return ret;
}
/**
* @brief Sends the given message to the server, expects an ACK from the server.
*
* @param msg - void pointer to the message
* @param len - length of the message
* @return int - returns
-> positive number of bytes on successful reliable send
-> 0 if the message was sent successfully, but no ACK was received
-> UNO_TRANSPORT_ERR on general failure
*/
int UnoTransportClient :: send_msg_reliable (const void *msg, size_t len)
{
assert (msg!=nullptr);
assert (len<=UNO_TRANSPORT_MTU);
if(msg==nullptr || len > UNO_TRANSPORT_MTU) {
return UNO_TRANSPORT_ERR;
}
if(this->connected==false) {
return UNO_TRANSPORT_ERR;
}
//need to set the reliable msg bit in the cmd section of the header
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
cmd_flags = UNO_SET_BIT (cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG);
uno_hdr hdr (seq, cmd_flags, len);
hdr.serialise (hdr_ser);
int ret;
//send out the message
ret = _uno_send_reliable (this->fd, hdr_ser, msg, len, addr, &seq, UNO_TRANSPORT_REL_MAX_RETRIES,
UNO_TRANSPORT_REL_RETRY_INT_MS);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sen reliable message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, this->fd, ret);
#endif
if(ret == UNO_TRANSPORT_CONN_CLOSE_RECVD) {
//close the socket and clear all fields
close(this->fd);
memset (&(this->addr), 0, sizeof(this->addr));
this->seq = 0;
this->server_seq = 0;
this->connected = 0;
this->can_broadcast = 0;
this->self_port = 0;
}
return ret;
}
/**
* @brief Receives a message from the connected server into the specified server
*
* @param buffer - The buffer where the message is to be written
* @param buffer_size - The size of this buffer
* @param to_ms - The timeout in milliseconds
* @return int - The number of bytes received
*/
int UnoTransportClient :: recv_msg (void *buffer, size_t buffer_size, int to_ms)
{
if(buffer == nullptr || buffer_size == 0) {
return UNO_TRANSPORT_ERR;
}
if(connected == false) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
bool exit_condition = false;
ssize_t bytes;
int ret = UNO_TRANSPORT_ERR;
uno_hdr hdr;
//loop until we get a message intended for the caller
while(!exit_condition) {
memset (hdr_ser, 0, sizeof(hdr_ser));
/*
TODO - reduce to_ms after every iteration of the loop, the whole function should not take more
than to_ms milliseconds. This current version will keep waiting to_ms milliseconds on every
iteration
*/
bytes = _uno_timed_recv (this->fd, hdr_ser, buffer, buffer_size, MSG_WAITALL, NULL, to_ms);
//timedout
if(bytes == 0) {
ret = 0;
break;
}
//every message must be atleast UNO_TRANSPORT_HDR bytes long
if(bytes < UNO_TRANSPORT_HDR_LEN) {
//drop the messsage, continue
continue;
}
//check the validity of the sequence number
if(_is_seq_valid (this->fd, hdr.seq_id, server_seq) == false) {
//drop the packet;
continue;
}
//send ack if reliable message
hdr.deserialise (hdr_ser);
if(_uno_is_reliable_msg(hdr.cmd)) {
_uno_send_ack (this->fd, addr, hdr);
}
//process the message, now that we know it has a valid fmt
bytes = _uno_client_process_recv_msg (hdr, static_cast<uint8_t*>(buffer), bytes, server_seq);
if(bytes == UNO_TRANSPORT_CONN_CLOSE_RECVD) {
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "received conn close req from server" UNO_DBG_SUFFIX);
#endif
ret = (int)bytes;
exit_condition = true;
//close the socket and clear all fields
close(this->fd);
memset (&(this->addr), 0, sizeof(this->addr));
this->seq = 0;
this->server_seq = 0;
this->connected = 0;
this->can_broadcast = 0;
this->self_port = 0;
}
//if unknown message, ignore and continue waiting
else if (bytes == UNO_TRANSPORT_ERR) {
continue;
}
//for positive bytes, this is a data message that is to be delivered to the caller
else if (bytes > 0) {
ret = (int) (bytes - UNO_TRANSPORT_HDR_LEN);
}
//ack messages should not be caught in this function, drop them
else {
// assert (false && "this should never happen");
continue;
}
exit_condition = true;
}
return ret;
}
/**
* @brief - Sends a keepalive message to the server
*
* @return int - returns 0 on success, UNO_TRANSPORT_ERR on failure, UNO_TRANSPORT_CLIENT_NOT_CONN if not connected
*/
int UnoTransportClient :: send_keepalive (void)
{
if(connected == false) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_KEEPALIVE_LEN];
data[0] = UNO_TRANSPORT_CTRL_KEEPALIVE; //command id
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (this->fd, hdr_ser, data, sizeof(data), &addr, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent keepalive ret=%d, fd=%d port %hu" UNO_DBG_SUFFIX, ret,
this->fd, ntohs(addr.sin_port));
#endif
return (ret==UNO_TRANSPORT_ERR) ? (UNO_TRANSPORT_ERR) : (0);
}
/**************************************************************************************************************************/
//code specific to the UnoTransportServer class
/**
* @brief Construct a new Uno Transport Server object. Does not create a socket
*
*/
UnoTransportServer :: UnoTransportServer(void)
{
//intialise all fields, don't create socket without port specified
fd = UNO_TRANSPORT_ERR;
seq = 0;
keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT;
max_conn = UNO_TRANSPORT_DFL_MAX_CONN;
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created server WITHOUT socket" UNO_DBG_SUFFIX);
#endif
// client_list.reserve (max_conn);
}
/**
* @brief Construct a new Uno Transport Server object. Creates a socket with the specified port
*
* @param port - the port number of this server socket
*/
UnoTransportServer :: UnoTransportServer(uint16_t port)
{
keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT;
max_conn = UNO_TRANSPORT_DFL_MAX_CONN;
create_socket (port);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created server at port=%hu" UNO_DBG_SUFFIX, port);
#endif
seq = 0;
}
/**
* @brief Construct a new Uno Transport Server object. Creates a socket with the specified port
*
* @param port - the port number of this server socket
* @param max_connections - the max number of connections supported by this socket
*/
UnoTransportServer :: UnoTransportServer (uint16_t port, uint8_t max_connections)
{
keepalive_dur = UNO_TRANSPORT_KEEPALIVE_INT;
max_conn = max_connections;
create_socket (port);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "created server at port=%hu" UNO_DBG_SUFFIX, port);
#endif
seq = 0;
}
/**
* @brief Destroy the Uno Transport Server object. Sends connection close message to all connected clients
and closes the server side socket
*
*/
UnoTransportServer :: ~UnoTransportServer(void)
{
//close the socket
if(fd != UNO_TRANSPORT_ERR) {
close (fd);
fd = UNO_TRANSPORT_ERR;
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "destroyed server" UNO_DBG_SUFFIX);
#endif
//clear other fields
seq = 0;
}
/**
* @brief Create a socket object at the specified port
*
* @param port - the port number of this server socket
* @return int - the fd number
*/
int UnoTransportServer :: create_socket (uint16_t port)
{
fd = _uno_create_server_fd (port);
if(fd == UNO_TRANSPORT_ERR) {
return fd;
}
seq = 0;
return 0;
}
/**
* @brief Receives the incoming message in the specified buffer. Does not bother the caller with the protocol specific
packets. Handles connection requests, acks, etc
*
* @param buffer - the buffer to store the incoming msg
* @param buffer_size - the size of this buffer
* @param src - optional pointer to the struct sockaddr_in object where the source address is to be filled in
* @param is_spl - reference to the bool variable that will be set if the incoming message is a spl message
* @return int - number of bytes received
*/
int UnoTransportServer :: recv_msg (void *buffer, size_t buffer_size, struct sockaddr_in *src_arg, bool &is_spl)
{
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
struct sockaddr_in src = {0,};
std::vector<struct pollfd> pfds;
ssize_t bytes;
bool exit_condition=false;
int success_count=0;
int ret;
uno_hdr hdr;
struct timespec curr_time;
uno_timer timer;
static std::list<UnoConnection>::iterator _most_stale;
struct timespec _timer_val;
while(!exit_condition) {
timer.disarm();
//clear all data structures
pfds.clear(); //this can probably be optimised
memset (&src, 0, sizeof(src));
memset (hdr_ser, 0, sizeof(hdr_ser));
//build the vector for poll
//first fd is always the server fd
pfds.push_back ({.fd = this->fd, .events = POLLIN});
//note down curr time - we use clock monotonic here because we're not bothered about the actual time
clock_gettime (CLOCK_MONOTONIC, &curr_time);
//find the connection that is going to timeout first
_most_stale = _uno_find_most_stale_connection (client_list);
if(_most_stale != client_list.end()) {
//determine the time remaining till timeout
memset (&_timer_val, 0, sizeof(_timer_val));
_uno_compute_timer_value (_most_stale->last_msg_time, keepalive_dur, curr_time, _timer_val);
timer.arm_non_recurring (_timer_val);
}
//second fd will be the timer fd - it does nothing if it is not armed, so no issue
pfds.push_back ({.fd = timer.fd, .events = POLLIN});
//add the other fd's after this
for(auto iter=this->client_list.begin(); iter!=this->client_list.end(); ++iter) {
pfds.push_back ({.fd = iter->fd, .events = POLLIN});
}
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "pollfd structure has %d fd's" UNO_DBG_SUFFIX, pfds.size());
#endif
//poll on this set of fd's
ret = poll (pfds.data(), pfds.size(), UNO_TRANSPORT_TIMEOUT_INFINITE);
if(ret == UNO_TRANSPORT_ERR) {
perror("poll");
exit_condition = true;
}
else if (ret == 0) {
//this must never happen since we're polling for an indefinite time period
assert (false && "This must never happen");
}
else {
//note down curr time - to minimise number of syscalls
clock_gettime (CLOCK_MONOTONIC, &curr_time);
//read from all fd's with data
success_count = 0;
int index=0;
for(auto iter=pfds.begin(); iter!=pfds.end(), success_count!=ret; index++, iter++) {
//ding ding ding, we have a winner!!!
if((iter->revents) & POLLIN) {
//check if this fd is the timer fd
if(iter->fd == timer.fd) {
assert (_most_stale != this->client_list.end());
//then close the most stale connection
_most_stale->set_close_reason (_close_reason::CLOSE_REASON_TIMEDOUT);
_uno_close_connection_requested_iter (_most_stale, client_list);
break;
}
//receive data from this fd
bytes = _uno_recv (iter->fd, hdr_ser, buffer, buffer_size, MSG_WAITALL, &src);
success_count++;
//the message must atleast by UNO_TRANSPORT_HDR_LEN bytes
if(bytes < UNO_TRANSPORT_HDR_LEN) {
//invalid msg, drop the packet
continue;
}
//deserialise the header
hdr.deserialise (hdr_ser);
//check if reliable msg
if(_uno_is_reliable_msg(hdr.cmd)) {
_uno_send_ack (this->fd, src, hdr);
}
//check if fd that's ready is the server fd
if(iter==pfds.begin()) {
bytes = _uno_process_server_msg (iter->fd, hdr, static_cast<uint8_t*>(buffer), bytes,
this->client_list, this->keepalive_dur, src, max_conn, curr_time, is_spl);
}
//else it must be one of the client conneciton fd's
else {
//find the client in the list
auto _this_client = _find_client_in_list (this->client_list, iter->fd);
//update the last message time
memcpy (&(_this_client->last_msg_time), &curr_time, sizeof(curr_time));
//check the validity of the sequence number
if(_is_seq_valid (iter->fd, hdr.seq_id, _this_client->client_seq) == false) {
//drop the packet;
continue;
}
bytes = _uno_process_client_msg (iter->fd, hdr, static_cast<uint8_t*>(buffer), bytes,
this->client_list, src);
}
//since our process function returns positive values if the messages are data messages
if(bytes > 0) {
ret = (int) bytes;
exit_condition = true;
if(src_arg) { memcpy (src_arg, &src, sizeof(src)); }
break;
}
} //end of if((iter->revents) & POLLIN)
} //end of for loop
} //end of else block
} //end of while(1) loop
return ret;
}
/**
* @brief Sends the given message to the specified client, if connected
*
* @param msg - void pointer to the message
* @param len - the length of the message
* @param dst - const reference to the structure containing the destination
* @return int - returns number of bytes sent on success, UNO_TRANSPORT_CLIENT_NOT_CONN if the client is not found
in the client table, UNO_TRANSPORT_ERR on any general purpose failures
*/
int UnoTransportServer :: send_msg (const void *msg, size_t len, const struct sockaddr_in &dst)
{
if(msg==nullptr) {
return UNO_TRANSPORT_ERR;
}
if(len == 0 ) {
return len;
}
//check if we can find this destination address in the list
auto iter = _find_client_in_list (client_list, dst);
if(iter == client_list.end()) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
//since this is a data message, no bits are to be set in the cmd_info section of the header
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
// uint8_t cmd_flags = 0;
uno_hdr hdr (seq, 0, len);
hdr.serialise (hdr_ser);
//send this header and the message
int ret = _uno_send (iter->fd, hdr_ser, msg, len, &dst, &seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "send message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, iter->fd, ret);
#endif
return ret;
}
/**
* @brief Sends the given message to the given client (if connected), expects an ACK from the recipient.
*
* @param msg - void pointer to the message
* @param len - length of the message
* @return int - returns
-> positive number of bytes on successful reliable send
-> 0 if the message was sent successfully, but no ACK was received
-> UNO_TRANSPORT_ERR on general failure
*/
int UnoTransportServer :: send_msg_reliable (const void *msg, size_t len, const struct sockaddr_in &dst)
{
if(msg==nullptr) {
return UNO_TRANSPORT_ERR;
}
if(len == 0 ) {
return len;
}
//check if we can find this destination address in the list
auto iter = _find_client_in_list (client_list, dst);
if(iter == client_list.end()) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
//need to set the reliable msg bit in the cmd section of the header
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
cmd_flags = UNO_SET_BIT (cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG);
uno_hdr hdr (seq, cmd_flags, len);
hdr.serialise (hdr_ser);
//send this header and the message
int ret = _uno_send_reliable (iter->fd, hdr_ser, msg, len, dst, &seq, UNO_TRANSPORT_REL_MAX_RETRIES,
UNO_TRANSPORT_REL_RETRY_INT_MS);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "send reliable message of len=%d through fd=%d: ret=%d" UNO_DBG_SUFFIX, len, iter->fd, ret);
#endif
if(ret == UNO_TRANSPORT_CONN_CLOSE_RECVD) {
iter->set_close_reason (_close_reason::CLOSE_REASON_REQUESTED_BY_CLIENT);
_uno_close_connection_requested_iter (iter, client_list);
}
return ret;
}
/**
* @brief Sends the connection close requet to the specified client
*
* @param dst - reference to the structure containing the destination
* @return int - returns 0 on success, UNO_TRANSPORT_CLIENT_NOT_CONN if the client is not found
in the client table, UNO_TRANSPORT_ERR on any general purpose failures
*/
int UnoTransportServer ::close_connection (struct sockaddr_in &dst)
{
//first check if we can find this client in the client list
auto iter = _find_client_in_list (client_list, dst);
if(iter == client_list.end()) {
return UNO_TRANSPORT_CLIENT_NOT_CONN;
}
int ret = _uno_send_conn_close_expl (iter->fd, dst, &seq);
//close socket and cleanup
iter->set_close_reason (_close_reason::CLOSE_REASON_REQUESTED_BY_SERVER);
_uno_close_connection_requested_iter (iter, client_list);
return ret;
}
/**************************************************************************************************************************/
/* STATIC FUNCTION DEFINITIONS */
/**************************************************************************************************************************/
/**
* @brief This function creates a client specific socket
*
* @param opt - the option value for SO_BROADCAST
* @return int - the fd value of the socket, returns UNO_TRANSPORT_ERR on failure
*/
static int _uno_create_client_fd (int opt)
{
struct sockaddr_in addr = {0,};
//create the socket
int fd = socket (AF_INET, SOCK_DGRAM, 0);
if(fd == -1) {
perror("socket");
return fd;
}
//set the socket as non blocking since we can use this to discard data
if(fcntl(fd, F_SETFL, O_NONBLOCK) == UNO_TRANSPORT_ERR) {
perror("fcntl");
goto cleanup;
}
//set SO_BROADCAST
if(setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &opt, sizeof(opt)) == UNO_TRANSPORT_ERR) {
perror("setsockopt");
goto cleanup;
}
//bind to address - leave port as 0, the OS will select a random port
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (INADDR_ANY);
if(bind(fd, (const struct sockaddr*)&addr, sizeof(addr)) == UNO_TRANSPORT_ERR) {
perror("bind");
goto cleanup;
}
return fd;
//if error, close the socket to avoid fd leaks
cleanup:
close(fd);
return UNO_TRANSPORT_ERR;
}
/**
* @brief This function creates a server specific socket
*
* @param port - the port to which this socket is to be bound to
* @return int - the fd of the socket, returns UNO_TRANSPORT_ERR on failure
*/
static int _uno_create_server_fd (uint16_t port)
{
struct sockaddr_in addr = {0,};
//create the socket
int fd = socket (AF_INET, SOCK_DGRAM, 0);
if(fd == UNO_TRANSPORT_ERR) {
perror("socket");
return fd;
}
//set the socket as non blocking since we can use this to discard data
if(fcntl(fd, F_SETFL, O_NONBLOCK) == UNO_TRANSPORT_ERR) {
perror("fcntl");
goto cleanup;
}
//bind the socket
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (INADDR_ANY);
addr.sin_port = htons (port);
if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == UNO_TRANSPORT_ERR) {
perror("bind");
goto cleanup;
}
return fd;
//close the fd before returning if failure
cleanup:
close(fd);
return UNO_TRANSPORT_ERR;
}
/**
* @brief THe local function for sending out a message with header and buffef, supports null buffer
*
* @param fd - The fd through which this has to be sent
* @param hdr - uint8_t pointer to the structure containing the fixed length header
* @param msg - the const void pointer to the buffer containing the message
* @param len - the length of the message
* @param dst - pointer to the struct containing the destination
* @param seq - optional pointer to the uint16_t variable tracking the sequence id, will be incremented on successful send
* @return ssize_t - number of bytes sent on success, UNO_TRANSPORT_ERR on failure
*/
static ssize_t _uno_send (int fd, uint8_t *hdr, const void *msg, size_t len, const struct sockaddr_in *dst, uint16_t *seq)
{
//initilase the io vector with the hdr and then the message
//unfortunately, we need a const_cast here because of the way the sendmsg() API is.
size_t iov_len = (msg==NULL) ? (1) : (2);
//prepare the array of vectors, 1st one being the header, followed by the message
struct iovec iov[] = { { .iov_base = hdr,
.iov_len = UNO_TRANSPORT_HDR_LEN},
{ .iov_base = const_cast<void*>(msg),
.iov_len = len},
};
//add these vectors to the message
struct msghdr msg_hdr = { .msg_name = (void*)dst,
.msg_namelen= sizeof(*dst),
.msg_iov = iov,
.msg_iovlen = iov_len,
};
ssize_t ret = sendmsg (fd, &msg_hdr, 0);
if(ret == UNO_TRANSPORT_ERR) {perror("sendmsg");}
else {
//increment the sequence number, if required
if(seq) (*seq)++;
}
return ret;
}
/**
* @brief Waits for the specified number of milliseconds to receive the message. uses poll() for timeout.
uses _uno_recv() for the actual socket recv
*
* @param fd - the fd through which the message is to be received
* @param hdr - pointer to the buffer where the header is to be filled.
* @param buffer - the buffer where the message is to be stored
* @param buffer_size - the size of the provided buffer
* @param flags - the syscall specific flags that are to be passed to _uno_recv()
* @param src - the optional struct sockaddr_in where the source address is to be stored
* @param to_ms - the timeout in milliseconds
* @return ssize_t - returns the number of bytes received if successful, 0 if timedout, UNO_TRANSPORT_ERR if failed
*/
static ssize_t _uno_timed_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src, int to_ms)
{
int ret;
if(to_ms == 0) {
//since it is a non blocking fd, if there is no data, the call will exit immediately
ret = _uno_recv (fd, hdr, buffer, buffer_size, flags, src);
}
else {
//poll on the specified fd
struct pollfd pfd = {.fd = fd, .events = POLLIN};
ret = poll (&pfd, 1, to_ms);
if(ret == UNO_TRANSPORT_ERR) {
//this must never happen
perror("poll");
return ret;
}
//data is ready to be read
else if (ret>0) {
ret = _uno_recv (fd, hdr, buffer, buffer_size, flags, src);
}
}
return ret;
}
/**
* @brief Receives the message into the given header buffer and message buffer provided using recvmsg()
*
* @param fd - the fd through which the data is to be received
* @param hdr - uint8_t pointer to the buffer where the fixed length header is to be received
* @param buffer - the buffer where the mesasge is to be received
* @param buffer_size - the size of the message buffer
* @param flags - flags to be passed to recvmsg()
* @param src - optional pointer to the struct sockaddr_in where the source address is to be filled
* @return ssize_t - returns number of bytes received if successful, UNO_TRANSPORT_ERR if failed
*/
static ssize_t _uno_recv (int fd, uint8_t *hdr, void *buffer, size_t buffer_size, int flags, struct sockaddr_in *src)
{
assert (fd > 2); //since fd's 0,1,2 are reserved
struct iovec iov[] = {{.iov_base = hdr, .iov_len = UNO_TRANSPORT_HDR_LEN}, {.iov_base = buffer, .iov_len = buffer_size}};
struct msghdr msg = { .msg_name = (void*)src,
.msg_namelen= sizeof(*src),
.msg_iov = iov,
.msg_iovlen = 2,
};
ssize_t ret = recvmsg (fd, &msg, flags);
if(ret == UNO_TRANSPORT_ERR) {
perror("recvmsg");
}
return ret;
}
/**
* @brief Returns the enum class value of _uno_msg_type by examining the cmd field of the header
*
* @param cmd The uint8_t value of the cmd_flags
* @return _uno_msg_type - the type of message that this is
*/
static _uno_msg_type _uno_get_msg_type (uint8_t cmd)
{
_uno_msg_type ret = _uno_msg_type :: UNO_MSG_UNKNOWN;
//check ACK bit
if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_ACK_MSG)) {
ret = _uno_msg_type :: UNO_MSG_ACK;
}
//check control bit
else if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_CONTROL_MSG)) {
//ensure that spl bit is not set
if(!(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_SPL_MSG))) {
ret = _uno_msg_type :: UNO_MSG_CTRL;
}
}
//check spl bit
else if (UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_SPL_MSG)) {
//ensure that control bit is not set
if(UNO_IS_BIT_SET(cmd, UNO_TRANSPORT_CMD_CONTROL_MSG)) {
ret = _uno_msg_type :: UNO_MSG_SPL;
}
}
else {
ret = _uno_msg_type :: UNO_MSG_DATA;
}
assert (ret != _uno_msg_type::UNO_MSG_UNKNOWN);
return ret;
}
/**
* @brief Creates a new connection in the client list, or sends a server full message
*
* @param fd - The fd of the server
* @param client_list - reference to the client list
* @param src - reference to the sockaddr_in struct containing the source address
* @param hdr - reference to the structure containing the header
* @param ka_dur - the keepalive duration that is to be sent to the client
* @param max_conn - the max connections supported
* @param curr_time - const reference to the struct timespec containing this message's time
*/
static void _create_new_connection (int fd, std::list<UnoConnection> &client_list, const struct sockaddr_in &src,
uno_hdr &hdr, uint16_t ka_dur, uint8_t max_conn, const struct timespec &curr_time)
{
bool found = false;
int index = 0;
//check if client already exists in the list - if so reuse the connection
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter, index++) {
if(memcmp(&src, &(*iter), sizeof(src)) == 0) {
found = true;
break;
}
}
if(found) {
//TODO
//1. create a new connection and destroy the old one?
//2. reuse the old connection
}
else {
//add the client if the server has space
if(client_list.size() < max_conn) {
//the constructor will send the conection response
client_list.emplace_back (fd, src, hdr, ka_dur, curr_time);
}
else {
//send a server full response
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "sending conn refused msg" PRIu8 UNO_DBG_SUFFIX);
#endif
_uno_send_server_full_rsp (fd, src, hdr);
}
}
}
/**
* @brief returns the port number of the given fd, in host byte order
*
* @param fd - the fd whose port needs to be determined
* @return int - the port number if successful, UNO_TRANSPORT_ERR if failed
*/
static int _uno_get_port_from_fd (int fd)
{
struct sockaddr_in addr = {0,};
socklen_t len = sizeof(addr);
int ret = UNO_TRANSPORT_ERR;
if(getsockname(fd, (struct sockaddr*)&addr, &len) == UNO_TRANSPORT_ERR) {
perror("getsockname");
}
else {
ret = (int)ntohs(addr.sin_port);
}
return ret;
}
/**
* @brief processes incoming messages addressed to the server (not connections)
*
* @param fd - the fd of the server
* @param hdr - rerference to the struct containing the header
* @param buffer - the buffer containing the message
* @param bytes - the length of the message (as returned by _uno_recv())
* @param client_list - reference to the client list of this server
* @param ka_dur - the keepalive duration of this server
* @param src - const reference to the struct containing the source address
* @param max_conn - max connections supported by this server
* @param is_spl - reference to the variable that will be set if the incoming msg is a spl message
* @return int - returns
-> a positive number is a data message and is intended for the caller (spl message)
-> 0 if it is a control message intended for the server, and NOT the caller
-> UNO_TRANSPORT_ERR if failed
*/
static int _uno_process_server_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes,
std::list<UnoConnection> &client_list, uint16_t ka_dur, const struct sockaddr_in &src,
uint8_t max_conn, const struct timespec &curr_time, bool &is_spl)
{
int ret = 0;
is_spl = false;
switch(_uno_get_msg_type (hdr.cmd)) {
case _uno_msg_type :: UNO_MSG_CTRL: {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]);
#endif
//check command id
switch(buffer[0]) {
//incoming connection request, setup the new socket and sent connection rsp
case UNO_TRANSPORT_CTRL_CONN_REQ: {
//if
switch(buffer[1]) {
//process connection open request
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN:
_create_new_connection (fd, client_list, src, hdr, ka_dur, max_conn, curr_time);
ret = 0;
break;
//close connection request must not be coming to the server fd
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO:
default:
ret = UNO_TRANSPORT_ERR;
break;
}
break;
}
//should not be receiving conn response here, drop this packet
case UNO_TRANSPORT_CTRL_CONN_RSP:
//unknown control command, drop this packet
default:
ret = UNO_TRANSPORT_ERR;
break;
}
}
case _uno_msg_type :: UNO_MSG_ACK:
break;
case _uno_msg_type :: UNO_MSG_DATA:
break;
//spl msg is a message from an unconnected client that is intended for the caller
case _uno_msg_type :: UNO_MSG_SPL:
is_spl = true;
ret = hdr.msg_len;
break;
case _uno_msg_type :: UNO_MSG_UNKNOWN:
break;
}
//clear the buffer since it is the caller's buffer, not our own
//bury the evidence
if(ret <= 0) {
memset (buffer, 0, bytes);
}
return ret;
}
/**
* @brief processes incoming messages addressed to the connection (not the server)
*
* @param fd - the fd of the connection
* @param hdr - reference to the struct containing the header
* @param buffer - the buffer containing the message
* @param bytes - the length of the message
* @param client_list - reference to the list of clients of this server
* @param src - const reference to the struct containing the source address
* @return int - returns
-> a positive number is a data message and is intended for the caller
-> 0 if it is a control message intended for the server/connection, and NOT the caller
-> UNO_TRANSPORT_ERR if failed
*/
static int _uno_process_client_msg (int fd, uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, std::list<UnoConnection> &client_list,
const struct sockaddr_in &src)
{
int ret = 0;
switch(_uno_get_msg_type (hdr.cmd)) {
case _uno_msg_type :: UNO_MSG_CTRL: {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]);
#endif
//check command id
switch(buffer[0]) {
//incoming connection request, setup the new socket and sent connection rsp
case UNO_TRANSPORT_CTRL_CONN_REQ: {
//check the options
switch(buffer[1]) {
//drop connection request since this is a connection fd, not the server fd
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN:
ret = UNO_TRANSPORT_ERR;
break;
//process the close connection request from the client
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ:
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received close connection for fd=%d" UNO_DBG_SUFFIX, fd);
#endif
_uno_close_connection_requested (fd, client_list);
ret = 0;
break;
//drop the below connection requests since these modes are reserved from server
//to client
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL:
default:
ret = UNO_TRANSPORT_ERR;
break;
}
break;
}
//keepalive message, don't do anything, just update the last msg time
case UNO_TRANSPORT_CTRL_KEEPALIVE:
ret = 0;
break;
//should not be receiving conn response here, drop this packet
case UNO_TRANSPORT_CTRL_CONN_RSP:
ret = UNO_TRANSPORT_ERR;
break;
//unknown control command, drop this packet
default:
ret = UNO_TRANSPORT_ERR;
break;
}
}
case _uno_msg_type :: UNO_MSG_ACK:
break;
//we need to pass the data message to the caller
case _uno_msg_type :: UNO_MSG_DATA:
ret = (int) hdr.msg_len;
break;
//spl messages are connectionless messages that are only supported in the server fd
case _uno_msg_type :: UNO_MSG_SPL:
ret = UNO_TRANSPORT_ERR;
break;
case _uno_msg_type :: UNO_MSG_UNKNOWN:
break;
}
//clear the buffer since it is the caller's buffer, not our own
if(ret <= 0) {
memset (buffer, 0, bytes);
}
return ret;
}
/**
* @brief Send a connection response message to the client saying that the server is full
*
* @param fd - fd through which the message is to be sent
* @param src - const reference to the sockaddr_in struct containing the source address
* @param hdr - reference to the header structure
* @return int - returns number of bytes sent if successful, UNO_TRANSPORT_ERR if not successful
*/
static int _uno_send_server_full_rsp (int fd, const struct sockaddr_in &src, uno_hdr &hdr)
{
hdr.msg_len = 1;
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
hdr.serialise(hdr_ser);
uint8_t data = UNO_TRANSPORT_CTRL_CONN_RSP;
return _uno_send (fd, hdr_ser, &data, 1, &src, NULL);
}
/**
* @brief Send a connection close message from the client. Called in destructor
*
* @param fd - The fd through which the message is to be sent
* @param dst - const reference to the struct containing the destination address
* @param seq - optional pointer to the uint16_t variable tracking the sequence number
* @return int
*/
static int _uno_send_conn_close (int fd, const struct sockaddr_in &dst, uint16_t *seq)
{
uint16_t seq_id = (seq==nullptr) ? (0) : (*seq);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_RELIABLE_MSG);
uno_hdr hdr (seq_id, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send_reliable (fd, hdr_ser, data, sizeof(data), dst, seq,
UNO_TRANSPORT_REL_MAX_RETRIES, UNO_TRANSPORT_REL_RETRY_INT_MS);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "send conn close cmd fd=%d, ret=%d" UNO_DBG_SUFFIX, fd, ret);
#endif
return ret;
}
/**
* @brief closes the connection of the given fd when a close request is received
*
* @param fd - the fd of the connection to be closexd
* @param client_list - reference to the client list
*/
static void _uno_close_connection_requested (int fd, std::list<UnoConnection> &client_list)
{
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) {
if(fd == iter->fd) {
//found the client in the list
iter->set_close_reason (_close_reason :: CLOSE_REASON_REQUESTED_BY_CLIENT);
_uno_close_connection_requested_iter (iter, client_list);
return;
}
}
}
/**
* @brief closes the connection at the given iterator when a close request is received
*
* @param iter iterator of the node in the client list
* @param client_list reference to the client list
*/
static void _uno_close_connection_requested_iter (std::list<UnoConnection>::iterator iter, std::list<UnoConnection> &client_list)
{
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "closing conn of fd=%d" UNO_DBG_SUFFIX, iter->fd);
#endif
// iter->connected = false;
client_list.erase (iter);
}
/**
* @brief searches the list by IPv4 addr and returns the iterator of the node where the required client info is stored
*
* @param client_list reference to the client list
* @param dst reference to the struct containing the IPv4 address
* @return std::list<UnoConnection>::iterator - position of the client if found, client_list.end() if not found
*/
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list,
const struct sockaddr_in &dst)
{
auto ret = client_list.end();
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) {
if(memcmp(&dst, &(iter->cli_addr), sizeof(dst)) == 0) {
ret = iter;
break;
}
}
return ret;
}
/**
* @brief searches the list by fd and returns the iterator of the node where the required client's info is stored
*
* @param client_list - reference to the client list
* @param fd - fd of the client to be found
* @return std::list<UnoConnection>::iterator - position of the client if found, client_list.end() if not found
*/
static std::list<UnoConnection>::iterator _find_client_in_list (std::list<UnoConnection> &client_list, int fd)
{
auto ret = client_list.end();
for(auto iter=client_list.begin(); iter!=client_list.end(); ++iter) {
if(iter->fd == fd) {
ret = iter;
break;
}
}
return ret;
}
/**
* @brief processes the received message on the client side
*
* @param hdr - reference to the struct containing the header
* @param buffer - pointer to the buffer containing the message
* @param bytes - number of bytes of the total message (including header, arithmetic will be handled here)
* @param server_seq - reference to the variable tracking the sequence numbers used by the server
* @return int - returns
-> positive number (number of bytes) if the message is a data message and should be passed to
the caller
-> 0 if the message is a control message and is not relevant to the caller
-> UNO_TRANSPORT_CONN_CLOSE_RECVD if the server has closed the connection
-> UNO_TRANSPORT_ERR for any other failure case
*/
static int _uno_client_process_recv_msg (uno_hdr &hdr, uint8_t *buffer, ssize_t bytes, uint16_t &server_seq)
{
int ret = 0;
switch(_uno_get_msg_type (hdr.cmd)) {
case _uno_msg_type :: UNO_MSG_CTRL: {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received control message. cmd_id = %" PRIu8 UNO_DBG_SUFFIX, buffer[0]);
#endif
//check command id
switch(buffer[0]) {
//incoming connection request, setup the new socket and sent connection rsp
case UNO_TRANSPORT_CTRL_CONN_REQ: {
//if
switch(buffer[1]) {
//drop connection request since this is a client, not a server (we don't take connections here)
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_CLIENT_REQ:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_OPEN:
ret = UNO_TRANSPORT_ERR;
break;
//process the close connection request - the server wants to close the connection
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO:
case UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL:
ret = UNO_TRANSPORT_CONN_CLOSE_RECVD;
break;
default:
ret = UNO_TRANSPORT_ERR;
break;
}
break;
}
//should not be receiving conn response here, drop this packet
case UNO_TRANSPORT_CTRL_CONN_RSP:
//unknown control command, drop this packet
default:
ret = UNO_TRANSPORT_ERR;
break;
}
}
case _uno_msg_type :: UNO_MSG_ACK:
//ACK packet, we coo'
break;
//we need to pass the data message to the caller
case _uno_msg_type :: UNO_MSG_DATA:
ret = (int) hdr.msg_len;
break;
//spl messages are connectionless messages that are only supported in the server fd
case _uno_msg_type :: UNO_MSG_SPL:
ret = UNO_TRANSPORT_ERR;
break;
case _uno_msg_type :: UNO_MSG_UNKNOWN:
ret = UNO_TRANSPORT_ERR;
break;
}
//clear the buffer since it is the caller's buffer, not our own
if(ret <= 0) {
memset (buffer, 0, bytes);
}
return ret;
}
/**
* @brief function that performs reliable send according to this protocol
*
* @param fd - the fd through which the message is to be sent and the ACK is to be received
* @param hdr_ser - pointer to the buffer containing the fixed length header
* @param msg - pointer to the buffer containing the message
* @param len - length of the message
* @param dst - reference to the struct containing the IPv4 address of the destination
* @param seq - optional pointer to the variable that is being used to track the sequence number of the sender
* @param max_retries - the max retries if ACK is not received
* @param retry_interval - the time to wait before every retry
* @return int - returns
-> positive number of bytes on successful reliable send
-> 0 if the message was sent successfully, but no ACK was received
-> UNO_TRANSPORT_CONN_CLOSE_RECVD if conn close msg is delivered
-> UNO_TRANSPORT_ERR on general failure
*/
static int _uno_send_reliable (int fd, uint8_t *hdr_ser, const void *msg, size_t len,
const struct sockaddr_in &dst, uint16_t *seq, uint8_t max_retries, uint16_t retry_interval)
{
//make sure that the reliable msg bit is set
assert (_uno_is_reliable_msg(hdr_ser[UNO_TRANSPORT_HDR_CMD_POS])==true);
int ret = 0;
uint8_t hdr[UNO_TRANSPORT_HDR_LEN];
struct sockaddr_in src;
int temp;
uint8_t data[2];
//loop and perform all attempts
for(int i=0; i<max_retries; i++) {
memset (hdr, 0, sizeof(hdr));
memset (&src, 0, sizeof(src));
//send out the message
temp = _uno_send (fd, hdr_ser, msg, len, &dst, NULL);
if(temp == UNO_TRANSPORT_ERR) {
ret = temp;
break;
}
//recv the message
temp = _uno_timed_recv (fd, hdr, data, sizeof(data), MSG_WAITALL, &src, retry_interval);
if(temp == UNO_TRANSPORT_ERR) {
break;
}
//if we received a response, check the response
if(temp > 0) {
//check if it is an ack response
if(_uno_get_msg_type(hdr[UNO_TRANSPORT_HDR_CMD_POS]) == _uno_msg_type::UNO_MSG_ACK) {
//TODO - validate seq id and msg len
//successful ack, set ret as temp
ret = temp;
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received ack msg for seq=%" PRIu16 UNO_DBG_SUFFIX,(*seq)-1);
#endif
break;
}
//else check if this is a connection close msg
if(_uno_get_msg_type(hdr[UNO_TRANSPORT_HDR_CMD_POS]) == _uno_msg_type::UNO_MSG_CTRL) {
if(data[0] == UNO_TRANSPORT_CTRL_CONN_CLOSED) {
ret = UNO_TRANSPORT_CONN_CLOSE_RECVD;
break;
}
}
}
//else increment retry count and try again
hdr_ser[UNO_TRANSPORT_HDR_RC_POS]++;
} //end of for loop
//update the sequence number if the send was successful (regardless of ACK)
if(ret != UNO_TRANSPORT_ERR && (seq!=nullptr)) {
(*seq)++;
}
return ret;
}
/**
* @brief Checks if the given cmd_flags indicates that this message is a reliable msg
*
* @param cmd_flags The 8 bit value containing the cmd_flags
* @return - self explanatory
*/
static bool _uno_is_reliable_msg (uint8_t cmd_flags)
{
if(UNO_IS_BIT_SET(cmd_flags,UNO_TRANSPORT_CMD_RELIABLE_MSG)) return true;
else return false;
}
/**
* @brief Sends the ACK to the specified node for the given header
*
* @param fd - the fd through which the data is to be sent
* @param dst - const reference to the struct containing the destination IPv4 address
* @param hdr - reference to the struct containing the header
* @return int - number of bytes sent on success, UNO_TRANSPORT_ERR on failure
*/
static int _uno_send_ack (int fd, const struct sockaddr_in &dst, const uno_hdr &hdr)
{
//ack is the same header, but with msg len as 0 and ack bit as true
//and with no data
uno_hdr ack = hdr;
ack.msg_len = 0;
//make sure that the ACK bit is set
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN];
ack.cmd = UNO_SET_BIT(ack.cmd, UNO_TRANSPORT_CMD_ACK_MSG);
ack.serialise (hdr_ser);
//send out the message
int ret = _uno_send (fd, hdr_ser, NULL, 0, &dst, NULL);
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "received reliable msg at fd=%d of len=%" PRIu16 ", sending ack ret= %d" UNO_DBG_SUFFIX,
fd, hdr.msg_len, ret );
#endif
return ret;
}
/**
* @brief Checks if the sequence number is valid
*
* @param fd - the fd that is involved in this transaction (only for logging purpose)
* @param inc_seq - the incoming sequence number
* @param saved_seq - reference to the last saved sequence number (will be updated if this message is valid)
* @return - self explanatory
*/
static bool _is_seq_valid (int fd, uint16_t inc_seq, uint16_t &saved_seq)
{
//if inc_seq is UNO_SEQ_ID_RESET (0), that means that the device is new or the sequence number has overflown
if(inc_seq == UNO_SEQ_ID_RESET) {
#ifdef UNO_TRANSPORT_DEBUG
fprintf (stderr, UNO_DBG_PREFIX "WARN::seq id has been overflown/reset for fd=%d" UNO_DBG_SUFFIX,
fd);
#endif
saved_seq = inc_seq;
return true;
}
//incoming must always be greater than saved
else if(inc_seq > saved_seq) {
#ifdef UNO_TRANSPORT_DEBUG
if((inc_seq-saved_seq) > 1) {
fprintf (stderr, UNO_DBG_PREFIX "WARN::possible lost packetsinc_seq-saved_seq=%" PRIu16 " for fd=%d"
UNO_DBG_SUFFIX, inc_seq-saved_seq, fd);
}
#endif
saved_seq = inc_seq;
return true;
}
else {
//invalid sequence
#ifdef UNO_TRANSPORT_DEBUG
if(inc_seq == saved_seq) {
fprintf (stderr, UNO_DBG_PREFIX "dropping duplicate packet with seq=%" PRIu16 " for fd=%d" UNO_DBG_SUFFIX,
inc_seq, fd);
}
else {
fprintf (stderr, UNO_DBG_PREFIX "dropping out of order packet with seq=%" PRIu16 " for fd=%d"
" expected=%" PRIu16 UNO_DBG_SUFFIX,
inc_seq, fd, saved_seq+1);
}
#endif
return false;
}
}
/**
* @brief - Sends an explicit connection closure message from the server (caller asked for connection closure)
*
* @param fd - the fd through which the message is to be sent
* @param dst - const reference to the struct containing the destination address
* @param seq - optional pointer to the variable where the sequence id is being tracked, will be incremented if provided
* @return int - returns number of bytes sent if successful, else UNO_TRANSPORT_ERR if failure
*/
static int _uno_send_conn_close_expl (int fd, const struct sockaddr_in &dst, uint16_t *seq)
{
uint16_t seq_id = (seq==nullptr) ? (0) : (*seq);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_EXPL; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq_id, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (fd, hdr_ser, data, sizeof(data), &dst, seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent explicit connection close req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret,
fd, ntohs(dst.sin_port));
#endif
return ret;
}
/**
* @brief - Sends an explicit connection timedout message from the server (no data in the specified keepalive duration)
*
* @param fd - the fd through which the message is to be sent
* @param dst - const reference to the struct containing the destination address
* @param seq - optional pointer to the variable where the sequence id is being tracked, will be incremented if provided
* @return int - returns number of bytes sent if successful, else UNO_TRANSPORT_ERR if failure
*/
static int _uno_send_conn_close_to (int fd, const struct sockaddr_in &dst, uint16_t *seq)
{
uint16_t seq_id = (seq==nullptr) ? (0) : (*seq);
uint8_t hdr_ser[UNO_TRANSPORT_HDR_LEN] = {0,};
uint8_t cmd_flags = 0;
//this is the data section for the connection request command
uint8_t data[UNO_TRANSPORT_CTRL_CONN_REQ_LEN];
data[0] = UNO_TRANSPORT_CTRL_CONN_REQ; //command id
data[1] = UNO_TRANSPORT_CTRL_CONN_REQ_OPT_MODE_CLOSE_SERVER_TO; //command mode
//set the control msg bit in the cmd field of the hdr and serialise the hdr
cmd_flags = UNO_SET_BIT(cmd_flags, UNO_TRANSPORT_CMD_CONTROL_MSG);
uno_hdr hdr (seq_id, cmd_flags, sizeof(data));
//send this msg out
hdr.serialise (hdr_ser);
int ret = _uno_send (fd, hdr_ser, data, sizeof(data), &dst, seq);
#ifdef UNO_TRANSPORT_DEBUG
fprintf(stderr, UNO_DBG_PREFIX "sent timedout connection close req %d bytes to fd=%d port %hu" UNO_DBG_SUFFIX, ret,
fd, ntohs(dst.sin_port));
#endif
return ret;
}
/**
* @brief - linearly searches through the list and finds the connection that is set to timeout the earliest
*
* @param client_list - reference to the client list
* @return std::list<UnoConnection>::iterator - returns an iterator at the position in the client list
*/
static std::list<UnoConnection>::iterator _uno_find_most_stale_connection (std::list<UnoConnection> &client_list)
{
if(client_list.empty()) {
return client_list.end();
}
//initialise the oldest time
struct timeval oldest;
auto ret = client_list.begin();
memcpy (&oldest, &(ret->last_msg_time), sizeof(oldest));
//skip the first item since it is already stored in oldest
auto iter=client_list.begin();
++iter;
//loop through the list
for(; iter!=client_list.end(); ++iter) {
//compare seconds field
if(iter->last_msg_time.tv_sec < oldest.tv_sec) {
//update oldest and ret
memcpy (&oldest, &(iter->last_msg_time), sizeof(oldest));
ret = iter;
}
//if seconds are equal, compare nanoseconds field
else if(iter->last_msg_time.tv_nsec < iter->last_msg_time.tv_nsec) {
//update oldest and ret
memcpy (&oldest, &(iter->last_msg_time), sizeof(oldest));
ret = iter;
}
//else ignore
else {
; //left here for readability, the compiler will optimise this out
}
}
return ret;
}
/**
* @brief - computes the difference between 2 timespec structs. performs (end-start)
*
* @param start - const reference to the timespec containing the start time
* @param end - const reference to the timespec containing the end time.
* @param result - reference to the struct where the result of the difference will be stored
*/
static void __uno_timespec_diff (const struct timespec &start, const struct timespec &end, struct timespec &result)
{
assert (end.tv_sec >= start.tv_sec);
//assumes end is greater than start, does not check, it is the caller's responsibility to ensure this
if(end.tv_nsec < start.tv_nsec) {
assert (end.tv_sec > start.tv_sec);
result.tv_sec = end.tv_sec - start.tv_sec - 1;
result.tv_nsec = end.tv_nsec - start.tv_nsec + UNO_SEC_TO_NS(1);
}
else {
result.tv_sec = end.tv_sec - start.tv_sec;
result.tv_nsec = end.tv_nsec - start.tv_nsec;
}
}
/**
* @brief - computes the sum between 2 timespec structs
*
* @param start - const reference to the timespec containing the start time
* @param end - const reference to the timespec containing the end time
* @param result - reference to the struct where the result will be stored
*/
static void __uno_timespec_sum (const struct timespec &start, const struct timespec &end, struct timespec &result)
{
result.tv_sec = start.tv_sec + end.tv_sec;
result.tv_nsec = start.tv_nsec + end.tv_nsec;
//now check for "overflow", if result.tv_nsec is greater than 10^9
if(result.tv_nsec > UNO_SEC_TO_NS(1)) {
result.tv_sec++;
result.tv_nsec = result.tv_nsec % UNO_SEC_TO_NS(1);
}
}
/**
* @brief - computes the value to be passed to timerfd_settime given the last message time, the keepalive duration (in ms),
the current time
*
* @param last_msg_time - const reference to the struct containing the last message time
* @param keepalive_dur_ms - the expected keepalive duration (in milliseconds)
* @param curr_time - const reference to the timespec containing the curr time
* @param timer_val - the timespec where the computed timer value is to be written
*/
static void _uno_compute_timer_value (const struct timespec &last_msg_time, uint16_t keepalive_dur_ms,
const struct timespec &curr_time, struct timespec &timer_val)
{
//transform keepalive_dur_ms to struct timespec
struct timespec _keep_alive = {0,};
_keep_alive.tv_sec = UNO_MS_TO_SEC(keepalive_dur_ms);
if(keepalive_dur_ms % 1000) {
_keep_alive.tv_nsec = UNO_MS_TO_NS(keepalive_dur_ms % 1000);
}
//compute expiry time
struct timespec _expiry_time = {0,};
__uno_timespec_sum (last_msg_time, _keep_alive, _expiry_time);
//now the timervalue is the difference between _expiry_time and curr_time
__uno_timespec_diff (curr_time, _expiry_time, timer_val);
} | 39.094464 | 135 | 0.620371 | ashwin-nat |
08bff7998f296020b5eae82d91978a16d01d69da | 1,533 | cpp | C++ | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/ReadPenalties.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/ReadPenalties.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/ReadPenalties.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | #include "./INCLUDE/LKH.h"
/*
* The ReadPenalties function attempts to read node penalties (Pi-values)
* from file.
*
* The first line of the file contains the number of nodes.
*
* Each of the following lines is of the form
* <integer> <integer>
* where the first integer is a node number, and the second integer
* is the Pi-value associated with the node.
*
* If reading succeeds, the function returns 1; otherwise 0.
*
* The function is called from the CreateCandidateSet function.
*/
namespace LKH {
static thread_local int PenaltiesRead = 0;
void LKHAlg::freeReadPenalties()
{
PenaltiesRead = 0;
}
int LKHAlg::ReadPenalties()
{
int i, Id;
Node *Na, *Nb = 0;
if (PiFileName == 0)
return 0;
if (PenaltiesRead || !strcmp(PiFileName, "0"))
return PenaltiesRead = 1;
if (!(PiFile = fopen(PiFileName, "r")))
return 0;
if (TraceLevel >= 1)
printff("Reading PI_FILE: \"%s\" ... ", PiFileName);
fscanint(PiFile, &i);
if (i != Dimension)
eprintf("PI_FILE \"%s\" does not match problem", PiFileName);
fscanint(PiFile, &Id);
assert(Id >= 1 && Id <= Dimension);
FirstNode = Na = &NodeSet[Id];
fscanint(PiFile, &Na->Pi);
for (i = 2; i <= Dimension; i++) {
fscanint(PiFile, &Id);
assert(Id >= 1 && Id <= Dimension);
Nb = &NodeSet[Id];
fscanint(PiFile, &Nb->Pi);
Nb->Pred = Na;
Na->Suc = Nb;
Na = Nb;
}
FirstNode->Pred = Nb;
Nb->Suc = FirstNode;
fclose(PiFile);
if (TraceLevel >= 1)
printff("done\n");
return PenaltiesRead = 1;
}
} | 24.333333 | 73 | 0.629485 | BaiChunhui-9803 |
08c2155ebd781021501c4901e5fec5cbdd2518dd | 1,511 | cpp | C++ | launcher/settings/INIFile_test.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 2,777 | 2015-01-02T17:20:34.000Z | 2021-10-20T12:34:27.000Z | launcher/settings/INIFile_test.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 3,537 | 2015-01-01T00:51:03.000Z | 2021-10-20T07:35:33.000Z | launcher/settings/INIFile_test.cpp | Spacc-Inc/MultiMC5-Cracked | 4afe2466fd5639bf8a03bfb866c070e705420d86 | [
"Apache-2.0"
] | 774 | 2015-01-07T19:44:39.000Z | 2021-10-19T18:10:38.000Z | #include <QTest>
#include "TestUtil.h"
#include "settings/INIFile.h"
class IniFileTest : public QObject
{
Q_OBJECT
private
slots:
void initTestCase()
{
}
void cleanupTestCase()
{
}
void test_Escape_data()
{
QTest::addColumn<QString>("through");
QTest::newRow("unix path") << "/abc/def/ghi/jkl";
QTest::newRow("windows path") << "C:\\Program files\\terrible\\name\\of something\\";
QTest::newRow("Plain text") << "Lorem ipsum dolor sit amet.";
QTest::newRow("Escape sequences") << "Lorem\n\t\n\\n\\tAAZ\nipsum dolor\n\nsit amet.";
QTest::newRow("Escape sequences 2") << "\"\n\n\"";
QTest::newRow("Hashtags") << "some data#something";
}
void test_Escape()
{
QFETCH(QString, through);
QString there = INIFile::escape(through);
QString back = INIFile::unescape(there);
QCOMPARE(back, through);
}
void test_SaveLoad()
{
QString a = "a";
QString b = "a\nb\t\n\\\\\\C:\\Program files\\terrible\\name\\of something\\#thisIsNotAComment";
QString filename = "test_SaveLoad.ini";
// save
INIFile f;
f.set("a", a);
f.set("b", b);
f.saveFile(filename);
// load
INIFile f2;
f2.loadFile(filename);
QCOMPARE(a, f2.get("a","NOT SET").toString());
QCOMPARE(b, f2.get("b","NOT SET").toString());
}
};
QTEST_GUILESS_MAIN(IniFileTest)
#include "INIFile_test.moc"
| 23.609375 | 104 | 0.568498 | Spacc-Inc |
08c219c9ee01e0db5940f85eb21f871c5b6d4a68 | 1,376 | hxx | C++ | com/ole32/com/inc/memdebug.hxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/ole32/com/inc/memdebug.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/ole32/com/inc/memdebug.hxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+--------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1992
//
// File: memdebug.hxx
//
// Contents: Error code handler routines
//
// History: 19-Mar-92 DrewB Created
//
//---------------------------------------------------------------
#ifndef __MEMDEBUG_HXX__
#define __MEMDEBUG_HXX__
#if DBG == 1
#define ErrJmp(comp, label, errval, var) \
{\
var = errval;\
comp##DebugOut((DEB_IERROR, "Error %lX at %s:%d\n",\
(unsigned long)var, __FILE__, __LINE__));\
goto label;\
}
#else
#define ErrJmp(comp, label, errval, var) \
{\
var = errval;\
goto label;\
}
#endif
#define memErr(l, e) ErrJmp(mem, l, e, sc)
#define memChkTo(l, e) if (FAILED(sc = (e))) memErr(l, sc) else 1
#define memHChkTo(l, e) if (FAILED(sc = GetScode(e))) memErr(l, sc) else 1
#define memChk(e) memChkTo(EH_Err, e)
#define memHChk(e) memHChkTo(EH_Err, e)
#define memMemTo(l, e) \
if ((e) == NULL) memErr(l, E_OUTOFMEMORY) else 1
#define memMem(e) memMemTo(EH_Err, e)
#if DBG == 1
DECLARE_DEBUG(mem)
#define memDebugOut(x) memInlineDebugOut x
#define memAssert(x) Win4Assert(x)
#define memVerify(x) Win4Assert(x)
#else
#define memDebugOut(x)
#define memAssert(x)
#define memVerify(x) (x)
#endif
#endif // #ifndef __MEMDEBUG_HXX__
| 24.571429 | 75 | 0.579942 | npocmaka |
08c3d0fa4ab85ad2966db26ba479f8b6eb3dadb8 | 3,393 | cpp | C++ | src/engine/core/rendering/Texture.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null | src/engine/core/rendering/Texture.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null | src/engine/core/rendering/Texture.cpp | maksmaisak/Saxion_Y2Q2_Rendering | 14cf23c4e333599f16d200879301e8d5548e562b | [
"MIT"
] | null | null | null |
#include "Texture.hpp"
#include <algorithm>
#include <utility>
#include <iostream>
#include <string>
#include <cassert>
#include <array>
#include <SFML/Graphics.hpp> // For sf::Image
#include "glm.hpp"
#include "GLHelpers.h"
using namespace en;
namespace {
int getNumMipmaps(Texture::Size size) {
int i = 1;
while (true) {
size.x = std::max(1, size.x / 2);
size.y = std::max(1, size.y / 2);
if (size.x == 1 && size.y == 1)
break;
++i;
}
return i;
}
}
Texture::Texture(const std::string& filename, GLint internalFormat) {
// Load from file using sf::Image, then put the data in an openGL buffer.
sf::Image image;
if (!image.loadFromFile(filename))
return;
auto temp = image.getSize();
m_size = {temp.x, temp.y};
// 0, 0 in sf::Image is top left, but openGL expects 0,0 to be bottom left, flip to compensate.
image.flipVertically();
glCheckError();
glGenTextures(1, &m_id);
glBindTexture(GL_TEXTURE_2D, m_id);
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, m_size.x, m_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
glGenerateMipmap(GL_TEXTURE_2D);
}
glBindTexture(GL_TEXTURE_2D, 0);
m_kind = Kind::Texture2D;
}
Texture::Texture(const std::array<std::string, 6>& cubeSidePaths, GLint internalFormat) {
std::array<sf::Image, 6> images;
for (GLuint i = 0; i < images.size(); ++i)
if (!images[i].loadFromFile(cubeSidePaths[i]))
return;
glGenTextures(1, &m_id);
glBindTexture(GL_TEXTURE_CUBE_MAP, m_id);
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
for (GLuint i = 0; i < 6; ++i) {
const sf::Image& image = images[i];
auto temp = image.getSize();
m_size = {temp.x, temp.y};
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat, m_size.x, m_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
}
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
}
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
m_kind = Kind::TextureCube;
}
Texture::Texture(Texture&& other) noexcept : m_id(std::exchange(other.m_id, 0)) {}
Texture& Texture::operator=(Texture&& other) noexcept {
m_id = std::exchange(other.m_id, 0);
return *this;
}
Texture::~Texture() {
glDeleteTextures(1, &m_id);
}
GLuint Texture::getId() const {
return m_id;
}
bool Texture::isValid() const {
return m_id != 0 && m_kind != Kind::None;
}
Texture::Kind Texture::getKind() const {
return m_kind;
}
Texture::Size Texture::getSize() const {
return m_size;
}
| 27.144 | 153 | 0.625995 | maksmaisak |
c095ac245c998b6c3b6e13d78df775b1a04017ea | 3,032 | hxx | C++ | main/sw/inc/fmturl.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sw/inc/fmturl.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sw/inc/fmturl.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _FMTURL_HXX
#define _FMTURL_HXX
#include <svl/poolitem.hxx>
#include "swdllapi.h"
#include <hintids.hxx>
#include <format.hxx>
class ImageMap;
class IntlWrapper;
// URL, ServerMap und ClientMap
class SW_DLLPUBLIC SwFmtURL: public SfxPoolItem
{
String sTargetFrameName; // in diesen Frame soll die URL
String sURL; //Einfache URL
String sName; // Name des Anchors
ImageMap *pMap; //ClientSide Images
sal_Bool bIsServerMap; //mit der URL eine ServerSideImageMap
SwFmtURL& operator=( const SwFmtURL& );
public:
SwFmtURL();
// @@@ copy construction allowed, but assigment is not? @@@
SwFmtURL( const SwFmtURL& );
virtual ~SwFmtURL();
// "pure virtual Methoden" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
SfxMapUnit eCoreMetric,
SfxMapUnit ePresMetric,
String &rText,
const IntlWrapper* pIntl = 0 ) const;
virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const;
virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 );
void SetTargetFrameName( const String& rStr ) { sTargetFrameName = rStr; }
void SetURL( const String &rURL, sal_Bool bServerMap );
void SetMap( const ImageMap *pM ); //Pointer wird kopiert!
const String &GetTargetFrameName()const { return sTargetFrameName; }
const String &GetURL() const { return sURL; }
sal_Bool IsServerMap() const { return bIsServerMap; }
const ImageMap *GetMap() const { return pMap; }
ImageMap *GetMap() { return pMap; }
const String& GetName() const { return sName; }
void SetName( const String& rNm ) { sName = rNm; }
};
inline const SwFmtURL &SwAttrSet::GetURL(sal_Bool bInP) const
{ return (const SwFmtURL&)Get( RES_URL,bInP); }
inline const SwFmtURL &SwFmt::GetURL(sal_Bool bInP) const
{ return aSet.GetURL(bInP); }
#endif
| 34.067416 | 103 | 0.675132 | Grosskopf |
c09718d963b239802830ca2ce22bfbd41913313c | 13,342 | cpp | C++ | src/cost_functions/src/cost_functions.cpp | codyreading/CarND-Path-Planning-Project | b93f0da2e9ec30416b71497725521955e6c2c315 | [
"MIT"
] | null | null | null | src/cost_functions/src/cost_functions.cpp | codyreading/CarND-Path-Planning-Project | b93f0da2e9ec30416b71497725521955e6c2c315 | [
"MIT"
] | null | null | null | src/cost_functions/src/cost_functions.cpp | codyreading/CarND-Path-Planning-Project | b93f0da2e9ec30416b71497725521955e6c2c315 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <functional>
#include <math.h>
#include "cost_functions.hpp"
#include "vehicle.hpp"
#include "path.hpp"
#include "state_machine.hpp"
#include "collision_detector.hpp"
#include "utils.hpp"
double speedCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
double avg_speed = path.averageSpeed(CONTROLLER_UPDATE_RATE_SECONDS);
double epislon = 0.001;
if (avg_speed > MAX_SPEED_METERS_PER_SECOND + epislon)
{
return weight;
}
double diff = (MAX_SPEED_METERS_PER_SECOND - avg_speed) / MAX_SPEED_METERS_PER_SECOND;
// double diff = (MAX_SPEED_METERS_PER_SECOND - avg_speed);
// double diff = avg_speed / MAX_SPEED_METERS_PER_SECOND;
// cout << "**** Speed diff " << diff << endl;
return weight * (1 - exp(-abs(diff)));
}
double centerOfLaneDistCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
double final_d = path.m_d[path.m_d.size() - 1];
int lane = calculateLane(final_d, DEFAULT_LANE_SPACING, DEFAULT_LANE_INSIDE_OFFSET);
int lane_center = getLaneCenterFrenet(lane);
double diff = lane_center - final_d;
return weight * (1 - exp(-abs(diff)));
}
double laneChangeCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
if (state.current_lane == state.future_lane)
{
// No penalty if staying on the same lane
return 0.0;
}
// Weight penalty if switching lane
return weight;
}
/**
* @brief Cost function that increases the penalty the closer the car ahead is from the
* ego vehicle
*
* @param ego
* @param others
* @param path
* @param state
* @param weight
* @return double
*/
double distanceToClosestCarAheadCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// We are switching lanes and this is not a cancellable operation
// if (state.d_state == LateralState::CHANGE_LANE_LEFT || state.d_state == LateralState::CHANGE_LANE_RIGHT)
// {
// return 0;
// }
// Find closest car ahead and get distance
if (!ego.m_isInLane)
{
return weight;
}
// Find all vehicles ahead on the current lane
std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane);
if (ahead.size() == 0)
{
return 0.0;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : ahead)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
// TODO We may also want to take speed into account
double diff = (VEHICLE_DISTANCE_THRESHOLD_METERS - min_distance) / VEHICLE_DISTANCE_THRESHOLD_METERS;
return weight * (1 - exp(-abs(diff)));
}
double longitudinalDistanceToClosestAdjacentCarFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// This cost function only applies to lane changes
if (state.current_lane == state.future_lane && state.current_lane == ego.m_lane)
{
return 0.0;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : others)
{
if (v.m_isInLane && v.m_lane == state.future_lane)
{
// Other car is on different lane
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
}
// cout << "**************** DISTANCE ADJACENT LANE = " << min_distance << endl;
double diff = (VEHICLE_DISTANCE_THRESHOLD_METERS - min_distance);
return weight * (1 - exp(-abs(diff)));
}
double distanceToClosestCarAheadFutureLaneCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// Since we are not planning to switch lanes there is no cost in this case
if (state.d_state == LateralState::STAY_IN_LANE)
{
return 0.0;
// return distanceToClosestCarAheadCostFunction(ego, others, path, state, weight);
}
// Find closest car ahead and get distance
if (!ego.m_isInLane)
{
return weight;
}
std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane);
double min_distance = LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : ahead)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
double diff_ahead = (LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS - min_distance) / LANE_CHANGE_VEHICLE_AHEAD_DISTANCE_THRESHOLD_METERS;
std::vector<Vehicle> behind = ego.behind(others, state.future_lane);
min_distance = LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS;
for (const Vehicle &v : behind)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
}
}
double diff_behind = (LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS - min_distance) / LANE_CHANGE_VEHICLE_BEHIND_DISTANCE_THRESHOLD_METERS;
// cout << "*** DISTANCE RATIO AHEAD = " << diff_ahead << ", DISTANCE RATIO BEHIND = " << diff_behind << endl;
double diff = diff_behind + diff_ahead;
return weight * (1 - exp(-diff));
}
/**
* @brief Computes a cost function that penalises the future lane depending
* on the average speed of all vehicles ahead
*
* @param ego
* @param others
* @param path
* @param state
* @param weight
* @return double
*/
double averageLaneSpeedDiffCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// We are switching lanes and this is not a cancellable operation
if (state.d_state == LateralState::CHANGE_LANE_LEFT || state.d_state == LateralState::CHANGE_LANE_RIGHT)
{
return 0;
}
// Not in lane so doesn't count
if (!ego.m_isInLane)
{
return 0.0;
}
// Find all vehicles ahead
std::vector<Vehicle> ahead = ego.ahead(others, state.future_lane);
if (ahead.size() == 0)
{
return 0.0;
}
double speed_avg = 0.0;
int count = 0;
for (const Vehicle &v : ahead)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
// Only look a bit ahead
if (dist <= VEHICLE_DISTANCE_THRESHOLD_METERS * 1.5)
{
speed_avg += v.getSpeed();
++count;
}
}
if (count == 0)
{
return 0.0;
}
speed_avg /= (double)count;
cout << "** Speed average of lane " << state.future_lane << ": " << speed_avg << endl;
// It's OK if the future lane is very fast... as long as ego itself keeps within the speed limits
if (speed_avg >= MAX_SPEED_METERS_PER_SECOND)
{
return 0.0;
}
// This time, let's get a ratio as it will produce a smoother result
double diff = (MAX_SPEED_METERS_PER_SECOND - speed_avg) / MAX_SPEED_METERS_PER_SECOND;
return weight * (1 - exp(-abs(diff)));
}
double speedDifferenceWithClosestCarAheadCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// TODO need to review this
if (!ego.m_isInLane)
{
return 0.0;
}
std::vector<Vehicle> ahead = ego.ahead(others, state.current_lane);
if (ahead.size() == 0)
{
return 0.0;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
Vehicle closest_vehicle;
for (const Vehicle &v : ahead)
{
// Other car must be ahead in the same lane
if (v.m_s > ego.m_s)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
closest_vehicle = v;
}
}
}
if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS)
{
// No need to penalize if vehicle ahead is far enough...
return 0.0;
}
double ego_speed = path.averageSpeed(1.0);
double v_speed = closest_vehicle.getSpeed();
// cout << "** Future ego speed (future lane=" << state.future_lane << ", current lane=" << state.current_lane << ") : " << ego_speed
// << " other vehicle (lane=" << closest_vehicle.lane << ") : " << v_speed << endl;
// If ego is going faster than the vehicle ahead then we want to penalise it because it could lead to a collision
if (ego_speed > v_speed)
{
return weight;
}
// Otherwise we just want ego to match the speed of the vehicle ahead
double diff = v_speed - ego_speed;
return weight * (1 - exp(-abs(diff)));
}
// TODO Compute the average speed of lanes
double lanesAverageForwardSpeedCarsAhead(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// TODO need to review this
if (!ego.m_isInLane)
{
return weight;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
Vehicle closest_vehicle;
for (const Vehicle &v : others)
{
// Other car must be ahead in the same lane
if (v.m_isInLane && v.m_lane == state.future_lane && v.m_s > ego.m_s)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
closest_vehicle = v;
}
}
}
if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS)
{
// No need to penalize if vehicle ahead is far enough...
return 0.0;
}
double ego_speed = path.averageSpeed(1.0);
double v_speed = closest_vehicle.getSpeed();
// cout << "** Future ego speed (future lane=" << state.future_lane << ", current lane=" << state.current_lane << ") : " << ego_speed
// << " other vehicle (lane=" << closest_vehicle.lane << ") : " << closest_vehicle.getSpeed() << endl;
double diff = v_speed - ego_speed;
return weight * (1 - exp(-abs(diff)));
}
double collisionTimeCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
// TODO need to review this
if (!ego.m_isInLane)
{
return weight;
}
double min_distance = VEHICLE_DISTANCE_THRESHOLD_METERS;
Vehicle closest_vehicle;
for (const Vehicle &v : others)
{
if (v.m_isInLane && (v.m_lane == state.current_lane || v.m_lane == state.future_lane) && v.m_s >= ego.m_s)
{
double dist = distance(ego.m_x, ego.m_y, v.m_x, v.m_y);
if (dist < min_distance)
{
min_distance = dist;
closest_vehicle = v;
}
}
}
if (min_distance >= VEHICLE_DISTANCE_THRESHOLD_METERS)
{
// No need to penalize if vehicle ahead is far enough...
return 0.0;
}
Collision collision = predictCollision(path, closest_vehicle, CONTROLLER_UPDATE_RATE_SECONDS);
if (!collision.willCollide)
{
// If no collision foreseen then don't penalize
return 0.0;
}
double ego_speed = path.averageSpeed(1.0);
// cout << "** Collision with vehicle at timestep = " << collision.collision_timestep << endl;
// Collision is far away so can be ignored for now
if (collision.collision_timestep > COLLISION_MAX_TIMESTEP_THRESHOLD)
{
return 0.0;
}
double speed_ratio = ego_speed / MAX_SPEED_METERS_PER_SECOND;
double timestep_ratio = (COLLISION_MAX_TIMESTEP_THRESHOLD - collision.collision_timestep) / COLLISION_MAX_TIMESTEP_THRESHOLD;
cout << "*** SPEED RATIO = " << speed_ratio << endl;
cout << "*** TIMESTEP RATIO = " << timestep_ratio << endl;
// double diff = 75 - (collision.collision_timestep + 5 * speed_ratio);
double diff = speed_ratio + timestep_ratio;
cout << "*** TIMESTEP + SPEED RATIO = " << diff << endl;
// Otherwise penalize as a factor of the time to collision - the further away in time the better
return weight * (1 - exp(-abs(diff)));
}
/**
* @brief Measures the distance to the goal at the end of our path
*
* @param ego
* @param others
* @param path
* @param state
* @param weight
* @return double the distance to the goal at the end of our path
*/
double futureDistanceToGoalCostFunction(const Vehicle &ego, const std::vector<Vehicle> &others, Path &path,
const State &state, const double &weight)
{
int traj_size = path.size();
double diff = MAX_TRACK_S - path.m_s[traj_size - 1];
// cout << "** DISTANCE TO GOAL = " << diff << endl;
return weight * (1 - exp(-abs(diff / MAX_TRACK_S)));
} | 31.766667 | 150 | 0.625019 | codyreading |
c0976169ad487a34974c52771dc1de412c683277 | 1,043 | hpp | C++ | addons/ares_compositions/Ares Community/Vernei =SO=/Bunkers & Fighting Positions/Tank Fighting Position.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | addons/ares_compositions/Ares Community/Vernei =SO=/Bunkers & Fighting Positions/Tank Fighting Position.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | 4 | 2018-12-21T06:57:25.000Z | 2020-07-09T09:06:38.000Z | addons/ares_compositions/Ares Community/Vernei =SO=/Bunkers & Fighting Positions/Tank Fighting Position.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | class Object0 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-4.32715,1.41943,0};dir=282.158;};
class Object1 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={4.41309,1.22168,0};dir=261.111;};
class Object2 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={5.28711,-4.24902,0};dir=261.111;};
class Object3 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-5.51807,-4.05078,0};dir=282.158;};
class Object4 {side=8;rank="";vehicle="Land_HBarrier_5_F";position[]={-2.09058,5.51855,0};dir=0.640371;};
class Object5 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={-5.73682,2.41602,0};dir=283.253;};
class Object6 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={5.40674,5.48145,0};dir=79.4694;};
class Object7 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={2.37256,6.85742,0};dir=181.16;};
class Object8 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={6.73804,-2.20117,0};dir=79.4694;};
class Object9 {side=8;rank="";vehicle="Land_Razorwire_F";position[]={-7.64673,-5.54297,0};dir=283.253;}; | 104.3 | 105 | 0.714286 | Braincrushy |
c09a298bffa5ba0bd62b3ee28d231be5328aa06c | 15,266 | cpp | C++ | software/src/texttools.cpp | osharuda/home-lab-easy-k | 30f6e8ae3c5b27711e0da83cc823100b6ac14dfe | [
"Apache-2.0"
] | 5 | 2021-02-09T09:31:39.000Z | 2021-03-18T21:15:02.000Z | software/src/texttools.cpp | osharuda/home-lab-easy-kit | 30f6e8ae3c5b27711e0da83cc823100b6ac14dfe | [
"Apache-2.0"
] | null | null | null | software/src/texttools.cpp | osharuda/home-lab-easy-kit | 30f6e8ae3c5b27711e0da83cc823100b6ac14dfe | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Oleh Sharuda <oleh.sharuda@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.
*/
/*! \file
* \brief Text tools utilities
* \author Oleh Sharuda
*/
#include "texttools.hpp"
#include <memory>
#include <cassert>
#include <unicode/errorcode.h>
#include <cstdarg>
namespace tools {
// special array for faster decoding from text to buffer, 255 is not hex character, otherwise actual value
const uint8_t SpecialCharacterTables::hex_val[] = {255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255,
255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255};
const char SpecialCharacterTables::hex_upcase[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
const char SpecialCharacterTables::hex_lwcase[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
ICUHelper::ICUHelper () {
UErrorCode status = U_ZERO_ERROR;
conv_utf16_le = ucnv_open("UTF-16LE", &status);
assert(U_SUCCESS(status));
conv_utf16_be = ucnv_open("UTF-16BE", &status);
assert(U_SUCCESS(status));
conv_utf8 = ucnv_open("UTF8", &status);
assert(U_SUCCESS(status));
conv_default = ucnv_open(nullptr, &status);
assert(U_SUCCESS(status));
date_formatter = DateFormat::createDateTimeInstance();
}
ICUHelper::~ICUHelper() {
ucnv_close(conv_utf16_le);
ucnv_close(conv_utf16_be);
ucnv_close(conv_utf8);
delete date_formatter;
}
icu::UnicodeString ICUHelper::make_unicode_string(const std::string& src, UErrorCode& err) {
return icu::UnicodeString(src.c_str(), -1, conv_default, err);
}
icu::UnicodeString ICUHelper::make_unicode_string(const tools::u16_string& src, UConverter* convertor, UErrorCode& err) {
icu::UnicodeString res = icu::UnicodeString((char*)src.c_str(), src.length()*sizeof(char16_t), convertor, err);
return res;
}
void ICUHelper::make_string(icu::UnicodeString& us, std::string& dst, UErrorCode& err) {
size_t len = count_chars((const char16_t*)us.getTerminatedBuffer(), conv_utf8, err);
if (!U_SUCCESS(err)) {
return;
}
std::unique_ptr<char[]> buffer(new char[len+1]);
us.extract(buffer.get(), len, conv_utf8, err);
if (!U_SUCCESS(err)) {
return;
} else if (err==U_STRING_NOT_TERMINATED_WARNING){
err = U_ZERO_ERROR;
}
// extract is not required to make string null terminated, terminate it
buffer.get()[len] = 0;
dst = (const char*)buffer.get();
}
void ICUHelper::make_u16string(icu::UnicodeString& us, tools::u16_string& dst, UConverter* convertor, UErrorCode& err) {
size_t len = count_chars((const char16_t*)us.getTerminatedBuffer(), convertor, err) / sizeof(char16_t);
if (err!=U_ZERO_ERROR) {
return;
}
std::unique_ptr<char16_t[]> buffer(new char16_t[len+1]);
// convert to UTF16
us.extract((char*)buffer.get(), len*sizeof(char16_t), convertor, err);
if (!U_SUCCESS(err)) {
return;
} else if (err==U_STRING_NOT_TERMINATED_WARNING){
err = U_ZERO_ERROR;
}
// extract is not required to make string null terminated, terminate it
buffer.get()[len] = 0;
dst = (const char16_t*)buffer.get();
}
size_t ICUHelper::count_chars(const char16_t* s, UConverter* convertor, UErrorCode& err) {
size_t res = ucnv_fromUChars(convertor, NULL, 0, (const UChar*)s, -1, &err);
if(err==U_BUFFER_OVERFLOW_ERROR) {
err=U_ZERO_ERROR;
} else {
res = 0;
}
return res;
}
bool ICUHelper::utf8_to_utf16(const std::string& src, u16_string& dst, bool little_endian) {
UConverter* conv = little_endian ? conv_utf16_le : conv_utf16_be;
UErrorCode err = U_ZERO_ERROR;
icu::UnicodeString us(make_unicode_string(src, err));
make_u16string(us, dst, conv, err);
return U_SUCCESS(err);
}
bool ICUHelper::utf16_to_utf8(const u16_string& src, std::string& dst, bool little_endian) {
UConverter* conv = little_endian ? conv_utf16_le : conv_utf16_be;
UErrorCode err = U_ZERO_ERROR;
icu::UnicodeString us(make_unicode_string(src, conv, err));
make_string(us, dst, err);
return U_SUCCESS(err);
}
bool ICUHelper::to_case(std::string& s, bool lowcase) {
UErrorCode err = U_ZERO_ERROR;
icu::UnicodeString us(make_unicode_string(s, err));
if (err!=U_ZERO_ERROR) {
return false;
}
if (lowcase) {
us.toLower();
} else {
us.toUpper();
}
make_string(us, s, err);
return err==U_ZERO_ERROR;
}
bool ICUHelper::to_case(u16_string& s, bool lowcase, bool little_endian) {
UConverter* conv = little_endian ? conv_utf16_le : conv_utf16_be;
UErrorCode err = U_ZERO_ERROR;
icu::UnicodeString us(make_unicode_string(s, conv, err));
if (err!=U_ZERO_ERROR) {
return false;
}
if (lowcase) {
us.toLower();
} else {
us.toUpper();
}
make_u16string(us, s, conv, err);
return err==U_ZERO_ERROR;
}
void ICUHelper::utf16_to_wide(const u16_string& src, std::wstring& dst) {
size_t slen = src.length();
if (slen)
{
dst = std::wstring(slen, L' ');
for (size_t i = 0; i<slen; ++i) {
dst[i] = (wchar_t)src[i];
}
} else {
dst.clear();
}
}
void ICUHelper::wide_to_utf16(const std::wstring& src, u16_string& dst) {
size_t slen = src.length();
if (slen)
{
dst = u16_string(slen, L' ');
for (size_t i = 0; i<slen; ++i) {
dst[i] = (char16_t)src[i];
}
} else {
dst.clear();
}
}
std::wstring utf8_to_wstr(const std::string& s) {
u16_string u16s;
std::wstring res;
g_unicode_ts.utf8_to_utf16(s, u16s, true);
g_unicode_ts.utf16_to_wide(u16s, res);
return res;
}
std::string wstr_to_utf8(const std::wstring& s) {
u16_string u16s;
std::string res;
g_unicode_ts.wide_to_utf16(s, u16s);
g_unicode_ts.utf16_to_utf8(u16s, res, true);
return res;
}
std::unique_ptr<RegexPattern> ICUHelper::regex_pattern(const std::string& pattern, uint32_t flags) {
UErrorCode err = U_ZERO_ERROR;
UParseError pe;
std::unique_ptr<RegexPattern> rpattern;
icu::UnicodeString upattern(make_unicode_string(pattern, err));
if (err!=U_ZERO_ERROR) {
return rpattern;
}
// Construct pattern
rpattern.reset(RegexPattern::compile(upattern, flags, pe, err));
if (err!=U_ZERO_ERROR) {
rpattern.reset(nullptr);
}
return rpattern;
}
bool ICUHelper::regex_groups(const RegexPattern& pattern, const std::string& s, std::vector<std::string>& groups) {
UErrorCode err = U_ZERO_ERROR;
icu::UnicodeString us(make_unicode_string(s, err));
if (err!=U_ZERO_ERROR) {
return false;
}
// Create matcher
std::unique_ptr<RegexMatcher> rm(pattern.matcher(us, err));
if (!rm || err!=U_ZERO_ERROR) {
return false;
}
int32_t n_groups = rm->groupCount()+1;
if (rm->matches(0, err)) {
for (int32_t i=0; i<n_groups; ++i) {
UnicodeString ug = rm->group(i, err);
if (!U_SUCCESS(err)) {
return false;
}
std::string g;
make_string(ug, g, err);
if (!U_SUCCESS(err)) {
return false;
}
groups.push_back(g);
}
return true;
}
return false;
}
bool ICUHelper::regex_match(const RegexPattern& pattern, const std::string& s) {
UErrorCode err = U_ZERO_ERROR;
icu::UnicodeString us(make_unicode_string(s, err));
if (err!=U_ZERO_ERROR) {
return false;
}
// Create matcher
std::unique_ptr<RegexMatcher> rm(pattern.matcher(us, err));
if (!rm || err!=U_ZERO_ERROR) {
return false;
}
return rm->matches(err);
}
bool ICUHelper::is_ascii(const std::string& s) {
size_t len = s.length();
for (size_t i=0; i<len; ++i) {
if ((uint8_t)s[i] > 0x7f) {
return false;
}
}
return true;
}
std::string ICUHelper::dtime_to_utf8(std::time_t t) {
UErrorCode err = U_ZERO_ERROR;
UnicodeString t_string;
std::string res;
t_string.remove();
date_formatter->format(static_cast<UDate>(t)*1000, t_string, NULL, err);
assert(U_SUCCESS(err));
make_string(t_string, res, err);
assert(U_SUCCESS(err));
return res;
}
template <class _Ch>
std::string dump_string_hex(const std::basic_string<_Ch>& s, const std::string& separator) {
size_t n_char = s.length();
size_t n_sep = separator.length();
size_t res_len = n_char>1 ? n_sep*n_char-1 : 0;
res_len += (n_char+1)*sizeof(_Ch)*2;
static const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
std::string res;
res.reserve(res_len);
uint8_t* pbuf = (uint8_t*)s.c_str();
size_t buflen = n_char*sizeof(_Ch);
for (size_t i=0; i<buflen; ++i) {
if (i!=0 && i%sizeof(_Ch)==0) {
res+=separator;
}
uint8_t b = pbuf[i];
char c0 = digits[b >> 4];
char c1 = digits[b & 0x0F];
res+=c0;
res+=c1;
}
return res;
}
std::string buffer_to_hex(const uint8_t* buffer, size_t len, bool lwrcase, const char* separator) {
const char* digit_set = lwrcase ? SpecialCharacterTables::hex_lwcase : SpecialCharacterTables::hex_upcase;
size_t sep_len = separator!=nullptr ? strlen(separator) : 0;
size_t res_len = len>1 ? sep_len*(len-1)+(len+1)*2: (len+1)*2; // length of separators
std::string res;
res.reserve(res_len);
for (size_t i=0; i<len; ++i) {
if (sep_len!=0 && i!=0) {
res+=separator;
}
uint8_t b = buffer[i];
char c0 = digit_set[b >> 4];
char c1 = digit_set[b & 0x0F];
res+=c0;
res+=c1;
}
return res;
}
std::vector<uint8_t> buffer_from_hex(const std::string& hex) {
size_t slen = hex.length();
std::vector<uint8_t> result;
if (slen%2!=0) {
throw std::length_error("Hex buffer description must have even number of characters");
}
result.resize(slen/2);
for (size_t i=0;i<slen;) {
uint8_t b0 = SpecialCharacterTables::hex_val[hex[i++]];
uint8_t b1 = SpecialCharacterTables::hex_val[hex[i++]];
if (b0>0x0F || b1>0x0F) {
throw std::out_of_range("Is not hex character");
}
result[(i/2)-1] = (b0 << 4) + b1;
}
return result;
}
std::string format_buffer(size_t bytes_per_line,
const uint8_t* buffer,
size_t buffer_len,
const std::string& line_prefix,
const std::string& text_separator) {
size_t line_count = buffer_len/bytes_per_line;
size_t tail_bytes = buffer_len%bytes_per_line;
line_count+= (tail_bytes!=0);
std::list<std::string> slist;
size_t offset_length = 0;
size_t t = buffer_len;
for (size_t i=0; i<sizeof(size_t) && t!=0; i++, offset_length++) {
t = t >> 8;
}
offset_length*=2;
// get maximum width of the offset field
// line has the following format (for bytes_per_line==4)
// <prefix>XX XX XX XX XX<text_separator>....
for (size_t l=0; l<line_count; l++) {
const uint8_t* start = buffer + l*bytes_per_line;
size_t len = (l==line_count-1) ? tail_bytes : bytes_per_line;
size_t pad = bytes_per_line - len;
size_t offset = l*bytes_per_line;
std::string offset_prefix = str_format("%*X",offset_length, offset);
std::string hex =buffer_to_hex(start, len, true, " ");
hex += std::string(pad*3, ' ');
std::string ascii = buffer_to_ascii(start, len, '.');
ascii += std::string(pad, ' ');
slist.push_back(line_prefix + offset_prefix + text_separator + hex + text_separator + ascii);
}
return join_strings(slist, "\n");
}
std::string buffer_to_ascii(const uint8_t* buffer, size_t len, char unprintable_char) {
std::string res;
res.reserve(len);
for (size_t i=0; i<len; i++) {
uint8_t b = buffer[i];
res += (b>=0x20 && b<0x7F) ? (char)b : unprintable_char;
}
return res;
}
std::string str_format(const char *format, ... ) {
std::vector<char> buffer;
char* buf_ptr;
va_list args1;
va_start(args1, format);
va_list args2;
va_copy(args2, args1);
int buflen = std::vsnprintf( nullptr, 0, format, args1 );
va_end(args1);
if( buflen < 0 ) {
throw std::runtime_error( "bad format" );
}
buflen++;
buffer.resize(buflen);
buf_ptr = buffer.data();
std::vsnprintf( buf_ptr, buflen, format, args2 );
va_end(args2);
// Terminate string
buf_ptr[buflen-1] = '\0';
return std::string(buf_ptr);
}
}
| 30.532 | 135 | 0.581816 | osharuda |
c09a64bc764a0ee7b849dc5b95e85a29fcab89c3 | 2,760 | ipp | C++ | implement/oglplus/enums/memory_barrier_bit_names.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 459 | 2016-03-16T04:11:37.000Z | 2022-03-31T08:05:21.000Z | implement/oglplus/enums/memory_barrier_bit_names.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 2 | 2016-08-08T18:26:27.000Z | 2017-05-08T23:42:22.000Z | implement/oglplus/enums/memory_barrier_bit_names.ipp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | 47 | 2016-05-31T15:55:52.000Z | 2022-03-28T14:49:40.000Z | // File implement/oglplus/enums/memory_barrier_bit_names.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/memory_barrier_bit.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2015 Matus Chochlik.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
namespace enums {
OGLPLUS_LIB_FUNC StrCRef ValueName_(
MemoryBarrierBit*,
GLbitfield value
)
#if (!OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)) && \
!defined(OGLPLUS_IMPL_EVN_MEMORYBARRIERBIT)
#define OGLPLUS_IMPL_EVN_MEMORYBARRIERBIT
{
switch(value)
{
#if defined GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT
case GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT: return StrCRef("VERTEX_ATTRIB_ARRAY_BARRIER_BIT");
#endif
#if defined GL_ELEMENT_ARRAY_BARRIER_BIT
case GL_ELEMENT_ARRAY_BARRIER_BIT: return StrCRef("ELEMENT_ARRAY_BARRIER_BIT");
#endif
#if defined GL_UNIFORM_BARRIER_BIT
case GL_UNIFORM_BARRIER_BIT: return StrCRef("UNIFORM_BARRIER_BIT");
#endif
#if defined GL_TEXTURE_FETCH_BARRIER_BIT
case GL_TEXTURE_FETCH_BARRIER_BIT: return StrCRef("TEXTURE_FETCH_BARRIER_BIT");
#endif
#if defined GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
case GL_SHADER_IMAGE_ACCESS_BARRIER_BIT: return StrCRef("SHADER_IMAGE_ACCESS_BARRIER_BIT");
#endif
#if defined GL_COMMAND_BARRIER_BIT
case GL_COMMAND_BARRIER_BIT: return StrCRef("COMMAND_BARRIER_BIT");
#endif
#if defined GL_PIXEL_BUFFER_BARRIER_BIT
case GL_PIXEL_BUFFER_BARRIER_BIT: return StrCRef("PIXEL_BUFFER_BARRIER_BIT");
#endif
#if defined GL_TEXTURE_UPDATE_BARRIER_BIT
case GL_TEXTURE_UPDATE_BARRIER_BIT: return StrCRef("TEXTURE_UPDATE_BARRIER_BIT");
#endif
#if defined GL_BUFFER_UPDATE_BARRIER_BIT
case GL_BUFFER_UPDATE_BARRIER_BIT: return StrCRef("BUFFER_UPDATE_BARRIER_BIT");
#endif
#if defined GL_FRAMEBUFFER_BARRIER_BIT
case GL_FRAMEBUFFER_BARRIER_BIT: return StrCRef("FRAMEBUFFER_BARRIER_BIT");
#endif
#if defined GL_TRANSFORM_FEEDBACK_BARRIER_BIT
case GL_TRANSFORM_FEEDBACK_BARRIER_BIT: return StrCRef("TRANSFORM_FEEDBACK_BARRIER_BIT");
#endif
#if defined GL_ATOMIC_COUNTER_BARRIER_BIT
case GL_ATOMIC_COUNTER_BARRIER_BIT: return StrCRef("ATOMIC_COUNTER_BARRIER_BIT");
#endif
#if defined GL_SHADER_STORAGE_BARRIER_BIT
case GL_SHADER_STORAGE_BARRIER_BIT: return StrCRef("SHADER_STORAGE_BARRIER_BIT");
#endif
#if defined GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT
case GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT: return StrCRef("CLIENT_MAPPED_BUFFER_BARRIER_BIT");
#endif
#if defined GL_ALL_BARRIER_BITS
case GL_ALL_BARRIER_BITS: return StrCRef("ALL_BARRIER_BITS");
#endif
default:;
}
OGLPLUS_FAKE_USE(value);
return StrCRef();
}
#else
;
#endif
} // namespace enums
| 35.384615 | 94 | 0.838768 | Extrunder |
c09a93549fe66ee9fc78634d7a6ca089a788c931 | 31 | cpp | C++ | test/test_thrust.cpp | subhashis/MVEDDA | ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d | [
"MIT"
] | 3 | 2016-01-15T20:17:21.000Z | 2021-01-21T02:32:15.000Z | test/test_thrust.cpp | subhashis/MVEDDA | ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d | [
"MIT"
] | 11 | 2016-07-26T01:37:46.000Z | 2018-06-19T16:50:25.000Z | test/test_thrust.cpp | subhashis/MVEDDA | ff8fb64f8cd9d84ec4aa99a21ed146a8d3af7d7d | [
"MIT"
] | 12 | 2016-02-09T04:31:41.000Z | 2021-12-03T01:04:04.000Z | #include "test_thrust_cuda.cu"
| 15.5 | 30 | 0.806452 | subhashis |
c09c24f196f65b99747b025f09ca7f8a7d28d6df | 2,773 | cc | C++ | EventFilter/CSCRawToDigi/src/CSCDMBHeader2013.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | EventFilter/CSCRawToDigi/src/CSCDMBHeader2013.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | EventFilter/CSCRawToDigi/src/CSCDMBHeader2013.cc | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "EventFilter/CSCRawToDigi/interface/CSCDMBHeader2013.h"
#include "DataFormats/CSCDigi/interface/CSCConstants.h"
#include <iostream>
CSCDMBHeader2013::CSCDMBHeader2013() {
bzero(data(), sizeInWords() * 2);
bits.ddu_code_1 = bits.ddu_code_2 = bits.ddu_code_3 = bits.ddu_code_4 = 0xA;
bits.newddu_code_1 = bits.newddu_code_2 = bits.newddu_code_3 = bits.newddu_code_4 = 0x9;
}
CSCDMBHeader2013::CSCDMBHeader2013(const uint16_t* buf) { memcpy(data(), buf, sizeInWords() * 2); }
unsigned CSCDMBHeader2013::cfebMovlp() const { return bits.cfeb_movlp; }
unsigned CSCDMBHeader2013::dmbCfebSync() const { return bits.dmb_cfeb_sync; }
unsigned CSCDMBHeader2013::activeDavMismatch() const { return bits.clct_dav_mismatch; }
unsigned CSCDMBHeader2013::format_version() const { return bits.fmt_version; }
unsigned CSCDMBHeader2013::cfebAvailable() const { return bits.cfeb_dav; }
unsigned CSCDMBHeader2013::nalct() const { return bits.alct_dav; }
unsigned CSCDMBHeader2013::nclct() const { return bits.tmb_dav; }
unsigned CSCDMBHeader2013::crateID() const { return bits.dmb_crate; }
unsigned CSCDMBHeader2013::dmbID() const { return bits.dmb_id; }
unsigned CSCDMBHeader2013::bxn() const { return bits.dmb_bxn; }
unsigned CSCDMBHeader2013::bxn12() const { return bits.dmb_bxn1; }
unsigned CSCDMBHeader2013::l1a() const { return bits.dmb_l1a; }
unsigned CSCDMBHeader2013::l1a24() const { return (bits.dmb_l1a_lowo | (bits.dmb_l1a_hiwo << 12)); }
void CSCDMBHeader2013::setL1A(int l1a) { bits.dmb_l1a = l1a & 0x1F; }
void CSCDMBHeader2013::setL1A24(int l1a) {
bits.dmb_l1a_lowo = l1a & 0xFFF;
bits.dmb_l1a_hiwo = (l1a >> 12) & 0xFFF;
}
void CSCDMBHeader2013::setBXN(int bxn) {
bits.dmb_bxn1 = bxn & 0xFFF;
bits.dmb_bxn = bxn & 0x1F;
}
void CSCDMBHeader2013::setCrateAddress(int crate, int dmbId) {
this->bits.dmb_crate = crate;
this->bits.dmb_id = dmbId;
}
unsigned CSCDMBHeader2013::sizeInWords() const { return 8; }
/// counts from zero
bool CSCDMBHeader2013::cfebAvailable(unsigned icfeb) {
assert(icfeb < CSCConstants::MAX_CFEBS_RUN2);
return (cfebAvailable() >> icfeb) & 1;
}
void CSCDMBHeader2013::addCFEB(int icfeb) {
assert(icfeb < CSCConstants::MAX_CFEBS_RUN2);
bits.cfeb_dav |= (1 << icfeb);
bits.cfeb_clct_sent |= (1 << icfeb);
}
void CSCDMBHeader2013::addNCLCT() { bits.tmb_dav = bits.tmb_dav_copy = bits.tmb_dav_copy2 = 1; }
void CSCDMBHeader2013::addNALCT() { bits.alct_dav = bits.alct_dav_copy = bits.alct_dav_copy2 = 1; }
bool CSCDMBHeader2013::check() const {
return (bits.ddu_code_1 == 0xA && bits.ddu_code_2 == 0xA && bits.ddu_code_3 == 0xA && bits.ddu_code_4 == 0xA &&
bits.newddu_code_1 == 0x9 && bits.newddu_code_2 == 0x9 && bits.newddu_code_3 == 0x9 &&
bits.newddu_code_4 == 0x9);
}
| 35.101266 | 113 | 0.734223 | Purva-Chaudhari |
c0a1c7382c4cbfc294ca103c1d33c314c28ca55e | 2,701 | cpp | C++ | src/main/cpp/dedekind-mkl/ComplexFloatArray.cpp | stefan-zobel/dedekind-MKL | 7064ff6fb6f7fc320a519b49da2be215e66dd5b7 | [
"Apache-2.0"
] | 1 | 2021-04-01T01:16:46.000Z | 2021-04-01T01:16:46.000Z | src/main/cpp/dedekind-mkl/ComplexFloatArray.cpp | stefan-zobel/dedekind-MKL | 7064ff6fb6f7fc320a519b49da2be215e66dd5b7 | [
"Apache-2.0"
] | null | null | null | src/main/cpp/dedekind-mkl/ComplexFloatArray.cpp | stefan-zobel/dedekind-MKL | 7064ff6fb6f7fc320a519b49da2be215e66dd5b7 | [
"Apache-2.0"
] | 1 | 2021-04-01T01:16:50.000Z | 2021-04-01T01:16:50.000Z | /*
* Copyright 2020 Stefan Zobel
*
* 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 "ComplexFloatArray.h"
#ifndef JEXCEPTION_INCLUDED_
#include "JException.h"
#endif /* JEXCEPTION_INCLUDED_ */
#ifndef SLIMSTRING_INCLUDED_
#include "SlimString.h"
#endif /* SLIMSTRING_INCLUDED_ */
#include <string.h> // for memcpy
__GCC_DONT_EXPORT void floatCopy(long len, float* mixed, MKL_Complex8* complex) {
if (len > 0 && mixed && complex) {
memcpy(mixed, complex, len * sizeof(MKL_Complex8));
// cblas_scopy(len, &(complex[0].real), 2, &(mixed[0]), 2);
// cblas_scopy(len, &(complex[0].imag), 2, &(mixed[1]), 2);
}
}
ComplexFloatArray::ComplexFloatArray(FloatArray& array_, bool copy)
: array(array_), complex_array_len(0), complex_array(NULL), isCopy(copy)
{
long length = array.length();
if (length > 0) {
if (length % 2 != 0) {
SlimString msg("complex arrays must have even length: ");
msg.append(length);
throw JException(msg);
}
length /= 2;
complex_array_len = length;
if (isCopy) {
complex_array = (MKL_Complex8*) mkl_malloc(length * sizeof(MKL_Complex8), 64);
if (!complex_array) {
SlimString msg("couldn't allocate MKL_Complex8 array of length ");
msg.append(length);
throw JException(msg);
}
memcpy(complex_array, array.ptr(), length * sizeof(MKL_Complex8));
// float* mixed = array.ptr();
// cblas_scopy(length, &(mixed[0]), 2, &(complex_array[0].real), 2);
// cblas_scopy(length, &(mixed[1]), 2, &(complex_array[0].imag), 2);
}
else {
complex_array = (MKL_Complex8*) array.ptr();
}
}
}
MKL_Complex8* ComplexFloatArray::ptr() {
return complex_array;
}
long ComplexFloatArray::complexLength() {
return complex_array_len;
}
bool ComplexFloatArray::hasCopy() {
return isCopy;
}
ComplexFloatArray::~ComplexFloatArray() {
if (isCopy && complex_array) {
mkl_free(complex_array);
}
}
| 31.406977 | 91 | 0.616068 | stefan-zobel |
c0a45801b4089c575176675f343a93584898c772 | 1,046 | hpp | C++ | bunsan/common/include/bunsan/property_tree/info_parser.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | null | null | null | bunsan/common/include/bunsan/property_tree/info_parser.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 10 | 2018-02-06T14:46:36.000Z | 2018-03-20T13:37:20.000Z | bunsan/common/include/bunsan/property_tree/info_parser.hpp | bacsorg/bacs | 2b52feb9efc805655cdf7829cf77ee028d567969 | [
"Apache-2.0"
] | 1 | 2021-11-26T10:59:09.000Z | 2021-11-26T10:59:09.000Z | #pragma once
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/scope_exit.hpp>
#include <locale>
#include <string>
namespace bunsan::property_tree {
/*!
* \brief Read info from filename with relative path bug fix
*
* \warning This function is not safe,
* it should be used only from single thread.
*/
template <typename Ptree>
void read_info(const std::string &filename, Ptree &pt,
const std::locale &loc = std::locale()) {
boost::filesystem::initial_path(); // initialize for future use
BOOST_SCOPE_EXIT_ALL() {
boost::filesystem::current_path(boost::filesystem::initial_path());
};
boost::filesystem::current_path(
boost::filesystem::absolute(boost::filesystem::path(filename))
.parent_path());
boost::property_tree::info_parser::read_info(
boost::filesystem::path(filename).filename().string(), pt, loc);
}
} // namespace bunsan::property_tree
| 28.27027 | 71 | 0.713193 | bacsorg |
c0a55a4e17fe63b7d2278271b068ab7579edf0e1 | 1,095 | hh | C++ | src/ir/Quad.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | 1 | 2020-01-06T09:43:56.000Z | 2020-01-06T09:43:56.000Z | src/ir/Quad.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | src/ir/Quad.hh | walecome/seal | 204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1 | [
"MIT"
] | null | null | null | #pragma once
#include <tuple>
#include <vector>
#include "Constants.hh"
#include "OPCode.hh"
#include "Operand.hh"
#include "Register.hh"
#include "QuadSource.hh"
#include "QuadDest.hh"
class Quad {
public:
Quad(OPCode op_code, QuadDest dest, QuadSource src_a, QuadSource src_b)
: m_op_code { op_code },
m_dest { dest },
m_src_a { src_a },
m_src_b { src_b } {}
std::string to_string() const;
std::tuple<std::string, std::string, std::string, std::string, std::string>
to_string_segments() const;
const std::vector<unsigned>& label_ids() const { return m_label_ids; }
bool has_label() const { return m_has_label; }
void add_label(unsigned label_id);
OPCode opcode() const { return m_op_code; };
QuadDest dest() const { return m_dest; }
QuadSource src_a() const { return m_src_a; }
QuadSource src_b() const { return m_src_b; }
private:
std::vector<unsigned> m_label_ids {};
bool m_has_label { false };
OPCode m_op_code;
QuadDest m_dest;
QuadSource m_src_a;
QuadSource m_src_b;
}; | 27.375 | 79 | 0.659361 | walecome |
c0a71e6edb6e374a032b575ecaa6eac3c0865496 | 1,566 | cpp | C++ | ProfilerHost/IpcClient.cpp | varunramc/clr-profiling | 461a9dc834ad2791c0889a7ec843674a2be2b47c | [
"MIT"
] | 8 | 2018-03-27T09:35:23.000Z | 2022-01-31T06:26:04.000Z | ProfilerHost/IpcClient.cpp | varunramc/clr-profiling | 461a9dc834ad2791c0889a7ec843674a2be2b47c | [
"MIT"
] | 1 | 2018-08-07T11:00:26.000Z | 2020-04-04T12:38:23.000Z | ProfilerHost/IpcClient.cpp | varunramc/clr-profiling | 461a9dc834ad2791c0889a7ec843674a2be2b47c | [
"MIT"
] | 4 | 2018-10-11T17:43:49.000Z | 2021-06-23T06:58:58.000Z | #include "stdafx.h"
#include "IpcClient.h"
#include <grpc/grpc.h>
#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/security/credentials.h>
#include "ProfilingConfig.h"
#include "StringUtils.h"
namespace ipc = profilerHostIpc;
using grpc::ClientContext;
std::unique_ptr<ClientContext> IpcClient::GetClientContext() const
{
auto context = std::make_unique<ClientContext>();
context->AddMetadata("pid", this->processId);
return context;
}
IpcClient::IpcClient()
{
auto channel = CreateChannel("localhost:7777", grpc::InsecureChannelCredentials());
this->stub = ProfilerHostIpc::NewStub(channel);
this->processId = std::to_string(GetCurrentProcessId());
}
void IpcClient::GetProfilingConfig() const
{
ipc::Void request;
ipc::ProfilingConfigMsg response;
this->stub->GetProfilingConfig(this->GetClientContext().get(), request, &response);
auto& config = ProfilingConfig::Get();
config.SetNamespaceToProfile(ToWstring(response.namespacetoprofile()));
config.SetProfilerCoreDllPath(ToWstring(response.profilercoredllpath()));
}
void IpcClient::RegisterMethod(const MethodMetadata& method) const
{
ipc::MethodMetadataMsg request;
ipc::Void response;
request.set_assemblyname(ToString(method.assemblyName));
request.set_typename_(ToString(method.typeName));
request.set_signature(ToString(method.signature));
request.set_token(method.token);
this->stub->RegisterMethod(this->GetClientContext().get(), request, &response);
}
| 30.115385 | 87 | 0.743295 | varunramc |
c0acb905a2e128130982b721b209e67dc245db7f | 1,765 | cpp | C++ | samples/03_sdp/2017/00_interpreter/src/ast/loopexpr.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 32 | 2016-11-24T01:40:21.000Z | 2021-11-01T19:24:22.000Z | samples/03_sdp/2017/00_interpreter/src/ast/loopexpr.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 6 | 2016-10-15T05:57:00.000Z | 2021-08-13T12:29:24.000Z | samples/03_sdp/2017/00_interpreter/src/ast/loopexpr.cpp | code-hunger/lecture-notes | 0200c57a4c2539b4d8b7cb172c2b6e4f5c689268 | [
"MIT"
] | 49 | 2016-01-26T13:36:02.000Z | 2022-03-16T10:24:41.000Z | #include <iostream>
#include <assert.h>
#include <math.h>
#include "loopexpr.h"
#include "vars.h"
#include "constant.h"
using namespace std;
LoopExpr::LoopExpr (string _cv,
Expression *_frome,
Expression *_toe,
Expression *_stepe,
Expression *_bodye):frome(_frome),toe(_toe),stepe(_stepe),bodye(_bodye),controlVar(_cv){};
LoopExpr::~LoopExpr()
{
delete frome;
delete toe;
delete stepe;
delete bodye;
}
Value* LoopExpr::execute()
{
Value* garbage;
Value *control = frome->execute();
Value* to = toe->execute();
while(!control->equals(to))
{
setControlVariableTo(control);
executeBodyAndDeleteGarbage();
garbage = control;
control = makeStep(control);
delete garbage;
}
setControlVariableTo(control);
delete control;
delete to;
return bodye->execute();
}
void LoopExpr::setControlVariableTo(Value* value)
{
SetExpression *set = new SetExpression(controlVar, new Constant(value->clone()));
Value* garbage = set->execute();
delete garbage;
delete set;
}
void LoopExpr::executeBodyAndDeleteGarbage()
{
Value* garbage = bodye->execute();
delete garbage;
}
Value* LoopExpr::makeStep(Value* currentControlValue)
{
Value* stepValue = stepe->execute();
Value* newControlValue = currentControlValue->plus(stepValue);
delete stepValue;
return newControlValue;
}
void LoopExpr::print (ostream &out)
{
out << getID () << "[label=\"LOOP:" << controlVar << "\"];" << endl;
out << getID () << "->" << frome->getID() << ";" << endl;
out << getID () << "->" << toe->getID() << ";" << endl;
out << getID () << "->" << stepe->getID() << ";" << endl;
out << getID () << "->" << bodye->getID() << ";" << endl;
frome->print (out);
toe->print (out);
stepe->print (out);
bodye->print (out);
}
| 20.523256 | 99 | 0.645892 | code-hunger |
c0b025deb2081b9de3e54ec411148f31b96d01cf | 1,363 | cpp | C++ | MyConditionalPrior.cpp | eggplantbren/Perceptron | 75845a2c9110a83ec1520249d8addc459aedbe77 | [
"MIT"
] | 1 | 2016-07-25T20:52:47.000Z | 2016-07-25T20:52:47.000Z | MyConditionalPrior.cpp | eggplantbren/Perceptron | 75845a2c9110a83ec1520249d8addc459aedbe77 | [
"MIT"
] | null | null | null | MyConditionalPrior.cpp | eggplantbren/Perceptron | 75845a2c9110a83ec1520249d8addc459aedbe77 | [
"MIT"
] | null | null | null | #include "MyConditionalPrior.h"
#include "DNest4/code/DNest4.h"
#include <cmath>
using namespace DNest4;
namespace Perceptron
{
MyConditionalPrior::MyConditionalPrior()
{
}
void MyConditionalPrior::from_prior(RNG& rng)
{
mu.from_prior(rng);
const Cauchy cauchy(0.0, 5.0);
do
{
sigma = cauchy.generate(rng);
}while(std::abs(sigma) >= 50.0);
sigma = exp(sigma);
}
double MyConditionalPrior::perturb_hyperparameters(RNG& rng)
{
double logH = 0.0;
if(rng.rand() <= 0.5)
{
logH += mu.perturb(rng);
}
else
{
const Cauchy cauchy(0.0, 5.0);
sigma = log(sigma);
logH += cauchy.perturb(sigma, rng);
if(std::abs(sigma) >= 50.0)
{
sigma = 1.0;
return -1E300;
}
sigma = exp(sigma);
}
return logH;
}
double MyConditionalPrior::log_pdf(const std::vector<double>& vec) const
{
Laplace l(mu.get_value(), sigma);
return l.log_pdf(vec[0]);
}
void MyConditionalPrior::from_uniform(std::vector<double>& vec) const
{
Laplace l(mu.get_value(), sigma);
vec[0] = l.cdf_inverse(vec[0]);
}
void MyConditionalPrior::to_uniform(std::vector<double>& vec) const
{
Laplace l(mu.get_value(), sigma);
vec[0] = l.cdf(vec[0]);
}
void MyConditionalPrior::print(std::ostream& out) const
{
}
} // namespace Perceptron
| 17.701299 | 72 | 0.613353 | eggplantbren |
c0b04b8945cc8e291e4a372e5f92bd84ef54a60f | 4,726 | cpp | C++ | loom/engine/loom2d/l2dQuad.cpp | ellemenno/LoomSDK | c6ff83f99b313f402326948c57661908933dabdd | [
"ECL-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | 109 | 2015-01-04T00:32:38.000Z | 2022-02-06T22:59:30.000Z | loom/engine/loom2d/l2dQuad.cpp | RichardRanft/LoomSDK | 7f12b9d572f2ca409b9070ba92a284a82263ae97 | [
"ECL-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | 237 | 2015-01-10T19:42:56.000Z | 2017-01-02T21:23:32.000Z | loom/engine/loom2d/l2dQuad.cpp | RichardRanft/LoomSDK | 7f12b9d572f2ca409b9070ba92a284a82263ae97 | [
"ECL-2.0",
"Apache-2.0",
"BSD-2-Clause"
] | 34 | 2015-01-01T21:45:01.000Z | 2020-07-19T15:33:25.000Z | /*
* ===========================================================================
* Loom SDK
* Copyright 2011, 2012, 2013
* The Game Engine Company, 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 "loom/engine/loom2d/l2dQuad.h"
#include "loom/engine/loom2d/l2dImage.h"
#include "loom/engine/loom2d/l2dBlendMode.h"
#include "loom/graphics/gfxGraphics.h"
#include "loom/graphics/gfxColor.h"
namespace Loom2D
{
Type *Quad::typeQuad = NULL;
void Quad::updateNativeVertexData(lua_State *L, int index)
{
int didx = lua_gettop(L);
index = lua_absindex(L, index);
// todo: optimize VertexData in script needs to be moved native
if (nativeVertexDataInvalid)
{
nativeVertexDataInvalid = false;
const char *vmember = imageOrDerived ? "mVertexDataCache" : "mVertexData";
lualoom_getmember(L, index, vmember);
lualoom_getmember(L, -1, "mRawData");
lua_rawgeti(L, -1, LSINDEXVECTOR);
int rawDataTable = lua_gettop(L);
int rcounter = 0;
tinted = false;
for (int i = 0; i < 4; i++)
{
GFX::VertexPosColorTex *v = &quadVertices[i];
lua_rawgeti(L, rawDataTable, rcounter++);
v->x = (float)lua_tonumber(L, -1);
lua_rawgeti(L, rawDataTable, rcounter++);
v->y = (float)lua_tonumber(L, -1);
//printf("%i %f %f\n", i, v->x, v->y);
v->z = 0.0f;
GFX::Color c(0);
lua_rawgeti(L, rawDataTable, rcounter++);
c.a = (float)lua_tonumber(L, -1);
lua_rawgeti(L, rawDataTable, rcounter++);
c.b = (float)lua_tonumber(L, -1);
lua_rawgeti(L, rawDataTable, rcounter++);
c.g = (float)lua_tonumber(L, -1);
lua_rawgeti(L, rawDataTable, rcounter++);
c.r = (float)lua_tonumber(L, -1);
// todo: optimize this too:
v->abgr = c.getHex();
if(v->abgr != 0x00FFFFFFFF)
tinted = true;
lua_rawgeti(L, rawDataTable, rcounter++);
v->u = (float)lua_tonumber(L, -1);
lua_rawgeti(L, rawDataTable, rcounter++);
v->v = (float)lua_tonumber(L, -1);
}
lua_settop(L, didx);
}
}
void Quad::render(lua_State *L)
{
if (nativeTextureID == -1)
{
return;
}
GFX::TextureInfo *tinfo = GFX::Texture::getTextureInfo(nativeTextureID);
if (!tinfo)
{
return;
}
// if render state has 0.0 alpha, quad batch is invisible so don't render at all and get out of here now!
renderState.alpha = parent ? parent->renderState.alpha * alpha : alpha;
renderState.clampAlpha();
if(renderState.alpha == 0.0f)
{
return;
}
updateLocalTransform();
Matrix mtx;
getTargetTransformationMatrix(NULL, &mtx);
renderState.clipRect = parent ? parent->renderState.clipRect : Loom2D::Rectangle(0, 0, -1, -1);
renderState.blendMode = (blendMode == BlendMode::AUTO && parent) ? parent->renderState.blendMode : blendMode;
unsigned int blendSrc, blendDst;
BlendMode::BlendFunction(renderState.blendMode, blendSrc, blendDst);
if (renderState.isClipping()) GFX::Graphics::setClipRect((int)renderState.clipRect.x, (int)renderState.clipRect.y, (int)renderState.clipRect.width, (int)renderState.clipRect.height);
GFX::VertexPosColorTex *v = GFX::QuadRenderer::getQuadVertexMemory(4, nativeTextureID, blendEnabled, blendSrc, blendDst, shader);
GFX::VertexPosColorTex *src = quadVertices;
if (!v)
{
return;
}
for (int i = 0; i < 4; i++)
{
*v = *src;
src++;
lmscalar _x = mtx.a * v->x + mtx.c * v->y + mtx.tx;
lmscalar _y = mtx.b * v->x + mtx.d * v->y + mtx.ty;
v->x = (float) _x;
v->y = (float) _y;
// modulate vertex alpha by our DisplayObject alpha setting
if (renderState.alpha != 1.0f)
{
lmscalar va = ((float)(v->abgr >> 24)) * renderState.alpha;
v->abgr = ((uint32_t)va << 24) | (v->abgr & 0x00FFFFFF);
}
v++;
}
}
}
| 29.5375 | 186 | 0.580195 | ellemenno |
c0b08d0f8f46353005d205b81e5015b074873991 | 22,889 | cpp | C++ | parser/pe/LdConfigDirWrapper.cpp | yjd/bearparser | 7ec04943a7b7f478d8b924aebe1fc0e831cb27da | [
"BSD-2-Clause"
] | 516 | 2015-01-04T14:04:21.000Z | 2022-03-13T05:07:27.000Z | parser/pe/LdConfigDirWrapper.cpp | yjd/bearparser | 7ec04943a7b7f478d8b924aebe1fc0e831cb27da | [
"BSD-2-Clause"
] | 12 | 2018-08-04T22:37:46.000Z | 2021-02-17T00:37:56.000Z | parser/pe/LdConfigDirWrapper.cpp | yjd/bearparser | 7ec04943a7b7f478d8b924aebe1fc0e831cb27da | [
"BSD-2-Clause"
] | 99 | 2015-04-23T01:59:24.000Z | 2022-03-03T04:38:28.000Z | #include "pe/LdConfigDirWrapper.h"
// offset from the beginning of the structure
#define getStructFieldOffset(STRUCT, FIELD) ((ULONGLONG) &(STRUCT.FIELD) - (ULONGLONG)&STRUCT)
bufsize_t LdConfigDirWrapper::getLdConfigDirSize()
{
bufsize_t dirSize = 0;
if (m_Exe->getBitMode() == Executable::BITS_32) {
dirSize = sizeof(pe::IMAGE_LOAD_CONFIG_DIRECTORY32);
} else if (m_Exe->getBitMode() == Executable::BITS_64) {
dirSize = sizeof(pe::IMAGE_LOAD_CONFIG_DIRECTORY64);
}
return dirSize;
}
bufsize_t LdConfigDirWrapper::getHdrDefinedSize()
{
const offset_t rva = getDirEntryAddress();
offset_t raw = INVALID_ADDR;
try {
raw = m_Exe->rvaToRaw(rva);
} catch (CustomException &e) {
raw = INVALID_ADDR;
}
if (raw == INVALID_ADDR) return 0;
offset_t offset = INVALID_ADDR;
if (m_Exe->getBitMode() == Executable::BITS_32) {
pe::IMAGE_LOAD_CONFIG_DIRECTORY32 ld = { 0 };
offset = getStructFieldOffset(ld, Size);
} else if (m_Exe->getBitMode() == Executable::BITS_64) {
pe::IMAGE_LOAD_CONFIG_DIRECTORY64 ld = { 0 };
offset = getStructFieldOffset(ld, Size);
}
DWORD* sizePtr = (DWORD*) m_Exe->getContentAt((raw + offset), sizeof(DWORD));
if (!sizePtr) return 0;
return bufsize_t(*sizePtr);
}
void* LdConfigDirWrapper::getLdConfigDirPtr()
{
offset_t rva = getDirEntryAddress();
BYTE *ptr = m_Exe->getContentAt(rva, Executable::RVA, this->getSize());
return ptr;
}
bool LdConfigDirWrapper::wrapSubentriesTable(size_t parentFieldId, size_t counterFieldId)
{
bool isOk = false;
size_t count = this->getNumValue(counterFieldId, &isOk);
if (!isOk) {
return false;
}
for (size_t i = 0 ; i < count; i++) {
LdConfigEntryWrapper *entry = new LdConfigEntryWrapper(m_Exe, this, i, parentFieldId);
if (!entry || !entry->getPtr()) {
delete entry;
break;
}
this->entries.push_back(entry);
this->subEntriesMap[parentFieldId].push_back(entry);
}
return isOk;
}
bool LdConfigDirWrapper::wrap()
{
clear();
if (!getPtr()) return false;
//SEHandlerTable:
wrapSubentriesTable(SEH_TABLE, SEH_COUNT);
//GuardCFFunctionTable:
wrapSubentriesTable(GUARD_TABLE, GUARD_COUNT);
wrapSubentriesTable(GUARD_LONG_JUMP_TABLE, GUARD_LONG_JUMP_COUNT);
wrapSubentriesTable(GUARD_ADDR_IAT_ENTRY_TABLE, GUARD_ADDR_IAT_ENTRY_COUNT);
wrapSubentriesTable(GUARD_EH_CONT_TABLE, GUARD_EH_CONT_COUNT);
return true;
}
void* LdConfigDirWrapper::getPtr()
{
return getLdConfigDirPtr();
}
void LdConfigDirWrapper::clear()
{
std::map<uint32_t, std::vector<ExeNodeWrapper*> >::iterator mapItr;
for (mapItr = this->subEntriesMap.begin(); mapItr != this->subEntriesMap.end(); mapItr++) {
std::vector<ExeNodeWrapper*> &vec = mapItr->second;
vec.clear();
}
ExeNodeWrapper::clear();
}
void* LdConfigDirWrapper::firstSubEntryPtr(size_t parentId)
{
bool isOk = false;
offset_t offset = this->getNumValue(parentId, &isOk);
if (!isOk) return NULL;
Executable::addr_type aT = containsAddrType(parentId);
if (aT == Executable::NOT_ADDR) return NULL;
bufsize_t handlerSize = static_cast<bufsize_t>(this->firstSubEntrySize(parentId));
char *ptr = (char*) m_Exe->getContentAt(offset, aT, handlerSize);
if (!ptr) return NULL;
return ptr;
}
bufsize_t LdConfigDirWrapper::getSize()
{
//validate the offset
const offset_t rva = getDirEntryAddress();
if (!m_Exe->isValidAddr(rva, Executable::RVA)) {
return 0;
}
const bufsize_t hdrSize = this->getHdrDefinedSize();
const bufsize_t structSize = getLdConfigDirSize();
const bufsize_t totalSize = (hdrSize < structSize) ? hdrSize : structSize;
// is the size correct
const offset_t rvaEnd = rva + totalSize - 1;
if (!m_Exe->isValidAddr(rvaEnd, Executable::RVA)) {
return 0;
}
return totalSize;
}
offset_t LdConfigDirWrapper::_getFieldDelta(bool is32b, size_t fId)
{
static pe::IMAGE_LOAD_CONFIG_DIRECTORY32 ld32 = { 0 };
static pe::IMAGE_LOAD_CONFIG_DIRECTORY64 ld64 = { 0 };
//offset from the beginning of the IMAGE_LOAD_CONFIG_DIRECTORY_T strucure
offset_t fieldOffset = INVALID_ADDR;
switch (fId) {
case SIZE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, Size) : getStructFieldOffset(ld64, Size);
break;
case TIMEST :
fieldOffset = (is32b) ? getStructFieldOffset(ld32,TimeDateStamp) : getStructFieldOffset(ld64, TimeDateStamp);
break;
case MAJOR_VER :
fieldOffset = (is32b) ? getStructFieldOffset(ld32,MajorVersion) : getStructFieldOffset(ld64, MajorVersion);
break;
case MINOR_VER :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, MinorVersion) : getStructFieldOffset(ld64, MinorVersion);
break;
case GLOBAL_FLAGS_CLEAR :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GlobalFlagsClear) : getStructFieldOffset(ld64, GlobalFlagsClear);
break;
case GLOBAL_FLAGS_SET :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GlobalFlagsSet) : getStructFieldOffset(ld64, GlobalFlagsSet);
break;
case CRITICAT_SEC_TIMEOUT :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CriticalSectionDefaultTimeout) : getStructFieldOffset(ld64, CriticalSectionDefaultTimeout);
break;
case DECOMMIT_FREE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DeCommitFreeBlockThreshold) : getStructFieldOffset(ld64, DeCommitFreeBlockThreshold);
break;
case DECOMMIT_TOTAL :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DeCommitTotalFreeThreshold) : getStructFieldOffset(ld64, DeCommitTotalFreeThreshold);
break;
case LOCK_PREFIX :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, LockPrefixTable) : getStructFieldOffset(ld64, LockPrefixTable);
break;
case MAX_ALLOC :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, MaximumAllocationSize) : getStructFieldOffset(ld64, MaximumAllocationSize);
break;
case VIRTUAL_MEM :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, VirtualMemoryThreshold) : getStructFieldOffset(ld64, VirtualMemoryThreshold);
break;
case PROC_HEAP_FLAGS32 : //PROC_AFF_MASK64
{
fieldOffset = (is32b) ? getStructFieldOffset(ld32, ProcessHeapFlags) : getStructFieldOffset(ld64, ProcessAffinityMask);
break;
}
case PROC_AFF_MASK32 : // PROC_HEAP_FLAGS64
{
fieldOffset = (is32b) ? getStructFieldOffset(ld32, ProcessAffinityMask) : getStructFieldOffset(ld64, ProcessHeapFlags);
break;
}
case CSD_VER :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CSDVersion) : getStructFieldOffset(ld64, CSDVersion);
break;
case DEPENDENT_LOAD_FLAGS :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DependentLoadFlags) : getStructFieldOffset(ld64, DependentLoadFlags);
break;
case EDIT_LIST :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, EditList) : getStructFieldOffset(ld64, EditList);
break;
case SEC_COOKIE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, SecurityCookie) : getStructFieldOffset(ld64, SecurityCookie);
break;
case SEH_TABLE :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, SEHandlerTable) : getStructFieldOffset(ld64, SEHandlerTable);
break;
case SEH_COUNT :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, SEHandlerCount) : getStructFieldOffset(ld64, SEHandlerCount);
break;
// W8.1 part:
case GUARD_CHECK :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFCheckFunctionPointer) : getStructFieldOffset(ld64, GuardCFCheckFunctionPointer);
break;
case GUARD_DISPATCH :
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFDispatchFunctionPointer) : getStructFieldOffset(ld64, GuardCFDispatchFunctionPointer);
break;
case GUARD_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFFunctionTable) : getStructFieldOffset(ld64, GuardCFFunctionTable);
break;
case GUARD_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardCFFunctionCount) : getStructFieldOffset(ld64, GuardCFFunctionCount);
break;
case GUARD_FLAGS:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardFlags) : getStructFieldOffset(ld64, GuardFlags);
break;
// W10 part:
case CODE_INTEGRITY_FLAGS:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Flags) : getStructFieldOffset(ld64, CodeIntegrity.Flags);
break;
case CODE_INTEGRITY_CATALOG:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Catalog) : getStructFieldOffset(ld64, CodeIntegrity.Catalog);
break;
case CODE_INTEGRITY_CATALOG_OFFSET:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.CatalogOffset) : getStructFieldOffset(ld64, CodeIntegrity.CatalogOffset);
break;
case CODE_INTEGRITY_RESERVED:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CodeIntegrity.Reserved) : getStructFieldOffset(ld64, CodeIntegrity.Reserved);
break;
case GUARD_ADDR_IAT_ENTRY_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardAddressTakenIatEntryTable) : getStructFieldOffset(ld64, GuardAddressTakenIatEntryTable);
break;
case GUARD_ADDR_IAT_ENTRY_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardAddressTakenIatEntryCount) : getStructFieldOffset(ld64, GuardAddressTakenIatEntryCount);
break;
case GUARD_LONG_JUMP_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardLongJumpTargetTable) : getStructFieldOffset(ld64, GuardLongJumpTargetTable);
break;
case GUARD_LONG_JUMP_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardLongJumpTargetCount) : getStructFieldOffset(ld64, GuardLongJumpTargetCount);
break;
case DYNAMIC_VAL_RELOC:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTable) : getStructFieldOffset(ld64, DynamicValueRelocTable);
break;
case CHPE_METADATA_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, CHPEMetadataPointer) : getStructFieldOffset(ld64, CHPEMetadataPointer);
break;
case GUARD_FAILURE_ROUTINE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFFailureRoutine) : getStructFieldOffset(ld64, GuardRFFailureRoutine);
break;
case GUARD_FAILURE_ROUTINE_FUNC_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFFailureRoutineFunctionPointer) : getStructFieldOffset(ld64, GuardRFFailureRoutineFunctionPointer);
break;
case DYNAMIC_VAL_RELOC_TABLE_OFFSET:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTableOffset) : getStructFieldOffset(ld64, DynamicValueRelocTableOffset);
break;
case DYNAMIC_VAL_RELOC_TABLE_SECTION:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, DynamicValueRelocTableSection) : getStructFieldOffset(ld64, DynamicValueRelocTableSection);
break;
case RESERVED2:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, Reserved2) : getStructFieldOffset(ld64, Reserved2);
break;
case GUARD_VERIFY_STACK_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardRFVerifyStackPointerFunctionPointer) : getStructFieldOffset(ld64, GuardRFVerifyStackPointerFunctionPointer);
break;
case HOT_PATCH_TABLE_OFFSET:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, HotPatchTableOffset) : getStructFieldOffset(ld64, HotPatchTableOffset);
break;
case RESERVED3:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, Reserved3) : getStructFieldOffset(ld64, Reserved3);
break;
case ENCLAVE_CONFIG_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, EnclaveConfigurationPointer) : getStructFieldOffset(ld64, EnclaveConfigurationPointer);
break;
case VOLATILE_METADATA_PTR:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, VolatileMetadataPointer) : getStructFieldOffset(ld64, VolatileMetadataPointer);
break;
case GUARD_EH_CONT_TABLE:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardEHContinuationTable) : getStructFieldOffset(ld64, GuardEHContinuationTable);
break;
case GUARD_EH_CONT_COUNT:
fieldOffset = (is32b) ? getStructFieldOffset(ld32, GuardEHContinuationCount) : getStructFieldOffset(ld64, GuardEHContinuationCount);
break;
}
return fieldOffset;
}
void* LdConfigDirWrapper::getFieldPtr(size_t fId, size_t subField)
{
const bool is32b = (m_Exe->getBitMode() == Executable::BITS_32) ? true : false;
offset_t fieldDelta = _getFieldDelta(is32b, fId);
if (fieldDelta != INVALID_ADDR) {
const offset_t hdrSize = this->getHdrDefinedSize();
if (fieldDelta >= hdrSize) {
return NULL;
}
return m_Exe->getContentAt(this->getOffset() + fieldDelta, 1);
}
return NULL;
}
QString LdConfigDirWrapper::getFieldName(size_t fieldId)
{
if (!m_Exe) return "";
const bool is32bit = (m_Exe->getBitMode() == Executable::BITS_32);
switch (fieldId) {
case SIZE : return "Size";
case TIMEST : return "TimeDateStamp";
case MAJOR_VER : return "MajorVersion";
case MINOR_VER : return "MinorVersion";
case GLOBAL_FLAGS_CLEAR : return "GlobalFlagsClear";
case GLOBAL_FLAGS_SET : return "GlobalFlagsSet";
case CRITICAT_SEC_TIMEOUT : return "CriticalSectionDefaultTimeout";
case DECOMMIT_FREE : return "DeCommitFreeBlockThreshold";
case DECOMMIT_TOTAL : return "DeCommitTotalFreeThreshold";
case LOCK_PREFIX : return "LockPrefixTable";
case MAX_ALLOC : return "MaximumAllocationSize";
case VIRTUAL_MEM : return "VirtualMemoryThreshold";
case PROC_HEAP_FLAGS32 : //PROC_AFF_MASK64
{
return (is32bit) ? "ProcessHeapFlags" : "ProcessAffinityMask";
}
case PROC_AFF_MASK32 : // PROC_HEAP_FLAGS64
{
return (is32bit) ? "ProcessAffinityMask" : "ProcessHeapFlags";
}
case CSD_VER : return "CSDVersion";
case DEPENDENT_LOAD_FLAGS : return "DependentLoadFlags";
case EDIT_LIST : return "EditList";
case SEC_COOKIE : return "SecurityCookie";
case SEH_TABLE : return "SEHandlerTable";
case SEH_COUNT : return "SEHandlerCount";
// W8.1 part :
case GUARD_CHECK : return "GuardCFCheckFunctionPtr";
case GUARD_DISPATCH : return "GuardCFDispatchFunctionPointer";
case GUARD_TABLE: return "GuardCFFunctionTable";
case GUARD_COUNT: return "GuardCFFunctionCount";
case GUARD_FLAGS: return "GuardFlags";
// W10 part:
case CODE_INTEGRITY_FLAGS: return "CodeIntegrity.Flags"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Flags
case CODE_INTEGRITY_CATALOG: return "CodeIntegrity.Catalog"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Catalog
case CODE_INTEGRITY_CATALOG_OFFSET: return "CodeIntegrity.CatalogOffset"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.CatalogOffset
case CODE_INTEGRITY_RESERVED: return "CodeIntegrity.Reserved"; //IMAGE_LOAD_CONFIG_CODE_INTEGRITY.Reserved
case GUARD_ADDR_IAT_ENTRY_TABLE: return "GuardAddressTakenIatEntryTable";
case GUARD_ADDR_IAT_ENTRY_COUNT: return "GuardAddressTakenIatEntryCount";
case GUARD_LONG_JUMP_TABLE: return "GuardLongJumpTargetTable";
case GUARD_LONG_JUMP_COUNT: return "GuardLongJumpTargetCount";
case DYNAMIC_VAL_RELOC: return "DynamicValueRelocTable";
case CHPE_METADATA_PTR: return "CHPEMetadataPointer";
case GUARD_FAILURE_ROUTINE: return "GuardRFFailureRoutine";
case GUARD_FAILURE_ROUTINE_FUNC_PTR: return "GuardRFFailureRoutineFunctionPointer";
case DYNAMIC_VAL_RELOC_TABLE_OFFSET: return "DynamicValueRelocTableOffset";
case DYNAMIC_VAL_RELOC_TABLE_SECTION: return "DynamicValueRelocTableSection";
case RESERVED2: return "Reserved2";
case GUARD_VERIFY_STACK_PTR: return "GuardRFVerifyStackPointerFunctionPointer";
case HOT_PATCH_TABLE_OFFSET: return "HotPatchTableOffset";
case RESERVED3: return "Reserved3";
case ENCLAVE_CONFIG_PTR: return "EnclaveConfigurationPointer";
case VOLATILE_METADATA_PTR: return "VolatileMetadataPointer";
case GUARD_EH_CONT_TABLE: return "GuardEHContinuationTable";
case GUARD_EH_CONT_COUNT: return "GuardEHContinuationCount";
}
return getName();
}
Executable::addr_type LdConfigDirWrapper::containsAddrType(size_t fieldId, size_t subField)
{
switch (fieldId) {
case LOCK_PREFIX :
case EDIT_LIST :
case SEC_COOKIE :
case SEH_TABLE :
case GUARD_CHECK :
case GUARD_DISPATCH :
case GUARD_TABLE :
case GUARD_ADDR_IAT_ENTRY_TABLE:
case GUARD_LONG_JUMP_TABLE:
case DYNAMIC_VAL_RELOC:
case GUARD_FAILURE_ROUTINE:
case GUARD_FAILURE_ROUTINE_FUNC_PTR:
case GUARD_VERIFY_STACK_PTR:
case ENCLAVE_CONFIG_PTR:
case VOLATILE_METADATA_PTR:
case GUARD_EH_CONT_TABLE:
return Executable::VA;
}
return Executable::NOT_ADDR;
}
std::set<DWORD> LdConfigDirWrapper::getGuardFlagsSet(DWORD flags)
{
const size_t guardFlagsCount = 13;
const DWORD guardFlags[guardFlagsCount] = {
IMAGE_GUARD_CF_INSTRUMENTED,
IMAGE_GUARD_CFW_INSTRUMENTED,
IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT,
IMAGE_GUARD_SECURITY_COOKIE_UNUSED,
IMAGE_GUARD_PROTECT_DELAYLOAD_IAT,
IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION,
IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT,
IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION,
IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT,
IMAGE_GUARD_RF_INSTRUMENTED,
IMAGE_GUARD_RF_ENABLE,
IMAGE_GUARD_RF_STRICT,
IMAGE_GUARD_RETPOLINE_PRESENT
};
std::set<DWORD> allFlags;
for (size_t i = 0; i < guardFlagsCount; ++i) {
const DWORD nextFlag = guardFlags[i];
if (flags & nextFlag) {
allFlags.insert(nextFlag);
}
}
return allFlags;
}
QString LdConfigDirWrapper::translateGuardFlag(DWORD flags)
{
if (flags & IMAGE_GUARD_CF_INSTRUMENTED) {
return ("CF_INSTRUMENTED");
}
if (flags & IMAGE_GUARD_CFW_INSTRUMENTED) {
return ("CFW_INSTRUMENTED");
}
if (flags & IMAGE_GUARD_CF_FUNCTION_TABLE_PRESENT) {
return ("CF_FUNCTION_TABLE_PRESENT");
}
if (flags & IMAGE_GUARD_SECURITY_COOKIE_UNUSED) {
return ("SECURITY_COOKIE_UNUSED");
}
if (flags & IMAGE_GUARD_PROTECT_DELAYLOAD_IAT) {
return ("PROTECT_DELAYLOAD_IAT");
}
if (flags & IMAGE_GUARD_DELAYLOAD_IAT_IN_ITS_OWN_SECTION) {
return ("DELAYLOAD_IAT_IN_ITS_OWN_SECTION");
}
if (flags & IMAGE_GUARD_CF_EXPORT_SUPPRESSION_INFO_PRESENT) {
return ("CF_EXPORT_SUPPRESSION_INFO_PRESENT");
}
if (flags & IMAGE_GUARD_CF_ENABLE_EXPORT_SUPPRESSION) {
return ("CF_ENABLE_EXPORT_SUPPRESSION");
}
if (flags & IMAGE_GUARD_CF_LONGJUMP_TABLE_PRESENT) {
return ("CF_LONGJUMP_TABLE_PRESENT");
}
if (flags & IMAGE_GUARD_RF_INSTRUMENTED) {
return ("RF_INSTRUMENTED");
}
if (flags & IMAGE_GUARD_RF_ENABLE) {
return ("RF_ENABLE");
}
if (flags & IMAGE_GUARD_RF_STRICT) {
return ("RF_STRICT");
}
if (flags & IMAGE_GUARD_RETPOLINE_PRESENT) {
return ("RETPOLINE_PRESENT");
}
return "";
}
QString LdConfigDirWrapper::translateGuardFlagsContent(const QString& delim)
{
bool isOk = false;
DWORD GuardFlags = this->getNumValue(GUARD_FLAGS, &isOk);
if (!isOk) {
return "-";
}
std::set<DWORD> flagsSet = LdConfigDirWrapper::getGuardFlagsSet(GuardFlags);
std::set<DWORD>::iterator itr;
QStringList list;
for (itr = flagsSet.begin() ; itr != flagsSet.end(); itr++) {
const DWORD nextFlag = *itr;
const QString flagInfo = LdConfigDirWrapper::translateGuardFlag(nextFlag);
if (flagInfo.length() == 0) continue;
list.append(flagInfo);
}
return list.join(delim);
}
QString LdConfigDirWrapper::translateFieldContent(size_t fieldId)
{
if (fieldId == GUARD_FLAGS) {
return translateGuardFlagsContent(";");;
}
return "";
}
//----------------
void* LdConfigEntryWrapper::getPtr()
{
if (this->parentDir == NULL) return NULL;
void* first = parentDir->firstSubEntryPtr(this->parentFieldId);
if (first == NULL) return NULL;
bufsize_t fieldSize = static_cast<bufsize_t>(parentDir->firstSubEntrySize(this->parentFieldId));
if (fieldSize == 0) return NULL;
offset_t offset = this->getOffset(first);
if (offset == INVALID_ADDR) return NULL;
//offset from the beginning:
offset_t fieldOffset = (this->entryNum * fieldSize);
offset += fieldOffset;
void *ptr = m_Exe->getContentAt(offset, Executable::RAW, fieldSize);
return ptr;
}
bufsize_t LdConfigEntryWrapper::getSize()
{
if (this->parentDir == NULL) return 0;
if (!getPtr()) return 0;
bufsize_t size = static_cast<bufsize_t>(parentDir->firstSubEntrySize(this->parentFieldId));
return size;
}
void* LdConfigEntryWrapper::getFieldPtr(size_t fieldId, size_t subField)
{
void* ptr = getPtr();
if (!ptr) return NULL;
if (fieldId == NONE) {
return ptr;
}
size_t counter = getFieldsCount();
if (fieldId >= counter) return NULL;
if (fieldId == HANDLER_ADDR) {
return ptr;
}
return (void*)((ULONGLONG)ptr + sizeof(DWORD));
}
bufsize_t LdConfigEntryWrapper::getFieldSize(size_t fieldId, size_t subField)
{
size_t count = this->getFieldsCount();
if (fieldId >= count) {
return 0;
}
if (fieldId == HANDLER_ADDR) {
return sizeof(DWORD);
}
return sizeof(BYTE);
}
| 41.093357 | 176 | 0.680676 | yjd |
c0b0c585b2bfa025ee88c817acf33c5a4a6e711c | 13,633 | cpp | C++ | DBProCompiler/DBPCompiler/DataTable.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 231 | 2018-01-28T00:06:56.000Z | 2022-03-31T21:39:56.000Z | DBProCompiler/DBPCompiler/DataTable.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 9 | 2016-02-10T10:46:16.000Z | 2017-12-06T17:27:51.000Z | DBProCompiler/DBPCompiler/DataTable.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 66 | 2018-01-28T21:54:52.000Z | 2022-02-16T22:50:57.000Z | // DataTable.cpp: implementation of the CDataTable class.
//
//////////////////////////////////////////////////////////////////////
#include "DataTable.h"
// Includes and external ptr for AssociateDLL scan
#include "DBPCompiler.h"
#include "direct.h"
extern CDBPCompiler* g_pDBPCompiler;
extern bool g_bExternaliseDLLS;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDataTable::CDataTable()
{
m_dwIndex=0;
m_dwType=0;
m_pNumeric=0;
m_pString=NULL;
m_pString2=NULL;
m_pNext=NULL;
m_bAddedToEXEData=false;
}
CDataTable::CDataTable(LPSTR pInitString)
{
m_dwIndex=0;
m_dwType=0;
m_pNumeric=0;
m_pString=new CStr(pInitString);
m_pString2=new CStr("");
m_pNext=NULL;
m_bAddedToEXEData=false;
}
CDataTable::~CDataTable()
{
SAFE_DELETE(m_pString);
SAFE_DELETE(m_pString2);
}
void CDataTable::Free(void)
{
CDataTable* pCurrent = this;
while(pCurrent)
{
CDataTable* pNext = pCurrent->GetNext();
delete pCurrent;
pCurrent = pNext;
}
}
void CDataTable::Add(CDataTable* pNew)
{
CDataTable* pCurrent = this;
while(pCurrent->m_pNext)
{
pCurrent=pCurrent->GetNext();
}
pCurrent->m_pNext=pNew;
}
bool CDataTable::AddNumeric(double dNum, DWORD dwIndex)
{
// Create new data item
CDataTable* pNewData = new CDataTable;
pNewData->SetNumeric(dNum);
// Set index
pNewData->SetIndex(dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
bool CDataTable::AddString(LPSTR pString, DWORD dwIndex)
{
// Create new data item
CDataTable* pNewData = new CDataTable;
CStr* pStr = new CStr(pString);
pNewData->SetString(pStr);
pNewData->SetString2(NULL);
// Set index
pNewData->SetIndex(dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
bool CDataTable::AddTwoStrings(LPSTR pString, LPSTR pString2, DWORD* dwIndex)
{
// If string is NOT unique, fail
DWORD dwResult = FindString(pString);
if(dwResult>0)
{
*dwIndex=dwResult;
return false;
}
// Create new data item
CDataTable* pNewData = new CDataTable;
CStr* pStr1 = new CStr(pString);
CStr* pStr2 = new CStr(pString2);
pNewData->SetString(pStr1);
pNewData->SetString2(pStr2);
// Set index
pNewData->SetIndex(*dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
bool CDataTable::AddUniqueString(LPSTR pString, DWORD* dwIndex)
{
// If string is NOT unique, fail
DWORD dwResult = FindString(pString);
if(dwResult>0)
{
*dwIndex=dwResult;
return false;
}
// Create new data item
CDataTable* pNewData = new CDataTable;
CStr* pStr = new CStr(pString);
pNewData->SetString(pStr);
pNewData->SetString2(NULL);
// Set index
pNewData->SetIndex(*dwIndex);
// Add to Data Table
Add(pNewData);
// Complete
return true;
}
DWORD CDataTable::FindString(LPSTR pFindString)
{
// Find String
CDataTable* pCurrent = this;
while(pCurrent)
{
// Match list item with search string
if(pCurrent->GetString())
if(stricmp(pCurrent->GetString()->GetStr(), pFindString)==NULL)
return pCurrent->GetIndex();
pCurrent=pCurrent->GetNext();
}
// Failed to find
return 0;
}
bool CDataTable::FindIndexStr(LPSTR pIndexAsString)
{
// Convert String to Index
DWORD dwFindIndex = atoi(pIndexAsString);
// Find String
CDataTable* pCurrent = this;
while(pCurrent)
{
// Match list item with search string
if(pCurrent->GetString())
if(pCurrent->GetIndex()==dwFindIndex)
return true;
pCurrent=pCurrent->GetNext();
}
// Soft Failed to find
return false;
}
bool CDataTable::NotExcluded ( LPSTR pFilename )
{
// false if excluded from compile
for ( DWORD i=1; i<g_pDBPCompiler->g_dwExcludeFilesCount; i++)
if ( g_pDBPCompiler->g_pExcludeFiles [ i ] )
if ( stricmp ( g_pDBPCompiler->g_pExcludeFiles [ i ], pFilename )==NULL )
return false;
// lee - 270308 - u67 - do not include DLL at all if flagged
if ( g_bExternaliseDLLS==true )
return false;
// complete, not excluded
return true;
}
int CDataTable::CompleteAnyLinkAssociates(void)
{
// Scan user plugins - check if associations require any DBPro DLLs
bool bAtLeastOneUserDLLNeeds3D = false;
bool bAtLeastOneUserDLLNeedsSOUND = false;
// reset index
DWORD dwIndex=0;
DWORD dwIndexBeforeAdds=0;
// First pass basic DLLs, second pass is dependence additions
for ( int iAddDependentsLoop=0; iAddDependentsLoop<2; iAddDependentsLoop++ )
{
for ( int iPass=0; iPass<2; iPass++ )
{
// Switch to PLUGINS-XXXX Folder
char pOldDir [ _MAX_PATH ];
getcwd ( pOldDir, _MAX_PATH );
// Depends on pass value
if ( iPass==0 ) _chdir(g_pDBPCompiler->GetInternalFile(PATH_PLUGINSUSERFOLDER));
if ( iPass==1 ) _chdir(g_pDBPCompiler->GetInternalFile(PATH_PLUGINSLICENSEDFOLDER));
// Go through DLLs from direct-command-list
CDataTable* pCurrent = this->GetNext();
while(pCurrent)
{
// Check if DLL is user-dll ( leefix - 011208 - u71 - gameFX needed to link to Basic3D! )
LPSTR pDLLName = pCurrent->GetString()->GetStr();
if ( strnicmp ( pDLLName, "dbpro", 5 )!=NULL || strnicmp ( pDLLName, "dbprogamefx", 11 )==NULL )
{
// must be user DLL (associated with main DLL)
int iAssociationCode = 0;
HMODULE hModule = LoadLibrary(pDLLName);
if(hModule)
{
// get associate dll value if any
if ( iAddDependentsLoop==0 )
{
typedef int ( *RETINTNOPARAM ) ( void );
RETINTNOPARAM GetAssociatedDLLs = ( RETINTNOPARAM ) GetProcAddress ( hModule, "?GetAssociatedDLLs@@YAHXZ" );
if (!GetAssociatedDLLs)
GetAssociatedDLLs = (RETINTNOPARAM)GetProcAddress(hModule, "GetAssociatedDLLs");
if ( GetAssociatedDLLs ) iAssociationCode=GetAssociatedDLLs();
}
else
{
// get num of additional dependencies
int iNumDLLDependencies = 0;
typedef int ( *RETINTNOPARAM ) ( void );
RETINTNOPARAM GetNumDependencies = ( RETINTNOPARAM ) GetProcAddress ( hModule, "?GetNumDependencies@@YAHXZ" );
if (!GetNumDependencies)
GetNumDependencies = (RETINTNOPARAM)GetProcAddress(hModule, "GetNumDependencies");
if ( GetNumDependencies ) iNumDLLDependencies=GetNumDependencies();
if ( iNumDLLDependencies > 0 )
{
typedef const char * ( *RETLPSTRNOPARAM ) ( int n );
RETLPSTRNOPARAM GetDependencyID = ( RETLPSTRNOPARAM ) GetProcAddress ( hModule, "?GetDependencyID@@YAPBDH@Z" );
if (!GetDependencyID)
GetDependencyID = (RETLPSTRNOPARAM)GetProcAddress(hModule, "GetDependencyID");
// store dependencies in list
for ( int iD=0; iD<iNumDLLDependencies; iD++ )
{
char pDependencyStr[256];
//LPSTR pDependencyStr = new char[256];
strcpy ( pDependencyStr, GetDependencyID(iD) );
DWORD dwTry=dwIndex+1;
if(AddUniqueString(pDependencyStr, &dwTry)) dwIndex=dwTry;
//SAFE_DELETE(pDependencyStr);
}
}
}
}
// free it if loaded
if(hModule)
{
FreeLibrary(hModule);
hModule=NULL;
}
// Association Codes (1=3d/2=sound/4-//)
if ( iAssociationCode & 1 ) bAtLeastOneUserDLLNeeds3D=true;
if ( iAssociationCode & 2 ) bAtLeastOneUserDLLNeedsSOUND=true;
}
// Next DLL
if ( iAddDependentsLoop==0 && iPass==0 ) dwIndex++;
pCurrent=pCurrent->GetNext();
}
// Restore dir before continue
_chdir(pOldDir);
}
// DLL index before adding any associations
if ( iAddDependentsLoop==0 ) dwIndexBeforeAdds=dwIndex;
}
// link Basic3D
if ( bAtLeastOneUserDLLNeeds3D )
{
DWORD dwTry=dwIndex+1;
if(AddUniqueString("DBProBasic3DDebug.dll", &dwTry)) dwIndex=dwTry;
}
// link Sound
if ( bAtLeastOneUserDLLNeedsSOUND )
{
DWORD dwTry=dwIndex+1;
if(AddUniqueString("DBProSoundDebug.dll", &dwTry)) dwIndex=dwTry;
}
// Scan all DLLS, and add any that are link-associated
CDataTable* pCurrent = this->GetNext();
while(pCurrent)
{
// If DLLTable Entry has string..
if(pCurrent->GetString())
{
// DLL Name contained in stringname
DWORD dwTry = 0;
LPSTR pDLL = NULL;
LPSTR pDLLName = pCurrent->GetString()->GetStr();
#define TRY_DLL(nm) dwTry=dwIndex+1;pDLL=nm;if(NotExcluded(pDLL))if(AddUniqueString(pDLL,&dwTry))dwIndex=dwTry
// Add other DLLs Associated With These..
if(stricmp(pDLLName, "DBProSetupDebug.dll")==NULL)
{
// Associate DLLs
TRY_DLL("DBProBasic2DDebug.dll");
TRY_DLL("DBProTextDebug.dll");
}
if(stricmp(pDLLName, "DBProTextDebug.dll")==NULL)
{
// Associate DLLs
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProInputDebug.dll")==NULL)
{
// Checklist Support
TRY_DLL("DBProSystemDebug.dll");
}
if(stricmp(pDLLName, "DBProSpritesDebug.dll")==NULL)
{
// Image Support
TRY_DLL("DBProImageDebug.dll");
}
if(stricmp(pDLLName, "DBProBasic3DDebug.dll")==NULL)
{
// Image Support
TRY_DLL("DBProImageDebug.dll");
// Transforms Support
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProBasic2DDebug.dll")==NULL)
{
// Minimal DirectX
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProImageDebug.dll")==NULL
|| stricmp(pDLLName, "DBProAnimationDebug.dll")==NULL
|| stricmp(pDLLName, "DBProBitmapDebug.dll")==NULL)
{
// Sprite Support for pasting
TRY_DLL("DBProSpritesDebug.dll");
// Minimal DirectX
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProBasic2DDebug.dll");
TRY_DLL("DBProTextDebug.dll");
}
if(stricmp(pDLLName, "DBProMultiplayerDebug.dll")==NULL)
{
// Need access to memblock support
TRY_DLL("DBProMemblocksDebug.dll");
}
if(stricmp(pDLLName, "DBProMemblocksDebug.dll")==NULL)
{
// Memblocks Access to Bitmap, Image, Sound and Mesh
TRY_DLL("DBProBitmapDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProSoundDebug.dll");
TRY_DLL("DBProBasic3DDebug.dll");
}
if(stricmp(pDLLName, "DBProCameraDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
TRY_DLL("DBProBasic3DDebug.dll");
}
if(stricmp(pDLLName, "DBProLightDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProMatrixDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProBasic3DDebug.dll")==NULL)
{
// Primary Support
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProLightDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
// Secondary Support
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("ConvX.dll");
TRY_DLL("Conv3DS.dll");
TRY_DLL("ConvMDL.dll");
TRY_DLL("ConvMD2.dll");
TRY_DLL("ConvMD3.dll");
}
if(stricmp(pDLLName, "DBProWorld3DDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProLODTerrainDebug.dll");
TRY_DLL("DBProQ2BSPDebug.dll");
TRY_DLL("DBProBasic3DDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
TRY_DLL("DBProOwnBSPDebug.dll");
}
if(stricmp(pDLLName, "DBProLODTerrainDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProSetupDebug.dll");
TRY_DLL("DBProImageDebug.dll");
TRY_DLL("DBProCameraDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProCSGDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProParticlesDebug.dll")==NULL )
{
// Primary Support
TRY_DLL("DBProParticlesDebug.dll");
TRY_DLL("DBProVectorsDebug.dll");
TRY_DLL("DBProTransformsDebug.dll");
}
if(stricmp(pDLLName, "DBProSystemDebug.dll")==NULL )
{
// for access to display mem
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProVectorsDebug.dll")==NULL )
{
TRY_DLL("DBProSetupDebug.dll");
}
if(stricmp(pDLLName, "DBProTransformsDebug.dll")==NULL)
{
TRY_DLL("DBProSetupDebug.dll");
}
#undef TRY_DLL
}
// Next entry in DLL Table
pCurrent=pCurrent->GetNext();
}
// Complete
return (dwIndex-dwIndexBeforeAdds);
}
// WriteDBM
bool CDataTable::WriteDBMHeader(DWORD dwKindOfTable)
{
// Blank Line
CStr strDBMBlank(1);
if(g_pDBMWriter->OutputDBM(&strDBMBlank)==false) return false;
// header Line
CStr strDBMLine(256);
if(dwKindOfTable==1) strDBMLine.SetText("STRING:");
if(dwKindOfTable==2) strDBMLine.SetText("DATA:");
if(dwKindOfTable==3) strDBMLine.SetText("DLLS:");
if(dwKindOfTable==4) strDBMLine.SetText("COMMANDS:");
if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false;
return true;
}
bool CDataTable::WriteDBM(void)
{
// Write out text
CStr strDBMLine(256);
strDBMLine.SetText(">>");
if(GetType()==1)
{
strDBMLine.AddNumericText(GetIndex());
strDBMLine.AddText("=");
strDBMLine.AddDoubleText(GetNumeric());
}
if(GetType()==2)
{
strDBMLine.AddNumericText(GetIndex());
strDBMLine.AddText("=");
strDBMLine.AddText(GetString());
}
// Output details
if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false;
// Write next one
if(GetNext())
{
if((GetNext()->WriteDBM())==false) return false;
}
// Complete
return true;
}
| 25.434701 | 119 | 0.672559 | domydev |
c0b4f0c46557b3568a06437544cbfebd5c055175 | 1,631 | hpp | C++ | src/snabl/func.hpp | codr4life/snabl | b1c8a69e351243a3ae73d69754971d540c224733 | [
"MIT"
] | 22 | 2018-08-27T15:28:10.000Z | 2022-02-13T08:18:00.000Z | src/snabl/func.hpp | codr4life/snabl | b1c8a69e351243a3ae73d69754971d540c224733 | [
"MIT"
] | 3 | 2018-08-27T01:44:51.000Z | 2020-06-28T20:07:42.000Z | src/snabl/func.hpp | codr4life/snabl | b1c8a69e351243a3ae73d69754971d540c224733 | [
"MIT"
] | 2 | 2018-08-26T18:55:47.000Z | 2018-09-29T01:04:36.000Z | #ifndef SNABL_FUNC_HPP
#define SNABL_FUNC_HPP
#include "snabl/def.hpp"
#include "snabl/fimp.hpp"
#include "snabl/ptrs.hpp"
#include "snabl/stack.hpp"
#include "snabl/std.hpp"
namespace snabl {
struct Lib;
struct Func: Def {
Lib &lib;
const I64 nargs;
unordered_map<Sym, unique_ptr<Fimp>> fimps;
Func(const Func &)=delete;
const Func &operator =(const Func &)=delete;
Func(Lib &lib, Sym id, I64 nargs): Def(id), lib(lib), nargs(nargs) { }
template <typename... ImpT>
Fimp &add_fimp(const Fimp::Args &args, ImpT &&... imp);
Fimp &get_fimp() const { return *fimps.begin()->second; }
Fimp *get_best_fimp(Stack::const_iterator begin,
Stack::const_iterator end) const {
I64 best_score(-1);
Fimp *best_fimp(nullptr);
for (auto &fp: fimps) {
auto &f(*fp.second);
auto fs(f.score(begin, end));
if (fs != -1) {
if (fs == 0) { return &f; }
if (best_score == -1 || fs < best_score) {
best_score = fs;
best_fimp = &f;
}
}
}
return best_fimp;
}
};
template <typename... ImpT>
Fimp &Func::add_fimp(const Fimp::Args &args, ImpT &&... imp) {
auto id(Fimp::get_id(*this, args));
auto found = fimps.find(id);
if (found == fimps.end()) {
return *fimps.emplace(id, make_unique<Fimp>(*this, args, forward<ImpT>(imp)...))
.first->second;
}
auto *fi(found->second.get());
fi->~Fimp();
new (fi) Fimp(*this, args, forward<ImpT>(imp)...);
return *fi;
}
}
#endif
| 23.637681 | 86 | 0.551196 | codr4life |
c0b5f5df675f79f3c14e1c71280430164c57e7ef | 1,174 | cpp | C++ | oculus/LibOVR/Src/Kernel/OVR_String_FormatUtil.cpp | mikeadams1/oculus-drone | fb22b6d0f9ec4ab700313f19ffadd0214b76ca32 | [
"MIT"
] | 46 | 2015-02-11T13:56:53.000Z | 2021-03-25T20:46:14.000Z | oculus/LibOVR/Src/Kernel/OVR_String_FormatUtil.cpp | mikeadams1/oculus-drone | fb22b6d0f9ec4ab700313f19ffadd0214b76ca32 | [
"MIT"
] | 2 | 2018-02-23T02:22:51.000Z | 2020-07-17T03:57:09.000Z | oculus/LibOVR/Src/Kernel/OVR_String_FormatUtil.cpp | feross/oculus-drone | fb22b6d0f9ec4ab700313f19ffadd0214b76ca32 | [
"MIT"
] | 20 | 2015-03-03T16:03:07.000Z | 2020-01-23T14:48:49.000Z | /************************************************************************************
Filename : OVR_String_FormatUtil.cpp
Content : String format functions.
Created : February 27, 2013
Notes :
Copyright : Copyright 2013 Oculus VR, Inc. All Rights reserved.
Use of this software is subject to the terms of the Oculus license
agreement provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
************************************************************************************/
#include "OVR_String.h"
#include "OVR_Log.h"
namespace OVR {
void StringBuffer::AppendFormat(const char* format, ...)
{
va_list argList;
va_start(argList, format);
UPInt size = OVR_vscprintf(format, argList);
va_end(argList);
char* buffer = (char*) OVR_ALLOC(sizeof(char) * (size+1));
va_start(argList, format);
UPInt result = OVR_vsprintf(buffer, size+1, format, argList);
OVR_UNUSED1(result);
va_end(argList);
OVR_ASSERT_LOG(result == size, ("Error in OVR_vsprintf"));
AppendString(buffer);
OVR_FREE(buffer);
}
} // OVR
| 1,174 | 1,174 | 0.592845 | mikeadams1 |
c0b776e122dd83a325cd92f2998b8112f48072a6 | 80 | cpp | C++ | tests/files/test_parse_and_generate/group_common_flags_clang_cl/source/a.cpp | alexsharoff/BuildMigrator | 4495907d93ae11b1e88d16dfda3b0b570b8106ed | [
"Apache-2.0"
] | 17 | 2020-09-09T15:16:21.000Z | 2021-12-20T01:21:19.000Z | tests/files/test_parse_and_generate/group_common_flags_clang_cl/source/a.cpp | KasperskyLab/BuildMigrator | 4495907d93ae11b1e88d16dfda3b0b570b8106ed | [
"Apache-2.0"
] | null | null | null | tests/files/test_parse_and_generate/group_common_flags_clang_cl/source/a.cpp | KasperskyLab/BuildMigrator | 4495907d93ae11b1e88d16dfda3b0b570b8106ed | [
"Apache-2.0"
] | null | null | null | #include "file.h"
#ifndef MODE_A
#error MODE_A
#endif
int a() { return s_a; }
| 10 | 23 | 0.6625 | alexsharoff |
c0b9271b98af2c80e040a3e1814ea675cb9da9cb | 12,843 | cpp | C++ | plugin.cpp | CrackerCat/ida-strikeout | 3f10e0964739aae9dd49b694efa5045c7f0f6376 | [
"MIT"
] | null | null | null | plugin.cpp | CrackerCat/ida-strikeout | 3f10e0964739aae9dd49b694efa5045c7f0f6376 | [
"MIT"
] | null | null | null | plugin.cpp | CrackerCat/ida-strikeout | 3f10e0964739aae9dd49b694efa5045c7f0f6376 | [
"MIT"
] | null | null | null | /*
StrikeOut: a plugin that allows you to delete Ctree statements and patch the disassembly code.
When StrikeOut is active, you will see context menu items in the decompiler window.
(c) Elias Bachaalany <elias.bachaalany@gmail.com>
*/
#include "plugin.h"
#include "storage.hpp"
#include "utils.hpp"
static ssize_t idaapi hr_callback(
void* ud,
hexrays_event_t event,
va_list va);
//-------------------------------------------------------------------------
struct strikeout_plg_t : public plugmod_t, event_listener_t
{
action_manager_t am;
eanodes_t marked;
eavec_t patchstmt_queue;
strikeout_plg_t() : am(this), marked(STORE_NODE_NAME)
{
install_hexrays_callback(hr_callback, this);
setup_ui();
}
ssize_t idaapi on_event(ssize_t code, va_list va) override
{
if (code == ui_finish_populating_widget_popup)
am.on_ui_finish_populating_widget_popup(va);
return 0;
}
void setup_ui()
{
auto enable_for_expr = FO_ACTION_UPDATE([],
auto vu = get_widget_vdui(widget);
return (vu == nullptr) ? AST_DISABLE_FOR_WIDGET
: vu->item.citype != VDI_EXPR ? AST_DISABLE : AST_ENABLE;
);
auto enable_for_vd = FO_ACTION_UPDATE([],
auto vu = get_widget_vdui(widget);
return vu == nullptr ? AST_DISABLE_FOR_WIDGET : AST_ENABLE;
);
auto enable_for_disasm = FO_ACTION_UPDATE([],
return get_widget_type(widget) == BWN_DISASM ? AST_ENABLE_FOR_WIDGET : AST_DISABLE_FOR_WIDGET;
);
am.set_popup_path("StrikeOut/");
// Delete statement
am.add_action(
AMAHF_HXE_POPUP,
ACTION_NAME_DELSTMT,
"Delete statement",
"Del",
enable_for_expr,
FO_ACTION_ACTIVATE([this]) {
vdui_t &vu = *get_widget_vdui(ctx->widget);
ea_t stmt_ea = this->do_del_stmt(vu);
if (stmt_ea != BADADDR)
this->marked.add(stmt_ea);
vu.refresh_ctext();
return 1;
}
);
// Patch code
am.add_action(
AMAHF_IDA_POPUP,
ACTION_NAME_PATCHCODE,
"Patch disassembly code",
"Ctrl-Shift-Del",
enable_for_disasm,
FO_ACTION_ACTIVATE([this]) {
return this->do_patch_disasm_code(ctx->widget);
}
);
// Move line: up
am.add_action(
AMAHF_IDA_POPUP,
ACTION_NAME_DISASM_LINEUP,
"Move line up",
"Alt-Shift-Up",
enable_for_disasm,
FO_ACTION_ACTIVATE([this]) {
return this->do_move_disasm_line(ctx->cur_ea, true);
}
);
// Move line: down
am.add_action(
AMAHF_IDA_POPUP,
ACTION_NAME_DISASM_LINEDOWN,
"Move line down",
"Alt-Shift-Down",
enable_for_disasm,
FO_ACTION_ACTIVATE([this]) {
return this->do_move_disasm_line(ctx->cur_ea, false);
}
);
// Flush the statement patcher
am.add_action(
AMAHF_HXE_POPUP,
ACTION_NAME_PATCHSTMT_FLUSH,
"Apply patch statements queue",
"Alt-Shift-End",
enable_for_vd,
FO_ACTION_ACTIVATE([this]) {
vdui_t& vu = *get_widget_vdui(ctx->widget);
this->do_flush_patch_stmt(vu);
return 0;
}
);
// ================================ Clear =============================
am.set_popup_path("StrikeOut/Clear/");
// Transfer hidden statements as a patch
am.add_action(
AMAHF_HXE_POPUP | AMAHF_IDA_POPUP,
ACTION_NAME_DEL2PATCH,
"Reset deleted statements for current function",
"Alt-Shift-Ins",
FO_ACTION_UPDATE([],
auto t = get_widget_type(widget);
return (t == BWN_DISASM || t == BWN_PSEUDOCODE) ? AST_ENABLE_FOR_WIDGET : AST_DISABLE_FOR_WIDGET;
), FO_ACTION_ACTIVATE([this]) {
this->do_transfer_to_patch_queue(ctx);
vdui_t *vu = get_widget_vdui(ctx->widget);
if (vu != nullptr)
vu->refresh_ctext();
return 1;
});
// Clear the queue patch statements
am.add_action(
AMAHF_HXE_POPUP | AMAHF_IDA_POPUP,
ACTION_NAME_PATCHSTMT_CLEAR,
"Clear patch statement queue",
"Alt-Shift-Del",
enable_for_vd,
FO_ACTION_ACTIVATE([this]) {
this->patchstmt_queue.qclear();
return 0;
}
);
// Reset all deleted statements
am.add_action(
AMAHF_HXE_POPUP,
ACTION_NAME_DELSTMTS,
"Clear all deleted statements",
"",
enable_for_vd,
FO_ACTION_ACTIVATE([this]) {
vdui_t &vu = *get_widget_vdui(ctx->widget);
this->do_reset_stmts(vu);
vu.refresh_ctext();
return 1;
}
);
am.set_popup_path();
hook_event_listener(HT_UI, this);
}
virtual ~strikeout_plg_t()
{
remove_hexrays_callback(hr_callback, this);
}
bool idaapi run(size_t) override
{
return false;
}
void transform_ctree(cfunc_t* cfunc)
{
marked.load();
cinsnptrvec_t marked_insn;
hexrays_collect_cinsn_from_ea helper(cfunc, &marked, &marked_insn);
hexrays_keep_lca_cinsns(cfunc, &helper, marked_insn);
for (auto stmt_item : marked_insn)
{
cblock_t* cblock;
cblock_t::iterator pos;
if (hexrays_get_stmt_block_pos(cfunc, stmt_item, &cblock, &pos, &helper))
cblock->erase(pos);
}
cfunc->remove_unused_labels();
}
// Move disassembly lines
int do_move_disasm_line(ea_t ea, bool up)
{
// Sort addresses
codeitem_t items[2];
items[0] = up ? ea : next_head(ea, BADADDR);
items[1] = up ? prev_head(ea, 0) : ea;
if (!items[0] || !items[1])
{
msg("Cannot swap at %a\n", ea);
return 0;
}
if (items[0] == items[1])
return 0;
ea_t start_ea, end_ea;
start_ea = items[1].ea;
end_ea = items[0].ea + ea_t(items[0].size());
auto old_auto = enable_auto(false);
msg("Swapping....%a and %a\n", start_ea, end_ea);
del_items(start_ea, 0, end_ea - start_ea);
// Paste elements
end_ea = items[0].paste(start_ea);
ea = items[1].paste(end_ea);
// Re-create instructions
create_insn(start_ea);
enable_auto(old_auto);
auto_wait();
ea_t navto = up ? start_ea : end_ea;
jumpto(navto);
return 1;
}
int do_patch_disasm_code(TWidget* widget)
{
ea_t ea2;
ea_t ea1 = get_selection_range(widget, &ea2, BWN_DISASM);
if (ea1 == BADADDR)
return 0;
msg("patched selection: %a .. %a\n", ea1, ea2);
for (; ea1 < ea2; ++ea1)
patch_byte(ea1, 0x90);
return 1;
}
ea_t do_del_stmt(vdui_t& vu, bool use_helper=true)
{
auto cfunc = vu.cfunc;
auto item = vu.item.i;
hexrays_ctreeparent_visitor_t *helper = nullptr;
const citem_t* stmt_item = hexrays_get_stmt_insn(cfunc, item, use_helper ? &helper : nullptr);
if (stmt_item == nullptr)
return BADADDR;
ea_t stmt_ea = stmt_item->ea;
cblock_t* cblock;
cblock_t::iterator pos;
if (hexrays_get_stmt_block_pos(cfunc, stmt_item, &cblock, &pos, use_helper ? helper : nullptr))
{
cblock->erase(pos);
cfunc->remove_unused_labels();
#if _DEBUG
cfunc->verify(ALLOW_UNUSED_LABELS, true);
#endif
}
delete helper;
return stmt_ea;
}
void do_flush_patch_stmt(vdui_t& vu)
{
// Walk the tree just to get citem_t* from actual saved EAs
struct collect_eas_t : public hexrays_ctreeparent_visitor_t
{
std::map<ea_t, int> eas;
bool do_remember = false;
void clear() { eas.clear(); }
void remember(ea_t ea)
{
if (ea == BADADDR)
return;
auto p = eas.find(ea);
if (p != eas.end())
return;
insn_t ins;
decode_insn(&ins, ea);
eas[ea] = int(ins.size);
}
int idaapi visit_insn(cinsn_t* ins) override
{
if (do_remember)
remember(ins->ea);
hexrays_ctreeparent_visitor_t::visit_insn(ins);
return 0;
}
int idaapi visit_expr(cexpr_t* expr)
{
if (do_remember)
remember(expr->ea);
hexrays_ctreeparent_visitor_t::visit_expr(expr);
return 0;
}
} ti;
auto cfunc = vu.cfunc;
ti.do_remember = false;
ti.apply_to(&cfunc->body, nullptr);
static char noops[32] = { 0 };
if (!noops[0])
memset(noops, 0x90, sizeof(noops));
// Collect all children
ti.do_remember = true;
for (auto ea : patchstmt_queue)
{
auto citem = ti.by_ea(ea);
if (citem == nullptr)
continue;
ti.apply_to((citem_t*)citem, nullptr);
}
for (auto& kv : ti.eas)
{
if (kv.second == 0)
continue;
patch_bytes(kv.first, noops, kv.second);
msg("Patching %a with %d byte(s)...\n", kv.first, kv.second);
}
msg("Total: %u\n", uint(ti.eas.size()));
patchstmt_queue.clear();
}
void do_reset_stmts(vdui_t& vu)
{
marked.reset();
}
void do_transfer_to_patch_queue(action_activation_ctx_t *ctx)
{
if (!marked.load() || ctx->cur_func == nullptr)
{
msg("No hidden statements or not positioned in a function!\n");
return;
}
auto f_ea = ctx->cur_func->start_ea;
for (auto it = marked.nodes().begin(), end=marked.nodes().end(); it != end; )
{
ea_t ea = *it;
auto f = get_func(ea);
if (f != nullptr && f->start_ea == f_ea)
{
patchstmt_queue.push_back(ea);
marked.nodes().erase(it++);
}
else
{
++it;
}
}
marked.save();
msg("Removed %u hidden statement(s) and moved to patch queue. Refresh to pseudo-code to take effect.\n", (uint)patchstmt_queue.size());
}
};
//--------------------------------------------------------------------------
// This decompiler callback handles various hexrays events.
static ssize_t idaapi hr_callback(void* ud, hexrays_event_t event, va_list va)
{
strikeout_plg_t* plugmod = (strikeout_plg_t*)ud;
switch (event)
{
case hxe_populating_popup:
plugmod->am.on_hxe_populating_popup(va);
break;
case hxe_maturity:
{
auto cfunc = va_arg(va, cfunc_t*);
ctree_maturity_t new_maturity = va_argi(va, ctree_maturity_t);
if (new_maturity == CMAT_FINAL)
plugmod->transform_ctree(cfunc);
break;
}
}
return 0;
}
//--------------------------------------------------------------------------
// Initialize the plugin.
static plugmod_t* idaapi init()
{
return init_hexrays_plugin() ? new strikeout_plg_t() : nullptr;
}
//--------------------------------------------------------------------------
plugin_t PLUGIN =
{
IDP_INTERFACE_VERSION,
PLUGIN_HIDE | PLUGIN_MULTI,
init,
nullptr,
nullptr,
"StrikeOut: Hex-Rays statements editor",
"",
"hxstrikeout",
""
};
| 28.860674 | 144 | 0.494978 | CrackerCat |
c0ba48d1e9f1c6011597c911dfced4c12a18267d | 17,749 | cpp | C++ | test/diff/diff_files/reordered_switch_blocks_autogen.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | test/diff/diff_files/reordered_switch_blocks_autogen.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | test/diff/diff_files/reordered_switch_blocks_autogen.cpp | G-P-S/SPIRV-Tools | 19b156b940d17bf67e93ac2532c6cac840fb46d8 | [
"Apache-2.0"
] | null | null | null | // GENERATED FILE - DO NOT EDIT.
// Generated by generate_tests.py
//
// Copyright (c) 2022 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 "../diff_test_utils.h"
#include "gtest/gtest.h"
namespace spvtools {
namespace diff {
namespace {
// Test where src and dst have cases of a switch in different order.
constexpr char kSrc[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpName %4 "main"
OpName %7 "BufferIn"
OpMemberName %7 0 "i"
OpName %9 ""
OpName %23 "BufferOut"
OpMemberName %23 0 "o"
OpName %25 ""
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%22 = OpLabel
OpReturn
OpFunctionEnd)";
constexpr char kDst[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpName %4 "main"
OpName %7 "BufferIn"
OpMemberName %7 0 "i"
OpName %9 ""
OpName %23 "BufferOut"
OpMemberName %23 0 "o"
OpName %25 ""
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
TEST(DiffTest, ReorderedSwitchBlocks) {
constexpr char kDiff[] = R"( ; SPIR-V
; Version: 1.6
; Generator: Khronos SPIR-V Tools Assembler; 0
-; Bound: 58
+; Bound: 62
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpName %4 "main"
OpName %7 "BufferIn"
OpMemberName %7 0 "i"
OpName %9 ""
OpName %23 "BufferOut"
OpMemberName %23 0 "o"
OpName %25 ""
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
Options options;
DoStringDiffTest(kSrc, kDst, kDiff, options);
}
TEST(DiffTest, ReorderedSwitchBlocksNoDebug) {
constexpr char kSrcNoDebug[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
constexpr char kDstNoDebug[] = R"( OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
constexpr char kDiff[] = R"( ; SPIR-V
; Version: 1.6
; Generator: Khronos SPIR-V Tools Assembler; 0
-; Bound: 58
+; Bound: 62
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %4 "main"
OpExecutionMode %4 LocalSize 1 1 1
OpSource ESSL 310
OpMemberDecorate %7 0 Offset 0
OpDecorate %7 Block
OpDecorate %9 DescriptorSet 0
OpDecorate %9 Binding 0
OpMemberDecorate %23 0 Offset 0
OpDecorate %23 BufferBlock
OpDecorate %25 DescriptorSet 0
OpDecorate %25 Binding 1
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 0
%7 = OpTypeStruct %6
%8 = OpTypePointer Uniform %7
%9 = OpVariable %8 Uniform
%10 = OpTypeInt 32 1
%11 = OpConstant %10 0
%12 = OpTypePointer Uniform %6
%23 = OpTypeStruct %6
%24 = OpTypePointer Uniform %23
%25 = OpVariable %24 Uniform
%28 = OpConstant %10 1
%34 = OpConstant %6 2
%52 = OpConstant %6 1
%4 = OpFunction %2 None %3
%5 = OpLabel
%13 = OpAccessChain %12 %9 %11
%14 = OpLoad %6 %13
OpSelectionMerge %22 None
OpSwitch %14 %21 0 %15 1 %16 2 %17 3 %18 4 %19 5 %20
%20 = OpLabel
%53 = OpAccessChain %12 %25 %11
OpStore %53 %52
OpBranch %21
%19 = OpLabel
%45 = OpAccessChain %12 %25 %11
%46 = OpLoad %6 %45
%47 = OpAccessChain %12 %25 %11
%48 = OpLoad %6 %47
%49 = OpIMul %6 %46 %48
%50 = OpAccessChain %12 %25 %11
OpStore %50 %49
OpBranch %22
%18 = OpLabel
%40 = OpAccessChain %12 %25 %11
%41 = OpLoad %6 %40
%42 = OpUDiv %6 %41 %34
%43 = OpAccessChain %12 %25 %11
OpStore %43 %42
OpBranch %22
%16 = OpLabel
%31 = OpAccessChain %12 %25 %11
%32 = OpLoad %6 %31
%33 = OpISub %6 %32 %28
OpStore %31 %33
OpBranch %17
%17 = OpLabel
%35 = OpAccessChain %12 %25 %11
%36 = OpLoad %6 %35
%37 = OpIMul %6 %36 %34
%38 = OpAccessChain %12 %25 %11
OpStore %38 %37
OpBranch %22
%15 = OpLabel
%26 = OpAccessChain %12 %25 %11
%27 = OpLoad %6 %26
%29 = OpIAdd %6 %27 %28
OpStore %26 %29
OpBranch %22
%21 = OpLabel
%54 = OpAccessChain %12 %25 %11
%55 = OpLoad %6 %54
%56 = OpIAdd %6 %55 %34
%57 = OpAccessChain %12 %25 %11
OpStore %57 %56
OpBranch %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
Options options;
DoStringDiffTest(kSrcNoDebug, kDstNoDebug, kDiff, options);
}
} // namespace
} // namespace diff
} // namespace spvtools
| 30.444254 | 75 | 0.525607 | G-P-S |
c0bce06730b088981acc0b74199f6c44ef32337c | 16,185 | cpp | C++ | discovery_F429/src/lcd_test.cpp | nvitya/nvcmtests | 0f8bfedf16bbe3a5803bf8a9300b1a1a73da805b | [
"Zlib"
] | null | null | null | discovery_F429/src/lcd_test.cpp | nvitya/nvcmtests | 0f8bfedf16bbe3a5803bf8a9300b1a1a73da805b | [
"Zlib"
] | null | null | null | discovery_F429/src/lcd_test.cpp | nvitya/nvcmtests | 0f8bfedf16bbe3a5803bf8a9300b1a1a73da805b | [
"Zlib"
] | null | null | null | // lcd_test.cpp
#include "platform.h"
#include "lcd_test.h"
#include "hwpins.h"
#include "traces.h"
#include "hwlcdctrl.h"
#include "hwsdram.h"
#include "framebuffer16.h"
#include "clockcnt.h"
THwLcdCtrl lcdctrl;
TFrameBuffer16 disp;
#if defined(BOARD_DISCOVERY_F746)
void lcd_init()
{
uint32_t tmp;
uint32_t pinflags = 0;
// LCD CONTROLLER PINS
hwpinctrl.PinSetup(PORTNUM_E, 4, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_G, 12, pinflags | PINCFG_AF_12); //
hwpinctrl.PinSetup(PORTNUM_I, 9, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_I, 10, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_I, 14, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_I, 15, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 0, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 1, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 2, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 3, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 4, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 5, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 6, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 7, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 8, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 9, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 10, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 11, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 13, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 14, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_J, 15, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 0, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 1, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 2, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 4, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 5, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 6, pinflags | PINCFG_AF_14); //
hwpinctrl.PinSetup(PORTNUM_K, 7, pinflags | PINCFG_AF_14); //
// LCD GPIO PINS
hwpinctrl.PinSetup(PORTNUM_I, 12, PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); // LCD_DISP
hwpinctrl.PinSetup(PORTNUM_K, 3, PINCFG_OUTPUT | PINCFG_GPIO_INIT_1); // LCD_BL_CTRL
// Configure the LCD clock
uint32_t lcd_pixel_clock = 8000000;
//lcdctrl.Init(480, 272, (void *)0x08000000); // give the rom start as the framebuffer
lcdctrl.Init(480, 272, (void *)hwsdram.address);
}
#endif
#if defined(BOARD_DISCOVERY_F429)
#include "hwspi.h"
TGpioPin pin_disp_cs(PORTNUM_C, 2, false);;
TGpioPin pin_disp_rs(PORTNUM_D, 13, false);
THwSpi disp_spi;
/* Level 1 Commands */
#define LCD_SWRESET 0x01 /* Software Reset */
#define LCD_READ_DISPLAY_ID 0x04 /* Read display identification information */
#define LCD_RDDST 0x09 /* Read Display Status */
#define LCD_RDDPM 0x0A /* Read Display Power Mode */
#define LCD_RDDMADCTL 0x0B /* Read Display MADCTL */
#define LCD_RDDCOLMOD 0x0C /* Read Display Pixel Format */
#define LCD_RDDIM 0x0D /* Read Display Image Format */
#define LCD_RDDSM 0x0E /* Read Display Signal Mode */
#define LCD_RDDSDR 0x0F /* Read Display Self-Diagnostic Result */
#define LCD_SPLIN 0x10 /* Enter Sleep Mode */
#define LCD_SLEEP_OUT 0x11 /* Sleep out register */
#define LCD_PTLON 0x12 /* Partial Mode ON */
#define LCD_NORMAL_MODE_ON 0x13 /* Normal Display Mode ON */
#define LCD_DINVOFF 0x20 /* Display Inversion OFF */
#define LCD_DINVON 0x21 /* Display Inversion ON */
#define LCD_GAMMA 0x26 /* Gamma register */
#define LCD_DISPLAY_OFF 0x28 /* Display off register */
#define LCD_DISPLAY_ON 0x29 /* Display on register */
#define LCD_COLUMN_ADDR 0x2A /* Colomn address register */
#define LCD_PAGE_ADDR 0x2B /* Page address register */
#define LCD_GRAM 0x2C /* GRAM register */
#define LCD_RGBSET 0x2D /* Color SET */
#define LCD_RAMRD 0x2E /* Memory Read */
#define LCD_PLTAR 0x30 /* Partial Area */
#define LCD_VSCRDEF 0x33 /* Vertical Scrolling Definition */
#define LCD_TEOFF 0x34 /* Tearing Effect Line OFF */
#define LCD_TEON 0x35 /* Tearing Effect Line ON */
#define LCD_MAC 0x36 /* Memory Access Control register*/
#define LCD_VSCRSADD 0x37 /* Vertical Scrolling Start Address */
#define LCD_IDMOFF 0x38 /* Idle Mode OFF */
#define LCD_IDMON 0x39 /* Idle Mode ON */
#define LCD_PIXEL_FORMAT 0x3A /* Pixel Format register */
#define LCD_WRITE_MEM_CONTINUE 0x3C /* Write Memory Continue */
#define LCD_READ_MEM_CONTINUE 0x3E /* Read Memory Continue */
#define LCD_SET_TEAR_SCANLINE 0x44 /* Set Tear Scanline */
#define LCD_GET_SCANLINE 0x45 /* Get Scanline */
#define LCD_WDB 0x51 /* Write Brightness Display register */
#define LCD_RDDISBV 0x52 /* Read Display Brightness */
#define LCD_WCD 0x53 /* Write Control Display register*/
#define LCD_RDCTRLD 0x54 /* Read CTRL Display */
#define LCD_WRCABC 0x55 /* Write Content Adaptive Brightness Control */
#define LCD_RDCABC 0x56 /* Read Content Adaptive Brightness Control */
#define LCD_WRITE_CABC 0x5E /* Write CABC Minimum Brightness */
#define LCD_READ_CABC 0x5F /* Read CABC Minimum Brightness */
#define LCD_READ_ID1 0xDA /* Read ID1 */
#define LCD_READ_ID2 0xDB /* Read ID2 */
#define LCD_READ_ID3 0xDC /* Read ID3 */
/* Level 2 Commands */
#define LCD_RGB_INTERFACE 0xB0 /* RGB Interface Signal Control */
#define LCD_FRMCTR1 0xB1 /* Frame Rate Control (In Normal Mode) */
#define LCD_FRMCTR2 0xB2 /* Frame Rate Control (In Idle Mode) */
#define LCD_FRMCTR3 0xB3 /* Frame Rate Control (In Partial Mode) */
#define LCD_INVTR 0xB4 /* Display Inversion Control */
#define LCD_BPC 0xB5 /* Blanking Porch Control register */
#define LCD_DFC 0xB6 /* Display Function Control register */
#define LCD_ETMOD 0xB7 /* Entry Mode Set */
#define LCD_BACKLIGHT1 0xB8 /* Backlight Control 1 */
#define LCD_BACKLIGHT2 0xB9 /* Backlight Control 2 */
#define LCD_BACKLIGHT3 0xBA /* Backlight Control 3 */
#define LCD_BACKLIGHT4 0xBB /* Backlight Control 4 */
#define LCD_BACKLIGHT5 0xBC /* Backlight Control 5 */
#define LCD_BACKLIGHT7 0xBE /* Backlight Control 7 */
#define LCD_BACKLIGHT8 0xBF /* Backlight Control 8 */
#define LCD_POWER1 0xC0 /* Power Control 1 register */
#define LCD_POWER2 0xC1 /* Power Control 2 register */
#define LCD_VCOM1 0xC5 /* VCOM Control 1 register */
#define LCD_VCOM2 0xC7 /* VCOM Control 2 register */
#define LCD_NVMWR 0xD0 /* NV Memory Write */
#define LCD_NVMPKEY 0xD1 /* NV Memory Protection Key */
#define LCD_RDNVM 0xD2 /* NV Memory Status Read */
#define LCD_READ_ID4 0xD3 /* Read ID4 */
#define LCD_PGAMMA 0xE0 /* Positive Gamma Correction register */
#define LCD_NGAMMA 0xE1 /* Negative Gamma Correction register */
#define LCD_DGAMCTRL1 0xE2 /* Digital Gamma Control 1 */
#define LCD_DGAMCTRL2 0xE3 /* Digital Gamma Control 2 */
#define LCD_INTERFACE 0xF6 /* Interface control register */
/* Extend register commands */
#define LCD_POWERA 0xCB /* Power control A register */
#define LCD_POWERB 0xCF /* Power control B register */
#define LCD_DTCA 0xE8 /* Driver timing control A */
#define LCD_DTCB 0xEA /* Driver timing control B */
#define LCD_POWER_SEQ 0xED /* Power on sequence register */
#define LCD_3GAMMA_EN 0xF2 /* 3 Gamma enable register */
#define LCD_PRC 0xF7 /* Pump ratio control register */
/* Size of read registers */
#define LCD_READ_ID4_SIZE 3 /* Size of Read ID4 */
void disp_write_data(uint16_t avalue)
{
pin_disp_rs.Set1(); // Set WRX to send data
pin_disp_cs.Set0(); // Reset LCD control line(/CS) and Send data
disp_spi.SendData(avalue);
disp_spi.WaitSendFinish();
uint16_t d16;
while (disp_spi.TryRecvData(&d16))
{
//
}
pin_disp_cs.Set1(); // Deselect: Chip Select high
}
void disp_write_reg(uint8_t avalue)
{
pin_disp_rs.Set0(); // Reset WRX to send command
pin_disp_cs.Set0(); // Reset LCD control line(/CS) and Send data
disp_spi.SendData(avalue);
disp_spi.WaitSendFinish();
uint16_t d16;
while (disp_spi.TryRecvData(&d16))
{
//
}
pin_disp_cs.Set1(); // Deselect: Chip Select high
}
void init_ili9341()
{
TRACE("Initializing ILI9341...\r\n");
pin_disp_cs.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
pin_disp_rs.Setup(PINCFG_OUTPUT | PINCFG_GPIO_INIT_1);
//pin_disp_cs.Set0();
//pin_disp_cs.Set1();
// init SPI5
hwpinctrl.PinSetup(PORTNUM_F, 7, PINCFG_AF_5); // SPI5.SCK
hwpinctrl.PinSetup(PORTNUM_F, 8, PINCFG_AF_5 | PINCFG_PULLDOWN); // SPI5.MISO
hwpinctrl.PinSetup(PORTNUM_F, 9, PINCFG_AF_5); // SPI5.MOSI
disp_spi.idleclk_high = false;
disp_spi.speed = 4000000;
disp_spi.databits = 8;
disp_spi.Init(5);
delay_ms(100);
/* Configure LCD */
disp_write_reg(0xCA);
disp_write_data(0xC3);
disp_write_data(0x08);
disp_write_data(0x50);
disp_write_reg(LCD_POWERB);
disp_write_data(0x00);
disp_write_data(0xC1);
disp_write_data(0x30);
disp_write_reg(LCD_POWER_SEQ);
disp_write_data(0x64);
disp_write_data(0x03);
disp_write_data(0x12);
disp_write_data(0x81);
disp_write_reg(LCD_DTCA);
disp_write_data(0x85);
disp_write_data(0x00);
disp_write_data(0x78);
disp_write_reg(LCD_POWERA);
disp_write_data(0x39);
disp_write_data(0x2C);
disp_write_data(0x00);
disp_write_data(0x34);
disp_write_data(0x02);
disp_write_reg(LCD_PRC);
disp_write_data(0x20);
disp_write_reg(LCD_DTCB);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_reg(LCD_FRMCTR1);
disp_write_data(0x00);
disp_write_data(0x1B);
disp_write_reg(LCD_DFC);
disp_write_data(0x0A);
disp_write_data(0xA2);
disp_write_reg(LCD_POWER1);
disp_write_data(0x10);
disp_write_reg(LCD_POWER2);
disp_write_data(0x10);
disp_write_reg(LCD_VCOM1);
disp_write_data(0x45);
disp_write_data(0x15);
disp_write_reg(LCD_VCOM2);
disp_write_data(0x90);
disp_write_reg(LCD_MAC);
disp_write_data(0xC8);
disp_write_reg(LCD_3GAMMA_EN);
disp_write_data(0x00);
disp_write_reg(LCD_RGB_INTERFACE);
disp_write_data(0xC2);
disp_write_reg(LCD_DFC);
disp_write_data(0x0A);
disp_write_data(0xA7);
disp_write_data(0x27);
disp_write_data(0x04);
/* Colomn address set */
disp_write_reg(LCD_COLUMN_ADDR);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_data(0xEF);
/* Page address set */
disp_write_reg(LCD_PAGE_ADDR);
disp_write_data(0x00);
disp_write_data(0x00);
disp_write_data(0x01);
disp_write_data(0x3F);
disp_write_reg(LCD_INTERFACE);
disp_write_data(0x01);
disp_write_data(0x00);
disp_write_data(0x06);
disp_write_reg(LCD_GRAM);
delay_ms(200);
disp_write_reg(LCD_GAMMA);
disp_write_data(0x01);
disp_write_reg(LCD_PGAMMA);
disp_write_data(0x0F);
disp_write_data(0x29);
disp_write_data(0x24);
disp_write_data(0x0C);
disp_write_data(0x0E);
disp_write_data(0x09);
disp_write_data(0x4E);
disp_write_data(0x78);
disp_write_data(0x3C);
disp_write_data(0x09);
disp_write_data(0x13);
disp_write_data(0x05);
disp_write_data(0x17);
disp_write_data(0x11);
disp_write_data(0x00);
disp_write_reg(LCD_NGAMMA);
disp_write_data(0x00);
disp_write_data(0x16);
disp_write_data(0x1B);
disp_write_data(0x04);
disp_write_data(0x11);
disp_write_data(0x07);
disp_write_data(0x31);
disp_write_data(0x33);
disp_write_data(0x42);
disp_write_data(0x05);
disp_write_data(0x0C);
disp_write_data(0x0A);
disp_write_data(0x28);
disp_write_data(0x2F);
disp_write_data(0x0F);
disp_write_reg(LCD_SLEEP_OUT);
delay_ms(200);
disp_write_reg(LCD_DISPLAY_ON);
/* GRAM start writing */
disp_write_reg(LCD_GRAM);
}
void lcd_init()
{
uint32_t tmp;
uint32_t pinflags = PINCFG_SPEED_MEDIUM;
/*
+------------------------+-----------------------+----------------------------+
+ LCD pins assignment +
+------------------------+-----------------------+----------------------------+
| LCD_TFT R2 <-> PC.10 | LCD_TFT G2 <-> PA.06 | LCD_TFT B2 <-> PD.06 |
| LCD_TFT R3 <-> PB.00 | LCD_TFT G3 <-> PG.10 | LCD_TFT B3 <-> PG.11 |
| LCD_TFT R4 <-> PA.11 | LCD_TFT G4 <-> PB.10 | LCD_TFT B4 <-> PG.12 |
| LCD_TFT R5 <-> PA.12 | LCD_TFT G5 <-> PB.11 | LCD_TFT B5 <-> PA.03 |
| LCD_TFT R6 <-> PB.01 | LCD_TFT G6 <-> PC.07 | LCD_TFT B6 <-> PB.08 |
| LCD_TFT R7 <-> PG.06 | LCD_TFT G7 <-> PD.03 | LCD_TFT B7 <-> PB.09 |
-------------------------------------------------------------------------------
| LCD_TFT HSYNC <-> PC.06 | LCDTFT VSYNC <-> PA.04 |
| LCD_TFT CLK <-> PG.07 | LCD_TFT DE <-> PF.10 |
-----------------------------------------------------
*/
// LCD CONTROLLER PINS
hwpinctrl.PinSetup(PORTNUM_A, 3, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 4, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 11, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_A, 12, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 0, pinflags | PINCFG_AF_9);
hwpinctrl.PinSetup(PORTNUM_B, 1, pinflags | PINCFG_AF_9);
hwpinctrl.PinSetup(PORTNUM_B, 8, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 9, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 10, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_B, 11, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_C, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_C, 7, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_C, 10, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_D, 3, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_D, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_F, 10, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 6, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 7, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 10, pinflags | PINCFG_AF_9);
hwpinctrl.PinSetup(PORTNUM_G, 11, pinflags | PINCFG_AF_14);
hwpinctrl.PinSetup(PORTNUM_G, 12, pinflags | PINCFG_AF_9);
// The ILI9341 must be initialized trough SPI
init_ili9341();
//--------------------------------------------------------------
// Configure the internal LCD controller
lcdctrl.hsync = 10;
lcdctrl.hbp = 20;
lcdctrl.hfp = 10;
lcdctrl.vsync = 2;
lcdctrl.vbp = 2;
lcdctrl.vfp = 5;
lcdctrl.Init(240, 320, (void *)hwsdram.address);
//lcdctrl.Init(240, 320, (void *)0x08000000);
}
#endif
void lcd_test()
{
TRACE("--- LCD TEST ---\r\n");
lcd_init();
uint16_t w = lcdctrl.hwwidth;
uint16_t h = lcdctrl.hwheight;
uint16_t * pp;
uint16_t color = 0x001F;
uint32_t cnt = w * 10;
uint32_t n;
pp = (uint16_t *)hwsdram.address;
for (n = 0; n < cnt; ++n)
{
*(pp++) = color;
}
#if 1
disp.Init(w, h, (void *)(hwsdram.address));
disp.FillScreen(0);
disp.color = RGB16(0, 255, 0);
disp.FillRect(10, 10, 100, 100, disp.color);
disp.color = RGB16(255, 0, 0);
disp.DrawRect(0, 0, disp.width, disp.height);
disp.color = 0xffff;
disp.SetCursor(50, 150);
disp.DrawString("Hello World!");
#endif
TRACE("LCD test finished.\r\n");
}
| 35.493421 | 88 | 0.658943 | nvitya |
c0bd30ce8ddff04a3834a4f8b85db11c1cdd9bec | 2,541 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/telephony/cdma/sms/CBearerDataHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/telephony/cdma/sms/CBearerDataHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/internal/telephony/cdma/sms/CBearerDataHelper.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "elastos/droid/internal/telephony/cdma/sms/CBearerDataHelper.h"
#include "elastos/droid/internal/telephony/cdma/sms/BearerData.h"
namespace Elastos {
namespace Droid {
namespace Internal {
namespace Telephony {
namespace Cdma {
namespace Sms {
CAR_INTERFACE_IMPL(CBearerDataHelper, Singleton, IBearerDataHelper)
CAR_SINGLETON_IMPL(CBearerDataHelper)
ECode CBearerDataHelper::CalcTextEncodingDetails(
/* [in] */ ICharSequence* msg,
/* [in] */ Boolean force7BitEncoding,
/* [out] */ IGsmAlphabetTextEncodingDetails** result)
{
VALIDATE_NOT_NULL(result);
AutoPtr<IGsmAlphabetTextEncodingDetails> gsted = BearerData::CalcTextEncodingDetails(msg, force7BitEncoding);
*result = gsted;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode CBearerDataHelper::Encode(
/* [in] */ IBearerData* bData,
/* [out, callee] */ ArrayOf<Byte>** result)
{
VALIDATE_NOT_NULL(result);
AutoPtr<ArrayOf<Byte> > array = BearerData::Encode(bData);
*result = array;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode CBearerDataHelper::Decode(
/* [in] */ ArrayOf<Byte>* smsData,
/* [out] */ IBearerData** result)
{
VALIDATE_NOT_NULL(result);
AutoPtr<IBearerData> bd = BearerData::Decode(smsData);
*result = bd;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode CBearerDataHelper::Decode(
/* [in] */ ArrayOf<Byte>* smsData,
/* [in] */ Int32 serviceCategory,
/* [out] */ IBearerData** result)
{
VALIDATE_NOT_NULL(result);
AutoPtr<IBearerData> bd = BearerData::Decode(smsData, serviceCategory);
*result = bd;
REFCOUNT_ADD(*result);
return NOERROR;
}
} // namespace Sms
} // namespace Cdma
} // namespace Telephony
} // namespace Internal
} // namespace Droid
} // namespace Elastos
| 30.987805 | 113 | 0.669815 | jingcao80 |
c0bf52def1951745aca51f0d6cc56c2bc7c16281 | 330 | hpp | C++ | test_gen.hpp | fleex-x/ssmhasher | e8b7117aaf6ded5adbc9259eff2b4b9251fac14d | [
"WTFPL"
] | null | null | null | test_gen.hpp | fleex-x/ssmhasher | e8b7117aaf6ded5adbc9259eff2b4b9251fac14d | [
"WTFPL"
] | null | null | null | test_gen.hpp | fleex-x/ssmhasher | e8b7117aaf6ded5adbc9259eff2b4b9251fac14d | [
"WTFPL"
] | null | null | null | #pragma once
#include <cstdint>
#include <vector>
namespace ssmhasher {
class TestGen {
private:
uint32_t x;
uint32_t y;
uint32_t z;
uint32_t w;
void mix();
uint32_t randU32();
public:
TestGen();
explicit TestGen(uint32_t seed);
void gen(std::byte *blob, std::size_t size);
};
} // namespace ssmhasher | 12.692308 | 46 | 0.669697 | fleex-x |
c0c317cd42ea3fe7533a4089872bd120875e3e84 | 1,534 | cpp | C++ | src/pipe.cpp | lu4/node-opencl-ts | 9dc971eafd3647a50aebbcfe85a346e7fbaa13f5 | [
"BSD-3-Clause"
] | 167 | 2015-04-03T20:09:33.000Z | 2022-03-11T08:38:08.000Z | src/pipe.cpp | lu4/node-opencl-ts | 9dc971eafd3647a50aebbcfe85a346e7fbaa13f5 | [
"BSD-3-Clause"
] | 57 | 2015-06-22T23:44:35.000Z | 2020-06-09T07:37:26.000Z | src/pipe.cpp | mikeseven/node-opencl | c059fee1fea1fb417c7e5b30fac78001826efb5e | [
"BSD-3-Clause"
] | 35 | 2015-02-02T23:11:49.000Z | 2021-05-09T19:48:50.000Z | #include "pipe.h"
#include "types.h"
#include "common.h"
#include <node_buffer.h>
using namespace node;
namespace opencl {
#ifdef CL_VERSION_2_0
NAN_METHOD(CreatePipe) {
Nan::HandleScope scope;
REQ_ARGS(5);
// Arg 1
NOCL_UNWRAP(context, NoCLContext, info[0]);
// Arg 2
cl_mem_flags flags = Nan::To<uint32_t>(info[1]).FromJust();
// Arg 2
cl_uint size = Nan::To<uint32_t>(info[2]).FromJust();
// Arg 3
cl_uint qty = Nan::To<uint32_t>(info[3]).FromJust();
// Arg 4
if (!info[4]->IsNull()) {
THROW_ERR(CL_INVALID_VALUE)
}
cl_int err;
cl_mem pipe = ::clCreatePipe(
context->getRaw(),
flags,
size,
qty,
NULL,
&err
);
CHECK_ERR(err);
info.GetReturnValue().Set(NOCL_WRAP(NoCLMem, pipe));
}
NAN_METHOD(GetPipeInfo) {
Nan::HandleScope scope;
REQ_ARGS(2);
// Arg 0
NOCL_UNWRAP(mem, NoCLMem, info[0]);
// Arg 1
cl_pipe_info param_name = Nan::To<uint32_t>(info[1]).FromJust();
switch(param_name) {
case CL_PIPE_MAX_PACKETS:
case CL_PIPE_PACKET_SIZE: {
cl_uint val;
CHECK_ERR(::clGetPipeInfo(mem->getRaw(),param_name,sizeof(cl_uint), &val, NULL))
info.GetReturnValue().Set(JS_INT(val));
return;
}
}
return Nan::ThrowError(JS_STR(opencl::getExceptionMessage(CL_INVALID_VALUE)));
}
#endif
namespace Pipe {
NAN_MODULE_INIT(init)
{
#ifdef CL_VERSION_2_0
Nan::SetMethod(target, "createPipe", CreatePipe);
Nan::SetMethod(target, "getPipeInfo", GetPipeInfo);
#endif
}
} // namespace Pipe
} // namespace opencl
| 17.837209 | 86 | 0.661669 | lu4 |
c0c61d7e15a88f2d8928138c025678ea99eb54d1 | 4,079 | cc | C++ | src/cpp/learn/backprop/fully_connected_test.cc | SanggunLee/edgetpu | d3cf166783265f475c1ddba5883e150ee84f7bfe | [
"Apache-2.0"
] | 320 | 2019-09-19T07:10:48.000Z | 2022-03-12T01:48:56.000Z | src/cpp/learn/backprop/fully_connected_test.cc | Machine-Learning-Practice/edgetpu | 6d699665efdc5d84944b5233223c55fe5d3bd1a6 | [
"Apache-2.0"
] | 563 | 2019-09-27T06:40:40.000Z | 2022-03-31T23:12:15.000Z | src/cpp/learn/backprop/fully_connected_test.cc | Machine-Learning-Practice/edgetpu | 6d699665efdc5d84944b5233223c55fe5d3bd1a6 | [
"Apache-2.0"
] | 119 | 2019-09-25T02:51:10.000Z | 2022-03-03T08:11:12.000Z | #include "src/cpp/learn/backprop/fully_connected.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "src/cpp/learn/backprop/test_utils.h"
namespace coral {
namespace learn {
namespace backprop {
namespace {
using ::Eigen::MatrixXf;
using ::testing::FloatEq;
using ::testing::FloatNear;
using ::testing::Pointwise;
TEST(FullyConnectedTest, SimpleInputs) {
Tensor mat_x(2, 5);
mat_x << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;
Tensor mat_w = mat_x.transpose();
Tensor vec_b(1, 2);
vec_b << 1, 1;
std::vector<Tensor> inputs = {mat_x, mat_w, vec_b};
Tensor mat_y_expected(2, 2);
mat_y_expected << 31, 81, 81, 256;
FullyConnected fc_forward;
std::vector<Tensor> outputs = fc_forward.Compute(inputs);
Tensor* mat_y = &outputs[0];
EXPECT_THAT(mat_y->reshaped(),
Pointwise(FloatEq(), mat_y_expected.reshaped()));
}
TEST(FullyConnectedGradientTest, GradientOfAveragingElementsOfY) {
Tensor mat_x(2, 3);
mat_x << 0, 1, 2, 3, 4, 5;
Tensor mat_w(3, 1);
mat_w << 0, 1, 2;
Tensor vec_b(1, 1);
vec_b << 7;
std::vector<Tensor> inputs = {mat_x, mat_w, vec_b};
// dmat_y is a vector of constants equal to 1/numElements, because the
// derivative of the Average value with respect to each element of mat_y is
// 1/numElements
Tensor dmat_y = Tensor::Ones(mat_x.rows(), mat_w.cols());
dmat_y *= 1.0 / dmat_y.size();
FullyConnected fc;
auto x_fc_avg = [&fc, &mat_w, &vec_b](const Tensor& x) {
return fc.Compute({x, mat_w, vec_b})[0].mean();
};
auto w_fc_avg = [&fc, &mat_x, &vec_b](const Tensor& w) {
return fc.Compute({mat_x, w, vec_b})[0].mean();
};
auto b_fc_avg = [&fc, &mat_x, &mat_w](const Tensor& b) {
return fc.Compute({mat_x, mat_w, b})[0].mean();
};
Tensor dx_numerical = numerical_gradient(x_fc_avg, &mat_x);
Tensor dw_numerical = numerical_gradient(w_fc_avg, &mat_w);
Tensor db_numerical = numerical_gradient(b_fc_avg, &vec_b);
inputs.push_back(dmat_y);
FullyConnectedGradient fc_gradient;
std::vector<Tensor> outputs = fc_gradient.Compute(inputs);
const auto& dmat_x = outputs[0];
const auto& dmat_w = outputs[1];
const auto& dvec_b = outputs[2];
EXPECT_THAT(dmat_x.reshaped(),
Pointwise(FloatNear(2e-3), dx_numerical.reshaped()));
EXPECT_THAT(dmat_w.reshaped(),
Pointwise(FloatNear(2e-3), dw_numerical.reshaped()));
EXPECT_THAT(dvec_b.reshaped(),
Pointwise(FloatNear(2e-3), db_numerical.reshaped()));
}
TEST(FullyConnectedGradientTest, GradientOfSummingElementsOfY) {
Tensor mat_x(3, 3);
mat_x << 0, 1, 2, 3, 4, 5, 6, 7, 8;
Tensor mat_w(3, 5);
mat_w << 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2;
Tensor vec_b(1, 5);
vec_b << 4, 3, 2, 1, 0;
// dmat_y is a vector of ones, because the derivative of the Summed value with
// respect to each element of mat_y is 1.
Tensor dmat_y = MatrixXf::Ones(mat_x.rows(), mat_w.cols());
FullyConnected fc;
auto x_fc_sum = [&fc, &mat_w, &vec_b](const Tensor& x) {
return fc.Compute({x, mat_w, vec_b})[0].sum();
};
auto w_fc_sum = [&fc, &mat_x, &vec_b](const Tensor& w) {
return fc.Compute({mat_x, w, vec_b})[0].sum();
};
auto b_fc_sum = [&fc, &mat_x, &mat_w](const Tensor& b) {
return fc.Compute({mat_x, mat_w, b})[0].sum();
};
Tensor dx_numerical = numerical_gradient(x_fc_sum, &mat_x);
Tensor dw_numerical = numerical_gradient(w_fc_sum, &mat_w);
Tensor db_numerical = numerical_gradient(b_fc_sum, &vec_b);
FullyConnectedGradient fc_gradient;
std::vector<Tensor> outputs =
fc_gradient.Compute({mat_x, mat_w, vec_b, dmat_y});
const auto& dmat_x = outputs[0];
const auto& dmat_w = outputs[1];
const auto& dvec_b = outputs[2];
EXPECT_THAT(dmat_x.reshaped(),
Pointwise(FloatNear(5e-2), dx_numerical.reshaped()));
EXPECT_THAT(dmat_w.reshaped(),
Pointwise(FloatNear(5e-2), dw_numerical.reshaped()));
EXPECT_THAT(dvec_b.reshaped(),
Pointwise(FloatNear(5e-2), db_numerical.reshaped()));
}
} // namespace
} // namespace backprop
} // namespace learn
} // namespace coral
| 33.162602 | 80 | 0.664869 | SanggunLee |
c0ca2ef32f84e6385b70a2ec58b533a91acbc866 | 55,202 | cc | C++ | src/main/util/conversions.cc | jsa-research/aerospike-client-nodejs | f8e5559f3a7146aa7c5ba0dd15bf694904b149d8 | [
"Apache-2.0"
] | null | null | null | src/main/util/conversions.cc | jsa-research/aerospike-client-nodejs | f8e5559f3a7146aa7c5ba0dd15bf694904b149d8 | [
"Apache-2.0"
] | null | null | null | src/main/util/conversions.cc | jsa-research/aerospike-client-nodejs | f8e5559f3a7146aa7c5ba0dd15bf694904b149d8 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2013-2019 Aerospike, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
#include <cstdint>
#include <node.h>
#include <node_buffer.h>
#if defined(_MSC_VER)
#include "io.h"
#include "fcntl.h"
#endif
extern "C" {
#include <aerospike/aerospike.h>
#include <aerospike/aerospike_key.h>
#include <aerospike/aerospike_batch.h>
#include <aerospike/as_key.h>
#include <aerospike/as_record.h>
#include <aerospike/as_record_iterator.h>
#include <aerospike/aerospike_scan.h>
#include <aerospike/as_arraylist.h>
#include <aerospike/as_arraylist_iterator.h>
#include <aerospike/as_boolean.h>
#include <aerospike/as_geojson.h>
#include <aerospike/as_hashmap.h>
#include <aerospike/as_hashmap_iterator.h>
#include <aerospike/as_pair.h>
#include <aerospike/as_scan.h>
#include <aerospike/as_map.h>
#include <aerospike/as_nil.h>
#include <aerospike/as_stringmap.h>
#include <aerospike/as_vector.h>
#include <citrusleaf/alloc.h>
}
#include "client.h"
#include "conversions.h"
#include "log.h"
#include "enums.h"
#include "string.h"
using namespace node;
using namespace v8;
const char * DoubleType = "Double";
const char * GeoJSONType = "GeoJSON";
/*******************************************************************************
* FUNCTIONS
******************************************************************************/
int get_string_property(char** strp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsString()) {
as_v8_error(log, "Type error: %s property should be string", prop);
return AS_NODE_PARAM_ERR;
}
(*strp) = strdup(*Nan::Utf8String(value));
as_v8_detail(log, "%s => \"%s\"", prop, *strp);
return AS_NODE_PARAM_OK;
}
int get_optional_string_property(char** strp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsString()) {
if (defined != NULL) (*defined) = true;
(*strp) = strdup(*Nan::Utf8String(value));
as_v8_detail(log, "%s => \"%s\"", prop, *strp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
} else {
as_v8_error(log, "Type error: %s property should be string", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_int_property(int* intp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsNumber()) {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
(*intp) = Nan::To<int>(value).FromJust();
as_v8_detail(log, "%s => (int) %d", prop, *intp);
return AS_NODE_PARAM_OK;
}
int get_optional_int_property(int* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<int>(value).FromJust();
as_v8_detail(log, "%s => (int) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
} else {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_int64_property(int64_t* intp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsNumber()) {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
(*intp) = Nan::To<int64_t>(value).FromJust();
as_v8_detail(log, "%s => (int64) %d", prop, *intp);
return AS_NODE_PARAM_OK;
}
int get_uint32_property(uint32_t* uintp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
(*uintp) = Nan::To<uint32_t>(value).FromJust();
as_v8_detail(log, "%s => (uint32) %d", prop, *uintp);
} else {
as_v8_error(log, "Type error: %s property should be integer (uint32)", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_int64_property(int64_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<int64_t>(value).FromJust();
as_v8_detail(log, "%s => (int64) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be integer", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_int32_property(int32_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<int32_t>(value).FromJust();
as_v8_detail(log, "%s => (uint32) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be integer (int32)", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_uint32_property(uint32_t* intp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsNumber()) {
if (defined != NULL) (*defined) = true;
(*intp) = Nan::To<uint32_t>(value).FromJust();
as_v8_detail(log, "%s => (uint32) %d", prop, *intp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be integer (uint32)", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_optional_bool_property(bool* boolp, bool* defined, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsBoolean()) {
if (defined != NULL) (*defined) = true;
(*boolp) = Nan::To<bool>(value).FromJust();
as_v8_detail(log, "%s => (bool) %d", prop, *boolp);
} else if (value->IsUndefined() || value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
} else {
as_v8_error(log, "Type error: %s property should be boolean", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_bool_property(bool* boolp, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (value->IsBoolean()) {
(*boolp) = Nan::To<bool>(value).FromJust();
as_v8_detail(log, "%s => (bool) %d", prop, *boolp);
} else {
as_v8_error(log, "Type error: %s property should be boolean", prop);
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_list_property(as_list** list, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!value->IsArray()) {
as_v8_error(log, "Type error: %s property should be array", prop);
return AS_NODE_PARAM_ERR;
}
return list_from_jsarray(list, Local<Array>::Cast(value), log);
}
int get_bytes_property(uint8_t** bytes, int* size, Local<Object> obj, char const* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (!node::Buffer::HasInstance(value)) {
as_v8_error(log, "Type error: %s property should be Buffer", prop);
return AS_NODE_PARAM_ERR;
}
as_v8_debug(log, "Extracting bytes from JS Buffer");
if (extract_blob_from_jsobject(bytes, size, value.As<Object>(), log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Extracting bytes from a JS Buffer failed");
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int get_asval_property(as_val** value, Local<Object> obj, const char* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> v8value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (v8value->IsUndefined()) {
as_v8_error(log, "Type error: %s property should not be undefined", prop);
return AS_NODE_PARAM_ERR;
}
return asval_from_jsvalue(value, v8value, log);
}
int get_optional_asval_property(as_val** value, bool* defined, Local<Object> obj, const char* prop, const LogInfo* log)
{
Nan::HandleScope scope;
Local<Value> v8value = Nan::Get(obj, Nan::New(prop).ToLocalChecked()).ToLocalChecked();
if (v8value->IsUndefined() || v8value->IsNull()) {
if (defined != NULL) (*defined) = false;
as_v8_detail(log, "%s => undefined", prop);
return AS_NODE_PARAM_OK;
}
if (defined != NULL) (*defined) = true;
return asval_from_jsvalue(value, v8value, log);
}
int host_from_jsobject(Local<Object> obj, char** addr, uint16_t* port, const LogInfo* log)
{
Local<Value> v8_addr = Nan::Get(obj, Nan::New("addr").ToLocalChecked()).ToLocalChecked();
Local<Value> v8_port = Nan::Get(obj, Nan::New("port").ToLocalChecked()).ToLocalChecked();
if (v8_addr->IsString()) {
*addr = (char*) malloc(HOST_ADDRESS_SIZE);
strcpy(*addr, *Nan::Utf8String(v8_addr.As<String>()));
as_v8_detail(log, "host addr : %s", (*addr));
} else {
return AS_NODE_PARAM_ERR;
}
if (v8_port->IsNumber()) {
*port = (uint16_t) Nan::To<uint32_t>(v8_port).FromJust();
} else {
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int log_from_jsobject(LogInfo* log, Local<Object> obj)
{
int rc = AS_NODE_PARAM_OK;
as_log_level level = log->level;
FILE* fd = log->fd;
if (obj->IsObject()) {
Local<Object> v8_log = obj.As<Object>();
Local<Value> v8_level = Nan::Get(v8_log, Nan::New("level").ToLocalChecked()).ToLocalChecked();
Local<Value> v8_file = Nan::Get(v8_log, Nan::New("file").ToLocalChecked()).ToLocalChecked();
// `level` is optional
if (v8_level->IsNumber()){
level = (as_log_level) Nan::To<int>(v8_level).FromJust();
} else if (v8_level->IsNull() || v8_level->IsUndefined()){
// `null` and `undefined` imply the value should not change.
} else {
// Any other value is a bad parameter
rc = AS_NODE_PARAM_ERR;
}
// `file` is optional
if (rc == AS_NODE_PARAM_OK) {
if (v8_file->IsNumber()) {
int fildes = Nan::To<int>(v8_file).FromJust();
#if !defined(_MSC_VER)
fd = fdopen(fildes, "a");
#else
intptr_t osfptr = _get_osfhandle(fildes);
int osfd = _open_osfhandle(osfptr, O_APPEND);
fd = _fdopen(osfd, "a");
#endif
if (fd == NULL) {
fprintf(stderr, "Could not open file descriptor for logging: %s\n", strerror(errno));
rc = AS_NODE_PARAM_ERR;
}
} else if (v8_file->IsNull() || v8_file->IsUndefined()){
// `null` and `undefined` imply the value should not change.
} else {
// Any other value is a bad parameter
rc = AS_NODE_PARAM_ERR;
}
}
} else {
// The value should be an object. Otherwise it should fail.
rc = AS_NODE_PARAM_ERR;
}
// Only if no error occurred do we set the log values.
if (rc == AS_NODE_PARAM_OK) {
log->level = level;
log->fd = fd;
}
return rc;
}
as_val* asval_clone(const as_val* val, const LogInfo* log)
{
as_val_t t = as_val_type( (as_val*)val);
as_val* clone_val = NULL;
switch(t) {
case AS_NIL: {
clone_val = (as_val*) &as_nil;
break;
}
case AS_BOOLEAN: {
as_boolean *bool_val = as_boolean_fromval(val);
as_boolean *clone_bool = as_boolean_new(bool_val->value);
if( clone_bool == NULL)
{
as_v8_error(log, "cloning a boolean value failed");
}
clone_val = as_boolean_toval(clone_bool);
break;
}
case AS_INTEGER: {
as_integer* int_val = as_integer_fromval( val );
int64_t ival = as_integer_get( int_val);
as_v8_detail(log, "Cloning Integer value %d", ival);
as_integer* clone_int = as_integer_new(ival);
if(clone_int == NULL)
{
as_v8_error(log, "Cloning integer failed");
}
clone_val = as_integer_toval(clone_int);
break;
}
case AS_STRING: {
as_string* str_val = as_string_fromval( val );
char* strval = as_string_get( str_val);
as_v8_detail(log, "Cloning String value %s", strval);
char* clone_str = (char*) cf_strdup( strval);
if(clone_str == NULL)
{
as_v8_error(log, "cloning string failed");
}
as_string* clone_as = as_string_new(clone_str, true);
if(clone_as == NULL)
{
as_v8_error(log, "cloning string failed");
}
clone_val = as_string_toval( clone_as);
break;
}
case AS_BYTES: {
as_bytes* bytes_val = as_bytes_fromval( val);
size_t size = as_bytes_size(bytes_val);
uint8_t *bytes = (uint8_t*) cf_malloc(size);
memcpy(bytes, as_bytes_get(bytes_val), size);
as_v8_detail(log, "Cloning Blob value %u ", bytes);
clone_val = as_bytes_toval(as_bytes_new_wrap( bytes, size, true));
break;
}
case AS_LIST: {
as_arraylist* list = (as_arraylist*) as_list_fromval((as_val*)val);
clone_val = as_list_toval( (as_list*)as_arraylist_new(as_arraylist_size(list), list->block_size));
as_arraylist_iterator it;
as_arraylist_iterator_init( &it, list);
int index = 0;
as_v8_detail(log, "Cloning a list value of size %d ", as_arraylist_size(list));
while( as_arraylist_iterator_has_next( &it)) {
as_val* arr_element = (as_val*) as_arraylist_iterator_next( &it);
as_val* clone_element = asval_clone( arr_element, log);
as_arraylist_set((as_arraylist*) clone_val, index++, clone_element);
}
as_v8_detail(log, "Cloning a list SUCCESS");
break;
}
case AS_MAP: {
as_hashmap* map = (as_hashmap*) as_map_fromval(val);
clone_val = as_map_toval( (as_map*)as_hashmap_new(as_hashmap_size(map)));
as_hashmap_iterator it;
as_hashmap_iterator_init( &it, map);
while( as_hashmap_iterator_has_next( &it )) {
as_pair* pair = (as_pair*) as_hashmap_iterator_next( &it);
as_val* orig_key = as_pair_1(pair);
as_val* orig_val = as_pair_2(pair);
as_val* clone_key = asval_clone( orig_key, log);
as_val* clone_mapval = asval_clone( orig_val, log);
as_hashmap_set( (as_hashmap*) clone_val, clone_key, clone_mapval);
}
as_v8_detail( log, "Cloning a map SUCCESS");
break;
}
case AS_DOUBLE: {
as_double * dbl_val = as_double_fromval(val);
double dval = as_double_get(dbl_val);
as_v8_detail(log, "Cloning double value %g", dval);
as_double * clone_dbl = as_double_new(dval);
if(clone_dbl == NULL)
{
as_v8_error(log, "Cloning double failed");
}
clone_val = as_double_toval(clone_dbl);
break;
}
case AS_GEOJSON: {
as_geojson * geo_val = as_geojson_fromval(val);
char* strval = as_geojson_get(geo_val);
as_v8_detail(log, "Cloning GeoJSON value %s", strval);
char* clone_str = (char*) cf_strdup(strval);
if(clone_str == NULL)
{
as_v8_error(log, "cloning GeoJSON failed");
}
as_geojson * clone_as = as_geojson_new(clone_str, true);
if(clone_as == NULL)
{
as_v8_error(log, "cloning GeoJSON failed");
}
clone_val = as_geojson_toval(clone_as);
break;
}
default:
as_v8_error( log, "as_val received is UNKNOWN type %d", (int)t);
break;
}
return clone_val;
}
bool key_clone(const as_key* src, as_key** dest, const LogInfo* log, bool alloc_key)
{
if (src == NULL || dest== NULL) {
as_v8_info(log, "Parameter error : NULL in source/destination");
return false;
}
as_v8_detail(log, "Cloning the key");
as_key_value* val = src->valuep;
if (src->digest.init == true) {
if (alloc_key) {
*dest = as_key_new_digest(src->ns, src->set, src->digest.value);
} else {
as_key_init_digest(*dest, src->ns, src->set, src->digest.value);
}
if (val != NULL) {
(*dest)->valuep = (as_key_value*) asval_clone((as_val*) val, log);
}
} else if (val != NULL) {
as_key_value* clone_val = (as_key_value*) asval_clone((as_val*) val, log);
if (alloc_key) {
*dest = as_key_new_value(src->ns, src->set, (as_key_value*) clone_val);
} else {
as_key_init_value(*dest, src->ns, src->set, (as_key_value*) clone_val);
}
} else {
as_v8_detail(log, "Key has neither value nor digest ");
}
return true;
}
bool record_clone(const as_record* src, as_record** dest, const LogInfo* log)
{
if(src == NULL || dest == NULL) {
return false;
}
as_v8_detail( log, "Cloning the record");
(*dest)->ttl = src->ttl;
(*dest)->gen = src->gen;
as_record_iterator it;
as_record_iterator_init(&it, src);
while (as_record_iterator_has_next(&it)) {
as_bin * bin = as_record_iterator_next(&it);
as_bin_value * val = as_bin_get_value(bin);
as_bin_value* clone_val = (as_bin_value*) asval_clone( (as_val*) val, log);
as_v8_detail(log, "Bin Name: %s", as_bin_get_name(bin));
as_record_set( *dest, as_bin_get_name(bin), clone_val);
}
as_key* src_key = (as_key*) &src->key;
as_key* dest_key = (as_key*) &(*dest)->key;
if(src_key != NULL) {
//clone the key but do not malloc the key structure,
// use the structure available inside record structure.
key_clone( src_key, &dest_key, log, false);
}
return true;
}
Local<Object> error_to_jsobject(as_error* error, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> err = Nan::New<Object>();
if (error == NULL) {
as_v8_info(log, "error(C structure) object is NULL, node.js error object cannot be constructed");
return scope.Escape(err);
}
// LDT error codes are populated as a string message.
// Parse the string and populate the error object appropriately
// so that application can look up the error codes and doesn't have
// to look at strings.
// Check if it's an UDF ERROR and message has string LDT in it
// then it implies it is an LDT error, so parse the error
// and populate the error object.
if(error->code == AEROSPIKE_ERR_UDF && strstr(error->message, "LDT") != NULL) {
char err_message[AS_ERROR_MESSAGE_MAX_LEN] = {"\0"};
as_strlcpy(err_message, error->message, AS_ERROR_MESSAGE_MAX_LEN);
char *ptr;
ptr = strtok(err_message, ":");
if(ptr != NULL) {
error->file = ptr;
ptr = strtok(NULL, ":");
}
if(ptr != NULL) {
error->line = atoi(ptr);
ptr = strtok(NULL, ":");
}
if(ptr != NULL) {
error->code = (as_status) atoi(ptr);
ptr = strtok(NULL, ":");
}
if(ptr != NULL) {
as_strlcpy(error->message, ptr, AS_ERROR_MESSAGE_MAX_LEN);
ptr = strtok(NULL, ":");
}
// LDT error does not populate function name as of now.
error->func = NULL;
}
Nan::Set(err, Nan::New("code").ToLocalChecked(), Nan::New(error->code));
Nan::Set(err, Nan::New("message").ToLocalChecked(), error->message[0] != '\0' ? Nan::New(error->message).ToLocalChecked() : Nan::New("\0").ToLocalChecked() );
Nan::Set(err, Nan::New("func").ToLocalChecked(), error->func ? Nan::New(error->func).ToLocalChecked() : Nan::New("\0").ToLocalChecked() );
Nan::Set(err, Nan::New("file").ToLocalChecked(), error->file ? Nan::New(error->file).ToLocalChecked() : Nan::New("\0").ToLocalChecked() );
Nan::Set(err, Nan::New("line").ToLocalChecked(), error->line ? Nan::New(error->line) : Nan::New((uint32_t)0) );
Nan::Set(err, Nan::New("inDoubt").ToLocalChecked(), error->in_doubt ? Nan::True() : Nan::False());
return scope.Escape(err);
}
Local<Value> val_to_jsvalue(as_val* val, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
if ( val == NULL) {
as_v8_debug(log, "value = NULL");
return scope.Escape(Nan::Null());
}
switch ( as_val_type(val) ) {
case AS_NIL: {
as_v8_detail(log,"value is of type as_null");
return scope.Escape(Nan::Null());
}
case AS_INTEGER : {
as_integer * ival = as_integer_fromval(val);
if ( ival ) {
int64_t data = as_integer_getorelse(ival, -1);
as_v8_detail(log, "value = %lld ", data);
return scope.Escape(Nan::New((double)data));
}
break;
}
case AS_DOUBLE : {
as_double* dval = as_double_fromval(val);
if( dval ) {
double d = as_double_getorelse(dval, -1);
as_v8_detail(log, "value = %lf ",d);
return scope.Escape(Nan::New((double)d));
}
break;
}
case AS_STRING : {
as_string * sval = as_string_fromval(val);
if ( sval ) {
char * data = as_string_getorelse(sval, NULL);
as_v8_detail(log, "value = \"%s\"", data);
return scope.Escape(Nan::New(data).ToLocalChecked());
}
break;
}
case AS_BYTES : {
as_bytes * bval = as_bytes_fromval(val);
if ( bval ) {
uint8_t * data = as_bytes_getorelse(bval, NULL);
uint32_t size = as_bytes_size(bval);
as_v8_detail(log,
"value = <%x %x %x%s>",
size > 0 ? data[0] : 0,
size > 1 ? data[1] : 0,
size > 2 ? data[2] : 0,
size > 3 ? " ..." : ""
);
// this constructor actually copies data into the new Buffer
Local<Object> buff = Nan::CopyBuffer((char*) data, size).ToLocalChecked();
return scope.Escape(buff);
}
break;
}
case AS_LIST : {
as_arraylist* listval = (as_arraylist*) as_list_fromval((as_val*)val);
int size = as_arraylist_size(listval);
Local<Array> jsarray = Nan::New<Array>(size);
for ( int i = 0; i < size; i++ ) {
as_val * arr_val = as_arraylist_get(listval, i);
Local<Value> jsval = val_to_jsvalue(arr_val, log);
Nan::Set(jsarray, i, jsval);
}
return scope.Escape(jsarray);
}
case AS_MAP : {
Local<Object> jsobj = Nan::New<Object>();
as_hashmap* map = (as_hashmap*) as_map_fromval(val);
as_hashmap_iterator it;
as_hashmap_iterator_init(&it, map);
while ( as_hashmap_iterator_has_next(&it) ) {
as_pair *p = (as_pair*) as_hashmap_iterator_next(&it);
as_val* key = as_pair_1(p);
as_val* val = as_pair_2(p);
Nan::Set(jsobj, val_to_jsvalue(key, log), val_to_jsvalue(val, log));
}
return scope.Escape(jsobj);
}
case AS_GEOJSON : {
as_geojson * gval = as_geojson_fromval(val);
if ( gval ) {
char * data = as_geojson_getorelse(gval, NULL);
as_v8_detail(log, "geojson = \"%s\"", data);
return scope.Escape(Nan::New<String>(data).ToLocalChecked());
}
break;
}
default:
break;
}
return scope.Escape(Nan::Undefined());
}
Local<Object> recordbins_to_jsobject(const as_record* record, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> bins ;
if (record == NULL) {
as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js record object");
return scope.Escape(bins);
}
bins = Nan::New<Object>();
as_record_iterator it;
as_record_iterator_init(&it, record);
while ( as_record_iterator_has_next(&it) ) {
as_bin * bin = as_record_iterator_next(&it);
char * name = as_bin_get_name(bin);
as_val * val = (as_val *) as_bin_get_value(bin);
Local<Value> obj = val_to_jsvalue(val, log );
Nan::Set(bins, Nan::New(name).ToLocalChecked(), obj);
as_v8_detail(log, "Setting binname %s ", name);
}
return scope.Escape(bins);
}
Local<Object> recordmeta_to_jsobject(const as_record* record, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> meta;
if(record == NULL) {
as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js metadata object");
return scope.Escape(meta);
}
meta = Nan::New<Object>();
Local<Number> ttl;
switch(record->ttl) {
case AS_RECORD_NO_EXPIRE_TTL:
ttl = Nan::New<Number>(TTL_NEVER_EXPIRE);
break;
default:
ttl = Nan::New<Number>(record->ttl);
}
Nan::Set(meta, Nan::New("ttl").ToLocalChecked(), ttl);
as_v8_detail(log, "TTL of the record %d", record->ttl);
Nan::Set(meta, Nan::New("gen").ToLocalChecked(), Nan::New(record->gen));
as_v8_detail(log, "Gen of the record %d", record->gen);
return scope.Escape(meta);
}
Local<Object> record_to_jsobject(const as_record* record, const as_key* key, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> okey;
if ( record == NULL ) {
as_v8_debug( log, "Record ( C structure) is NULL, cannot form node.js record object");
return scope.Escape(okey);
}
okey = key_to_jsobject(key ? key : &record->key, log);
Local<Object> bins = recordbins_to_jsobject(record, log );
Local<Object> meta = recordmeta_to_jsobject(record, log);
Local<Object> rec = Nan::New<Object>();
Nan::Set(rec, Nan::New("key").ToLocalChecked(), okey);
Nan::Set(rec, Nan::New("meta").ToLocalChecked(), meta);
Nan::Set(rec, Nan::New("bins").ToLocalChecked(), bins);
return scope.Escape(rec);
}
Local<Array> batch_records_to_jsarray(const as_batch_read_records* records, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
const as_vector* list = &records->list;
Local<Array> results = Nan::New<Array>(list->size);
for (uint32_t i = 0; i < list->size; i++) {
as_batch_read_record* batch_record = (as_batch_read_record*) as_vector_get((as_vector*) list, i);
as_status status = batch_record->result;
as_record* record = &batch_record->record;
as_key* key = &batch_record->key;
Local<Object> result = Nan::New<Object>();
Nan::Set(result, Nan::New("status").ToLocalChecked(), Nan::New(status));
Nan::Set(result, Nan::New("key").ToLocalChecked(), key_to_jsobject(key ? key : &record->key, log));
if (status == AEROSPIKE_OK) {
Nan::Set(result, Nan::New("meta").ToLocalChecked(), recordmeta_to_jsobject(record, log));
Nan::Set(result, Nan::New("bins").ToLocalChecked(), recordbins_to_jsobject(record, log));
}
Nan::Set(results, i, result);
}
return scope.Escape(results);
}
//Forward references;
int asval_from_jsvalue(as_val** value, Local<Value> v8value, const LogInfo* log);
int extract_blob_from_jsobject(uint8_t** data, int* len, Local<Object> obj, const LogInfo* log);
bool instanceof(Local<Value> value, const char * type)
{
if (value->IsObject()) {
Local<String> ctor_name = value.As<Object>()->GetConstructorName();
Nan::Utf8String cn(ctor_name);
return 0 == strncmp(*cn, type, strlen(type));
} else {
return false;
}
}
/**
* Node.js stores all number values > 2^31 in the class Number and
* values < 2^31 are stored in the class SMI (Small Integers). To distinguish
* between a double and int64_t value in Node.js, retrieve the value as double
* and also as int64_t. If the values are same, then store it as int64_t. Else
* store it as double.
* The problem with this implementation is var 123.00 will be treated as int64_t.
* Applications can enforce double type by using the `Aerospike.Double` data type,
* e.g.
*
* const Double = Aerospike.Double
* var f = new Double(123)
**/
bool is_double_value(Local<Value> value)
{
if (value->IsNumber()) {
int64_t i = Nan::To<int64_t>(value).FromJust();
double d = Nan::To<double>(value).FromJust();
return d != (double)i;
}
return instanceof(value, DoubleType);
}
double double_value(Local<Value> value)
{
if (instanceof(value, DoubleType)) {
value = Nan::Get(value.As<Object>(), Nan::New<String>("Double").ToLocalChecked()).ToLocalChecked();
}
return Nan::To<double>(value).FromJust();
}
bool is_geojson_value(Local<Value> value)
{
return instanceof(value, GeoJSONType);
}
char* geojson_as_string(Local<Value> value)
{
Local<Value> strval = Nan::Get(value.As<Object>(), Nan::New("str").ToLocalChecked()).ToLocalChecked();
return strdup(*Nan::Utf8String(strval));
}
int list_from_jsarray(as_list** list, Local<Array> array, const LogInfo* log)
{
const uint32_t capacity = array->Length();
as_v8_detail(log, "Creating new as_arraylist with capacity %d", capacity);
as_arraylist* arraylist = as_arraylist_new(capacity, 0);
if (arraylist == NULL) {
as_v8_error(log, "List allocation failed");
Nan::ThrowError("List allocation failed");
return AS_NODE_PARAM_ERR;
}
*list = (as_list*) arraylist;
for (uint32_t i = 0; i < capacity; i++) {
as_val* val;
if (asval_from_jsvalue(&val, Nan::Get(array, i).ToLocalChecked(), log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_list_append(*list, val);
}
return AS_NODE_PARAM_OK;
}
int map_from_jsobject(as_map** map, Local<Object> obj, const LogInfo* log)
{
const Local<Array> props = Nan::GetOwnPropertyNames(obj.As<Object>()).ToLocalChecked();
const uint32_t capacity = props->Length();
as_v8_detail(log, "Creating new as_hashmap with capacity %d", capacity);
as_hashmap* hashmap = as_hashmap_new(capacity);
if (hashmap == NULL) {
as_v8_error(log, "Map allocation failed");
Nan::ThrowError("Map allocation failed");
return AS_NODE_PARAM_ERR;
}
*map = (as_map*) hashmap;
for (uint32_t i = 0; i < capacity; i++) {
const Local<Value> name = Nan::Get(props, i).ToLocalChecked();
const Local<Value> value = Nan::Get(obj, name).ToLocalChecked();
as_val* val = NULL;
if (asval_from_jsvalue(&val, value, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_stringmap_set(*map, *Nan::Utf8String(name), val);
}
return AS_NODE_PARAM_OK;
}
int asval_from_jsvalue(as_val** value, Local<Value> v8value, const LogInfo* log)
{
if (v8value->IsNull()) {
as_v8_detail(log, "The as_val is NULL");
*value = (as_val*) &as_nil;
} else if (v8value->IsUndefined()) {
// asval_from_jsvalue is called recursively.
// If a bin value is undefined, it should be handled by the caller of
// this function gracefully.
// If an entry in a map/list is undefined the corresponding entry becomes null.
as_v8_detail(log, "Object passed is undefined");
*value = (as_val*) &as_nil;
} else if (v8value->IsBoolean()) {
*value = (as_val*) as_boolean_new(Nan::To<bool>(v8value).FromJust());
} else if (v8value->IsString()) {
*value = (as_val*) as_string_new(strdup(*Nan::Utf8String(v8value)), true);
} else if (v8value->IsInt32()) {
*value = (as_val*) as_integer_new(Nan::To<int32_t>(v8value).FromJust());
} else if (v8value->IsUint32()) {
*value = (as_val*) as_integer_new(Nan::To<uint32_t>(v8value).FromJust());
} else if (is_double_value(v8value)) {
*value = (as_val*) as_double_new(double_value(v8value));
} else if (v8value->IsNumber()) {
*value = (as_val*) as_integer_new(Nan::To<int64_t>(v8value).FromJust());
} else if (node::Buffer::HasInstance(v8value)) {
int size;
uint8_t* data;
if (extract_blob_from_jsobject(&data, &size, v8value.As<Object>(), log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Extractingb blob from a js object failed");
return AS_NODE_PARAM_ERR;
}
*value = (as_val*) as_bytes_new_wrap(data, size, true);
} else if (v8value->IsArray()) {
if (list_from_jsarray((as_list**) value, Local<Array>::Cast(v8value), log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
} else if (is_geojson_value(v8value)) {
char* jsonstr = geojson_as_string(v8value);
*value = (as_val*) as_geojson_new(jsonstr, true);
} else { // generic object - treat as map
if (map_from_jsobject((as_map**) value, v8value.As<Object>(), log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
}
if (as_v8_detail_enabled(log)) {
auto val_type = as_val_type(*value);
char* val_str = as_val_tostring(*value);
as_v8_detail(log, "type: %d, string value: %s", val_type, val_str);
cf_free(val_str);
}
return AEROSPIKE_OK;
}
int recordbins_from_jsobject(as_record* rec, Local<Object> obj, const LogInfo* log)
{
const Local<Array> props = Nan::GetOwnPropertyNames(obj).ToLocalChecked();
const uint32_t count = props->Length();
as_record_init(rec, count);
for ( uint32_t i = 0; i < count; i++ ) {
const Local<Value> name = Nan::Get(props, i).ToLocalChecked();
const Local<Value> value = Nan::Get(obj, name).ToLocalChecked();
// A bin can be undefined, or an entry inside a CDT(list, map)
// can be an undefined value.
// If a bin is undefined, it must error out at the earliest.
if( value->IsUndefined()) {
as_v8_error(log, "Bin value 'undefined' not supported: %s", *Nan::Utf8String(name));
return AS_NODE_PARAM_ERR;
}
Nan::Utf8String n(name);
if( strlen(*n) > AS_BIN_NAME_MAX_SIZE ) {
as_v8_error(log, "Bin name length exceeded (max. 14): %s", *n);
return AS_NODE_PARAM_ERR;
}
as_val* val = NULL;
if (asval_from_jsvalue(&val, value, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
switch(as_val_type(val)) {
case AS_BOOLEAN:
as_val_destroy(val);
as_v8_error(log, "Boolean type not supported: %s", *n);
return AS_NODE_PARAM_ERR;
case AS_INTEGER:
as_record_set_integer(rec, *n, (as_integer*)val);
break;
case AS_DOUBLE:
as_record_set_as_double(rec, *n, (as_double*)val);
break;
case AS_STRING:
as_record_set_string(rec, *n, (as_string*)val);
break;
case AS_BYTES:
as_record_set_bytes(rec, *n, (as_bytes*) val);
break;
case AS_LIST:
as_record_set_list(rec, *n, (as_list*) val);
break;
case AS_MAP:
as_record_set_map(rec, *n, (as_map*) val);
break;
case AS_GEOJSON:
as_record_set_geojson(rec, *n, (as_geojson*) val);
break;
case AS_NIL:
as_record_set_nil(rec, *n);
break;
default:
as_v8_error(log,"Skipping unsupported as_val type %i: %s", as_val_type(val), *n);
break;
}
}
return AS_NODE_PARAM_OK;
}
int recordmeta_from_jsobject(as_record* rec, Local<Object> obj, const LogInfo* log)
{
as_v8_detail(log, "Setting record meta from JS object");
if (setTTL(obj, &rec->ttl, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
};
if (setGeneration(obj, &rec->gen, log) != AS_NODE_PARAM_OK) {;
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int extract_blob_from_jsobject(uint8_t** data, int* len, Local<Object> obj, const LogInfo* log)
{
if (!node::Buffer::HasInstance(obj)) {
as_v8_error(log, "The binary data is not of the type UnsignedBytes");
return AS_NODE_PARAM_ERR;
}
(*len) = node::Buffer::Length(obj);
(*data) = (uint8_t*) cf_malloc(sizeof(uint8_t) * (*len));
memcpy((*data), node::Buffer::Data(obj), (*len));
return AS_NODE_PARAM_OK;
}
int setTTL(Local<Object> obj, uint32_t* ttl, const LogInfo* log)
{
Local<Value> v8_ttl = Nan::Get(obj, Nan::New("ttl").ToLocalChecked()).ToLocalChecked();
if (v8_ttl->IsNumber()) {
(*ttl) = Nan::To<uint32_t>(v8_ttl).FromJust();
as_v8_detail(log, "TTL: %d", (*ttl));
} else if (v8_ttl->IsNull() || v8_ttl->IsUndefined()) {
// noop - ttl may not be specified
} else {
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
int setGeneration(Local<Object> obj, uint16_t* generation, const LogInfo* log)
{
Local<Value> v8_gen = Nan::Get(obj, Nan::New("gen").ToLocalChecked()).ToLocalChecked();
if (v8_gen->IsNumber()) {
(*generation) = (uint16_t) Nan::To<uint32_t>(v8_gen).FromJust();
as_v8_detail(log, "Generation: %d", (*generation));
} else if (v8_gen->IsNull() || v8_gen->IsUndefined()) {
// noop - gen may not be specified
} else {
as_v8_error(log, "Generation should be an integer");
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
Local<Object> key_to_jsobject(const as_key* key, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
Local<Object> obj;
if (key == NULL) {
as_v8_debug(log, "Key (C structure) is NULL, cannot form node.js key object");
return scope.Escape(obj);
}
obj = Nan::New<Object>();
if (strlen(key->ns) > 0) {
as_v8_detail(log, "key.ns = \"%s\"", key->ns);
Nan::Set(obj, Nan::New("ns").ToLocalChecked(), Nan::New(key->ns).ToLocalChecked());
} else {
as_v8_debug(log, "Key namespace is NULL");
}
if (strlen(key->set) > 0) {
as_v8_detail(log, "key.set = \"%s\"", key->set);
Nan::Set(obj, Nan::New("set").ToLocalChecked(), Nan::New(key->set).ToLocalChecked());
} else {
as_v8_debug(log, "Key set is NULL");
}
if ( key->valuep ) {
as_val * val = (as_val *) key->valuep;
as_val_t type = as_val_type(val);
switch(type) {
case AS_INTEGER: {
as_integer * ival = as_integer_fromval(val);
as_v8_detail(log, "key.key = %d", as_integer_get(ival));
Nan::Set(obj, Nan::New("key").ToLocalChecked(), Nan::New((double)as_integer_get(ival)));
break;
}
case AS_STRING: {
as_string * sval = as_string_fromval(val);
as_v8_detail(log, "key.key = \"%s\"", as_string_get(sval));
Nan::Set(obj, Nan::New("key").ToLocalChecked(), Nan::New(as_string_get(sval)).ToLocalChecked());
break;
}
case AS_BYTES: {
as_bytes * bval = as_bytes_fromval(val);
if ( bval ) {
uint32_t size = as_bytes_size(bval);
as_v8_detail(log,"key.key = \"%u\"", bval->value);
Local<Object> buff = Nan::CopyBuffer((char*)bval->value, size).ToLocalChecked();
Nan::Set(obj, Nan::New("key").ToLocalChecked(), buff);
break;
}
}
default:
break;
}
} else {
as_v8_detail(log, "Key value is NULL");
}
if (key->digest.init == true) {
Local<Object> buff = Nan::CopyBuffer((char*)key->digest.value, AS_DIGEST_VALUE_SIZE).ToLocalChecked();
Nan::Set(obj, Nan::New("digest").ToLocalChecked(), buff);
}
return scope.Escape(obj);
}
Local<Object> jobinfo_to_jsobject(const as_job_info* info, const LogInfo* log)
{
Local<Object> jobinfo;
if (info == NULL) {
as_v8_debug(log, "Job Info ( C structure) is NULL, cannot form node.js jobInfo object");
return jobinfo;
}
jobinfo = Nan::New<Object>();
Nan::Set(jobinfo, Nan::New("progressPct").ToLocalChecked(), Nan::New(info->progress_pct));
as_v8_detail(log, "Progress pct of the job %d", info->progress_pct);
Local<Value> recordsRead = Nan::New((double)info->records_read);
Nan::Set(jobinfo, Nan::New("recordsRead").ToLocalChecked(), recordsRead);
as_v8_detail(log, "Number of records read so far %d", info->records_read);
Nan::Set(jobinfo, Nan::New("status").ToLocalChecked(), Nan::New(info->status));
return jobinfo;
}
int key_from_jsobject(as_key* key, Local<Object> obj, const LogInfo* log)
{
Nan::EscapableHandleScope scope;
as_namespace ns = {'\0'};
as_set set = {'\0'};
if (obj->IsNull()) {
as_v8_error(log, "The key object passed is Null");
return AS_NODE_PARAM_ERR;
}
Local<Value> ns_obj = Nan::Get(obj, Nan::New("ns").ToLocalChecked()).ToLocalChecked();
if (ns_obj->IsString()) {
if (as_strlcpy(ns, *Nan::Utf8String(ns_obj), AS_NAMESPACE_MAX_SIZE) > AS_NAMESPACE_MAX_SIZE) {
as_v8_error(log, "The key namespace is too long (max. %d)", AS_NAMESPACE_MAX_SIZE);
return AS_NODE_PARAM_ERR;
}
if (strlen(ns) == 0) {
as_v8_error(log, "The key namespace must not be empty");
return AS_NODE_PARAM_ERR;
}
as_v8_detail(log, "key.ns = \"%s\"", ns);
} else {
as_v8_error(log, "The key namespace must be a string");
return AS_NODE_PARAM_ERR;
}
Local<Value> set_obj = Nan::Get(obj, Nan::New("set").ToLocalChecked()).ToLocalChecked();
if (set_obj->IsString()) {
if (as_strlcpy(set, *Nan::Utf8String(set_obj), AS_SET_MAX_SIZE) > AS_SET_MAX_SIZE) {
as_v8_error(log, "The key set is too long (max. %d)", AS_SET_MAX_SIZE);
return AS_NODE_PARAM_ERR;
}
if (strlen(set) == 0) {
as_v8_debug(log, "Key set passed is empty string");
}
as_v8_detail(log,"key.set = \"%s\"", set);
} else if (set_obj->IsNull() || set_obj->IsUndefined()) {
// noop - set name may not be specified
} else {
as_v8_error(log, "The key set must be a string");
return AS_NODE_PARAM_ERR;
}
bool has_value = false;
Local<Value> val_obj = Nan::Get(obj, Nan::New("key").ToLocalChecked()).ToLocalChecked();
if (val_obj->IsString()) {
char* value = strdup(*Nan::Utf8String(val_obj));
as_key_init(key, ns, set, value);
as_v8_detail(log, "key.key = \"%s\"", value);
((as_string*) key->valuep)->free = true;
has_value = true;
} else if (is_double_value(val_obj)) {
as_v8_error(log, "Invalid key value: double - only string, integer and Buffer are supported");
return AS_NODE_PARAM_ERR;
} else if (val_obj->IsNumber()) {
int64_t value = Nan::To<int64_t>(val_obj).FromJust();
as_key_init_int64(key, ns, set, value);
as_v8_detail(log, "key.key = %d", value);
has_value = true;
} else if (val_obj->IsObject()) {
Local<Object> obj = val_obj.As<Object>();
int size ;
uint8_t* data ;
if (extract_blob_from_jsobject(&data, &size, obj, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_key_init_rawp(key, ns, set, data, size, true);
has_value = true;
as_v8_detail(log,
"key.key = <%x %x %x%s>",
size > 0 ? data[0] : 0,
size > 1 ? data[1] : 0,
size > 2 ? data[2] : 0,
size > 3 ? " ..." : ""
);
} else if (val_obj->IsNull() || val_obj->IsUndefined()) {
// noop - value can be omitted if digest is given
} else {
as_v8_error(log, "Invalid key value - only string, integer and Buffer are supported");
return AS_NODE_PARAM_ERR;
}
if (has_value) {
// Copy the digest back to the JS key object
as_digest* digest = as_key_digest(key);
uint8_t* bytes = digest->value;
Local<Object> buff = scope.Escape(Nan::CopyBuffer((char*) bytes, AS_DIGEST_VALUE_SIZE).ToLocalChecked());
Nan::Set(obj, Nan::New("digest").ToLocalChecked(), buff);
} else {
Local<Value> digest_value = Nan::Get(obj, Nan::New("digest").ToLocalChecked()).ToLocalChecked();
if (digest_value->IsObject()) {
Local<Object> digest_obj = digest_value.As<Object>();
int size;
uint8_t* data;
if (extract_blob_from_jsobject(&data, &size, digest_obj, log) != AS_NODE_PARAM_OK) {
return AS_NODE_PARAM_ERR;
}
as_digest_value digest;
memcpy(digest, data, AS_DIGEST_VALUE_SIZE);
as_v8_detail(log,
"key.digest = <%x %x %x%s>",
size > 0 ? digest[0] : 0,
size > 1 ? digest[1] : 0,
size > 2 ? digest[2] : 0,
size > 3 ? " ..." : ""
);
as_key_init_digest(key, ns, set, digest);
} else if (digest_value->IsNull() || digest_value->IsUndefined()) {
as_v8_error(log, "The key must have either a \"value\" or a \"digest\"");
return AS_NODE_PARAM_ERR;
} else {
as_v8_error(log, "Invalid digest value: \"digest\" must be a 20-byte Buffer");
return AS_NODE_PARAM_ERR;
}
}
return AS_NODE_PARAM_OK;
}
int batch_from_jsarray(as_batch* batch, Local<Array> arr, const LogInfo* log)
{
uint32_t len = arr->Length();
as_batch_init(batch, len);
for (uint32_t i = 0; i < len; i++) {
Local<Object> key = Nan::Get(arr, i).ToLocalChecked().As<Object>();
if (key_from_jsobject(as_batch_keyat(batch, i), key, log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Parsing batch key [%d] failed", i);
return AS_NODE_PARAM_ERR;
}
}
return AS_NODE_PARAM_OK;
}
int batch_read_records_from_jsarray(as_batch_read_records** records, Local<Array> arr, const LogInfo* log)
{
uint32_t no_records = arr->Length();
*records = as_batch_read_create(no_records);
for (uint32_t i = 0; i < no_records; i++) {
as_batch_read_record* record = as_batch_read_reserve(*records);
Local<Object> obj = Nan::Get(arr, i).ToLocalChecked().As<Object>();
Local<Object> key = Nan::Get(obj, Nan::New("key").ToLocalChecked()).ToLocalChecked().As<Object>();
if (key_from_jsobject(&record->key, key, log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Parsing batch keys failed");
return AS_NODE_PARAM_ERR;
}
Local<Value> v8_bins = Nan::Get(obj, Nan::New("bins").ToLocalChecked()).ToLocalChecked();
if (v8_bins->IsArray()) {
char** bin_names;
uint32_t n_bin_names;
if (bins_from_jsarray(&bin_names, &n_bin_names, Local<Array>::Cast(v8_bins), log) != AS_NODE_PARAM_OK) {
as_v8_error(log, "Parsing batch bin names failed");
return AS_NODE_PARAM_ERR;
}
record->bin_names = bin_names;
record->n_bin_names = n_bin_names;
}
Local<Value> v8_read_all_bins = Nan::Get(obj, Nan::New("read_all_bins").ToLocalChecked()).ToLocalChecked();
if (v8_read_all_bins->IsBoolean()) {
record->read_all_bins = Nan::To<bool>(v8_read_all_bins).FromJust();
}
}
return AS_NODE_PARAM_OK;
}
int bins_from_jsarray(char*** bins, uint32_t* num_bins, Local<Array> arr, const LogInfo* log)
{
int arr_length = arr->Length();
char** c_bins = (char**) cf_calloc(sizeof(char*), arr_length+1);
as_v8_debug(log, "Number of bins requested %d", arr_length);
for( int i = 0; i < arr_length; i++) {
Local<Value> bname = Nan::Get(arr, i).ToLocalChecked();
c_bins[i] = (char*)cf_malloc(AS_BIN_NAME_MAX_SIZE);
as_strlcpy(c_bins[i], *Nan::Utf8String(bname), AS_BIN_NAME_MAX_SIZE);
as_v8_detail(log, "name of the bin %s", c_bins[i]);
}
// The last entry should be NULL because we are passing to select API calls.
c_bins[arr_length] = NULL;
*bins = c_bins;
*num_bins = (uint32_t) arr_length;
return AS_NODE_PARAM_OK;
}
void
free_batch_records(as_batch_read_records* records)
{
const as_vector* list = &records->list;
for (uint32_t i = 0; i < list->size; i++) {
as_batch_read_record* batch_record = (as_batch_read_record*) as_vector_get((as_vector*) list, i);
if (batch_record->n_bin_names > 0) {
for (uint32_t j = 0; j < batch_record->n_bin_names; j++) {
cf_free(batch_record->bin_names[j]);
}
cf_free(batch_record->bin_names);
}
}
as_batch_read_destroy(records);
}
int udfargs_from_jsobject(char** filename, char** funcname, as_list** args, Local<Object> obj, const LogInfo* log)
{
if (obj->IsNull()) {
as_v8_error(log, "Object passed is NULL");
return AS_NODE_PARAM_ERR;
}
// Extract UDF module name
Local<Value> v8_module = Nan::Get(obj, Nan::New("module").ToLocalChecked()).ToLocalChecked();
if (v8_module->IsString()) {
size_t size = v8_module.As<String>()->Length() + 1;
if (*filename == NULL) {
*filename = (char*) cf_malloc(sizeof(char) * size);
}
if (as_strlcpy(*filename, *Nan::Utf8String(v8_module), size) > size) {
as_v8_error(log, "UDF module name is too long (> %d)", size);
return AS_NODE_PARAM_ERR;
}
as_v8_detail(log, "Filename in the udf args is set to %s", *filename);
} else {
as_v8_error(log, "UDF module name should be string");
return AS_NODE_PARAM_ERR;
}
// Extract UDF function name
Local<Value> v8_funcname = Nan::Get(obj, Nan::New("funcname").ToLocalChecked()).ToLocalChecked();
if (v8_funcname->IsString()) {
size_t size = v8_funcname.As<String>()->Length() + 1;
if (*funcname == NULL) {
*funcname = (char*) cf_malloc(sizeof(char) * size);
}
if (as_strlcpy(*funcname, *Nan::Utf8String(v8_funcname), size) > size) {
as_v8_error(log, "UDF function name is too long (> %d)", size);
return AS_NODE_PARAM_ERR;
}
as_v8_detail(log, "The function name in the UDF args set to %s", *funcname);
} else {
as_v8_error(log, "UDF function name should be string");
return AS_NODE_PARAM_ERR;
}
Local<Value> arglist = Nan::Get(obj, Nan::New("args").ToLocalChecked()).ToLocalChecked();
if (arglist->IsArray()) {
list_from_jsarray(args, Local<Array>::Cast(arglist), log);
as_v8_detail(log, "Parsing UDF args -- done !!!");
} else if (arglist->IsNull() || arglist->IsUndefined()) {
// No argument case: Initialize array with 0 elements.
*args = (as_list*) as_arraylist_new(0, 0);
} else {
as_v8_error(log, "UDF args should be an array");
return AS_NODE_PARAM_ERR;
}
return AS_NODE_PARAM_OK;
}
// Like strncpy but does not 0 fill the buffer and always null
// terminates. bufsize is the size of the destination buffer.
size_t as_strlcpy(char *d, const char *s, size_t bufsize)
{
size_t len = strlen(s);
size_t ret = len;
if (len >= bufsize) len = bufsize-1;
memcpy(d, s, len);
d[len] = 0;
return ret;
}
| 37.88744 | 162 | 0.591156 | jsa-research |
c0cbe96d938eef7ed67b4be296fed9f40e9c4ac1 | 15,112 | cpp | C++ | cpp/src/objdetect/app.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | cpp/src/objdetect/app.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | cpp/src/objdetect/app.cpp | robotalks/think | a734a6496b796e4e4435cc9214e6ede9847dc3c3 | [
"MIT"
] | null | null | null | #include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <exception>
#include <iostream>
#include <thread>
#include <atomic>
#include <vector>
#include <string>
#include <functional>
#include <condition_variable>
#include <mutex>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <boost/network/protocol/http/server.hpp>
#include <boost/network/uri.hpp>
#include "dp/graph.h"
#include "dp/operators.h"
#include "dp/ingress/udp.h"
#include "dp/ingress/videocap.h"
#include "dp/util/error.h"
#include "mqtt/mqtt.h"
#include "movidius/ncs.h"
#include "movidius/ssd_mobilenet.h"
using namespace std;
using namespace dp;
static constexpr int http_port = 2052;
static constexpr int cast_port = 2053;
DEFINE_int32(port, in::udp::default_port, "listening port");
DEFINE_string(mqtt_host, "127.0.0.1", "MQTT server address");
DEFINE_int32(mqtt_port, mqtt::client::default_port, "MQTT server port");
DEFINE_string(mqtt_client_id, "", "MQTT client ID");
DEFINE_string(mqtt_topic, "", "MQTT topic");
DEFINE_string(model, "graph", "Model name");
DEFINE_string(http_addr, "", "image server listening address");
DEFINE_int32(http_port, http_port, "image server listening port");
DEFINE_int32(stream_port, cast_port, "TCP streaming port");
struct pub_op {
mqtt::client *client;
pub_op(mqtt::client* c) : client(c) { }
void operator() (graph::ctx ctx) {
const auto& str = ctx.in(0)->as<string>();
client->publish(FLAGS_mqtt_topic, str);
}
};
static string index_html(R"(<!DOCTYPE html>
<html>
<head>
<script language="javascript">
function refreshImage() {
document.getElementById('cam0').src = '/jpeg?ts='+Date.now();
setTimeout(refreshImage, 30);
}
document.addEventListener('DOMContentLoaded', refreshImage);
</script>
</head>
<body>
<img id="cam0">
</body>
</html>
)");
static string sz2str(size_t sz) {
char str[64];
sprintf(str, "%u", sz);
return str;
}
struct image_buffer {
vector<unsigned char> data;
size_t size;
image_id id;
static constexpr size_t max_buf_size = 0x10000;
image_buffer() : data(max_buf_size), size(0) { }
const unsigned char* ptr() const {
return &data[0];
}
void update(const void *buf, size_t _sz, const image_id& _id) {
if (_sz > max_buf_size) _sz = max_buf_size;
memcpy(&data[0], buf, _sz);
size = _sz;
id = _id;
}
};
class image_handler;
typedef ::boost::network::http::server<image_handler> http_server_t;
class image_handler {
public:
image_handler() : m_images(2), m_current_buf(0) { }
void set_image(const void *buf, size_t size, const image_id& id) {
int write_buf = 1 - m_current_buf.load();
m_images[write_buf].update(buf, size, id);
atomic_exchange(&m_current_buf, write_buf);
m_set_image_cv.notify_all();
}
const image_buffer* wait() const {
unique_lock<mutex> lock(m_set_image_mux);
m_set_image_cv.wait(lock);
return &m_images[m_current_buf.load()];
}
void operator() (http_server_t::request const& request, http_server_t::connection_ptr conn) {
VLOG(4) << request.method << " " << request.destination;
boost::network::uri::uri uri("http://localhost:80"+request.destination);
static http_server_t::response_header error_headers[] = {
{"Content-type", "text/plain"},
{"Connection", "close"},
};
if (request.method == "GET") {
if (uri.path() == "/") {
handle_index(conn);
return;
}
if (uri.path() == "/jpeg") {
handle_jpeg(conn);
return;
}
if (uri.path() == "/stream") {
handle_stream(conn);
return;
}
conn->set_status(http_server_t::connection::not_found);
conn->set_headers(boost::make_iterator_range(error_headers,
error_headers+sizeof(error_headers)/sizeof(error_headers[0])));
conn->write("Path not supported");
return;
}
conn->set_status(http_server_t::connection::not_supported);
conn->set_headers(boost::make_iterator_range(error_headers,
error_headers+sizeof(error_headers)/sizeof(error_headers[0])));
conn->write("Method not supported");
}
graph::op_func op() {
return [this](graph::ctx ctx) {
const buf_ref &buf = ctx.in(0)->as<buf_ref>();
const auto& id = ctx.in(1)->as<image_id>();
set_image(buf.ptr, buf.len, id);
};
}
private:
vector<image_buffer> m_images;
atomic_int m_current_buf;
mutable mutex m_set_image_mux;
mutable condition_variable m_set_image_cv;
void handle_index(http_server_t::connection_ptr conn) {
http_server_t::response_header common_headers[] = {
{"Content-type", "text/html"},
{"Content-length", sz2str(index_html.length())},
};
conn->set_status(http_server_t::connection::ok);
conn->set_headers(boost::make_iterator_range(common_headers,
common_headers+sizeof(common_headers)/sizeof(common_headers[0])));
conn->write(index_html);
}
void handle_jpeg(http_server_t::connection_ptr conn) {
const image_buffer& buf = m_images[m_current_buf.load()];
http_server_t::response_header common_headers[] = {
{"Content-type", "image/jpeg"},
{"Content-length", sz2str(buf.size)},
{"Cache-control", "max-age=0, no-cache"},
{"X-ImageId-Seq", sz2str(buf.id.seq)},
{"X-ImageId-Src", buf.id.src},
};
conn->set_status(http_server_t::connection::ok);
conn->set_headers(boost::make_iterator_range(common_headers,
common_headers+sizeof(common_headers)/sizeof(common_headers[0])));
conn->write(boost::asio::const_buffers_1(buf.ptr(), buf.size),
[](boost::system::error_code const&) {});
}
void handle_stream(http_server_t::connection_ptr conn) {
conn->set_status(http_server_t::connection::not_supported);
conn->write("Not implemented");
}
};
class socket_listener {
public:
socket_listener(int type, int port) : m_socket(-1) {
try {
m_socket = socket(PF_INET, type, 0);
if (m_socket < 0) {
throw runtime_error(errmsg("socket"));
}
long en = 1;
if (setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, &en, sizeof(en)) < 0) {
throw runtime_error(errmsg("setsockopt"));
}
sockaddr_in sa;
memset(&sa, 0, sizeof(sa));
sa.sin_family = PF_INET;
sa.sin_port = htons((u_short)port);
sa.sin_addr.s_addr = INADDR_ANY;
if (bind(m_socket, (sockaddr*)&sa, sizeof(sa)) < 0) {
throw runtime_error(errmsg("socket bind"));
}
if (type != SOCK_STREAM) return;
if (listen(m_socket, SOMAXCONN) < 0) {
throw runtime_error(errmsg("listen"));
}
} catch (runtime_error&) {
if (m_socket >= 0) {
close(m_socket);
}
throw;
}
}
virtual ~socket_listener() {
if (m_socket >= 0) {
close(m_socket);
}
}
int socket_fd() const { return m_socket; }
private:
int m_socket;
};
class streamer : public socket_listener {
public:
streamer(int port = cast_port)
: socket_listener(SOCK_STREAM, port) {
}
void run(const image_handler* images) {
while (true) {
sockaddr_in sa;
socklen_t salen = sizeof(sa);
int conn = accept(socket_fd(), (sockaddr*)&sa, &salen);
if (conn < 0) {
LOG(ERROR) << errmsg("accept");
break;
}
thread client([this, conn, images] { stream_to(conn, images); });
client.detach();
}
}
private:
void stream_to(int conn, const image_handler* images) {
const image_buffer* buf;
while ((buf = images->wait()) != nullptr) {
uint16_t sz = (uint16_t)buf->size;
int r = send(conn, &sz, sizeof(sz), MSG_NOSIGNAL);
if (r > 0) {
r = send(conn, buf->ptr(), buf->size, MSG_NOSIGNAL);
}
if (r < 0) {
LOG(ERROR) << errmsg("send");
break;
}
}
close(conn);
}
};
class udp_caster : public socket_listener {
public:
udp_caster(int port = cast_port)
: socket_listener(SOCK_DGRAM, port) {
}
void run(const image_handler* images) {
thread listener_thread([this] { run_listener(); });
run_caster(images);
listener_thread.join();
}
private:
struct subscriber {
sockaddr_in addr;
int failures;
subscriber(const sockaddr_in& sa) : failures(0) {
memcpy(&addr, &sa, sizeof(addr));
}
bool same(const sockaddr_in& sa) const {
return addr.sin_port == sa.sin_port && addr.sin_addr.s_addr == sa.sin_addr.s_addr;
}
string str() const {
string s(inet_ntoa(addr.sin_addr));
s += ":" + sz2str(ntohs(addr.sin_port));
return s;
}
static function<bool(const subscriber&)> if_same(sockaddr_in sa) {
return [sa] (const subscriber& sub) -> bool {
return sub.same(sa);
};
}
};
list<subscriber> m_subscribers;
mutex m_lock;
static constexpr int max_failures = 5;
void run_listener() {
char buf[4];
while (true) {
sockaddr_in sa;
socklen_t salen = sizeof(sa);
int r = recvfrom(socket_fd(), buf, sizeof(buf), 0, (sockaddr*)&sa, &salen);
if (r < 0) {
LOG(ERROR) << errmsg("recvfrom");
break;
}
if (r == 0) continue;
switch (buf[0]) {
case '+':
add_subscriber(sa);
break;
case '-':
del_subscriber(sa);
break;
}
}
}
void run_caster(const image_handler* images) {
const image_buffer* buf;
while ((buf = images->wait()) != nullptr) {
uint16_t sz = (uint16_t)buf->size;
cast(buf);
}
}
void cast(const image_buffer* buf) {
unique_lock<mutex> lock(m_lock);
list<subscriber>::iterator it = m_subscribers.begin();
while (it != m_subscribers.end()) {
auto cur = it;
it ++;
int r = sendto(socket_fd(), buf->ptr(), buf->size, MSG_NOSIGNAL,
(sockaddr*)&cur->addr, sizeof(cur->addr));
if (r < 0) {
LOG(ERROR) << cur->str() << ": " << errmsg("sendto");
cur->failures ++;
if (cur->failures > max_failures) {
LOG(WARNING) << "remove " << cur->str() << " due to too many failures";
m_subscribers.erase(cur);
}
}
}
}
void add_subscriber(const sockaddr_in& sa) {
unique_lock<mutex> lock(m_lock);
list<subscriber>::iterator it = find_if(m_subscribers.begin(), m_subscribers.end(), subscriber::if_same(sa));
if (it != m_subscribers.end()) {
it->failures = 0;
return;
}
m_subscribers.push_back(subscriber(sa));
}
void del_subscriber(const sockaddr_in& sa) {
unique_lock<mutex> lock(m_lock);
m_subscribers.remove_if(subscriber::if_same(sa));
}
};
class app {
public:
app() {
mqtt::initialize();
http_server_t::options options(m_imghandler);
options.reuse_address(true)
.thread_pool(make_shared<boost::network::utils::thread_pool>())
.port(sz2str(FLAGS_http_port));
if (!FLAGS_http_addr.empty()) {
options.address(FLAGS_http_addr);
}
m_httpsrv.reset(new http_server_t(options));
auto names = movidius::compute_stick::devices();
if (names.empty()) throw runtime_error("no Movidius NCS found");
LOG(INFO) << "MQTT Connect " << FLAGS_mqtt_host << ":" << FLAGS_mqtt_port;
m_mqtt_client.reset(new mqtt::client(FLAGS_mqtt_client_id));
m_mqtt_client->connect(FLAGS_mqtt_host, (unsigned short)FLAGS_mqtt_port).wait();
for (auto& name : names) {
LOG(INFO) << "Loading " << name << " with model " << FLAGS_model;
unique_ptr<movidius::compute_stick> stick(new movidius::compute_stick(name));
unique_ptr<movidius::compute_stick::graph> model(stick->alloc_graph_from_file(FLAGS_model));
unique_ptr<graph> g(new graph(name));
g->def_vars({"input", "id", "size", "pixels", "objects", "result"});
g->add_op("imgid", {"input"}, {"id"}, op::image_id());
g->add_op("decode", {"input"}, {"pixels", "size"}, op::decode_image());
g->add_op("detect", {"pixels"}, {"objects"}, movidius::op::ssd_mobilenet(model.get()));
g->add_op("json", {"size", "id", "objects"}, {"result"}, op::detect_boxes_json());
g->add_op("publish", {"result"}, {}, pub_op(m_mqtt_client.get()));
g->add_op("imagesrv", {"input", "id"}, {}, m_imghandler.op());
m_dispatcher.add_graph(g.get());
m_ncs.push_back(move(stick));
m_models.push_back(move(model));
m_graphs.push_back(move(g));
}
}
~app() {
mqtt::cleanup();
}
void run() {
LOG(INFO) << "Run!";
in::udp udp((uint16_t)FLAGS_port);
thread httpsrv_thread([this] { m_httpsrv->run(); });
thread streamer_thread([this] { run_streamer(); });
thread caster_thread([this] { run_caster(); });
udp.run(&m_dispatcher);
httpsrv_thread.join();
caster_thread.join();
streamer_thread.join();
}
private:
unique_ptr<mqtt::client> m_mqtt_client;
vector<unique_ptr<movidius::compute_stick>> m_ncs;
vector<unique_ptr<movidius::compute_stick::graph>> m_models;
vector<unique_ptr<graph>> m_graphs;
graph_dispatcher m_dispatcher;
image_handler m_imghandler;
unique_ptr<http_server_t> m_httpsrv;
void run_streamer() {
if (FLAGS_stream_port == 0) {
return;
}
streamer strm(FLAGS_stream_port);
strm.run(&m_imghandler);
}
void run_caster() {
if (FLAGS_stream_port == 0) {
return;
}
udp_caster caster(FLAGS_stream_port);
caster.run(&m_imghandler);
}
};
int main(int argc, char* argv[]) {
google::InitGoogleLogging(argv[0]);
google::InstallFailureSignalHandler();
gflags::ParseCommandLineFlags(&argc, &argv, true);
app app;
app.run();
return 0;
}
| 31.287785 | 117 | 0.572128 | robotalks |
c0ccd87a26ac60b3c89e8dd5b45c154ffcf9aa51 | 1,512 | cpp | C++ | engine/src/core/Sprite.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | 2 | 2018-12-19T01:52:39.000Z | 2022-03-29T16:04:15.000Z | engine/src/core/Sprite.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | engine/src/core/Sprite.cpp | jsandham/PhysicsEngine | 51115ee9a59f3bc6e0895113c67563cfd4a1ef3c | [
"MIT"
] | null | null | null | #include "../../include/core/Sprite.h"
#include "../../include/graphics/Graphics.h"
using namespace PhysicsEngine;
Sprite::Sprite(World *world) : Asset(world)
{
mCreated = false;
mChanged = false;
mPixelsPerUnit = 100;
}
Sprite::Sprite(World *world, Guid id) : Asset(world, id)
{
mCreated = false;
mChanged = false;
mPixelsPerUnit = 100;
}
Sprite::~Sprite()
{
}
void Sprite::serialize(YAML::Node &out) const
{
Asset::serialize(out);
out["textureId"] = mTextureId;
out["pixelsPerUnit"] = mPixelsPerUnit;
}
void Sprite::deserialize(const YAML::Node &in)
{
Asset::deserialize(in);
mTextureId = YAML::getValue<Guid>(in, "textureId");
mPixelsPerUnit = YAML::getValue<int>(in, "pixelsPerUnit");
}
int Sprite::getType() const
{
return PhysicsEngine::SPRITE_TYPE;
}
std::string Sprite::getObjectName() const
{
return PhysicsEngine::SPRITE_NAME;
}
bool Sprite::isCreated() const
{
return mCreated;
}
bool Sprite::isChanged() const
{
return mChanged;
}
GLuint Sprite::getNativeGraphicsVAO() const
{
return mVao;
}
Guid Sprite::getTextureId() const
{
return mTextureId;
}
void Sprite::setTextureId(Guid textureId)
{
mTextureId = textureId;
mChanged = true;
}
void Sprite::create()
{
if (mCreated)
{
return;
}
Graphics::createSprite(&mVao);
mCreated = true;
}
void Sprite::destroy()
{
if (!mCreated)
{
return;
}
Graphics::destroySprite(&mVao);
mCreated = false;
} | 14.823529 | 62 | 0.646164 | jsandham |
c0cd865b906fc7bbbbb5eaf3526f4af66d947300 | 1,650 | hpp | C++ | src/3D/Spider.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | 4 | 2017-05-22T04:14:06.000Z | 2022-02-09T19:15:10.000Z | src/3D/Spider.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | src/3D/Spider.hpp | Reewr/master | 76725548d0b6ff3ac22f5383eb0c773d2fcc2a4b | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <string>
#include "../Drawable/Drawable3D.hpp"
#include "../Log.hpp"
class PhysicsMesh;
struct PhysicsElements;
class Program;
class btGeneric6DofSpringConstraint;
class btHingeConstraint;
class btTransform;
class Spider : public Drawable3D, public Logging::Log {
public:
struct Part {
Part();
Part(unsigned short group, unsigned short mask, float angle, bool active);
unsigned short collisionGroup;
unsigned short collisionMask;
float restAngle;
bool active;
Drawable3D* part;
btHingeConstraint* hinge;
btGeneric6DofSpringConstraint* dof;
};
Spider();
~Spider();
// Resets the positions, rotations and such for the whole spider
void reset();
void update(float deltaTime);
void draw(std::shared_ptr<Program>& program, bool bindTexture = false);
void draw(std::shared_ptr<Program>& program,
mmm::vec3 offset,
bool bindTexture = false);
void input(const Input::Event& event);
// Returns the child of spider if found by name
Drawable3D* child(const std::string& name);
std::map<std::string, Part>& parts();
// Upcasts a Drawable3D objet to a Spider object, if possible.
static Spider* upcast(Drawable3D* drawable);
static std::map<std::string, Part> SPIDER_PARTS;
private:
static std::map<std::string, btTransform> SPIDER_POSITIONS;
PhysicsElements* mElements;
std::shared_ptr<PhysicsMesh> mMesh;
std::map<std::string, Part> mParts;
};
| 25.78125 | 78 | 0.640606 | Reewr |
c0ce39bc7242daa28c2ced6a9563a9bf468294d6 | 1,532 | cc | C++ | src/server/Server.cc | kevinpolossat/rtype | 605707c430c4b5e6ebd2a19f8131ee59a1e990c5 | [
"MIT"
] | 5 | 2018-01-23T18:13:08.000Z | 2018-01-28T21:10:38.000Z | src/server/Server.cc | kevinpolossat/rtype | 605707c430c4b5e6ebd2a19f8131ee59a1e990c5 | [
"MIT"
] | 4 | 2018-01-10T15:56:30.000Z | 2018-01-28T16:08:57.000Z | src/server/Server.cc | polosskevin/rtype | 605707c430c4b5e6ebd2a19f8131ee59a1e990c5 | [
"MIT"
] | null | null | null | //
// Created by Kévin POLOSSAT on 14/01/2018.
//
#include <memory>
#include <iostream>
#include "Server.h"
#include "Resolver.h"
#include "Launcher.h"
Server::Server(): reactor_(), acceptor_(reactor_), gameManager_(std::make_unique<rtype::Launcher>()) {
lw_network::Reactor reactor;
lw_network::Resolver re;
re
.SetService("4242")
.SetFamily(AF_UNSPEC)
.SetSockType(SOCK_STREAM)
.SetFlags(AI_PASSIVE);
int yes = 1;
lw_network::error_code e = lw_network::no_error;
auto p = re.Resolve();
for (auto const & endPoint : p) {
e = lw_network::no_error;
acceptor_.open(endPoint.protocol(), e);
if (e) {
continue;
}
acceptor_.setOption(SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int), e);
acceptor_.bind(endPoint, e);
if (e) {
acceptor_.close(e);
continue;
}
break;
}
if (!acceptor_.isOpen()) {
std::cerr << "FAIL" << std::endl;
return ;
}
acceptor_.listen(SOMAXCONN, e);
if (e) {
std::cerr << "FAIL listen" << std::endl;
return ;
}
doAccept_();
}
void Server::run() {
reactor_.handleEvents();
}
void Server::doAccept_() {
acceptor_.asyncAccept(
[this](lw_network::ReactiveSocket peer, lw_network::error_code ec) {
connectionManager_.start(std::make_shared<Connection>(std::move(peer), connectionManager_, gameManager_));
this->doAccept_();
}
);
}
| 25.533333 | 122 | 0.575718 | kevinpolossat |
c0cf653f657e9df21c81ba65e7ba185dd477540b | 2,410 | cpp | C++ | Source/Runtime/Private/Scripting/Math/LuaModule_RectF.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 410 | 2017-03-03T08:56:54.000Z | 2022-03-29T07:18:46.000Z | Source/Runtime/Private/Scripting/Math/LuaModule_RectF.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 31 | 2017-03-05T11:37:44.000Z | 2021-09-15T21:28:34.000Z | Source/Runtime/Private/Scripting/Math/LuaModule_RectF.cpp | redchew-fork/BlueshiftEngine | fbc374cbc391e1147c744649f405a66a27c35d89 | [
"Apache-2.0"
] | 48 | 2017-03-18T05:28:21.000Z | 2022-03-05T12:27:17.000Z | // Copyright(c) 2017 POLYGONTEK
//
// 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 "Precompiled.h"
#include "Scripting/LuaVM.h"
#include "Math/Math.h"
BE_NAMESPACE_BEGIN
void LuaVM::RegisterRectF(LuaCpp::Module &module) {
LuaCpp::Selector _RectF = module["RectF"];
_RectF.SetClass<RectF>();
_RectF.AddClassCtor<RectF, float, float, float, float>();
_RectF.AddClassMembers<RectF>(
"x", &RectF::x,
"y", &RectF::y,
"w", &RectF::w,
"h", &RectF::h,
"__tostring", static_cast<const char*(RectF::*)(void)const>(&RectF::ToString),
"element", static_cast<float &(RectF::*)(int)>(&RectF::operator[]), // index start from zero
"assign", static_cast<RectF&(RectF::*)(const RectF&)>(&RectF::operator=),
"set", &RectF::Set,
"set_4coords", &RectF::SetFrom4Coords,
"is_empty", &RectF::IsEmpty,
"is_contain_point", static_cast<bool(RectF::*)(const PointF&)const>(&RectF::IsContainPoint),
"is_contain_rect", static_cast<bool(RectF::*)(const RectF&)const>(&RectF::IsContainRect),
"is_intersect_rect", static_cast<bool(RectF::*)(const RectF&)const>(&RectF::IsIntersectRect),
"add", static_cast<RectF(RectF::*)(const RectF&)const>(&RectF::Add),
"add_self", &RectF::AddSelf,
"add_point", static_cast<RectF(RectF::*)(const PointF&)const>(&RectF::AddPoint),
"add_point_self", &RectF::AddPointSelf,
"intersect", static_cast<RectF(RectF::*)(const RectF&)const>(&RectF::Intersect),
"intersect_self", &RectF::IntersectSelf,
"move", &RectF::Move,
"move_self", &RectF::MoveSelf,
"shrink", &RectF::Shrink,
"shrink_self", &RectF::ShrinkSelf,
"expand", &RectF::Expand,
"expand_self", &RectF::ExpandSelf,
"to_string", static_cast<const char*(RectF::*)()const>(&RectF::ToString));
}
BE_NAMESPACE_END
| 43.035714 | 101 | 0.655602 | redchew-fork |
c0d50317ce1222cc731771e9bfadf8da7a451eb8 | 22,104 | cpp | C++ | MoravaEngine/src/Platform/DX11/DX11TestLayer.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | null | null | null | MoravaEngine/src/Platform/DX11/DX11TestLayer.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | null | null | null | MoravaEngine/src/Platform/DX11/DX11TestLayer.cpp | imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine | b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b | [
"Apache-2.0"
] | 1 | 2022-01-05T03:51:02.000Z | 2022-01-05T03:51:02.000Z | #include "DX11TestLayer.h"
#include "H2M/Renderer/TextureH2M.h"
#include "H2M/Scene/ComponentsH2M.h"
#include "DX11Context.h"
#include "DX11SwapChain.h"
#include "DX11Renderer.h"
#include "DX11Shader.h"
#include "DX11InputSystem.h"
#include "Core/Application.h"
#include "Core/ResourceManager.h"
#include "Platform/Windows/WindowsWindow.h"
std::shared_ptr<DX11CameraFP> DX11TestLayer::s_Camera;
glm::vec2 DX11TestLayer::s_StartMousePosition;
H2M::RefH2M<DX11Mesh> DX11TestLayer::s_Mesh;
H2M::RefH2M<H2M::MeshH2M> DX11TestLayer::s_MeshLight;
H2M::RefH2M<H2M::MeshH2M> DX11TestLayer::s_SkyboxSphere;
// Render meshes with materials
std::vector<RenderObject> DX11TestLayer::s_RenderObjectsWithMaterials;
std::vector<H2M::RefH2M<DX11Material>> DX11TestLayer::s_ListMaterials;
ImGuizmo::OPERATION DX11TestLayer::s_ImGuizmoType;
bool DX11TestLayer::s_LeftControlKeyPressed = false;
bool DX11TestLayer::s_ShowWindowSceneHierarchy = true;
bool DX11TestLayer::s_ShowWindowAssetManager = true;
bool DX11TestLayer::s_ShowWindowMaterialEditor = true;
H2M::RefH2M<H2M::SceneH2M> DX11TestLayer::s_Scene;
glm::mat4 DX11TestLayer::s_CurrentlySelectedTransform;
float DX11TestLayer::s_ViewportWidth = 0.0f;
float DX11TestLayer::s_ViewportHeight = 0.0f;
glm::vec2 DX11TestLayer::s_ViewportBounds[2];
bool DX11TestLayer::s_AllowViewportCameraEvents = true;
H2M::SceneHierarchyPanelH2M* DX11TestLayer::s_SceneHierarchyPanel;
H2M::ContentBrowserPanelH2M* DX11TestLayer::s_ContentBrowserPanel;
MaterialEditorPanel* DX11TestLayer::s_MaterialEditorPanel;
DX11TestLayer::DX11TestLayer()
{
s_Camera = std::make_shared<DX11CameraFP>(glm::perspectiveFov(glm::radians(60.0f), 1280.0f, 720.0f, 0.1f, 1000.0f));
}
DX11TestLayer::DX11TestLayer(const std::string& name) : MoravaLayer(name)
{
s_Camera = std::make_shared<DX11CameraFP>(glm::perspectiveFov(glm::radians(60.0f), 1280.0f, 720.0f, 0.1f, 1000.0f));
}
DX11TestLayer::~DX11TestLayer()
{
}
void DX11TestLayer::OnAttach()
{
DX11InputSystem::Get()->AddListener(this);
s_Scene = H2M::RefH2M<H2M::SceneH2M>::Create();
s_SceneHierarchyPanel = new H2M::SceneHierarchyPanelH2M(s_Scene);
s_ContentBrowserPanel = new H2M::ContentBrowserPanelH2M();
s_MaterialEditorPanel = new MaterialEditorPanel();
// Application::Get()->GetWindow()->SetInFocus(false);
DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = true);
H2M::RefH2M<H2M::MeshH2M> meshSphere = H2M::RefH2M<H2M::MeshH2M>::Create("Models/PardCode/sphere_hq.obj");
/*
RenderObject renderObjectGladiator;
renderObjectGladiator.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/Gladiator/Gladiator.fbx");
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_weapon_BaseColor.jpg"));
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_weapon_Normal.jpg"));
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_BaseColor.jpg"));
renderObjectGladiator.Textures.push_back(ResourceManager::LoadHazelTexture2D("Models/Gladiator/Gladiator_Normal.jpg"));
renderObjectGladiator.Transform = glm::mat4(1.0f);
renderObjectGladiator.Transform = glm::translate(renderObjectGladiator.Transform, glm::vec3(0.0f, 0.0f, -2.0f));
renderObjectGladiator.Transform = glm::scale(renderObjectGladiator.Transform, glm::vec3(0.04f));
renderObjectGladiator.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectGladiator);
RenderObject renderObjectCerberus;
renderObjectCerberus.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/Cerberus/CerberusMaterials.fbx");
renderObjectCerberus.Textures.push_back(renderObjectCerberus.Mesh->GetTextures().at(0));
renderObjectCerberus.Textures.push_back(renderObjectCerberus.Mesh->GetTextures().at(1));
renderObjectCerberus.Transform = glm::mat4(1.0f);
renderObjectCerberus.Transform = glm::translate(renderObjectCerberus.Transform, glm::vec3(0.0f, 4.0f, 14.0f));
renderObjectCerberus.Transform = glm::rotate(renderObjectCerberus.Transform, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f));
renderObjectCerberus.Transform = glm::rotate(renderObjectCerberus.Transform, glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f));
renderObjectCerberus.Transform = glm::scale(renderObjectCerberus.Transform, glm::vec3(4.0f));
renderObjectCerberus.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectCerberus);
RenderObject renderObjectSphereLeft;
renderObjectSphereLeft.Mesh = meshSphere;
renderObjectSphereLeft.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg"));
renderObjectSphereLeft.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg"));
renderObjectSphereLeft.Transform = glm::mat4(1.0f);
renderObjectSphereLeft.Transform = glm::translate(renderObjectSphereLeft.Transform, glm::vec3(-4.0f, 2.0f, 0.0f));
renderObjectSphereLeft.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectSphereLeft);
RenderObject renderObjectSphereRight;
renderObjectSphereRight.Mesh = meshSphere;
renderObjectSphereRight.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg"));
renderObjectSphereRight.Textures.push_back(ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg"));
renderObjectSphereRight.Transform = glm::mat4(1.0f);
renderObjectSphereRight.Transform = glm::translate(renderObjectSphereRight.Transform, glm::vec3(4.0f, 2.0f, 0.0f));
renderObjectSphereRight.PipelineType = RenderObject::PipelineType::Light;
m_RenderObjects.push_back(renderObjectSphereRight);
*/
RenderObject renderObjectTerrain;
renderObjectTerrain.Mesh = H2M::RefH2M<H2M::MeshH2M>::Create("Models/PardCode/terrain.obj");
renderObjectTerrain.Textures.push_back(ResourceManager::LoadTexture2D_H2M("Textures/PardCode/sand.jpg", true));
renderObjectTerrain.Textures.push_back(ResourceManager::LoadTexture2D_H2M("Textures/PardCode/normal_blank.png", false));
renderObjectTerrain.Transform = glm::mat4(1.0f);
renderObjectTerrain.Transform = glm::scale(renderObjectTerrain.Transform, glm::vec3(4.0f));
renderObjectTerrain.PipelineType = RenderObject::PipelineType::Unlit;
m_RenderObjects.push_back(renderObjectTerrain);
// ---- other assets ----
ResourceManager::LoadTexture2D_H2M("Textures/PardCode/sky.jpg", true);
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/wood.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/normal_blank.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_d.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/brick_n.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/default_material_albedo.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/normal_blank.png");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/umhlanga_sunrise_4k.jpg");
// ResourceManager::LoadHazelTexture2D("Textures/PardCode/gold.png");
// ResourceManager::LoadHazelTexture2D("Textures/container/container2.png");
// ResourceManager::LoadHazelTexture2D("Textures/container/container2_normal.png");
s_Mesh = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/teapot.obj");
// s_Mesh = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/spaceship.obj");
s_MeshLight = meshSphere;
s_SkyboxSphere = meshSphere;
/**** BEGIN Pipeline Unlit ****/
H2M::PipelineSpecificationH2M pipelineSpecUnlit;
pipelineSpecUnlit.DebugName = "Pipeline Unlit";
pipelineSpecUnlit.Layout = H2M::VertexBufferLayoutH2M{};
MoravaShaderSpecification moravaShaderSpecificationUnlit;
moravaShaderSpecificationUnlit.ShaderType = MoravaShaderSpecification::ShaderType::DX11Shader;
moravaShaderSpecificationUnlit.VertexShaderPath = "Shaders/HLSL/UnlitVertexShader.hlsl";
moravaShaderSpecificationUnlit.PixelShaderPath = "Shaders/HLSL/UnlitPixelShader.hlsl";
moravaShaderSpecificationUnlit.ForceCompile = false;
ResourceManager::CreateOrLoadShader(moravaShaderSpecificationUnlit);
pipelineSpecUnlit.Shader = ResourceManager::CreateOrLoadShader(moravaShaderSpecificationUnlit);
H2M::RefH2M<DX11Pipeline> pipelineUnlit = DX11Pipeline::Create(pipelineSpecUnlit);
/**** END Pipeline Unlit ****/
/**** BEGIN Pipeline Illuminated ****/
H2M::PipelineSpecificationH2M pipelineSpecIlluminated;
pipelineSpecIlluminated.DebugName = "Pipeline Illuminated";
pipelineSpecIlluminated.Layout = H2M::VertexBufferLayoutH2M{};
MoravaShaderSpecification moravaShaderSpecificationIlluminated;
moravaShaderSpecificationIlluminated.ShaderType = MoravaShaderSpecification::ShaderType::DX11Shader;
moravaShaderSpecificationIlluminated.VertexShaderPath = "Shaders/HLSL/DirLightVertexShader.hlsl";
moravaShaderSpecificationIlluminated.PixelShaderPath = "Shaders/HLSL/DirLightPixelShader.hlsl";
moravaShaderSpecificationIlluminated.ForceCompile = false;
pipelineSpecIlluminated.Shader = ResourceManager::CreateOrLoadShader(moravaShaderSpecificationIlluminated);
H2M::RefH2M<DX11Pipeline> pipelineIlluminated = DX11Pipeline::Create(pipelineSpecIlluminated);
/**** END Pipeline Illuminated ****/
/**** BEGIN Create meshes with materials ****
H2M::RefH2M<DX11Material> materialIlluminated = H2M::RefH2M<DX11Material>::Create(pipelineIlluminated, "Material Illuminated");
H2M::RefH2M<DX11Material> materialUnlit = H2M::RefH2M<DX11Material>::Create(pipelineIlluminated, "Material Unlit");
H2M::RefH2M<DX11Material> materialIlluminatedDerived = H2M::RefH2M<DX11Material>::Create(materialIlluminated, "Material Illuminated Derived");
H2M::RefH2M<DX11Material> materialUnlitDerived = H2M::RefH2M<DX11Material>::Create(materialUnlit, "Material Unlit Derived");
// BEGIN prepare data for rendering meshes with materials (render objects and the list of materials)
// std::vector<RenderObject> DX11TestLayer::s_RenderObjectsWithMaterials;
// std::vector<H2M::RefH2M<DX11Material>> DX11TestLayer::s_ListMaterials;
s_ListMaterials.reserve(32); // reserve 32 slots
H2M::RefH2M<Hazel::HazelTexture2D> textureBarrel = ResourceManager::LoadHazelTexture2D("Textures/PardCode/barrel.jpg");
H2M::RefH2M<Hazel::HazelTexture2D> textureHouseBrick = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_brick.jpg");
H2M::RefH2M<Hazel::HazelTexture2D> textureHouseWindows = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_windows.jpg");
H2M::RefH2M<Hazel::HazelTexture2D> textureHouseWood = ResourceManager::LoadHazelTexture2D("Textures/PardCode/house_wood.jpg");
H2M::RefH2M<DX11Material> materialBarrel = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material Barrel");
H2M::RefH2M<DX11Material> materialHouseBrick = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Brick");
H2M::RefH2M<DX11Material> materialHouseWindows = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Windows");
H2M::RefH2M<DX11Material> materialHouseWood = DX11Material::Create(pipelineSpecIlluminated.Shader, "Material House Wood");
materialBarrel->AddTexture(textureBarrel.As<DX11Texture2D>());
materialHouseBrick->AddTexture(textureHouseBrick.As<DX11Texture2D>());
materialHouseWindows->AddTexture(textureHouseWindows.As<DX11Texture2D>());
materialHouseWood->AddTexture(textureHouseWood.As<DX11Texture2D>());
s_ListMaterials.push_back(materialBarrel);
s_ListMaterials.push_back(materialHouseBrick);
s_ListMaterials.push_back(materialHouseWindows);
s_ListMaterials.push_back(materialHouseWood);
RenderObject renderObjectHouse;
renderObjectHouse.MeshDX11 = H2M::RefH2M<DX11Mesh>::Create(L"Models/PardCode/house.obj");
renderObjectHouse.Transform = glm::mat4(1.0f);
renderObjectHouse.Transform = glm::translate(renderObjectHouse.Transform, glm::vec3(0.0f, 0.0f, -20.0f));
renderObjectHouse.Transform = glm::scale(renderObjectHouse.Transform, glm::vec3(6.0f));
renderObjectHouse.PipelineType = RenderObject::PipelineType::Light;
s_RenderObjectsWithMaterials.push_back(renderObjectHouse);
/**** END Create meshes with materials ****/
// END prepare data for rendering meshes with materials (render objects and the list of materials)
}
void DX11TestLayer::OnDetach()
{
}
void DX11TestLayer::OnUpdate(H2M::TimestepH2M ts)
{
bool windowInFocus = Application::Get()->GetWindow()->IsInFocus();
bool cameraEnabled = windowInFocus; // && !m_ShowMouseCursor;
s_Camera->SetEnabled(cameraEnabled);
// Log::GetLogger()->info("windowInFocus: {0}, m_ShowMouseCursor: {1}, cameraEnabled: {2}", windowInFocus, m_ShowMouseCursor, cameraEnabled);
DX11InputSystem::Get()->Update();
s_Camera->OnUpdate(ts);
s_Camera->SetProjectionMatrix(
glm::perspectiveFov(glm::radians(60.0f), (float)DX11Renderer::GetViewportWidth(), (float)DX11Renderer::GetViewportHeight(), 0.01f, 1000.0f));
glm::vec4 clearColor = { 0.1f, 0.1f, 0.1f, 1.0f };
Render(clearColor, s_Camera);
for (RenderObject renderObject : m_RenderObjects)
{
DX11Renderer::SubmitMesh(renderObject);
}
}
void DX11TestLayer::OnEvent(H2M::EventH2M& event)
{
s_Camera->OnEvent(event);
if (event.GetEventType() == H2M::EventTypeH2M::WindowResize)
{
H2M::WindowResizeEventH2M& e = (H2M::WindowResizeEventH2M&)event;
if (e.GetWidth() != 0 && e.GetHeight() != 0)
{
s_Camera->SetViewportSize((float)e.GetWidth(), (float)e.GetHeight());
s_Camera->SetProjectionMatrix(glm::perspectiveFov(glm::radians(60.0f), (float)e.GetWidth(), (float)e.GetHeight(), 0.1f, 1000.0f));
}
}
}
void DX11TestLayer::ShowExampleAppDockSpace(bool* p_open, Window* mainWindow)
{
}
void DX11TestLayer::OnRender(Window* mainWindow, Scene* scene)
{
DX11Renderer::Draw(scene->GetCamera());
}
void DX11TestLayer::OnImGuiRender(Window* mainWindow, Scene* scene)
{
}
void DX11TestLayer::Render(const glm::vec4& clearColor, std::shared_ptr<DX11CameraFP> camera)
{
}
void DX11TestLayer::OnKeyDown(int key)
{
if (key == VK_LCONTROL)
{
s_LeftControlKeyPressed = true;
}
}
void DX11TestLayer::OnKeyUp(int key)
{
if (key == VK_ESCAPE)
{
// Application::Get()->GetWindow()->SetInFocus(false);
DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = true);
}
if (key == 'F')
{
m_FullscreenEnabled = !m_FullscreenEnabled;
WindowsWindow* windowsWindow = (WindowsWindow*)Application::Get()->GetWindow();
RECT windowRECT = windowsWindow->GetSizeScreen();
uint32_t width = windowRECT.right; // - windowRECT.left;
uint32_t height = windowRECT.bottom; // - windowRECT.top;
DX11Context::Get()->GetSwapChain()->SetFullScreen(m_FullscreenEnabled, width, height);
}
// ImGizmo switching modes
switch (key)
{
case '1':
s_ImGuizmoType = ImGuizmo::OPERATION::TRANSLATE;
break;
case '2':
s_ImGuizmoType = ImGuizmo::OPERATION::ROTATE;
break;
case '3':
s_ImGuizmoType = ImGuizmo::OPERATION::SCALE;
break;
case '4':
s_ImGuizmoType = (ImGuizmo::OPERATION)-1;
break;
}
if (key == VK_LCONTROL)
{
s_LeftControlKeyPressed = false;
}
if (s_LeftControlKeyPressed)
{
if (key == 'H')
{
s_ShowWindowSceneHierarchy = !s_ShowWindowSceneHierarchy;
Log::GetLogger()->info("s_ShowWindowSceneHierarchy: {0}", s_ShowWindowSceneHierarchy);
}
if (key == VK_SPACE)
{
s_ShowWindowAssetManager = !s_ShowWindowAssetManager;
Log::GetLogger()->info("s_ShowWindowAssetManager: {0}", s_ShowWindowAssetManager);
}
if (key == 'M')
{
s_ShowWindowMaterialEditor = !s_ShowWindowMaterialEditor;
Log::GetLogger()->info("s_ShowWindowMaterialEditor: {0}", s_ShowWindowMaterialEditor);
}
}
}
void DX11TestLayer::OnMouseMove(const glm::vec2& mousePosDelta, const glm::vec2& mousePosAbs)
{
}
void DX11TestLayer::OnLeftMouseDown(const glm::vec2& mousePos)
{
// MOUSE events
POINT currentMousePos = {};
::GetCursorPos(¤tMousePos);
s_StartMousePosition = glm::vec2(currentMousePos.x, currentMousePos.y);
if (DX11InputSystem::Get()->IsMouseCursorAboveViewport())
{
Application::Get()->GetWindow()->SetInFocus(true);
}
// DX11InputSystem::Get()->ShowCursor(m_ShowMouseCursor = false);
// Log::GetLogger()->info("DX11TestLayer::OnLeftMouseDown {0}x{1}", mousePos.x, mousePos.y);
// bool windowInFocus = Application::Get()->GetWindow()->IsInFocus();
// Log::GetLogger()->info("Window::m_InFocus: {0}, m_ShowMouseCursor: {1}, m_Camera->IsEnabled: {2}",
// windowInFocus, m_ShowMouseCursor, DX11CameraFP::Get()->IsEnabled());
OnLeftMouseDownEventHandler(mousePos);
}
void DX11TestLayer::OnRightMouseDown(const glm::vec2& mousePos)
{
}
void DX11TestLayer::OnLeftMouseUp(const glm::vec2& mousePos)
{
}
void DX11TestLayer::OnRightMouseUp(const glm::vec2& mousePos)
{
}
bool DX11TestLayer::OnLeftMouseDownEventHandler(const glm::vec2& mousePos)
{
float mx = mousePos.x;
float my = mousePos.y;
Log::GetLogger()->debug("DX11TestLayer::OnLeftMouseDownEventHandler mousePos.x: {0}, mousePos.y: {1}", mousePos.x, mousePos.y);
if (!ImGuizmo::IsUsing() && !ImGuizmo::IsOver())
{
auto [mouseX, mouseY] = GetMouseViewportSpace();
Log::GetLogger()->debug("DX11TestLayer::OnLeftMouseDownEventHandler GetMouseViewportSpace mouseX: {0}, mouseY: {1}", mouseX, mouseY);
if (mouseX > -1.0f && mouseX < 1.0f && mouseY > -1.0f && mouseY < 1.0f)
{
auto [origin, direction] = CastRay(mouseX, mouseY);
EntitySelection::s_SelectionContext.clear();
auto meshEntities = s_Scene->GetAllEntitiesWith<H2M::MeshComponentH2M>();
for (auto e : meshEntities)
{
H2M::EntityH2M entity = { e, s_Scene.Raw() };
auto mesh = entity.GetComponent<H2M::MeshComponentH2M>().Mesh;
if (!mesh) {
continue;
}
std::vector<H2M::RefH2M<H2M::SubmeshH2M>>& submeshes = mesh->GetSubmeshes();
float lastT = std::numeric_limits<float>::max(); // Distance between camera and intersection in CastRay
// for (Hazel::Submesh& submesh : submeshes)
for (uint32_t i = 0; i < submeshes.size(); i++)
{
H2M::RefH2M<H2M::SubmeshH2M> submesh = submeshes[i];
auto transform = entity.GetComponent<H2M::TransformComponentH2M>().GetTransform();
H2M::RayH2M ray = {
glm::inverse(transform * submesh->Transform) * glm::vec4(origin, 1.0f),
glm::inverse(glm::mat3(transform) * glm::mat3(submesh->Transform)) * direction
};
float t;
bool intersects = ray.IntersectsAABB(submesh->BoundingBox, t);
if (intersects)
{
const auto& triangleCache = ((H2M::MeshH2M*)mesh.Raw())->GetTriangleCache(i);
if (triangleCache.size())
{
for (const auto& triangle : triangleCache)
{
if (ray.IntersectsTriangle(triangle.V0.Position, triangle.V1.Position, triangle.V2.Position, t))
{
AddSubmeshToSelectionContext({ entity, submesh, t });
Log::GetLogger()->debug("Adding submesh to selection context. Submesh Name: '{0}', selection size: '{1}'",
submesh->MeshName, EntitySelection::s_SelectionContext.size());
break;
}
}
}
else {
AddSubmeshToSelectionContext({ entity, submesh, t });
}
}
}
}
std::sort(EntitySelection::s_SelectionContext.begin(), EntitySelection::s_SelectionContext.end(), [](auto& a, auto& b) { return a.Distance < b.Distance; });
// TODO: Handle mesh being deleted, etc
if (EntitySelection::s_SelectionContext.size()) {
s_CurrentlySelectedTransform = EntitySelection::s_SelectionContext[0].Mesh->Transform;
OnSelected(EntitySelection::s_SelectionContext[0]);
}
else {
RefH2M<H2M::EntityH2M> meshEntity = GetMeshEntity();
if (meshEntity) {
s_CurrentlySelectedTransform = meshEntity->Transform().GetTransform();
}
}
}
}
return false;
}
std::pair<float, float> DX11TestLayer::GetMouseViewportSpace()
{
auto [mx, my] = ImGui::GetMousePos(); // Input::GetMousePosition();
mx -= s_ViewportBounds[0].x;
my -= s_ViewportBounds[0].y;
s_ViewportWidth = s_ViewportBounds[1].x - s_ViewportBounds[0].x;
s_ViewportHeight = s_ViewportBounds[1].y - s_ViewportBounds[0].y;
return { (mx / s_ViewportWidth) * 2.0f - 1.0f, ((my / s_ViewportHeight) * 2.0f - 1.0f) * -1.0f };
}
std::pair<glm::vec3, glm::vec3> DX11TestLayer::CastRay(float mx, float my)
{
glm::vec4 mouseClipPos = { mx, my, -1.0f, 1.0f };
glm::mat4 projectionMatrix = s_Camera->GetProjectionMatrix();
glm::mat4 viewMatrix = s_Camera->GetViewMatrix();
auto inverseProj = glm::inverse(projectionMatrix);
auto inverseView = glm::inverse(glm::mat3(viewMatrix));
glm::vec4 ray = inverseProj * mouseClipPos;
glm::vec3 rayPos = s_Camera->GetPosition();
glm::vec3 rayDir = inverseView * glm::vec3(ray); // inverseView * glm::vec3(ray)
Log::GetLogger()->debug("DX11TestLayer::CastRay | MousePosition [ {0} {1} ]", mx, my);
Log::GetLogger()->debug("DX11TestLayer::CastRay | m_ViewportBounds[0] [ {0} {1} ]", s_ViewportBounds[0].x, s_ViewportBounds[0].y);
Log::GetLogger()->debug("DX11TestLayer::CastRay | m_ViewportBounds[1] [ {0} {1} ]", s_ViewportBounds[1].x, s_ViewportBounds[1].y);
Log::GetLogger()->debug("DX11TestLayer::CastRay | mouseClipPos [ {0} {1} ]", mouseClipPos.x, mouseClipPos.y);
return { rayPos, rayDir };
}
void DX11TestLayer::AddSubmeshToSelectionContext(SelectedSubmesh submesh)
{
EntitySelection::s_SelectionContext.push_back(submesh);
if (EntitySelection::s_SelectionContext.size() && EntitySelection::s_SelectionContext[0].Mesh) {
Log::GetLogger()->debug("SelectionContext[0].Mesh->MeshName: '{0}'", EntitySelection::s_SelectionContext[0].Mesh->MeshName);
}
}
void DX11TestLayer::OnSelected(const SelectedSubmesh& selectionContext)
{
// TODO: move to SceneHazelEnvMap
s_SceneHierarchyPanel->SetSelected(selectionContext.Entity);
s_Scene->SetSelectedEntity(selectionContext.Entity);
}
RefH2M<H2M::EntityH2M> DX11TestLayer::GetMeshEntity()
{
RefH2M<H2M::EntityH2M> meshEntity;
auto meshEntities = s_Scene->GetAllEntitiesWith<H2M::MeshComponentH2M>();
if (meshEntities.size()) {
for (auto entt : meshEntities)
{
meshEntity = CreateRefH2M<H2M::EntityH2M>(entt, s_Scene.Raw());
}
return meshEntity;
}
return nullptr;
}
| 40.043478 | 159 | 0.76122 | imgui-works |
c0d5dd69f42d0f5e86e1c8a9e266325c6d74e0c8 | 1,258 | cpp | C++ | app/rocnnet/src/compounds/icompound.cpp | mingkaic/rocnnet | b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab | [
"MIT"
] | 3 | 2017-01-18T20:42:56.000Z | 2018-11-07T12:56:15.000Z | app/rocnnet/src/compounds/icompound.cpp | mingkaic/rocnnet | b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab | [
"MIT"
] | 10 | 2016-12-01T08:15:28.000Z | 2018-09-28T17:16:32.000Z | app/rocnnet/src/compounds/icompound.cpp | mingkaic/rocnnet | b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab | [
"MIT"
] | null | null | null | //
// icompound.cpp
// cnnet
//
// Created by Mingkai Chen on 2017-07-17.
// Copyright © 2017 Mingkai Chen. All rights reserved.
//
#include "compounds/mlp.hpp"
#ifdef ROCNNET_ICOMPOUND_HPP
namespace rocnnet
{
icompound::icompound (std::string scope) : ilayer(scope) {}
icompound::~icompound (void) {}
icompound* icompound::clone (std::string scope) const
{
return static_cast<icompound*>(this->clone_impl(scope));
}
icompound* icompound::move (void)
{
return static_cast<icompound*>(this->move_impl());
}
void icompound::initialize (std::string serialname, std::string readscope)
{
if (readscope.empty()) readscope = scope_;
std::vector<nnet::variable<double>*> vars = this->get_variables();
std::vector<nnet::inode<double>*> nv(vars.begin(), vars.end());
if (nnet::read_inorder<double>(nv, readscope, serialname) && nv.empty())
{
return;
}
for (nnet::variable<double>* v : vars)
{
v->initialize();
}
}
bool icompound::save (std::string fname, std::string writescope) const
{
if (writescope.empty()) writescope = scope_;
std::vector<nnet::variable<double>*> vars = this->get_variables();
std::vector<nnet::inode<double>*> nv(vars.begin(), vars.end());
return nnet::write_inorder<double>(nv, writescope, fname);
}
}
#endif | 22.070175 | 74 | 0.694754 | mingkaic |
c0d7c7690aa8b27e6ec9de5f6f6350c20312e689 | 862 | cpp | C++ | cpp-leetcode/leetcode621-task-scheduler_hash_count1.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode621-task-scheduler_hash_count1.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode621-task-scheduler_hash_count1.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include<vector>
#include<unordered_map>
#include<algorithm>
#include<iostream>
using namespace std;
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
unordered_map<char, int> dict;
int maxFreq = -1;
int maxFreqCount = 0;
for (auto& ch : tasks)
dict[ch]++;
for (auto& kvp : dict)
maxFreq = max(maxFreq, kvp.second);
for (auto& kvp : dict)
{
if (kvp.second == maxFreq) maxFreqCount++;
}
int res = 0;
const int len = tasks.size();
res = max((maxFreq - 1)*(n+1) + maxFreqCount, len);
return res;
}
};
// Test
int main()
{
Solution sol;
vector<char> tasks = {'A','A','A','B','B','B'};
int n = 2;
auto res = sol.leastInterval(tasks, n);
cout << res << endl;
return 0;
} | 22.684211 | 59 | 0.524362 | yanglr |
c0d85df88aee6e9cc6daa7c12f5ff143d26b589c | 7,096 | cpp | C++ | Library/ClothSolvers/FEMClothMesh.cpp | rgoldade/ClothSim | 2c2dbef10296777ccf91c5c9ec54f601edc06fbd | [
"MIT"
] | 2 | 2021-07-20T10:08:02.000Z | 2021-09-21T04:24:42.000Z | Library/ClothSolvers/FEMClothMesh.cpp | rgoldade/ClothSim | 2c2dbef10296777ccf91c5c9ec54f601edc06fbd | [
"MIT"
] | null | null | null | Library/ClothSolvers/FEMClothMesh.cpp | rgoldade/ClothSim | 2c2dbef10296777ccf91c5c9ec54f601edc06fbd | [
"MIT"
] | 2 | 2021-06-08T04:01:14.000Z | 2021-09-18T23:03:14.000Z | #include "FEMClothMesh.h"
#include <autodiff/forward.hpp>
#include <autodiff/forward/eigen.hpp>
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
namespace ClothSim
{
static std::vector<double> buildTriangleAreas(const TriMesh& mesh, const VecVec2d& restUVs)
{
std::vector<double> triangleAreas(mesh.triangleCount(), 0);
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range)
{
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
const Vec3i& tri = mesh.triangle(triIndex);
const Vec2d& v0 = restUVs[tri[0]];
const Vec2d& v1 = restUVs[tri[1]];
const Vec2d& v2 = restUVs[tri[2]];
triangleAreas[triIndex] = .5 * std::fabs(v0[0] * (v1[1] - v2[1]) + v1[0] * (v2[1] - v0[1]) + v2[0] * (v0[1] - v1[1]));
}
});
return triangleAreas;
}
static std::vector<double> buildVertexMasses(const TriMesh& mesh, const std::vector<double>& triangleAreas, double density)
{
std::vector<double> vertexMasses(mesh.vertexCount(), 0);
assert(mesh.vertexCount() == mesh.adjacentTriangles().size());
assert(triangleAreas.size() == mesh.triangleCount());
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.vertexCount()), [&](tbb::blocked_range<int>& range)
{
for (int vertexIndex = range.begin(); vertexIndex != range.end(); ++vertexIndex)
{
for (int triIndex : mesh.adjacentTriangles()[vertexIndex])
vertexMasses[vertexIndex] += 1. / 3. * density * triangleAreas[triIndex];
}
});
return vertexMasses;
}
static VecMat2x2d buildDmInv(const TriMesh& mesh, const VecVec2d& restUVs)
{
assert(mesh.vertexCount() == restUVs.size());
VecMat2x2d dmInv(mesh.triangleCount());
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range)
{
Mat2x2d localD;
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
const Vec3i& tri = mesh.triangle(triIndex);
localD.col(0) = restUVs[tri[1]] - restUVs[tri[0]];
localD.col(1) = restUVs[tri[2]] - restUVs[tri[0]];
dmInv[triIndex] = localD.inverse();
}
});
return dmInv;
}
template<typename Scalar>
Vec6t<Scalar> computeF(const Vec6t<Scalar>& D, const Vec4t<Scalar>& Dinv)
{
Mat3x2t<Scalar> Dmat;
Dmat.block(0, 0, 3, 1) = D.block(0, 0, 3, 1);
Dmat.block(0, 1, 3, 1) = D.block(3, 0, 3, 1);
Mat2x2t<Scalar> DinvMat;
DinvMat.block(0, 0, 2, 1) = Dinv.block(0, 0, 2, 1);
DinvMat.block(0, 1, 2, 1) = Dinv.block(2, 0, 2, 1);
Mat3x2t<Scalar> Fmat = Dmat * DinvMat;
Vec6t<Scalar> Fvec;
Fvec.block(0, 0, 3, 1) = Fmat.block(0, 0, 3, 1);
Fvec.block(3, 0, 3, 1) = Fmat.block(0, 1, 3, 1);
return Fvec;
}
static Mat3x2d computeF(const Vec3d& v0, const Vec3d& v1, const Vec3d& v2, const Mat2x2d& DmInv)
{
Mat3x2d Ds;
Ds.col(0) = v1 - v0;
Ds.col(1) = v2 - v0;
return Ds * DmInv;
}
template<typename Scalar>
static Vec6t<Scalar> computeFTemplated(const Vec3t<Scalar>& v0, const Vec3t<Scalar>& v1, const Vec3t<Scalar>& v2, const Mat2x2t<Scalar>& DmInv)
{
Mat3x2t<Scalar> Ds;
Ds.col(0) = v1 - v0;
Ds.col(1) = v2 - v0;
Mat3x2t<Scalar> Fmat = Ds * DmInv;
Vec6t<Scalar> Fvec;
Fvec.block(0, 0, 3, 1) = Fmat.col(0);
Fvec.block(3, 0, 3, 1) = Fmat.col(1);
return Fvec;
}
static Mat6x9d builddFdxAutodiff(const TriMesh& mesh, const VecMat2x2d& DmInv, int triIndex)
{
using autodiff::dual;
using autodiff::forward::jacobian;
using autodiff::forward::at;
using autodiff::forward::wrtpack;
const Vec3i& tri = mesh.triangle(triIndex);
const Vec3d& v0 = mesh.vertex(tri[0]);
const Vec3d& v1 = mesh.vertex(tri[1]);
const Vec3d& v2 = mesh.vertex(tri[2]);
Vec3t<dual> dualV0 = v0.cast<dual>();
Vec3t<dual> dualV1 = v1.cast<dual>();
Vec3t<dual> dualV2 = v2.cast<dual>();
Mat2x2t<dual> dualDmInv = DmInv[triIndex].cast<dual>();
Vec6t<dual> dualF;
Mat6x9d dFdx = jacobian(computeFTemplated<dual>, wrtpack(dualV0, dualV1, dualV2), at(dualV0, dualV1, dualV2, dualDmInv), dualF);
#if !defined(NDEBUG)
Mat3x2d F = computeF(v0, v1, v2, DmInv[triIndex]);
Mat3x2d Fautodiff;
Fautodiff.col(0) = dualF.block(0, 0, 3, 1).cast<double>();
Fautodiff.col(1) = dualF.block(3, 0, 3, 1).cast<double>();
assert((Fautodiff - F).lpNorm<Eigen::Infinity>() < 1e-10);
#endif
return dFdx;
}
static VecMat6x9d builddFdx(const TriMesh& mesh, const VecMat2x2d& DmInv)
{
VecMat6x9d dFdx(mesh.triangleCount(), Mat6x9d::Zero());
tbb::parallel_for(tbb::blocked_range<int>(0, mesh.triangleCount()), [&](tbb::blocked_range<int>& range)
{
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
double s0 = DmInv[triIndex].col(0).sum();
double s1 = DmInv[triIndex].col(1).sum();
double d0 = DmInv[triIndex](0, 0);
double d1 = DmInv[triIndex](1, 0);
double d2 = DmInv[triIndex](0, 1);
double d3 = DmInv[triIndex](1, 1);
// dF / dx0
dFdx[triIndex](0, 0) = -s0;
dFdx[triIndex](3, 0) = -s1;
// dF / dy0
dFdx[triIndex](1, 1) = -s0;
dFdx[triIndex](4, 1) = -s1;
// dF / dz0
dFdx[triIndex](2, 2) = -s0;
dFdx[triIndex](5, 2) = -s1;
// dF / dx1
dFdx[triIndex](0, 3) = d0;
dFdx[triIndex](3, 3) = d2;
// dF / dy1
dFdx[triIndex](1, 4) = d0;
dFdx[triIndex](4, 4) = d2;
// dF / dz1
dFdx[triIndex](2, 5) = d0;
dFdx[triIndex](5, 5) = d2;
// dF / dx2
dFdx[triIndex](0, 6) = d1;
dFdx[triIndex](3, 6) = d3;
// dF / dy2
dFdx[triIndex](1, 7) = d1;
dFdx[triIndex](4, 7) = d3;
// dF / dz2
dFdx[triIndex](2, 8) = d1;
dFdx[triIndex](5, 8) = d3;
#if !defined(NDEBUG)
// Autodiff verification
Mat6x9d dFdxAutodiff = builddFdxAutodiff(mesh, DmInv, triIndex);
assert((dFdx[triIndex] - dFdxAutodiff).lpNorm<Eigen::Infinity>() < 1e-10);
#endif
}
});
return dFdx;
}
FEMClothMesh::FEMClothMesh(const std::vector<int>& fixedVertices,
const double density,
const double stretchStiffness,
const double shearStiffness,
const VecVec2d& restUVs,
const TriMesh& inputMesh)
: TriMesh(inputMesh)
, myVertexVelocities(this->vertexCount(), Vec3d::Zero())
, myFixedVertices(this->vertexCount(), false)
, myDensity(density)
, myStretchStiffness(stretchStiffness)
, myShearStiffness(shearStiffness)
, myRestTriangleAreas(buildTriangleAreas(inputMesh, restUVs))
, myVertexMasses(buildVertexMasses(inputMesh, myRestTriangleAreas, myDensity))
, myDmInv(buildDmInv(inputMesh, restUVs))
, mydFdX(builddFdx(inputMesh, myDmInv))
, myF(this->triangleCount())
, myStateDirty(true)
{
for (int vertIndex : fixedVertices)
myFixedVertices[vertIndex] = true;
computeState();
}
void FEMClothMesh::buildF()
{
tbb::parallel_for(tbb::blocked_range<int>(0, this->triangleCount()), [&](const tbb::blocked_range<int>& range)
{
for (int triIndex = range.begin(); triIndex != range.end(); ++triIndex)
{
const Vec3i& tri = this->triangle(triIndex);
const Vec3d& v0 = this->vertex(tri[0]);
const Vec3d& v1 = this->vertex(tri[1]);
const Vec3d& v2 = this->vertex(tri[2]);
myF[triIndex] = computeF(v0, v1, v2, myDmInv[triIndex]);
}
});
}
void FEMClothMesh::computeState()
{
if (myStateDirty)
{
buildF();
myStateDirty = false;
}
}
} | 27.292308 | 143 | 0.661922 | rgoldade |
c0daa70d55ebb60a9d065a6e0fe9c31f1dc1952b | 7,869 | hpp | C++ | cpp/tanhValues32Bit.hpp | danmcleran/cppnnml | 314fcb34cc7a526e1dc11658a1d758172cd2b7e9 | [
"MIT"
] | 56 | 2020-06-17T17:43:36.000Z | 2022-03-20T22:43:19.000Z | cpp/tanhValues32Bit.hpp | danmcleran/cppnnml | 314fcb34cc7a526e1dc11658a1d758172cd2b7e9 | [
"MIT"
] | 15 | 2020-06-24T16:34:44.000Z | 2021-04-08T22:00:57.000Z | cpp/tanhValues32Bit.hpp | danmcleran/cppnnml | 314fcb34cc7a526e1dc11658a1d758172cd2b7e9 | [
"MIT"
] | 18 | 2020-06-18T13:47:59.000Z | 2022-01-23T21:01:33.000Z | /**
* Copyright (c) 2020 Intel Corporation
*
* 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.
*/
#pragma once
#include "activation.hpp"
namespace tinymind {
#if (defined(TINYMIND_USE_TANH_1_31))
struct TanhValuesTableQ1_31
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_1_31))
#if (defined(TINYMIND_USE_TANH_2_30))
struct TanhValuesTableQ2_30
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_2_30))
#if (defined(TINYMIND_USE_TANH_3_29))
struct TanhValuesTableQ3_29
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_3_29))
#if (defined(TINYMIND_USE_TANH_4_28))
struct TanhValuesTableQ4_28
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_4_28))
#if (defined(TINYMIND_USE_TANH_5_27))
struct TanhValuesTableQ5_27
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_5_27))
#if (defined(TINYMIND_USE_TANH_6_26))
struct TanhValuesTableQ6_26
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_6_26))
#if (defined(TINYMIND_USE_TANH_7_25))
struct TanhValuesTableQ7_25
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_7_25))
#if (defined(TINYMIND_USE_TANH_8_24))
struct TanhValuesTableQ8_24
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_8_24))
#if (defined(TINYMIND_USE_TANH_9_23))
struct TanhValuesTableQ9_23
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_9_23))
#if (defined(TINYMIND_USE_TANH_10_22))
struct TanhValuesTableQ10_22
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_10_22))
#if (defined(TINYMIND_USE_TANH_11_21))
struct TanhValuesTableQ11_21
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_11_21))
#if (defined(TINYMIND_USE_TANH_12_20))
struct TanhValuesTableQ12_20
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_12_20))
#if (defined(TINYMIND_USE_TANH_13_19))
struct TanhValuesTableQ13_19
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_13_19))
#if (defined(TINYMIND_USE_TANH_14_18))
struct TanhValuesTableQ14_18
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_14_18))
#if (defined(TINYMIND_USE_TANH_15_17))
struct TanhValuesTableQ15_17
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_15_17))
#if (defined(TINYMIND_USE_TANH_16_16))
struct TanhValuesTableQ16_16
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_16_16))
#if (defined(TINYMIND_USE_TANH_17_15))
struct TanhValuesTableQ17_15
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_17_15))
#if (defined(TINYMIND_USE_TANH_18_14))
struct TanhValuesTableQ18_14
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_18_14))
#if (defined(TINYMIND_USE_TANH_19_13))
struct TanhValuesTableQ19_13
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_19_13))
#if (defined(TINYMIND_USE_TANH_20_12))
struct TanhValuesTableQ20_12
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_20_12))
#if (defined(TINYMIND_USE_TANH_21_11))
struct TanhValuesTableQ21_11
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_21_11))
#if (defined(TINYMIND_USE_TANH_22_10))
struct TanhValuesTableQ22_10
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_22_10))
#if (defined(TINYMIND_USE_TANH_23_9))
struct TanhValuesTableQ23_9
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_23_9))
#if (defined(TINYMIND_USE_TANH_24_8))
struct TanhValuesTableQ24_8
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_24_8))
#if (defined(TINYMIND_USE_TANH_25_7))
struct TanhValuesTableQ25_7
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_25_7))
#if (defined(TINYMIND_USE_TANH_26_6))
struct TanhValuesTableQ26_6
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_26_6))
#if (defined(TINYMIND_USE_TANH_27_5))
struct TanhValuesTableQ27_5
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_27_5))
#if (defined(TINYMIND_USE_TANH_28_4))
struct TanhValuesTableQ28_4
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_28_4))
#if (defined(TINYMIND_USE_TANH_29_3))
struct TanhValuesTableQ29_3
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_29_3))
#if (defined(TINYMIND_USE_TANH_30_2))
struct TanhValuesTableQ30_2
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_30_2))
#if (defined(TINYMIND_USE_TANH_31_1))
struct TanhValuesTableQ31_1
{
static const uint32_t values[NUMBER_OF_ACTIVATION_TABLE_VALUES];
};
#endif // (defined(TINYMIND_USE_TANH_31_1))
}
| 36.6 | 81 | 0.706697 | danmcleran |
c0dbed743787137efa2b5c4a4acfc82c0fefc37f | 3,914 | cpp | C++ | src/coherence/util/filter/InKeySetFilter.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-01T21:38:30.000Z | 2021-11-03T01:35:11.000Z | src/coherence/util/filter/InKeySetFilter.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 1 | 2020-07-24T17:29:22.000Z | 2020-07-24T18:29:04.000Z | src/coherence/util/filter/InKeySetFilter.cpp | chpatel3/coherence-cpp-extend-client | 4ea5267eae32064dff1e73339aa3fbc9347ef0f6 | [
"UPL-1.0",
"Apache-2.0"
] | 6 | 2020-07-10T18:40:58.000Z | 2022-02-18T01:23:40.000Z | /*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "coherence/util/filter/InKeySetFilter.hpp"
#include "coherence/io/pof/SystemPofContext.hpp"
#include "coherence/util/filter/ExtractorFilter.hpp"
#include "coherence/util/HashSet.hpp"
#include "private/coherence/util/InvocableMapHelper.hpp"
COH_OPEN_NAMESPACE3(coherence,util,filter)
COH_REGISTER_PORTABLE_CLASS(72, InKeySetFilter);
// ----- constructors -------------------------------------------------------
InKeySetFilter::InKeySetFilter()
: f_vFilter(self()), m_vSetKeys(self(), NULL, /* mutable */ true), m_fConverted(false)
{
}
InKeySetFilter::InKeySetFilter(Filter::View vFilter, Set::View vSetKeys)
: f_vFilter(self(), vFilter), m_vSetKeys(self(), vSetKeys, /* mutable */ true),
m_fConverted(false)
{
}
// ----- EntryFilter interface ----------------------------------------------
bool InKeySetFilter::evaluateEntry(Map::Entry::View vEntry) const
{
if (!m_vSetKeys->contains(vEntry->getKey()))
{
return false;
}
return InvocableMapHelper::evaluateEntry(getFilter(), vEntry);
}
// ----- Filter interface ---------------------------------------------------
bool InKeySetFilter::evaluate(Object::View /* v */) const
{
COH_THROW (UnsupportedOperationException::create(
"InKeySetFilter::evaluate"));
}
// ----- IndexAwareFilter interface -----------------------------------------
size32_t InKeySetFilter::calculateEffectiveness(Map::View vMapIndexes,
Set::View vSetKeys) const
{
Filter::View vFilter = f_vFilter;
if (m_vSetKeys->size() < vSetKeys->size())
{
vSetKeys = m_vSetKeys;
}
return instanceof<IndexAwareFilter::View>(vFilter)
? (cast<IndexAwareFilter::View>(vFilter))->calculateEffectiveness(vMapIndexes, vSetKeys)
: vSetKeys->size()*ExtractorFilter::eval_cost;
}
Filter::View InKeySetFilter::applyIndex(Map::View vMapIndexes,
Set::Handle hSetKeys) const
{
hSetKeys->retainAll(m_vSetKeys);
Filter::View vFilter = f_vFilter;
return instanceof<IndexAwareFilter::View>(vFilter)
? (cast<IndexAwareFilter::View>(vFilter))->applyIndex(vMapIndexes, hSetKeys)
: NULL;
}
// ----- PortableObject interface -------------------------------------------
void InKeySetFilter::readExternal(PofReader::Handle hIn)
{
initialize(f_vFilter, cast<Filter::View>(hIn->readObject(0)));
m_vSetKeys = cast<Set::View>(hIn->readObject(1));
}
void InKeySetFilter:: writeExternal(PofWriter::Handle hOut) const
{
hOut->writeObject(0, getFilter());
hOut->writeObject(1, m_vSetKeys);
}
// ----- Object interface ---------------------------------------------------
TypedHandle<const String> InKeySetFilter::toString() const
{
return COH_TO_STRING("InKeySetFilter(" << getFilter() << ", keys=" << m_vSetKeys << ')');
}
// ----- data member accessors ----------------------------------------------
Filter::View InKeySetFilter::getFilter() const
{
return f_vFilter;
}
Set::View InKeySetFilter::getKeys() const
{
return m_vSetKeys;
}
// ----- helpers ------------------------------------------------------------
void InKeySetFilter::ensureConverted(Converter::View vConverter) const
{
COH_SYNCHRONIZED (this)
{
if (!m_fConverted)
{
HashSet::Handle hSetConv = HashSet::create();
for (Iterator::Handle iter = m_vSetKeys->iterator(); iter->hasNext();)
{
hSetConv->add(vConverter->convert(iter->next()));
}
m_vSetKeys = hSetConv;
m_fConverted = true;
}
}
}
COH_CLOSE_NAMESPACE3
| 28.362319 | 100 | 0.579969 | chpatel3 |
c0ded1ea466b2e8c2b64d8984c78eff2192c22d9 | 760 | cpp | C++ | bit/next_combination.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | bit/next_combination.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | bit/next_combination.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>;
/* next combination */
int next_combination(int sub) {
int x = sub & -sub, y = sub + x;
return (((sub & ~y) / x) >> 1) | y;
}
int main() {
int n = 5; // {0, 1, 2, 3, 4} の部分集合を考える
int k = 3;
int bit = (1 << k) - 1; // bit = {0, 1, 2}
for (; bit < (1 << n); bit = next_combination(bit)) {
/* ここに処理を書く */
/* きちんとできていることを確認してみる */
// bit の表す集合を求める
vector<int> s;
rep(i, n) {
if (bit & (1 << i)) { // i が bit に入るかどうか
s.push_back(i);
}
}
// bit の表す集合の出力
cout << bit << ": {";
rep(i, s.size()) { cout << s[i] << " "; }
cout << "}" << endl;
}
} | 21.714286 | 55 | 0.465789 | Takumi1122 |
c0e3aced600bbef60ab4a4bb6635e233b10ffb74 | 1,181 | hpp | C++ | apps/duck_charmer/wrapper_cursor.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 7 | 2019-06-02T12:04:22.000Z | 2019-10-15T18:01:21.000Z | apps/duck_charmer/wrapper_cursor.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 26 | 2019-10-27T12:58:42.000Z | 2020-05-30T16:43:48.000Z | apps/duck_charmer/wrapper_cursor.hpp | jinntechio/RocketJoe | 9b08a21fda1609c57b40ef8b9750897797ac815b | [
"BSD-3-Clause"
] | 1 | 2019-10-03T13:36:36.000Z | 2019-10-03T13:36:36.000Z | #pragma once
#include <components/cursor/cursor.hpp>
#include <components/session/session.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include "forward.hpp"
namespace py = pybind11;
class PYBIND11_EXPORT wrapper_cursor final : public boost::intrusive_ref_counter<wrapper_cursor> {
public:
using type = components::cursor::cursor_t;
using pointer = type*;
wrapper_cursor(components::session::session_id_t session, pointer cursor);
void close();
bool has_next();
wrapper_cursor &next();
wrapper_cursor &iter();
std::size_t size();
py::object get(py::object key);
std::string print();
wrapper_cursor &sort(py::object sorter, py::object order);
//paginate();
//_order();
private:
std::atomic_bool close_;
duck_charmer::session_id_t session_;
pointer ptr_;
actor_zeta::address_t dispatcher_;
py::object get_(const std::string &key) const;
py::object get_(std::size_t index) const;
};
using wrapper_cursor_ptr = boost::intrusive_ptr<wrapper_cursor>;
| 25.12766 | 100 | 0.718882 | jinntechio |
c0e839a5180c52e9018496e7e95d772cf7b0f848 | 3,942 | cpp | C++ | apps/hexagon_dma/process_raw_linear_ro_basic_interleaved.cpp | mbrukman/Halide | 8a08a705044c2da42581f1255ccae9e34030f703 | [
"MIT"
] | 2 | 2018-12-27T17:46:11.000Z | 2019-04-19T23:01:35.000Z | apps/hexagon_dma/process_raw_linear_ro_basic_interleaved.cpp | mbrukman/Halide | 8a08a705044c2da42581f1255ccae9e34030f703 | [
"MIT"
] | null | null | null | apps/hexagon_dma/process_raw_linear_ro_basic_interleaved.cpp | mbrukman/Halide | 8a08a705044c2da42581f1255ccae9e34030f703 | [
"MIT"
] | 1 | 2021-04-30T05:14:03.000Z | 2021-04-30T05:14:03.000Z | #include <stdio.h>
#include <memory.h>
#include <assert.h>
#include <stdlib.h>
#include "halide_benchmark.h"
#include "pipeline_raw_linear_ro_basic_interleaved.h"
#include "pipeline_raw_linear_ro_fold_interleaved.h"
#include "pipeline_raw_linear_ro_async_interleaved.h"
#include "pipeline_raw_linear_ro_split_interleaved.h"
#include "pipeline_raw_linear_ro_split_fold_interleaved.h"
#include "HalideRuntimeHexagonDma.h"
#include "HalideBuffer.h"
int main(int argc, char **argv) {
int ret = 0;
if (argc < 4) {
printf("Usage: %s width height func {basic, fold, async, split, split_fold} \n", argv[0]);
return ret;
}
const int width = atoi(argv[1]);
const int height = atoi(argv[2]);
const char *str = argv[3];
// Fill the input buffer with random test data. This is just a plain old memory buffer
const int buf_size = width * height * 4;
uint8_t *data_in = (uint8_t *)malloc(buf_size);
// Creating the Input Data so that we can catch if there are any Errors in DMA
for (int i = 0; i < buf_size; i++) {
data_in[i] = ((uint8_t)rand()) >> 1;
}
// Setup Halide input buffer with the test buffer
Halide::Runtime::Buffer<uint8_t> input(nullptr, width, height, 4);
input = input.make_interleaved(width, height, 4);
// DMA_step 1: Assign buffer to DMA interface
input.device_wrap_native(halide_hexagon_dma_device_interface(), reinterpret_cast<uint64_t>(data_in));
input.set_device_dirty();
// DMA_step 2: Allocate a DMA engine
void *dma_engine = nullptr;
halide_hexagon_dma_allocate_engine(nullptr, &dma_engine);
// DMA_step 3: Associate buffer to DMA engine, and prepare for copying to host (DMA read)
halide_hexagon_dma_prepare_for_copy_to_host(nullptr, input, dma_engine, false, halide_hexagon_fmt_RawData);
// Setup Halide output buffer
Halide::Runtime::Buffer<uint8_t> output(width, height, 4);
output = output.make_interleaved(width, height, 4);
if (!strcmp(str,"basic")) {
printf("Basic pipeline\n");
ret = pipeline_raw_linear_ro_basic_interleaved(input, output);
} else if (!strcmp(str,"fold")) {
printf("Fold pipeline\n");
ret = pipeline_raw_linear_ro_fold_interleaved(input, output);
} else if (!strcmp(str,"async")) {
printf("Async pipeline\n");
ret = pipeline_raw_linear_ro_async_interleaved(input, output);
} else if (!strcmp(str,"split")) {
printf("Split pipeline\n");
ret = pipeline_raw_linear_ro_split_interleaved(input, output);
} else if (!strcmp(str,"split_fold")) {
printf("Split Fold pipeline\n");
ret = pipeline_raw_linear_ro_split_fold_interleaved(input, output);
} else {
printf("Incorrect input Correct options: basic, fold, async, split, split_fold\n");
ret = -1;
}
if (ret != 0) {
printf("pipeline failed! %d\n", ret);
}
else {
// verify result by comparing to expected values
for (int y=0; y < height; y++) {
for (int x=0; x < width; x++) {
for (int z=0; z < 4; z++) {
uint8_t correct = data_in[x*4 + z + y*width*4] * 2;
if (correct != output(x, y, z)) {
static int cnt = 0;
printf("Mismatch at x=%d y=%d z=%d: %d != %d\n", x, y, z, correct, output(x, y, z));
if (++cnt > 20) abort();
}
}
}
}
printf("Success!\n");
}
// DMA_step 4: Buffer is processed, disassociate buffer from DMA engine
// Optional goto DMA_step 0 for processing more buffers
halide_hexagon_dma_unprepare(nullptr, input);
// DMA_step 5: Processing is completed and ready to exit, deallocate the DMA engine
halide_hexagon_dma_deallocate_engine(nullptr, dma_engine);
free(data_in);
return ret;
}
| 37.188679 | 111 | 0.632166 | mbrukman |
c0eaa3ef1bb304a50b653f2323e067700b06dccd | 3,321 | cpp | C++ | src/backend/gpopt/CGPOptimizer.cpp | Oliver-Luo/incubator-hawq | 195909207313d802a110666c76187cefab96d09c | [
"Apache-2.0"
] | null | null | null | src/backend/gpopt/CGPOptimizer.cpp | Oliver-Luo/incubator-hawq | 195909207313d802a110666c76187cefab96d09c | [
"Apache-2.0"
] | null | null | null | src/backend/gpopt/CGPOptimizer.cpp | Oliver-Luo/incubator-hawq | 195909207313d802a110666c76187cefab96d09c | [
"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.
*/
//---------------------------------------------------------------------------
// @filename:
// CGPOptimizer.cpp
//
// @doc:
// Entry point to GP optimizer
//
// @test:
//
//
//---------------------------------------------------------------------------
#include "gpopt/CGPOptimizer.h"
#include "gpopt/utils/COptTasks.h"
// the following headers are needed to reference optimizer library initializers
#include "naucrates/init.h"
#include "gpopt/init.h"
#include "gpos/_api.h"
//---------------------------------------------------------------------------
// @function:
// CGPOptimizer::TouchLibraryInitializers
//
// @doc:
// Touch library initializers to enforce linker to include them
//
//---------------------------------------------------------------------------
void
CGPOptimizer::TouchLibraryInitializers()
{
void (*gpos)() = gpos_init;
void (*dxl)() = gpdxl_init;
void (*opt)() = gpopt_init;
}
//---------------------------------------------------------------------------
// @function:
// CGPOptimizer::PlstmtOptimize
//
// @doc:
// Optimize given query using GP optimizer
//
//---------------------------------------------------------------------------
PlannedStmt *
CGPOptimizer::PplstmtOptimize
(
Query *pquery,
bool *pfUnexpectedFailure // output : set to true if optimizer unexpectedly failed to produce plan
)
{
return COptTasks::PplstmtOptimize(pquery, pfUnexpectedFailure);
}
//---------------------------------------------------------------------------
// @function:
// CGPOptimizer::SzDXL
//
// @doc:
// Serialize planned statement into DXL
//
//---------------------------------------------------------------------------
char *
CGPOptimizer::SzDXLPlan
(
Query *pquery
)
{
return COptTasks::SzOptimize(pquery);
}
//---------------------------------------------------------------------------
// @function:
// PplstmtOptimize
//
// @doc:
// Expose GP optimizer API to C files
//
//---------------------------------------------------------------------------
extern "C"
{
PlannedStmt *PplstmtOptimize
(
Query *pquery,
bool *pfUnexpectedFailure
)
{
return CGPOptimizer::PplstmtOptimize(pquery, pfUnexpectedFailure);
}
}
//---------------------------------------------------------------------------
// @function:
// SzDXLPlan
//
// @doc:
// Serialize planned statement to DXL
//
//---------------------------------------------------------------------------
extern "C"
{
char *SzDXLPlan
(
Query *pquery
)
{
return CGPOptimizer::SzDXLPlan(pquery);
}
}
// EOF
| 24.783582 | 99 | 0.512195 | Oliver-Luo |
c0ecbbe327cccc5da849b1ca21938e8b44f6900f | 974 | cpp | C++ | Tools/VisualStudio/VC10/PixelLightWizard/PixelLightWizard/Templates/1033/Application.cpp | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Tools/VisualStudio/VC10/PixelLightWizard/PixelLightWizard/Templates/1033/Application.cpp | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Tools/VisualStudio/VC10/PixelLightWizard/PixelLightWizard/Templates/1033/Application.cpp | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: Application.cpp *
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Application.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Constructor
*/
Application::Application() : GuiApplication()
{
// Set application title
SetTitle("<fill me>");
}
/**
* @brief
* Destructor
*/
Application::~Application()
{
}
| 25.631579 | 59 | 0.216632 | ktotheoz |
c0ee1c369e61032ba700744bab4cf75213db36d0 | 9,752 | cpp | C++ | sourceCode/dotNet4.6/vb/language/vbhosted/vbhosted/vbhostedcompiler.cpp | csoap/csoap.github.io | 2a8db44eb63425deff147652b65c5912f065334e | [
"Apache-2.0"
] | 5 | 2017-03-03T02:13:16.000Z | 2021-08-18T09:59:56.000Z | sourceCode/dotNet4.6/vb/language/vbhosted/vbhosted/vbhostedcompiler.cpp | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | null | null | null | sourceCode/dotNet4.6/vb/language/vbhosted/vbhosted/vbhostedcompiler.cpp | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | 4 | 2016-11-15T05:20:12.000Z | 2021-11-13T16:32:11.000Z | #include "stdafx.h"
VbHostedCompiler::VbHostedCompiler(gcroot<System::Collections::Generic::IList<System::Reflection::Assembly ^>^> referenceAssemblies)
:
m_fInit(false),
m_referenceAssemblies(gcnew System::Collections::Generic::List<System::Reflection::Assembly ^>(referenceAssemblies)),
m_ErrorTable()
{
}
VbHostedCompiler::~VbHostedCompiler()
{
if(m_spVbCompilerProject)
{
m_spVbCompilerProject->Disconnect();
}
if (m_spVbExternalCompilerProject)
{
m_spVbExternalCompilerProject->Disconnect();
}
}
STDMETHODIMP VbHostedCompiler::InitCompiler()
{
HRESULT hr = S_OK;
if (!m_fInit)
{
ASSERT(!m_spVbCompiler, "[VbHostedCompiler::InitCompiler] 'm_spVbCompiler' member is not NULL");
ASSERT(!m_spVbCompilerHost, "[VbHostedCompiler::InitCompiler] 'm_spVbCompilerHost' member is not NULL");
ASSERT(!m_spVbCompilerProject, "[VbHostedCompiler::InitCompiler] 'm_spVbCompilerProject' member is not NULL");
ASSERT(!m_pCompilerProject, "[VbHostedCompiler::InitCompiler] 'm_pCompilerProject' member is not NULL");
IfFailGo(VbCompilerHost::Create(&m_spVbCompilerHost));
IfFailGo(GetCompiler());
IfFailGo(SetupCompilerProject(&m_ErrorTable));
IfFailGo(CreateExternalCompilerProject());
m_fInit = true;
}
Error:
if (FAILED(hr))
{
m_spVbCompilerHost = NULL;
m_spVbCompiler = NULL;
}
return hr;
}
STDMETHODIMP VbHostedCompiler::CompileExpression
(
BSTR Expression,
VbContext* pContext,
gcroot<System::Type ^> TargetType,
VbParsed *pParsed
)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(Expression, "[VbHostedCompiler::CompileExpression] 'Expression' parameter is null");
VerifyParamCond(SysStringLen(Expression) > 0, E_INVALIDARG, "[VbHostedCompiler::CompileExpression] 'Expression' parameter is zero length string");
VerifyInPtr(pContext, "[VbHostedCompiler::CompileExpression] 'pContext' parameter is null");
VerifyInPtr(pParsed, "[VbHostedCompiler::CompileExpression] 'pParsed' parameter is null");
VB_ENTRY();
IfFailGo(InitCompiler());
pParsed->SetSharedErrorTable(&m_ErrorTable);
if (!m_ErrorTable.HasErrors())
{
VBHostedSession session(Expression, m_spVbCompiler, m_spVbCompilerHost, m_spVbCompilerProject, m_pExternalCompilerProject, pContext, TargetType);
pParsed->GetErrorTable()->Init(m_pCompiler, m_pCompilerProject, NULL);
IfFailGo(session.CompileExpression(pParsed));
}
g_pvbNorlsManager->GetPageHeap().ShrinkUnusedResources();
VB_EXIT_LABEL();
}
STDMETHODIMP VbHostedCompiler::CompileStatements
(
BSTR Statements,
VbContext* pContext,
VbParsed *pParsed
)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(Statements, "[VbHostedCompiler::CompileStatements] 'Statements' parameter is null");
VerifyParamCond(SysStringLen(Statements) > 0, E_INVALIDARG, "[VbHostedCompiler::CompileStatements] 'Statements' parameter is zero length string");
VerifyInPtr(pContext, "[VbHostedCompiler::CompileStatements] 'pContext' parameter is null");
VerifyInPtr(pParsed, "[VbHostedCompiler::CompileStatements] 'pParsed' parameter is null");
VB_ENTRY();
IfFailGo(InitCompiler());
pParsed->SetSharedErrorTable(&m_ErrorTable);
if (!m_ErrorTable.HasErrors())
{
VBHostedSession session(Statements, m_spVbCompiler, m_spVbCompilerHost, m_spVbCompilerProject, m_pExternalCompilerProject, pContext, nullptr);
pParsed->GetErrorTable()->Init(m_pCompiler, m_pCompilerProject, NULL);
IfFailGo(session.CompileStatements(pParsed));
}
VB_EXIT_LABEL();
}
STDMETHODIMP VbHostedCompiler::GetCompiler()
{
HRESULT hr = S_OK;
CompilerHost *pCompilerHost = NULL; // Don't need to manage lifetime of pCompilerHost as it is controlled by pCompiler.
// Create the compiler, this will have references to the default libraries
IfFailGo(VBCreateBasicCompiler(false, DelayLoadUICallback, m_spVbCompilerHost, &m_spVbCompiler));
m_pCompiler = (Compiler *)((IVbCompiler*)m_spVbCompiler);
//"Compile" the mscorlib project
if(m_pCompiler->FindCompilerHost(m_spVbCompilerHost, &pCompilerHost) && pCompilerHost && pCompilerHost->GetComPlusProject())
{
IfTrueGo(pCompilerHost->GetComPlusProject()->Compile(), E_FAIL);
}
else
{
ASSERT(pCompilerHost, "Could not get Compiler Host");
ASSERT(!pCompilerHost, "Could not get mscorlib's project");
IfFailGo(E_FAIL);
}
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::SetupCompilerProject(ErrorTable *pErrorTable)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(pErrorTable, "[VBHostedSession::SetupCompilerProject] 'pErrorTable' parameter is null");
ASSERT(m_spVbCompilerHost, "[VBHostedSession::SetupCompilerProject] 'm_spVbCompilerHost' is null");
ASSERT(m_spVbCompiler, "[VBHostedSession::SetupCompilerProject] 'm_spVbCompiler' is null");
HRESULT hr = S_OK;
IfFailGo(CreateCompilerProject());
IfFailGo(InitializeCompilerProject(pErrorTable));
// Ensure that all the projects (in particular mscorlib and the VB runtime
// have been compiled at least to CS_Bound).
//
IfFailGo(m_pCompiler->CompileToBound(
m_pCompilerProject->GetCompilerHost(),
NULL, // ULONG *pcWarnings
NULL, // ULONG *pcErrors,
NULL // VbError **ppErrors
));
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::CreateCompilerProject()
{
ASSERT(m_spVbCompilerHost, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompilerHost' is null");
ASSERT(m_spVbCompiler, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompiler' is null");
ASSERT(!m_spVbCompilerProject, "[VBHostedSession::CreateCompilerProject] 'm_spVbCompilerProject' is not null");
ASSERT(!m_pCompilerProject, "[VBHostedSession::CreateCompilerProject] 'm_pCompilerProject' is not null");
HRESULT hr = S_OK;
// Add System.Core.dll as it is required for DLR tree conversion
//
{
// Register the compiler host to get access to the underlying "CompierHost"
// object before the project is created so that System.Core can also be
// added to the list of standard libraries and thus found using the
// FX search paths and added as a reference to the project when it
// is created.
//
IfFailGo(m_pCompiler->RegisterVbCompilerHost(m_spVbCompilerHost));
CompilerHost *CompilerHost = NULL;
IfFalseGo(m_pCompiler->FindCompilerHost(m_spVbCompilerHost, &CompilerHost), E_UNEXPECTED);
ThrowIfNull(CompilerHost);
DynamicArray<STRING *> *StdLibs = CompilerHost->GetStandardLibraries();
ThrowIfNull(StdLibs);
STRING **StdLibsArray = StdLibs->Array();
// Add to the list only if not already present.
STRING *SystemCoreDLL = m_pCompiler->AddString(L"System.Core.dll");
for(unsigned i = 0; i < StdLibs->Count(); i++)
{
if (StringPool::IsEqual(StdLibsArray[i] , SystemCoreDLL)) break;
}
if (i == StdLibs->Count())
{
StdLibs->AddElement(SystemCoreDLL);
}
}
// Create our default project.
IfFailGo(m_spVbCompiler->CreateProject
(
L"vbhost",
m_spVbCompiler,
NULL,
m_spVbCompilerHost,
&m_spVbCompilerProject
));
m_pCompilerProject = (CompilerProject*)m_spVbCompilerProject.p;
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::InitializeCompilerProject(ErrorTable *pErrorTable)
{
// Asserts are NOT necessary since the Verify* macros all invoke VSFAIL which is a VSASSERT wrapper.
VerifyInPtr(pErrorTable, "[VBHostedSession::InitializeCompilerProject] 'pErrorTable' parameter is null");
ASSERT(m_pCompiler, "[VBHostedSession::InitializeCompilerProject] 'm_pCompiler' is null");
ASSERT(m_spVbCompilerProject, "[VBHostedSession::InitializeCompilerProject] 'm_spVbCompilerProject' is null");
HRESULT hr = S_OK;
// Must initialize errortable before calling SetAssemblyRefs so that failures encountered when processing
// the assembly references are captured correctly.
pErrorTable->Init(m_pCompiler, m_pCompilerProject, NULL);
m_pCompilerProject->AddStandardLibraries();
IfFailGo(VbContext::SetAssemblyRefs(m_referenceAssemblies, m_pCompiler, m_spVbCompilerProject, pErrorTable));
//Need to set the options to something so that the project will be compiled to bound.
IfFailGo(VbContext::SetDefaultOptions(m_spVbCompilerProject));
Error:
return hr;
}
STDMETHODIMP VbHostedCompiler::CreateExternalCompilerProject()
{
ASSERT(m_spVbCompilerHost, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbCompilerHost' is null");
ASSERT(m_spVbCompiler, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbCompiler' is null");
ASSERT(!m_spVbExternalCompilerProject, "[VBHostedSession::CreateExternalCompilerProject] 'm_spVbExternalCompilerProject' is not null");
ASSERT(!m_pExternalCompilerProject, "[VBHostedSession::CreateExternalCompilerProject] 'm_pExternalCompilerProject' is not null");
HRESULT hr = S_OK;
//Create the Type Scope Project
IfFailGo(m_pCompilerProject->AddTypeScopeReference(&m_pExternalCompilerProject));
m_spVbExternalCompilerProject = m_pExternalCompilerProject;
Error:
return hr;
}
| 35.591241 | 153 | 0.717904 | csoap |
c0ef5d287b39ace47f4b993c1bf516a59d9491e7 | 1,072 | cpp | C++ | test/test_large_messages.cpp | bripage/ygm | 6ef1a47b90474947ee751afe3a60eabfb20d4c0c | [
"MIT-0",
"MIT"
] | 10 | 2020-03-06T17:56:42.000Z | 2022-01-10T01:24:07.000Z | test/test_large_messages.cpp | bripage/ygm | 6ef1a47b90474947ee751afe3a60eabfb20d4c0c | [
"MIT-0",
"MIT"
] | 31 | 2021-04-13T23:08:13.000Z | 2022-03-29T21:40:21.000Z | test/test_large_messages.cpp | bripage/ygm | 6ef1a47b90474947ee751afe3a60eabfb20d4c0c | [
"MIT-0",
"MIT"
] | 10 | 2021-02-02T23:15:11.000Z | 2021-11-10T17:43:47.000Z | // Copyright 2019-2021 Lawrence Livermore National Security, LLC and other YGM
// Project Developers. See the top-level COPYRIGHT file for details.
//
// SPDX-License-Identifier: MIT
#undef NDEBUG
#include <ygm/comm.hpp>
#include <ygm/detail/ygm_ptr.hpp>
int main(int argc, char** argv) {
// Create comm for very small messages
ygm::comm world(&argc, &argv, 8);
// Test Rank 0 large message to all ranks
{
size_t large_msg_size = 1024;
size_t counter{};
ygm::ygm_ptr<size_t> pcounter(&counter);
if (world.rank() == 0) {
std::vector<size_t> large_msg(large_msg_size);
for (int dest = 0; dest < world.size(); ++dest) {
// Count elements in large message's vector
world.async(
dest,
[](auto pcomm, int from, auto pcounter,
const std::vector<size_t>& vec) {
for (size_t i = 0; i < vec.size(); ++i) { (*pcounter)++; }
},
pcounter, large_msg);
}
}
world.barrier();
ASSERT_RELEASE(counter == large_msg_size);
}
return 0;
}
| 27.487179 | 78 | 0.600746 | bripage |
c0f144f7483c32df2ae92bd5d203fc3d3e4185ad | 1,218 | cpp | C++ | signal-slot-benchmarks/benchmark/cpp/benchmark_nod.cpp | qubka/signals | 6bd39c662ab2b1e0caafc5a4c4510a74fb9f9e1c | [
"MIT"
] | 181 | 2020-01-17T13:49:59.000Z | 2022-03-17T03:23:12.000Z | signal-slot-benchmarks/benchmark/cpp/benchmark_nod.cpp | qubka/signals | 6bd39c662ab2b1e0caafc5a4c4510a74fb9f9e1c | [
"MIT"
] | 22 | 2020-01-16T23:37:02.000Z | 2021-09-08T23:51:12.000Z | signal-slot-benchmarks/benchmark/cpp/benchmark_nod.cpp | qubka/signals | 6bd39c662ab2b1e0caafc5a4c4510a74fb9f9e1c | [
"MIT"
] | 16 | 2020-01-28T15:40:18.000Z | 2022-02-25T08:32:15.000Z | #include "../hpp/benchmark_nod.hpp"
NOINLINE(void Nod::initialize())
{
// NOOP
}
NOINLINE(void Nod::validate_assert(std::size_t N))
{
return Benchmark<Signal, Nod>::validation_assert(N);
}
NOINLINE(double Nod::construction(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::construction(N, limit);
}
NOINLINE(double Nod::destruction(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::destruction(N, limit);
}
NOINLINE(double Nod::connection(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::connection(N, limit);
}
NOINLINE(double Nod::disconnect(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::disconnect(N, limit);
}
NOINLINE(double Nod::reconnect(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::reconnect(N, limit);
}
NOINLINE(double Nod::emission(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::emission(N, limit);
}
NOINLINE(double Nod::combined(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::combined(N, limit);
}
NOINLINE(double Nod::threaded(std::size_t N, std::size_t limit))
{
return Benchmark<Signal, Nod>::threaded(N, limit);
}
| 28.325581 | 68 | 0.703612 | qubka |
c0f25d2231d5e519dc15331a1450316114c94a6b | 277 | hpp | C++ | app/raytracing/ScreenRayTracer.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | 1 | 2021-08-07T13:02:01.000Z | 2021-08-07T13:02:01.000Z | app/raytracing/ScreenRayTracer.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | null | null | null | app/raytracing/ScreenRayTracer.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include<math/Math3d.hpp>
#include<render/Filter.hpp>
#include<render/Viewport.hpp>
namespace tutorial::graphics
{
class ScreenRayTracer
{
private:
ScreenRayTracer() = delete;
public:
static void draw(Viewport& viewport, ShaderVersion shader);
};
}
| 14.578947 | 61 | 0.736462 | Yousazoe |
c0f51aef2cf71e849d8dc831901f45e4818597a3 | 1,523 | cpp | C++ | src/Cluster/Cluster/MIWord.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Cluster/Cluster/MIWord.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Cluster/Cluster/MIWord.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#include "MIWord.h"
using namespace std;
const Vocabulary* MIWord::pVoc = 0;
MIWord::MIWord(int index) {
_index = index;
}
MIWord& MIWord::operator=(const MIWord& w) {
MIBaseElement::operator=(w);
_index = w._index;
return *this;
}
bool MIWord::operator==(const MIWord& w) const {
return _index == w._index;
}
bool MIWord::operator!=(const MIWord& w) const {
return _index != w._index;
}
bool MIWord::operator<(const MIWord &w) const {
return ((getTotalCount() < w.getTotalCount()) ||
((getTotalCount() == w.getTotalCount()) && (_index < w._index)));
}
bool MIWord::operator>(const MIWord& w) const {
return ((getTotalCount() > w.getTotalCount()) ||
((getTotalCount() == w.getTotalCount()) && (_index > w._index)));
}
bool MIWord::operator<=(const MIWord& w) const {
return ((getTotalCount()<w.getTotalCount()) ||
((getTotalCount() == w.getTotalCount()) && (_index <= w._index)));
}
bool MIWord::operator>=(const MIWord& w) const {
return ((getTotalCount() > w.getTotalCount()) ||
((getTotalCount() == w.getTotalCount()) && (_index >= w._index)));
}
void MIWord::setIndex(int index) {
_index = index;
}
int MIWord::index() const {
return _index;
}
const wstring& MIWord::name() const {
return pVoc->get(_index);
}
void MIWord::useVoc(const Vocabulary &voc) {
pVoc = &voc;
}
| 24.174603 | 79 | 0.598162 | BBN-E |
c0f68569b69b34722569b76c4d3691968324900c | 392 | cpp | C++ | Chapter08/Exercise58/Exercise58.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | 4 | 2019-08-12T08:59:46.000Z | 2022-03-08T07:49:29.000Z | Chapter08/Exercise58/Exercise58.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | null | null | null | Chapter08/Exercise58/Exercise58.cpp | Archiit19/The-Cpp-Workshop | ae2f8d0c375d6bcdd7fa5ab9e34370ce83d1f501 | [
"MIT"
] | 5 | 2019-10-09T17:00:56.000Z | 2022-03-08T07:49:41.000Z | #include <iostream>
#include <string>
using namespace std;
class Track
{
public:
float lengthInSeconds;
string trackName;
Track ()
{
lengthInSeconds = 0.0f;
trackName = "not set";
}
};
int main()
{
Track track;
cout << "Track Name = " << track.trackName << endl;
cout << "Track Length = " << track.lengthInSeconds << endl;
return 0;
}
| 15.076923 | 62 | 0.581633 | Archiit19 |
c0fb4254e90722633752903264a64c610e5625e6 | 4,096 | cpp | C++ | src/control_surface_map.cpp | NVIDIA/Korgi | c2dadc1a016f0ff463d559c40f45694734a5d01a | [
"MIT"
] | 14 | 2019-06-06T13:05:33.000Z | 2022-01-24T22:17:09.000Z | src/control_surface_map.cpp | NVIDIA/Korgi | c2dadc1a016f0ff463d559c40f45694734a5d01a | [
"MIT"
] | null | null | null | src/control_surface_map.cpp | NVIDIA/Korgi | c2dadc1a016f0ff463d559c40f45694734a5d01a | [
"MIT"
] | 3 | 2019-06-06T16:10:42.000Z | 2021-04-30T14:38:26.000Z | /*
* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
*
* 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 "control_surface_map.h"
#include <map>
#include <string>
#define BUTTON(__channel) ControlSurface(ControlSurface::Type::Button, __channel)
#define SLIDER(__channel) ControlSurface(ControlSurface::Type::Slider, __channel)
#define KNOB(__channel) ControlSurface(ControlSurface::Type::RotaryKnob, __channel)
typedef std::map<std::string, ControlSurface> ControlSurfaceMap;
static ControlSurfaceMap controlMap_Korg_nanoKONTROL2 = {
{ "rewind", BUTTON(43) },
{ "fwd", BUTTON(44) },
{ "stop", BUTTON(42) },
{ "play", BUTTON(41) },
{ "rec", BUTTON(45) },
{ "cycle", BUTTON(46) },
{ "marker_set", BUTTON(60) },
{ "marker_prev", BUTTON(61) },
{ "marker_next", BUTTON(62) },
{ "track_prev", BUTTON(58) },
{ "track_next", BUTTON(59) },
{ "S0", BUTTON(32) },
{ "S1", BUTTON(33) },
{ "S2", BUTTON(34) },
{ "S3", BUTTON(35) },
{ "S4", BUTTON(36) },
{ "S5", BUTTON(37) },
{ "S6", BUTTON(38) },
{ "S7", BUTTON(39) },
{ "M0", BUTTON(48) },
{ "M1", BUTTON(49) },
{ "M2", BUTTON(50) },
{ "M3", BUTTON(51) },
{ "M4", BUTTON(52) },
{ "M5", BUTTON(53) },
{ "M6", BUTTON(54) },
{ "M7", BUTTON(55) },
{ "R0", BUTTON(64) },
{ "R1", BUTTON(65) },
{ "R2", BUTTON(66) },
{ "R3", BUTTON(67) },
{ "R4", BUTTON(68) },
{ "R5", BUTTON(69) },
{ "R6", BUTTON(70) },
{ "R7", BUTTON(71) },
{ "sl0", SLIDER(0) },
{ "sl1", SLIDER(1) },
{ "sl2", SLIDER(2) },
{ "sl3", SLIDER(3) },
{ "sl4", SLIDER(4) },
{ "sl5", SLIDER(5) },
{ "sl6", SLIDER(6) },
{ "sl7", SLIDER(7) },
{ "kn0", KNOB(16) },
{ "kn1", KNOB(17) },
{ "kn2", KNOB(18) },
{ "kn3", KNOB(19) },
{ "kn4", KNOB(20) },
{ "kn5", KNOB(21) },
{ "kn6", KNOB(22) },
{ "kn7", KNOB(23) },
};
static std::map<std::string, ControlSurfaceMap*> controlSurfaces = {
{ "nanoKONTROL2", &controlMap_Korg_nanoKONTROL2 }
};
static ControlSurfaceMap *controlSurfaceMap = nullptr;
bool setControlSurfaceType(const char *name)
{
if (controlSurfaces.find(name) == controlSurfaces.end())
{
return false;
}
controlSurfaceMap = controlSurfaces[name];
return true;
}
bool mapControl(ControlSurface& out, const char *name)
{
if (controlSurfaceMap->find(name) == controlSurfaceMap->end())
{
return false;
}
out = (*controlSurfaceMap)[name];
return true;
}
| 35.617391 | 83 | 0.53833 | NVIDIA |
c0fd8bade2faca4c930605577999034ad87f3234 | 4,872 | cpp | C++ | src/mongo/db/matcher/schema/expression_internal_schema_max_length_test.cpp | MartinNeupauer/mongo | 6cc2dfe7edd312b8596355edef454e15988e350e | [
"Apache-2.0"
] | null | null | null | src/mongo/db/matcher/schema/expression_internal_schema_max_length_test.cpp | MartinNeupauer/mongo | 6cc2dfe7edd312b8596355edef454e15988e350e | [
"Apache-2.0"
] | 2 | 2021-03-26T00:01:11.000Z | 2021-03-26T00:02:19.000Z | src/mongo/db/matcher/schema/expression_internal_schema_max_length_test.cpp | MartinNeupauer/mongo | 6cc2dfe7edd312b8596355edef454e15988e350e | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2017 (c) 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/matcher/expression.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_length.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_length.h"
#include "mongo/unittest/unittest.h"
namespace mongo {
namespace {
TEST(InternalSchemaMaxLengthMatchExpression, RejectsNonStringElements) {
InternalSchemaMaxLengthMatchExpression maxLength;
ASSERT_OK(maxLength.init("a", 1));
ASSERT_FALSE(maxLength.matchesBSON(BSON("a" << BSONObj())));
ASSERT_FALSE(maxLength.matchesBSON(BSON("a" << 1)));
ASSERT_FALSE(maxLength.matchesBSON(BSON("a" << BSON_ARRAY(1))));
}
TEST(InternalSchemaMaxLengthMatchExpression, RejectsStringsWithTooManyChars) {
InternalSchemaMaxLengthMatchExpression maxLength;
ASSERT_OK(maxLength.init("a", 2));
ASSERT_FALSE(maxLength.matchesBSON(BSON("a"
<< "abc")));
ASSERT_FALSE(maxLength.matchesBSON(BSON("a"
<< "abcd")));
}
TEST(InternalSchemaMaxLengthMatchExpression, AcceptsStringsWithLessThanOrEqualToMax) {
InternalSchemaMaxLengthMatchExpression maxLength;
ASSERT_OK(maxLength.init("a", 2));
ASSERT_TRUE(maxLength.matchesBSON(BSON("a"
<< "ab")));
ASSERT_TRUE(maxLength.matchesBSON(BSON("a"
<< "a")));
ASSERT_TRUE(maxLength.matchesBSON(BSON("a"
<< "")));
}
TEST(InternalSchemaMaxLengthMatchExpression, MaxLengthZeroAllowsEmptyString) {
InternalSchemaMaxLengthMatchExpression maxLength;
ASSERT_OK(maxLength.init("a", 0));
ASSERT_TRUE(maxLength.matchesBSON(BSON("a"
<< "")));
}
TEST(InternalSchemaMaxLengthMatchExpression, RejectsNull) {
InternalSchemaMaxLengthMatchExpression maxLength;
ASSERT_OK(maxLength.init("a", 1));
ASSERT_FALSE(maxLength.matchesBSON(BSON("a" << BSONNULL)));
}
TEST(InternalSchemaMaxLengthMatchExpression, NestedArraysWorkWithDottedPaths) {
InternalSchemaMaxLengthMatchExpression maxLength;
ASSERT_OK(maxLength.init("a.b", 2));
ASSERT_TRUE(maxLength.matchesBSON(BSON("a" << BSON("b"
<< "a"))));
ASSERT_TRUE(maxLength.matchesBSON(BSON("a" << BSON("b"
<< "ab"))));
ASSERT_FALSE(maxLength.matchesBSON(BSON("a" << BSON("b"
<< "abc"))));
}
TEST(InternalSchemaMaxLengthMatchExpression, SameMaxLengthTreatedEquivalent) {
InternalSchemaMaxLengthMatchExpression maxLength1;
InternalSchemaMaxLengthMatchExpression maxLength2;
InternalSchemaMaxLengthMatchExpression maxLength3;
ASSERT_OK(maxLength1.init("a", 2));
ASSERT_OK(maxLength2.init("a", 2));
ASSERT_OK(maxLength3.init("a", 3));
ASSERT_TRUE(maxLength1.equivalent(&maxLength2));
ASSERT_FALSE(maxLength1.equivalent(&maxLength3));
}
TEST(InternalSchemaMaxLengthMatchExpression, MinLengthAndMaxLengthAreNotEquivalent) {
InternalSchemaMinLengthMatchExpression minLength;
InternalSchemaMaxLengthMatchExpression maxLength;
ASSERT_OK(minLength.init("a", 2));
ASSERT_OK(maxLength.init("a", 2));
ASSERT_FALSE(maxLength.equivalent(&minLength));
}
} // namespace
} // namespace mongo
| 40.264463 | 86 | 0.690681 | MartinNeupauer |
c0ffe7630a0e5ac395c0e996175645ec04ba8423 | 459 | cpp | C++ | 2021/day22/main.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | 3 | 2021-07-01T14:31:06.000Z | 2022-03-29T20:41:21.000Z | 2021/day22/main.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | 2021/day22/main.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | #include "file.h"
#include "utilities.h"
#include <iostream>
namespace aoc2021_day22 {
int part_1(std::string_view path) {
return 0;
}
int part_2(std::string_view path) {
return 0;
}
}
#ifndef TESTING
int main() {
std::cout << "Part 1: " << aoc2021_day22::part_1("../2021/day22/input.in") << std::endl;
std::cout << "Part 2: " << aoc2021_day22::part_2("../2021/day22/input.in") << std::endl;
return 0;
}
#endif
| 19.956522 | 92 | 0.59695 | alexandru-andronache |
8d06325146b5e2db60d6dbf217774fd60b04e894 | 1,070 | cpp | C++ | code_practice/10/1018_class/3_shared_ptr8.cpp | armkernel/armkernel.github.io | f74b8ddfc8a69dec8b5eeccb4d92c62dcc6c321a | [
"MIT"
] | 2 | 2019-08-06T13:45:02.000Z | 2019-11-06T01:15:30.000Z | code_practice/10/1018_class/3_shared_ptr8.cpp | armkernel/armkernel.github.io | f74b8ddfc8a69dec8b5eeccb4d92c62dcc6c321a | [
"MIT"
] | null | null | null | code_practice/10/1018_class/3_shared_ptr8.cpp | armkernel/armkernel.github.io | f74b8ddfc8a69dec8b5eeccb4d92c62dcc6c321a | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <memory>
using namespace std;
struct People
{
string name;
People(string n) : name(n) {}
~People() { cout << name << " 파괴" << endl; }
//shared_ptr<People> bestFriend; // 참조 계수 증가한다.
// People* bestFriend; // 참조계수가 증가하지 않는다.
weak_ptr<People> bestFriend; // 참조 계수가 증가하지 않는
// 스마트 포인터.
// 장점: 객체 파괴 여부 조사가능
};
int main()
{
shared_ptr<People> sp1 = make_shared<People>("kim");
{
shared_ptr<People> sp2 = make_shared<People>("lee");
sp1->bestFriend = sp2;
sp2->bestFriend = sp1; // weak는 shared랑 호환된다.
}
if (sp1->bestFriend.expired())
{
cout << "객체 파괴됨" << endl; // ??
}
else
{
// 살아 있는 경우..
// cout << sp1->bestFriend->name << endl;
// 접근이 안돼.. => compile error
// shared_ptr 만들어야해
shared_ptr<People> sp = sp1->bestFriend.lock();
if(sp)
{
cout << sp -> name << endl;
}
// weak 는 소유권이 없어
// 안전한 객체 접근을 하기 위해서는 shared_ptr로 변경해야해
// 안전함을 위해서 이렇게 설계
}
}
| 19.454545 | 56 | 0.536449 | armkernel |
8d0b163efb0d6c5cf58e16cc8eefc494031a3711 | 2,728 | cpp | C++ | src/convolution.cpp | NREL/repra | b2ed04bcf9f17a69efabd5e0e049ca37a4c9d44e | [
"BSD-3-Clause"
] | 6 | 2015-12-14T22:51:05.000Z | 2020-10-22T15:30:59.000Z | src/convolution.cpp | NREL/repra | b2ed04bcf9f17a69efabd5e0e049ca37a4c9d44e | [
"BSD-3-Clause"
] | 7 | 2015-02-02T19:57:47.000Z | 2020-12-18T03:27:05.000Z | src/convolution.cpp | NREL/repra | b2ed04bcf9f17a69efabd5e0e049ca37a4c9d44e | [
"BSD-3-Clause"
] | 6 | 2015-07-29T06:36:44.000Z | 2021-02-22T19:19:11.000Z | #include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// Function to perform convolution. See "?convolution" in R
// [[Rcpp::export]]
DataFrame convolution_table(NumericVector capacity, NumericVector efor, double threshold) {
// Initialize variables
int n = 0;
NumericVector cap(0), prob(0);
for (int i = 0; i < capacity.length(); ++i) {
NumericVector old_cap(cap), old_prob(prob);
if (i == 0) {
// Create table for first generator
cap = NumericVector(2, 0.0);
prob = NumericVector(2, 0.0);
n = 2;
cap[0] = capacity[0];
cap[1] = 0.0;
prob[0] = 1.0 - efor[0];
prob[1] = efor[0];
} else {
// Convolute i-th generator
int x1 = 0, x2 = 0, old_n = n, maxN = 2 * n;
double pushCap, pushProb;
cap = NumericVector(maxN, 0.0);
prob = NumericVector(maxN, 0.0);
n = 0;
while (x2 < old_n) {
if (x1 == old_n) {
pushCap = old_cap[x2];
pushProb = old_prob[x2] * efor[i];
++x2;
} else {
double cap1 = old_cap[x1] + capacity[i];
double cap2 = old_cap[x2];
if (cap1 > cap2) {
// Cap1 is larger
pushCap = cap1;
pushProb = old_prob[x1] * (1.0 - efor[i]);
++x1;
} else if (cap1 < cap2) {
// Cap2 is larger
pushCap = cap2;
pushProb = old_prob[x2] * efor[i];
++x2;
} else {
// Tie in cap1 and cap2
pushCap = cap1;
pushProb = old_prob[x1] * (1.0 - efor[i]) + old_prob[x2] * efor[i];
++x1;
++x2;
}
}
cap[n] = pushCap;
prob[n] = pushProb;
++n;
}
}
}
// Create LOLP vector
NumericVector lolp(cumsum(prob));
lolp = 1.0 - lolp + prob;
// Create vectors for data output
NumericVector outCap = cap[(lolp >= threshold) & (prob > 0.0)],
outProb = prob[(lolp >= threshold) & (prob > 0.0)],
outLolp = lolp[(lolp >= threshold) & (prob > 0.0)],
outBaseEue(outCap.size(), 0.0);
// Calculate fixed term in EUE
for (int i = 0; i < outCap.size(); ++i) {
double eue = 0.0;
for (int j = i + 1; j < outCap.size(); ++j)
eue += (outCap[i] - outCap[j]) * outProb[j];
outBaseEue[i] = eue;
}
// Create output as data frame
return DataFrame::create(Named("Capacity") = outCap,
Named("Capacity2") = outCap,
Named("Prob") = outProb,
Named("LOLP") = outLolp,
Named("BaseEUE") = outBaseEue);
}
| 28.715789 | 91 | 0.478739 | NREL |
8d0b8688a77ee3880255a9027c53e6c69e5e2619 | 9,815 | cpp | C++ | qmovstack.cpp | deepakm/deepquor | 6e7746ad7e9b359ed5b0567c580a97684a76ad12 | [
"BSD-3-Clause"
] | null | null | null | qmovstack.cpp | deepakm/deepquor | 6e7746ad7e9b359ed5b0567c580a97684a76ad12 | [
"BSD-3-Clause"
] | null | null | null | qmovstack.cpp | deepakm/deepquor | 6e7746ad7e9b359ed5b0567c580a97684a76ad12 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2005-2006
* Brent Miller and Charles Morrey. All rights reserved.
*
* See the COPYRIGHT_NOTICE file for terms.
*/
#include "qmovstack.h"
IDSTR("$Id: qmovstack.cpp,v 1.11 2006/07/31 06:25:50 bmiller Exp $");
/****/
/***********************
* class qWallMoveList *
***********************/
qMoveStack::qMoveStack
(const qPosition *pos, qPlayer player2move)
:sp(0)
{
moveStack[sp].resultingPos = *pos;
// moveStack[sp].move = qMove(); Unnecessary
moveStack[sp].wallMovesBlockedByMove.clearList();
moveStack[sp].playerMoved = qPlayer(player2move.getOtherPlayerId());
moveStack[sp].posInfo = NULL;
initWallMoveTable();
}
qMoveStack::~qMoveStack() {
return;
};
/* Good optimizations:
* !!! Prune "dead space" from the list of possible wall moves (well,
* everything after the first "dead" move).
* !!! Keep separate lists for white and black???
*/
void qMoveStack::initWallMoveTable()
{
qPosition pos = moveStack[0].resultingPos;
int rowColNo, posNo;
int rowOrCol;
qMove mv;
qWallMoveInfo *thisMove;
// Can't revise the wallMoveTable with a bunch of state in the stack
if (sp != 0) {
g_assert(sp==0);
return;
}
// 1st pass: construct list of all possible wall moves.
for (rowOrCol=1; rowOrCol >= 0; rowOrCol--)
for (rowColNo=7; rowColNo >= 0; rowColNo--)
for (posNo=7; posNo >= 0; posNo--)
{
mv = qMove(rowOrCol, rowColNo, posNo); // how about mv.qMove(...)???
thisMove = &allWallMoveArry[mv.getEncoding()];
thisMove->move = mv;
thisMove->possible = pos.canPutWall(rowOrCol, rowColNo, posNo);
thisMove->eliminates.clear();
if (thisMove->possible)
possibleWallMoves.push(thisMove);
else
thisMove->next = thisMove->prev = NULL;
}
// 2nd pass: for each possible move, note which future wall moves it blocks
#define MAYBE_ELIMINATE(m) if((m)->possible){thisMove->eliminates.push_back(m);}
for (thisMove=possibleWallMoves.getHead();
thisMove;
thisMove = thisMove->next)
{
mv = thisMove->move;
g_assert(mv.isWallMove());
if (mv.wallPosition()>0)
MAYBE_ELIMINATE(&allWallMoveArry[qMove(mv.wallMoveIsRow(),
mv.wallRowOrColNo(),
mv.wallPosition()-1).getEncoding()]);
if (mv.wallPosition()<7)
MAYBE_ELIMINATE(&allWallMoveArry[qMove(mv.wallMoveIsRow(),
mv.wallRowOrColNo(),
mv.wallPosition()+1).getEncoding()]);
MAYBE_ELIMINATE(&allWallMoveArry[qMove(!mv.wallMoveIsRow(),
mv.wallPosition(),
mv.wallRowOrColNo()).getEncoding()]);
}
}
void qMoveStack::pushMove
(qPlayer playerMoving,
qMove mv,
qPosition *endPos)
{
#define ARRAYSIZE(ARR) (sizeof(ARR)/sizeof((ARR)[0]))
g_assert(sp < ARRAYSIZE(moveStack));
qMoveStackFrame *frame = &moveStack[++sp];
// Record the move
frame->move = mv;
frame->playerMoved = playerMoving;
frame->posInfo = NULL;
// Record the new position
if (endPos)
frame->resultingPos = *endPos;
else
(frame->resultingPos = moveStack[sp-1].resultingPos).applyMove(playerMoving, mv);
if (mv.isPawnMove())
frame->wallMovesBlockedByMove.clearList();
else {
qWallMoveInfo *thisMove, *next;
list<qWallMoveInfo*>::iterator blockedMove;
thisMove = &allWallMoveArry[mv.getEncoding()];
g_assert(thisMove->possible == TRUE);
frame->wallMovesBlockedByMove.clearList();
// Of course, remove the wall placement from possible moves
thisMove->possible = FALSE;
possibleWallMoves.pop(thisMove);
frame->wallMovesBlockedByMove.push(thisMove);
// Remove any other wall move options that are now blocked
for (blockedMove=thisMove->eliminates.begin();
blockedMove != thisMove->eliminates.end();
++blockedMove)
{
if ((*blockedMove)->possible) {
(*blockedMove)->possible = FALSE;
possibleWallMoves.pop(*blockedMove);
frame->wallMovesBlockedByMove.push(*blockedMove);
}
}
}
return;
}
void qMoveStack::popMove
(void)
{
qWallMoveInfo *blockedMove, *next;
qMoveStackFrame *frame = &moveStack[sp--];
// Replace any wall moves that had been blocked by the popped move
while (blockedMove = frame->wallMovesBlockedByMove.pop())
{
blockedMove->possible = TRUE;
// !!! Optimization: we could insert the entire wallMovesBlockedByMove
// list into possibleWallMoves in one segment.
possibleWallMoves.push(blockedMove);
}
return;
}
/***************************
* class qWallMoveInfoList *
***************************/
qWallMoveInfoList::qWallMoveInfoList
(void):
head(NULL), tail(NULL)
{
DEBUG_CODE(numElts = 0;)
return;
}
#ifdef DEBUG
void qWallMoveInfoList::verifyEltCount()
{ // Make sure this mv isn't already in the info list (which will corrupt us)
qWallMoveInfo *tmp = head;
int countedElts = 0;
while (tmp) {
tmp = tmp->next;
countedElts++;
}
g_assert(countedElts == numElts);
}
#endif
void qWallMoveInfoList::push
(qWallMoveInfo *mv)
{
#ifdef DEBUG
{ // Make sure this mv isn't already in the info list (which will corrupt us)
qWallMoveInfo *tmp = head;
while (tmp) {
g_assert(tmp!=mv);
tmp = tmp->next;
}
}
#endif
DEBUG_CODE(verifyEltCount();)
mv->prev = NULL;
mv->next = head;
if (head) {
head->prev = mv;
} else {
tail = mv;
}
head = mv;
DEBUG_CODE(++numElts;)
DEBUG_CODE(verifyEltCount();) //Make sure we didn't break anything
}
void qWallMoveInfoList::pop
(qWallMoveInfo *mv)
{
#ifdef DEBUG
{ // Make sure the mv is actually in the list
qWallMoveInfo *tmp = head;
while (tmp) {
if (tmp==mv)
break;
tmp = tmp->next;
}
g_assert(tmp);
}
#endif
DEBUG_CODE(verifyEltCount();)
if (mv->next) {
mv->next->prev = mv->prev;
} else {
tail = mv->prev;
}
if (mv->prev) {
mv->prev->next = mv->next;
} else {
head = mv->next;
}
DEBUG_CODE(--numElts;)
DEBUG_CODE(verifyEltCount();) //Make sure we didn't break anything
}
qWallMoveInfo *qWallMoveInfoList::pop
(void)
{
DEBUG_CODE(verifyEltCount();)
qWallMoveInfo *rval=head;
if (head) {
head = head->next;
if (head)
head->prev = NULL;
else
tail = NULL;
}
DEBUG_CODE(if (rval) --numElts;)
DEBUG_CODE(verifyEltCount();) //Make sure we didn't break anything
return rval;
};
bool qMoveStack::getPossibleWallMoves(qMoveList *moveList) const
{
if (!moveList)
return FALSE;
qWallMoveInfo *c = possibleWallMoves.getHead();
while (c) {
g_assert(c->possible == TRUE);
moveList->push_back(c->move);
c = c->next;
}
return TRUE;
}
// Funcs that flag positions in the thought sequence (i.e. for evaluating
// moves temporarily rather than actually making them.
// These funcs use the positionHash to flag which moves are under evaluation
//
inline static void setMoveInEval
(qPositionInfo *posInfo, qPlayer playerToMove)
{
if (playerToMove.isWhite())
posInfo->setPositionFlagBits(qPositionInfo::flag_WhiteToMove);
else
posInfo->setPositionFlagBits(qPositionInfo::flag_BlackToMove);
}
inline static void clearMoveInEval
(qPositionInfo *posInfo, qPlayer playerToMove)
{
if (playerToMove.isWhite())
posInfo->clearPositionFlagBits(qPositionInfo::flag_WhiteToMove);
else
posInfo->clearPositionFlagBits(qPositionInfo::flag_BlackToMove);
}
qPositionInfo *qMoveStack::pushEval
(qPositionInfo *startPosInfo, // optimizer
qPositionInfo *endPosInfo, // optimizer
qPositionInfoHash *posHash, // reqd if endPosInfo==NULL or startPosInfo==NULL
qPlayer whoMoved, // From here down same
qMove move, // as pushMove()
qPosition *endPos)
{
g_assert(endPosInfo || posHash);
if (!endPosInfo && !posHash)
return NULL;
g_assert(whoMoved.getPlayerId() == this->getPlayer2Move().getPlayerId());
// 1. Mark position as under evaluation in posInfo w/setMoveInEval()
if (!this->moveStack[sp].posInfo) {
if (startPosInfo)
this->moveStack[sp].posInfo = startPosInfo;
else
this->moveStack[sp].posInfo = posHash->getOrAddElt(this->getPos());
}
g_assert(this->moveStack[sp].posInfo);
setMoveInEval(this->moveStack[sp].posInfo, whoMoved);
// 2. Push move onto stack with posInfo
if (!endPosInfo) {
if (!endPos) {
g_assert(this->getPos());
qPosition myPos = *this->getPos();
myPos.applyMove(whoMoved, move);
endPosInfo = posHash->getOrAddElt(&myPos);
this->pushMove(whoMoved, move, &myPos);
return endPosInfo;
}
endPosInfo = posHash->getOrAddElt(endPos);
}
this->pushMove(whoMoved, move, endPos);
return endPosInfo;
}
void qMoveStack::popEval(void)
{
// 1. Pop off to previous moveStack frame
this->popMove();
// Can't pop a move that's not in eval
g_assert(this->getPosInfo());
// 2. Mark the position we were examining as no longer under evaluation
clearMoveInEval(this->getPosInfo(), this->getPlayer2Move());
}
// This is a fast check--since revisiting positions is rare, it should
// be used before checking for which playerToMove is in the stack
inline static bool private_isInEvalStack
(qPositionInfo *posInfo)
{
return (posInfo->isPosExceptional() && (posInfo->getPositionFlag() > 0));
}
bool qMoveStack::isInEvalStack
(qPositionInfo *posInfo, qPlayer p) const
{
return (p.isWhite() ?
isWhiteMoveInEvalStack(posInfo) : isBlackMoveInEvalStack(posInfo));
}
bool qMoveStack::isWhiteMoveInEvalStack
(qPositionInfo *posInfo) const
{
return (private_isInEvalStack(posInfo) &&
(posInfo->getPositionFlag() & qPositionInfo::flag_WhiteToMove));
}
bool qMoveStack::isBlackMoveInEvalStack
(qPositionInfo *posInfo) const
{
return (private_isInEvalStack(posInfo) &&
(posInfo->getPositionFlag() & qPositionInfo::flag_BlackToMove));
}
| 25.038265 | 85 | 0.668263 | deepakm |
8d0e01232aa2658c99492909bfab42023691b260 | 4,777 | hpp | C++ | include/realm/core/system.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | 2 | 2020-03-01T18:15:27.000Z | 2020-03-25T10:21:59.000Z | include/realm/core/system.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | null | null | null | include/realm/core/system.hpp | pyrbin/realm.hpp | e34b18ce1f5c39b080a9e70f675adf740490ff83 | [
"MIT"
] | 1 | 2020-03-25T10:22:00.000Z | 2020-03-25T10:22:00.000Z | #pragma once
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <realm/core/archetype.hpp>
#include <realm/util/tuple_util.hpp>
namespace realm {
/**
* Forward declarations
*/
struct world;
template<typename... Ts>
struct view;
template<typename F>
constexpr internal::enable_if_query_fn<F, void> query(world* world, F&& f);
template<typename F>
constexpr internal::enable_if_query_fn<F, void> query_seq(world* world, F&& f);
/**
* @brief System meta
* Contains meta information about a system.
* Eg. which components it mutates/reads, mask etc.
*/
struct system_meta
{
const size_t mask{ 0 };
const size_t mut_mask{ 0 };
const size_t read_mask{ 0 };
template<typename... Args>
static constexpr system_meta from_pack()
{
using components = internal::component_tuple<Args...>;
size_t read{ 0 };
size_t mut{ 0 };
(from_pack_helper<Args>(read, mut), ...);
return { archetype::mask_from_tuple<components>(), mut, read };
}
template<typename F, typename... Args>
static constexpr system_meta of(void (F::*f)(Args...) const)
{
return from_pack<Args...>();
}
template<typename F, typename... Args>
static constexpr system_meta of(void (F::*f)(view<Args...>) const)
{
return from_pack<Args...>();
}
private:
template<typename T>
static constexpr void from_pack_helper(size_t& read, size_t& mut)
{
if constexpr (!internal::is_entity<T> && std::is_const_v<std::remove_reference_t<T>>) {
read |= component_meta::of<internal::pure_t<T>>().mask;
} else if constexpr (!internal::is_entity<T>) {
mut |= component_meta::of<internal::pure_t<T>>().mask;
}
}
};
/**
* @brief System reference
* Base system reference holder
*/
struct system_ref
{
const u64 id{ 0 };
const system_meta meta{ 0, 0 };
const std::string name{ "" };
system_ref() = default;
;
virtual ~system_ref() = default;
virtual bool compare(size_t hash) const = 0;
virtual bool mutates(size_t hash) const = 0;
virtual bool reads(size_t hash) const = 0;
virtual void invoke(world*) const = 0;
virtual void invoke_seq(world*) const = 0;
protected:
system_ref(const u64 id, system_meta meta, std::string name)
: id{ id }
, meta{ meta }
, name{ std::move(name) } {};
};
/**
* @brief System proxy
* A proxy class used to communicate with a defined system.
* Used to invoke the update function and uses query_helper functions to
* execute the query logic.
* @tparam T Underlying system class
*/
template<typename T>
struct system_proxy final : public system_ref
{
private:
/*! @brief Underlying system pointer */
const std::unique_ptr<T> instance_;
/*! @brief Creates a lamdba object to system update function */
template<typename R = void, typename... Args>
static constexpr auto update_lambda(const system_proxy<T>* proxy, void (T::*f)(Args...) const)
{
return [proxy, f](Args... args) -> void {
(proxy->instance_.get()->*f)(std::forward<Args>(args)...);
};
}
public:
/**
* Construct a system proxy from an object
* @param t Underlying system to make a proxy to
*/
explicit system_proxy(T& t)
: system_ref{ internal::identifier_hash_v<T>, system_meta::of(&T::update),
typeid(T).name() }
, instance_{ std::unique_ptr<T>(std::move(t)) }
{}
/**
* Construct a system proxy with arguments for the underlying system.
* @tparam Args Argument types
* @param args Arguments for underlying system
*/
template<typename... Args>
explicit system_proxy(Args&&... args)
: system_ref{ internal::identifier_hash_v<T>, system_meta::of(&T::update),
typeid(T).name() }
, instance_{ std::make_unique<T>(std::forward<Args>(args)...) }
{}
bool compare(const size_t other) const override { return archetype::subset(other, meta.mask); }
bool mutates(const size_t other) const override
{
return archetype::subset(meta.mut_mask, other);
}
bool reads(const size_t other) const override
{
return archetype::subset(meta.read_mask, other);
}
/**
* Call the system query on a world in parallel
* @param world
*/
[[nodiscard]] void invoke(world* world) const override
{
query(world, update_lambda(this, &T::update));
}
/**
* Call the system query on a world sequentially
* @param world
*/
[[nodiscard]] void invoke_seq(world* world) const override
{
query_seq(world, update_lambda(this, &T::update));
}
};
} // namespace realm | 27.297143 | 99 | 0.630731 | pyrbin |
8d0f08d6e0c4ebdcbfb75044839631e954ec1910 | 913 | cpp | C++ | Search Algorithms/C-CPP/LinearSearchSentinelValue.cpp | maulikchavda/Algorithms | 353010c3a88f7a239906d314a8a23f5cb9b21fd6 | [
"MIT"
] | 34 | 2019-10-02T15:27:03.000Z | 2021-07-13T03:48:43.000Z | Search Algorithms/C-CPP/LinearSearchSentinelValue.cpp | maulikchavda/Algorithms | 353010c3a88f7a239906d314a8a23f5cb9b21fd6 | [
"MIT"
] | 79 | 2019-10-02T14:44:25.000Z | 2021-12-17T14:54:42.000Z | Search Algorithms/C-CPP/LinearSearchSentinelValue.cpp | maulikchavda/Algorithms | 353010c3a88f7a239906d314a8a23f5cb9b21fd6 | [
"MIT"
] | 215 | 2019-02-27T09:04:48.000Z | 2021-12-17T10:53:12.000Z | //Linear research with a flag value that interrupts research until the value is found.
#include <iostream>
#define ELEMENTS 10
using namespace std;
bool research(int numSearch, int arr[]);
int main(){
int array[ELEMENTS] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int i;
int search;
bool found;
cout << "Array: ";
for(i=0; i<ELEMENTS; i++)
cout << " " << array[i];
cout << endl << "Insert number to search: ";
cin >> search;
found = research(search, array);
if(found)
cout << "The element is in the array." << endl;
else
cout << "Element not in the array." << endl;
return 0;
}
bool research(int numSearch, int arr[]){
bool found = false;
int i;
for (i=0; found == false && i<ELEMENTS; i++){
if(numSearch == arr[i])
found = true;
else
found = false;
}
return found;
} | 20.288889 | 86 | 0.544359 | maulikchavda |
8d113b4d4d99a7d401d40a781f59d327840b49b7 | 3,325 | cpp | C++ | HW2.cpp | banne2266/OS-NCTU-2020 | a579270bc9bcc415fecdad1728a5e74f19a1bfe2 | [
"MIT"
] | null | null | null | HW2.cpp | banne2266/OS-NCTU-2020 | a579270bc9bcc415fecdad1728a5e74f19a1bfe2 | [
"MIT"
] | null | null | null | HW2.cpp | banne2266/OS-NCTU-2020 | a579270bc9bcc415fecdad1728a5e74f19a1bfe2 | [
"MIT"
] | null | null | null | /*
Student No.: 07xx3xx
Student Name: xxxxxxx
Email: b-----------7@nctu.edu.tw
SE tag: xnxcxtxuxoxsx
Statement: I am fully aware that this program is not
supposed to be posted to a public server, such as a
public GitHub repository or a public web page.
*/
#include<bits/stdc++.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
pid_t pid;
int main()
{
int dim, size;
cout<<"Input the matrix dimension:";
cin>>dim;
size = dim * dim * sizeof(unsigned int);
int shmid_a, shmid_b, shmid_c;
unsigned int *shmaddr_a, *shmaddr_b, *shmaddr_c;
shmid_a = shmget(IPC_PRIVATE, size, IPC_CREAT|0600);
shmid_b = shmget(IPC_PRIVATE, size, IPC_CREAT|0600);
shmid_c = shmget(IPC_PRIVATE, size, IPC_CREAT|0600);
shmaddr_a = (unsigned int *) shmat(shmid_a, NULL, 0);
shmaddr_b = (unsigned int *) shmat(shmid_b, NULL, 0);
int idx = 0;
for(int i = 0; i < dim; i++){
for(int j = 0; j < dim; j++){
shmaddr_a[i*dim+j] = idx;
shmaddr_b[i*dim+j] = idx;
idx++;
}
}
for(int num = 1; num <= 16; num++){
struct timeval start, end;
gettimeofday(&start, 0);
int id = 0;
for(id = 0; id < num; id++){
pid = fork();
if(pid == 0)
break;
}
if(pid < 0){///fork error
fprintf(stderr, "Fork Failed");
exit(-1);
}
else if(pid == 0){///child
shmaddr_a = (unsigned int *) shmat(shmid_a, NULL, 0);
shmaddr_b = (unsigned int *) shmat(shmid_b, NULL, 0);
shmaddr_c = (unsigned int *) shmat(shmid_c, NULL, 0);
int num_to_calculate = dim / num + (((dim%num) == 0) ? 0 : 1);
int bottom = num_to_calculate * id, top = min (num_to_calculate * (id + 1), dim);
for(int i = bottom; i < top;i++){
for(int j = 0; j < dim;j++){
shmaddr_c[i*dim+j] = 0;
for(int k = 0; k < dim; k++){
shmaddr_c[i*dim+j] += shmaddr_a[i*dim+k] * shmaddr_b[k*dim+j];
}
}
}
shmdt(shmaddr_a);
shmdt(shmaddr_b);
shmdt(shmaddr_c);
return 0;
}
else{///parent
shmaddr_c = (unsigned int *) shmat(shmid_c, NULL, 0);
for(id = 0; id < num; id++)
wait(NULL);
gettimeofday(&end, 0);
int sec = end.tv_sec-start.tv_sec;
int usec = end.tv_usec-start.tv_usec;
unsigned int checksum = 0;
for(int i = 0; i < dim; i++){
for(int j = 0; j < dim; j++){
checksum += shmaddr_c[i*dim+j];
}
}
printf("Multiplying matrices using %d process", num);
(num > 1) ? printf("es\n") : printf("\n");
printf("Elapsed time: %f sec", sec+(usec/1000000.0));
printf(", Checksum: %u\n",checksum);
shmdt(shmaddr_a);
shmdt(shmaddr_b);
shmdt(shmaddr_c);
}
}
shmctl(shmid_a, IPC_RMID, NULL);
shmctl(shmid_b, IPC_RMID, NULL);
shmctl(shmid_c, IPC_RMID, NULL);
}
| 29.954955 | 93 | 0.502256 | banne2266 |
8d114342a7fa4f43cd2dcf2a26c1fc14ad8d9c88 | 844 | cpp | C++ | libmetartc5/src/yangutil/buffer/YangAudioBuffer.cpp | metartc/metaRTC | 7b3125c9244632c82c55aacd628e6f0d7b151488 | [
"MIT"
] | 136 | 2021-12-17T09:17:44.000Z | 2022-03-28T09:51:51.000Z | libmetartc5/src/yangutil/buffer/YangAudioBuffer.cpp | metartc/metaRTC | 7b3125c9244632c82c55aacd628e6f0d7b151488 | [
"MIT"
] | 2 | 2021-12-24T02:00:53.000Z | 2022-03-28T02:40:12.000Z | libmetartc5/src/yangutil/buffer/YangAudioBuffer.cpp | metartc/metaRTC | 7b3125c9244632c82c55aacd628e6f0d7b151488 | [
"MIT"
] | 40 | 2021-12-17T09:17:48.000Z | 2022-03-27T14:40:25.000Z | //
// Copyright (c) 2019-2022 yanggaofeng
//
#include "yangutil/buffer/YangAudioBuffer.h"
#include <stdlib.h>
#include "stdio.h"
YangAudioBuffer::YangAudioBuffer(int32_t pcacheNum)
{
resetIndex();
m_cache_num=pcacheNum;
m_bufLen=0;
}
void YangAudioBuffer::reset(){
resetIndex();
}
YangAudioBuffer::~YangAudioBuffer(void)
{
}
void YangAudioBuffer::putAudio(YangFrame* pframe)
{
if(m_bufLen==0){
m_bufLen=pframe->nb;
initFrames(m_cache_num,pframe->nb);
}
putFrame(pframe);
}
int32_t YangAudioBuffer::getAudio(YangFrame* pframe)
{
if(size()>0){
getFrame(pframe);
return 0;
}else
return 1;
}
uint8_t *YangAudioBuffer::getAudioRef(YangFrame* pframe)
{
if(size()>0){
return getFrameRef(pframe);
}else{
return NULL;
}
}
| 15.071429 | 57 | 0.632701 | metartc |
8d1258dc0ff0b4a25312f6a3661cefc9e7e25368 | 11,376 | cpp | C++ | yoshicar_base_controller/src/MotorStateMachine.cpp | Badenhoop/yoshicar | c542e75dccf73b006a6483ced357168c15d893fe | [
"MIT"
] | null | null | null | yoshicar_base_controller/src/MotorStateMachine.cpp | Badenhoop/yoshicar | c542e75dccf73b006a6483ced357168c15d893fe | [
"MIT"
] | null | null | null | yoshicar_base_controller/src/MotorStateMachine.cpp | Badenhoop/yoshicar | c542e75dccf73b006a6483ced357168c15d893fe | [
"MIT"
] | 1 | 2020-09-11T17:54:54.000Z | 2020-09-11T17:54:54.000Z | #include "yoshicar_base_controller/MotorStateMachine.h"
namespace yoshicar
{
double varianceDecay(double t, double vStart, double vEnd, double duration)
{
double vDelta = vStart - vEnd;
return vStart - (vDelta / (1 + std::exp(-(12. / duration * t - 6.))));
}
MotorStateMachine::MotorStateMachine()
{
ros::NodeHandle nh;
ros::NodeHandle nhPriv;
targetVelocitySubscriber =
nh.subscribe<std_msgs::Float64>("target_velocity", 1, &MotorStateMachine::targetVelocityCallback, this);
isDrivingSubscriber = nh.subscribe<std_msgs::Bool>("is_driving", 1, &MotorStateMachine::isDrivingCallback, this);
motorCommandPublisher = nh.advertise<std_msgs::Float64>("motor", 1);
estimatedVelocityPublisher = nh.advertise<yoshicar_msgs::VelocityEstimate>("msm_velocity_estimate", 1);
auto updatePeriod = nhPriv.param<double>("msm_update_period", 0.01);
stateUpdateTimer = nh.createTimer(
ros::Duration(updatePeriod), [this] { updateCallback(); }, false);
state = std::make_unique<StoppedMotorState>();
}
void MotorStateMachine::targetVelocityCallback(const std_msgs::Float64ConstPtr& msg)
{
performEvent([&] { return state->targetVelocityEvent(msg->data); });
}
void MotorStateMachine::isDrivingCallback(const std_msgs::BoolConstPtr& msg)
{
performEvent([&] { return state->isDrivingEvent(msg->data); });
}
void MotorStateMachine::updateCallback()
{
performEvent([&] { return state->updateEvent(); });
std_msgs::Float64 motorCommand;
motorCommand.data = state->getMotorCommand();
motorCommandPublisher.publish(motorCommand);
estimatedVelocityPublisher.publish(state->getVelocityEstimate());
}
void MotorStateMachine::performEvent(const std::function<MotorStatePtr()>& event)
{
auto newState = event();
if (newState == nullptr)
return;
state = std::move(newState);
}
StoppedMotorState::StoppedMotorState() : MotorState()
{
ros::NodeHandle nhPriv{ "~" };
brakeReleaseDuration = nhPriv.param<double>("brake_release_duration", 0.2);
}
MotorStatePtr StoppedMotorState::targetVelocityEvent(double targetVelocity)
{
return nullptr;
}
MotorStatePtr StoppedMotorState::isDrivingEvent(bool isDriving)
{
return nullptr;
}
MotorStatePtr StoppedMotorState::updateEvent()
{
if (ros::Time::now() - startTime > ros::Duration{ brakeReleaseDuration })
return std::make_unique<ReleasedBrakeMotorState>();
return nullptr;
}
double StoppedMotorState::getMotorCommand() const
{
return 0.;
}
yoshicar_msgs::VelocityEstimate StoppedMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
MotorStatePtr ReleasedBrakeMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity > 0.)
return std::make_unique<ForwardCommandMotorState>(targetVelocity);
if (targetVelocity < 0.)
return std::make_unique<ReverseCommandMotorState>(targetVelocity);
return nullptr;
}
MotorStatePtr ReleasedBrakeMotorState::isDrivingEvent(bool isDriving)
{
return nullptr;
}
MotorStatePtr ReleasedBrakeMotorState::updateEvent()
{
return nullptr;
}
double ReleasedBrakeMotorState::getMotorCommand() const
{
return 0.;
}
yoshicar_msgs::VelocityEstimate ReleasedBrakeMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
ForwardDrivingMotorState::ForwardDrivingMotorState(double currTargetVelocity)
: MotorState(), currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ForwardDrivingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity <= 0.)
return std::make_unique<ForwardBrakingMotorState>(currTargetVelocity);
double currMotorCommand = config.velocityToMotorCommand(currTargetVelocity);
double nextMotorCommand = config.velocityToMotorCommand(targetVelocity);
if (currMotorCommand == nextMotorCommand)
return nullptr;
// If the new target velocity results in a new motor command, we perform
// a self transition with the new target velocity
return std::make_unique<ForwardDrivingMotorState>(targetVelocity);
}
MotorStatePtr ForwardDrivingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
// This may only happen if the motor fails for some reason
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ForwardDrivingMotorState::updateEvent()
{
return nullptr;
}
double ForwardDrivingMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ForwardDrivingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
if (currTargetVelocity < config.getMinForwardVelocity())
{
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
estimate.velocity = currTargetVelocity;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, currTargetVelocity, currTargetVelocity * 0.1, 1.);
return estimate;
}
ForwardBrakingMotorState::ForwardBrakingMotorState(double prevTargetVelocity)
: MotorState(), prevTargetVelocity(prevTargetVelocity)
{
ros::NodeHandle nhPriv;
brakeMotorCommand = nhPriv.param<double>("forward_brake_motor_command", -1.);
}
MotorStatePtr ForwardBrakingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity <= 0.)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(targetVelocity);
}
MotorStatePtr ForwardBrakingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ForwardBrakingMotorState::updateEvent()
{
if (ros::Time::now() - startTime > ros::Duration{ 5. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ForwardBrakingMotorState::getMotorCommand() const
{
return brakeMotorCommand;
}
yoshicar_msgs::VelocityEstimate ForwardBrakingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, prevTargetVelocity * prevTargetVelocity, 0.01, 1.);
return estimate;
}
ForwardCommandMotorState::ForwardCommandMotorState(double currTargetVelocity) : currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ForwardCommandMotorState::targetVelocityEvent(double targetVelocity)
{
currTargetVelocity = targetVelocity;
return nullptr;
}
MotorStatePtr ForwardCommandMotorState::isDrivingEvent(bool isDriving)
{
if (!isDriving)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(currTargetVelocity);
}
MotorStatePtr ForwardCommandMotorState::updateEvent()
{
// In case the ESC is still in the weird state of not having
// recognized that we released the brakes we go back to the stop state
if (ros::Time::now() - startTime > ros::Duration{ 1. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ForwardCommandMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ForwardCommandMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
ReverseDrivingMotorState::ReverseDrivingMotorState(double currTargetVelocity)
: MotorState(), currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ReverseDrivingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity >= 0.)
return std::make_unique<ReverseBrakingMotorState>(currTargetVelocity);
double currMotorCommand = config.velocityToMotorCommand(currTargetVelocity);
double nextMotorCommand = config.velocityToMotorCommand(targetVelocity);
if (currMotorCommand == nextMotorCommand)
return nullptr;
// If the new target velocity results in a new motor command, we perform
// a self transition with the new target velocity
return std::make_unique<ReverseDrivingMotorState>(targetVelocity);
}
MotorStatePtr ReverseDrivingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
// This may only happen if the motor fails for some reason
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ReverseDrivingMotorState::updateEvent()
{
return nullptr;
}
double ReverseDrivingMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ReverseDrivingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
if (currTargetVelocity < config.getMinReverseVelocity())
{
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
estimate.velocity = currTargetVelocity;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, currTargetVelocity, currTargetVelocity * 0.1, 1.);
return estimate;
}
ReverseBrakingMotorState::ReverseBrakingMotorState(double prevTargetVelocity)
: MotorState(), prevTargetVelocity(prevTargetVelocity)
{
ros::NodeHandle nhPriv;
brakeMotorCommand = nhPriv.param<double>("reverse_brake_motor_command", 0.);
}
MotorStatePtr ReverseBrakingMotorState::targetVelocityEvent(double targetVelocity)
{
if (targetVelocity >= 0.)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(targetVelocity);
}
MotorStatePtr ReverseBrakingMotorState::isDrivingEvent(bool isDriving)
{
if (isDriving)
return nullptr;
return std::make_unique<StoppedMotorState>();
}
MotorStatePtr ReverseBrakingMotorState::updateEvent()
{
if (ros::Time::now() - startTime > ros::Duration{ 5. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ReverseBrakingMotorState::getMotorCommand() const
{
return brakeMotorCommand;
}
yoshicar_msgs::VelocityEstimate ReverseBrakingMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
double t = (ros::Time::now() - startTime).toSec();
estimate.variance = varianceDecay(t, prevTargetVelocity * prevTargetVelocity, 0.01, 1.);
return estimate;
}
ReverseCommandMotorState::ReverseCommandMotorState(double currTargetVelocity) : currTargetVelocity(currTargetVelocity)
{
}
MotorStatePtr ReverseCommandMotorState::targetVelocityEvent(double targetVelocity)
{
currTargetVelocity = targetVelocity;
return nullptr;
}
MotorStatePtr ReverseCommandMotorState::isDrivingEvent(bool isDriving)
{
if (!isDriving)
return nullptr;
return std::make_unique<ForwardDrivingMotorState>(currTargetVelocity);
}
MotorStatePtr ReverseCommandMotorState::updateEvent()
{
// In case the ESC is still in the weird state of not having
// recognized that we released the brakes we go back to the stop state
if (ros::Time::now() - startTime > ros::Duration{ 1. })
return std::make_unique<StoppedMotorState>();
return nullptr;
}
double ReverseCommandMotorState::getMotorCommand() const
{
return config.velocityToMotorCommand(currTargetVelocity);
}
yoshicar_msgs::VelocityEstimate ReverseCommandMotorState::getVelocityEstimate() const
{
yoshicar_msgs::VelocityEstimate estimate;
estimate.velocity = 0.;
estimate.variance = 0.01;
return estimate;
}
} // namespace yoshicar | 27.61165 | 118 | 0.774701 | Badenhoop |
8d12ccf482d8cb7b41e22716dbce49e1f2cff68b | 3,381 | cc | C++ | src/scsi2sd-util6/libzipper-1.0.4/Compressor.cc | fhgwright/SCSI2SD-V6 | 29555b30d3f96257ac12a546e75891490603aee8 | [
"BSD-3-Clause"
] | 2 | 2020-11-29T01:28:03.000Z | 2021-11-07T18:23:11.000Z | src/scsi2sd-util6/libzipper-1.0.4/Compressor.cc | tweakoz/SCSI2SD-V6 | 77db5f86712213e25c9b12fa5c9fa9c54b80cb80 | [
"BSD-3-Clause"
] | null | null | null | src/scsi2sd-util6/libzipper-1.0.4/Compressor.cc | tweakoz/SCSI2SD-V6 | 77db5f86712213e25c9b12fa5c9fa9c54b80cb80 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2011 Michael McMaster <michael@codesrc.com>
//
// This file is part of libzipper.
//
// libzipper 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.
//
// libzipper 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 libzipper. If not, see <http://www.gnu.org/licenses/>.
#include "zipper.hh"
#include "gzip.hh"
#include "zip.hh"
#include "util.hh"
#include <algorithm>
using namespace zipper;
class Compressor::CompressorImpl
{
public:
virtual ~CompressorImpl() {}
virtual void
addFile(const std::string& filename, const Reader& reader) = 0;
};
namespace
{
class PlainCompressor : public Compressor::CompressorImpl
{
public:
PlainCompressor(const WriterPtr& writer) : m_writer(writer) {}
virtual void
addFile(const std::string&, const Reader& reader)
{
enum Constants
{
ChunkSize = 64*1024
};
uint8_t buffer[ChunkSize];
zsize_t offset(0);
while (offset < reader.getSize())
{
zsize_t bytes(
std::min(zsize_t(ChunkSize), reader.getSize() - offset));
reader.readData(offset, bytes, &buffer[0]);
m_writer->writeData(offset, bytes, &buffer[0]);
offset += bytes;
}
}
private:
WriterPtr m_writer;
};
class ZipCompressor : public Compressor::CompressorImpl
{
public:
ZipCompressor(const WriterPtr& writer) : m_writer(writer) {}
virtual ~ZipCompressor()
{
zipFinalise(m_records, m_writer);
}
virtual void
addFile(const std::string& filename, const Reader& reader)
{
ZipFileRecord record;
zip(filename, reader, m_writer, record);
m_records.push_back(record);
}
private:
WriterPtr m_writer;
std::vector<ZipFileRecord> m_records;
};
class GzipCompressor : public Compressor::CompressorImpl
{
public:
GzipCompressor(const WriterPtr& writer) : m_writer(writer) {}
virtual void
addFile(const std::string& filename, const Reader& reader)
{
gzip(filename, reader, m_writer);
}
private:
WriterPtr m_writer;
};
}
Compressor::Compressor(ContainerFormat format, const WriterPtr& writer)
{
switch (format)
{
case Container_none:
m_compressor = new PlainCompressor(writer); break;
case Container_zip:
m_compressor = new ZipCompressor(writer); break;
case Container_gzip:
m_compressor = new GzipCompressor(writer); break;
default:
throw UnsupportedException("Unknown format");
}
}
Compressor::Compressor(ContainerFormat format, Writer& writer) :
m_compressor(NULL)
{
WriterPtr ptr(&writer, dummy_delete<Writer>());
switch (format)
{
case Container_none:
m_compressor = new PlainCompressor(ptr); break;
case Container_zip:
m_compressor = new ZipCompressor(ptr); break;
case Container_gzip:
m_compressor = new GzipCompressor(ptr); break;
default:
throw UnsupportedException("Unknown format");
}
}
Compressor::~Compressor()
{
delete m_compressor;
}
void
Compressor::addFile(const Reader& reader)
{
m_compressor->addFile(reader.getSourceName(), reader);
}
| 22.098039 | 71 | 0.722272 | fhgwright |
8d1899c71f93415feb9a58504bd0fe6f2a068d19 | 985 | hpp | C++ | include/commata/buffer_size.hpp | furfurylic/commata | 6afbc218d262d8363e8436fd943b1e13444d9f83 | [
"Unlicense"
] | null | null | null | include/commata/buffer_size.hpp | furfurylic/commata | 6afbc218d262d8363e8436fd943b1e13444d9f83 | [
"Unlicense"
] | null | null | null | include/commata/buffer_size.hpp | furfurylic/commata | 6afbc218d262d8363e8436fd943b1e13444d9f83 | [
"Unlicense"
] | null | null | null | /**
* These codes are licensed under the Unlicense.
* http://unlicense.org
*/
#ifndef COMMATA_GUARD_4E257056_FA43_4ED4_BF21_5638E8C46B14
#define COMMATA_GUARD_4E257056_FA43_4ED4_BF21_5638E8C46B14
#include <algorithm>
#include <cstddef>
#include <memory>
#include <limits>
namespace commata { namespace detail {
template <class Allocator>
std::size_t sanitize_buffer_size(
std::size_t buffer_size, Allocator alloc) noexcept
{
constexpr std::size_t buffer_size_max =
std::numeric_limits<std::size_t>::max();
constexpr std::size_t default_buffer_size =
std::min(buffer_size_max, static_cast<std::size_t>(8192U));
if (buffer_size == 0U) {
buffer_size = default_buffer_size;
}
const auto max_alloc0 = std::allocator_traits<Allocator>::max_size(alloc);
const auto max_alloc = (max_alloc0 > buffer_size_max) ?
static_cast<std::size_t>(buffer_size_max) : max_alloc0;
return std::min(buffer_size, max_alloc);
}
}}
#endif
| 27.361111 | 78 | 0.73198 | furfurylic |
8d18dce8c0d87e8faec199a4ebe1b70ccb7b6f32 | 2,626 | cc | C++ | algo/timsort.cc | anqurvanillapy/cppl | a15231dd0bd68b8857f6596fbf2604b86e5ffd89 | [
"MIT"
] | 1 | 2019-08-24T22:46:16.000Z | 2019-08-24T22:46:16.000Z | algo/timsort.cc | anqurvanillapy/cppl | a15231dd0bd68b8857f6596fbf2604b86e5ffd89 | [
"MIT"
] | 2 | 2018-11-12T12:20:52.000Z | 2019-06-05T06:58:34.000Z | algo/timsort.cc | anqurvanillapy/cppl | a15231dd0bd68b8857f6596fbf2604b86e5ffd89 | [
"MIT"
] | 2 | 2019-04-03T10:01:05.000Z | 2021-05-31T07:39:44.000Z | /**
* timsort
* =======
*
* Very naive implementation of the *glorious* timsort, sarcasm intended.
*
* Note: Compile with -std=c++17.
*/
#include <iostream>
#include <vector>
#include <cmath>
namespace {
template <typename T>
void
debug(const std::vector<T>& v)
{
std::cout << "[";
for (auto&& i : v) std::cout << i << ",";
if (!v.empty()) std::cout << "\b";
std::cout << "]" << std::endl;
}
template <typename T>
size_t
binsearch(const std::vector<T>& v, T val, size_t start, size_t end)
{
if (start < end) {
auto mid = std::round((start + end) / 2);
if (v[mid] < val) {
return binsearch(v, val, mid + 1, end);
} else if (v[mid] > val) {
return binsearch(v, val, start, mid - 1);
} else {
return mid;
}
} else if (start == end) {
return v[start] > val ? start : start + 1;
} else {
return start;
}
}
template <typename T>
auto
insertsort(std::vector<T>& v)
{
const auto siz = v.size();
for (size_t i = 1; i < siz; ++i) {
auto pos = binsearch(v, v[i], 0, i - 1);
auto item = v[i];
v.erase(v.begin() + i);
v.insert(v.begin() + pos, item);
}
return v;
}
template <typename T>
auto
merge(std::vector<T> lhs, std::vector<T> rhs)
{
if (lhs.empty()) {
return rhs;
}
if (rhs.empty()) {
return lhs;
}
auto v1 = std::vector<T>();
if (lhs[0] < rhs[0]) {
auto v2 = merge(std::vector<T>(lhs.begin() + 1, lhs.end()), rhs);
v1.push_back(lhs[0]);
v1.insert(v1.end(), v2.begin(), v2.end());
return v1;
}
auto v2 = merge(lhs, std::vector<T>(rhs.begin() + 1, rhs.end()));
v1.push_back(rhs[0]);
v1.insert(v1.end(), v2.begin(), v2.end());
return v1;
}
} /* namespace */
template <typename T>
std::vector<T>
timsort(const std::vector<T>& v)
{
const auto siz = v.size();
auto unsorted_runs = std::vector<std::vector<T>>();
auto sorted_runs = std::vector<std::vector<T>>();
auto run = std::vector{v[0]};
for (size_t i = 1; i < siz - 1; ++i) {
if (v[i] < v[i - 1]) {
if (run.empty()) {
auto item = v[i];
unsorted_runs.push_back(std::vector{item});
run.push_back(item);
} else {
unsorted_runs.push_back(run);
run.clear();
run.push_back(v[i]);
}
} else {
run.push_back(v[i]);
}
}
run.push_back(v[siz - 1]);
unsorted_runs.push_back(run);
for (auto&& r : unsorted_runs) {
sorted_runs.push_back(insertsort(r));
}
auto sorted = std::vector<T>();
for (auto&& r : sorted_runs) {
sorted = merge(sorted, r);
}
return sorted;
}
int
main()
{
debug(timsort(std::vector{2, 8, 3, 1, 5, 6, 4, 7}));
debug(timsort(std::vector{8, 7, 6, 5, 4, 3, 2, 1}));
debug(timsort(std::vector{1, 1, 1, 1}));
return 0;
}
| 18.892086 | 74 | 0.573496 | anqurvanillapy |
8d1907f99094d3d56c755e085ed46f84e01ba9bc | 1,130 | hh | C++ | src/circuit/pws_circuit.hh | hyraxZK/libpws | cc1b7dfdafb3d01b025cdb72ed83379d205a0147 | [
"Apache-2.0"
] | null | null | null | src/circuit/pws_circuit.hh | hyraxZK/libpws | cc1b7dfdafb3d01b025cdb72ed83379d205a0147 | [
"Apache-2.0"
] | null | null | null | src/circuit/pws_circuit.hh | hyraxZK/libpws | cc1b7dfdafb3d01b025cdb72ed83379d205a0147 | [
"Apache-2.0"
] | 1 | 2020-01-16T07:49:03.000Z | 2020-01-16T07:49:03.000Z | #pragma once
#include <vector>
#include <map>
#include "pws_circuit_parser.hh"
#include "cmt_circuit.hh"
#include "cmt_circuit_builder.hh"
class PWSCircuit : public CMTCircuit
{
private:
PWSCircuitParser& parser;
public:
PWSCircuit(PWSCircuitParser& pp);
Gate getGate(const GatePosition& pos);
CircuitLayer& getGatePosLayer(int gatePosLayer);
void evalGates(const std::vector<int>& start);
void evalGates(const std::vector<int>& start, const std::vector<int>& end);
virtual void evaluate();
virtual void initializeInputs(const MPQVector& inputs, const MPQVector& magic = MPQVector(0));
virtual void initializeOutputs(const MPQVector& outputs);
protected:
virtual void constructCircuit();
private:
void makeGateMapping(std::vector<Gate*>& gates, CircuitLayer& layer, const std::vector<int>& mapping);
void makeGateMapping(std::vector<Gate*>& gates, CircuitLayer& layer, const std::map<int, int>& mapping, int offset);
};
class PWSCircuitBuilder : public CMTCircuitBuilder
{
PWSCircuitParser& parser;
public:
PWSCircuitBuilder(PWSCircuitParser& pp);
PWSCircuit* buildCircuit();
};
| 25.681818 | 118 | 0.749558 | hyraxZK |
8d1937e31390cb045049750326c9a316f7be292e | 847 | cpp | C++ | cpgf/src/metadata/irrlicht/meta_irrlicht_IParticleSystemSceneNode.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | 187 | 2015-01-19T06:05:30.000Z | 2022-03-27T14:28:21.000Z | cpgf/src/metadata/irrlicht/meta_irrlicht_IParticleSystemSceneNode.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | 37 | 2015-01-16T04:15:11.000Z | 2020-03-31T23:42:55.000Z | cpgf/src/metadata/irrlicht/meta_irrlicht_IParticleSystemSceneNode.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | 50 | 2015-01-13T13:50:10.000Z | 2022-01-25T17:16:51.000Z | // Auto generated file, don't modify.
#include "irrlicht.h"
#include "IParticleSystemSceneNode.h"
#include "cpgf/metadata/irrlicht/meta_irrlicht_IParticleSystemSceneNode.h"
using namespace cpgf;
namespace meta_irrlicht {
GDefineMetaInfo createMetaClass_IParticleSystemSceneNode()
{
GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle();
{
GDefineMetaClass<irr::scene::IParticleSystemSceneNode, irr::scene::ISceneNode> _nd = GDefineMetaClass<irr::scene::IParticleSystemSceneNode, irr::scene::ISceneNode>::Policy<MakePolicy<GMetaRuleDefaultConstructorAbsent, GMetaRuleDefaultConstructorAbsent, GMetaRuleCopyConstructorAbsent> >::declare("IParticleSystemSceneNode");
buildMetaClass_IParticleSystemSceneNode(0, _nd);
_d._class(_nd);
}
return _d.getMetaInfo();
}
} // namespace meta_irrlicht
| 30.25 | 332 | 0.782763 | mousepawmedia |
8d1b7b5c7e67cb8d38f63cbe0f613a59b08398cb | 1,786 | hpp | C++ | gk++/include/gk/gk++.hpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | 11 | 2016-04-28T15:09:19.000Z | 2019-07-15T15:58:59.000Z | gk++/include/gk/gk++.hpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | null | null | null | gk++/include/gk/gk++.hpp | rpav/GameKernel | 1f3eb863b58243f5f14aa76283b60a259d881522 | [
"MIT"
] | null | null | null | #pragma once
/*
This uses a slight bit of STL. You can probably replace this with
a slimmer implementation without issues.
This also abuses templates and virtuals a bit to keep code concise.
*/
#include <stdexcept>
#include <vector>
#include <rpav/ptr.hpp>
#include "gk/gk++cmd.hpp"
#include "gk/gk++list.hpp"
#include "gk/gk++util.hpp"
#include "gk/gk.h"
namespace gk {
class Error : public std::runtime_error {
public:
gk_error_code code{};
Error(gk_error_code code, const char* msg) : runtime_error{msg}, code{code} {}
};
class Bundle {
ListVector lists;
public:
Bundle(unsigned int start = 0, gk_pass_sorting sort = GK_PASS_SORT_NONE);
~Bundle() {}
void handleError();
gk_bundle bundle;
template<typename... Rest>
inline void add(ListBase& list, Rest&... args)
{
lists.push_back(list.listPtr());
add(args...);
}
inline void add()
{
bundle.nlists = lists.size();
bundle.lists = lists.data();
}
inline void clear()
{
lists.clear();
bundle.nlists = 0;
bundle.lists = nullptr;
}
};
struct Context {
rpav::ptr<gk_context> ctx;
Context(gk_impl impl) { ctx = gk_create(impl); }
~Context() { gk_destroy(ctx); }
operator gk_context*() { return ctx; }
operator const gk_context*() const { return ctx; }
inline void process(Bundle& bundle)
{
gk_process(ctx, &bundle.bundle);
if(bundle.bundle.error.code) bundle.handleError();
}
template<typename L, typename...Ts>
inline void process(Ts&...vs) {
gk::Bundle b;
L list;
b.add(list);
list.add(vs...);
process(b);
}
};
} // namespace gk
#define BEGIN_NS_GK namespace gk {
#define END_NS_GK }
| 20.067416 | 82 | 0.613102 | rpav |
8d1fd7bf29ba66561d978fedc39bfcdc5314ea61 | 5,190 | cpp | C++ | Engine/Source/Editor/UnrealEd/Private/Fbx/FbxAssetImportData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Editor/UnrealEd/Private/Fbx/FbxAssetImportData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Editor/UnrealEd/Private/Fbx/FbxAssetImportData.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "Factories/FbxAssetImportData.h"
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "UObject/UObjectGlobals.h"
#include "UObject/UObjectBaseUtility.h"
#include "UObject/UObjectHash.h"
#include "UObject/Object.h"
#include "UObject/Class.h"
#include "UObject/UnrealType.h"
#include "ConfigCacheIni.h"
#include "FbxImporter.h"
UFbxAssetImportData::UFbxAssetImportData(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, ImportTranslation(0)
, ImportRotation(0)
, ImportUniformScale(1.0f)
, bConvertScene(true)
, bForceFrontXAxis(false)
, bConvertSceneUnit(false)
, bImportAsScene(false)
, FbxSceneImportDataReference(nullptr)
{
}
/** Load UI settings from ini file */
void UFbxAssetImportData::LoadOptions()
{
int32 PortFlags = 0;
for (UProperty* Property = GetClass()->PropertyLink; Property; Property = Property->PropertyLinkNext)
{
if (!Property->HasAnyPropertyFlags(CPF_Config))
{
continue;
}
FString Section = TEXT("FBX_Import_UI_Option_") + GetClass()->GetName();
FString Key = Property->GetName();
const bool bIsPropertyInherited = Property->GetOwnerClass() != GetClass();
UObject* SuperClassDefaultObject = GetClass()->GetSuperClass()->GetDefaultObject();
const FString& PropFileName = GEditorPerProjectIni;
UArrayProperty* Array = dynamic_cast<UArrayProperty*>(Property);
if (Array)
{
FConfigSection* Sec = GConfig->GetSectionPrivate(*Section, 0, 1, *GEditorPerProjectIni);
if (Sec != nullptr)
{
TArray<FConfigValue> List;
const FName KeyName(*Key, FNAME_Find);
Sec->MultiFind(KeyName, List);
FScriptArrayHelper_InContainer ArrayHelper(Array, this);
// Only override default properties if there is something to override them with.
if (List.Num() > 0)
{
ArrayHelper.EmptyAndAddValues(List.Num());
for (int32 i = List.Num() - 1, c = 0; i >= 0; i--, c++)
{
Array->Inner->ImportText(*List[i].GetValue(), ArrayHelper.GetRawPtr(c), PortFlags, this);
}
}
else
{
int32 Index = 0;
const FConfigValue* ElementValue = nullptr;
do
{
// Add array index number to end of key
FString IndexedKey = FString::Printf(TEXT("%s[%i]"), *Key, Index);
// Try to find value of key
const FName IndexedName(*IndexedKey, FNAME_Find);
if (IndexedName == NAME_None)
{
break;
}
ElementValue = Sec->Find(IndexedName);
// If found, import the element
if (ElementValue != nullptr)
{
// expand the array if necessary so that Index is a valid element
ArrayHelper.ExpandForIndex(Index);
Array->Inner->ImportText(*ElementValue->GetValue(), ArrayHelper.GetRawPtr(Index), PortFlags, this);
}
Index++;
} while (ElementValue || Index < ArrayHelper.Num());
}
}
}
else
{
for (int32 i = 0; i < Property->ArrayDim; i++)
{
if (Property->ArrayDim != 1)
{
Key = FString::Printf(TEXT("%s[%i]"), *Property->GetName(), i);
}
FString Value;
bool bFoundValue = GConfig->GetString(*Section, *Key, Value, *GEditorPerProjectIni);
if (bFoundValue)
{
if (Property->ImportText(*Value, Property->ContainerPtrToValuePtr<uint8>(this, i), PortFlags, this) == NULL)
{
// this should be an error as the properties from the .ini / .int file are not correctly being read in and probably are affecting things in subtle ways
UE_LOG(LogFbx, Error, TEXT("FBX Options LoadOptions (%s): import failed for %s in: %s"), *GetPathName(), *Property->GetName(), *Value);
}
}
}
}
}
}
/** Save UI settings to ini file */
void UFbxAssetImportData::SaveOptions()
{
int32 PortFlags = 0;
for (UProperty* Property = GetClass()->PropertyLink; Property; Property = Property->PropertyLinkNext)
{
if (!Property->HasAnyPropertyFlags(CPF_Config))
{
continue;
}
FString Section = TEXT("FBX_Import_UI_Option_") + GetClass()->GetName();
FString Key = Property->GetName();
const bool bIsPropertyInherited = Property->GetOwnerClass() != GetClass();
UObject* SuperClassDefaultObject = GetClass()->GetSuperClass()->GetDefaultObject();
UArrayProperty* Array = dynamic_cast<UArrayProperty*>(Property);
if (Array)
{
FConfigSection* Sec = GConfig->GetSectionPrivate(*Section, 1, 0, *GEditorPerProjectIni);
check(Sec);
Sec->Remove(*Key);
FScriptArrayHelper_InContainer ArrayHelper(Array, this);
for (int32 i = 0; i < ArrayHelper.Num(); i++)
{
FString Buffer;
Array->Inner->ExportTextItem(Buffer, ArrayHelper.GetRawPtr(i), ArrayHelper.GetRawPtr(i), this, PortFlags);
Sec->Add(*Key, *Buffer);
}
}
else
{
TCHAR TempKey[MAX_SPRINTF] = TEXT("");
for (int32 Index = 0; Index < Property->ArrayDim; Index++)
{
if (Property->ArrayDim != 1)
{
FCString::Sprintf(TempKey, TEXT("%s[%i]"), *Property->GetName(), Index);
Key = TempKey;
}
FString Value;
Property->ExportText_InContainer(Index, Value, this, this, this, PortFlags);
GConfig->SetString(*Section, *Key, *Value, *GEditorPerProjectIni);
}
}
}
GConfig->Flush(0);
}
| 29.657143 | 157 | 0.672832 | windystrife |
8d203b2bb42da1d3c8d32247b41c2f65a1c6d5f5 | 2,361 | cpp | C++ | src/byte_array.cpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | src/byte_array.cpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | src/byte_array.cpp | rnascunha/my_async | 5fbe3a46e87a2d74fc07d16252a3b3cf488b4684 | [
"MIT"
] | null | null | null | #include "my_async/util/byte_array.h"
#include <ostream>
#include <iomanip>
#include <sstream>
std::string Byte_Array::to_hex(bool up_case /* = true */, const char* separator /* = "" */,
unsigned int byte_space /* = 1 */) const
{
std::ostringstream ret;
for (std::string::size_type i = 0; i < size(); ++i){
ret << byte_to_hex(this->at(i), up_case);
if((i + 1) != size() && ((i+1) % byte_space) == 0){
ret << separator;
}
}
return std::move(ret.str());
}
std::string Byte_Array::to_string() const
{
std::string s(reinterpret_cast<char const*>(data()), size());
return s;
}
std::string Byte_Array::to_scape_string(Byte_Array::Escape_Format format /* = PRINTF */,
const char* enclose_begin /* = "\\" */, const char* enclose_end /* = "" */)
{
std::string str;
for(unsigned int i = 0; i < size(); i++){
if(isprint((int)at(i)) && (int)at(i) != '\\'){
str.push_back(at(i));
continue;
}
str += enclose_begin;
if(format == PRINTF){
switch(at(i)){
case 0x5C:
str.push_back('\\');
break;
case 0xA:
str.push_back('n');
break;
case 0xD:
str.push_back('n');
break;
case 0x9:
str.push_back('t');
break;
case 0xB:
str.push_back('v');
break;
default:
str.push_back('x');
str += byte_to_hex((int)at(i));
break;
}
} else if(format == HEX){
str.push_back('x');
str += byte_to_hex((int)at(i));
} else {
str += byte_to_octo((int)at(i));
}
str += enclose_end;
}
return str;
}
std::string Byte_Array::byte_to_hex(uint8_t byte, bool up_case /* = true */)
{
std::ostringstream ret;
ret << std::hex
<< std::setfill('0')
<< std::setw(2)
<< (up_case ? std::uppercase : std::nouppercase)
<< (int)byte;
return std::move(ret.str());
}
std::string Byte_Array::byte_to_octo(uint8_t byte)
{
std::ostringstream ret;
ret << std::oct
<< std::setfill('0')
<< std::setw(3)
<< (int)byte;
return std::move(ret.str());
}
void Byte_Array::copy(const std::string& str){
clear();
for(unsigned int i = 0; i < str.size(); i++)
push_back(str[i]);
}
void Byte_Array::copy(const std::stringstream& ss)
{
copy(ss.str());
}
Byte_Array& Byte_Array::operator=(const std::string& a)
{
this->copy(a);
return *this;
}
Byte_Array& Byte_Array::operator=(const std::stringstream& a)
{
this->copy(a);
return *this;
}
| 19.195122 | 91 | 0.591275 | rnascunha |
8d235600a6c1ec2dadba906f4f551f97177d9d55 | 5,374 | cpp | C++ | pnc/atlas_pnc/atlas_controller.cpp | junhyeokahn/PnC | 388440f7db7b2aedf1e397d0130d806090865c35 | [
"MIT"
] | 25 | 2019-01-31T13:51:34.000Z | 2022-02-08T13:19:01.000Z | pnc/atlas_pnc/atlas_controller.cpp | junhyeokahn/PnC | 388440f7db7b2aedf1e397d0130d806090865c35 | [
"MIT"
] | 5 | 2020-06-01T20:48:46.000Z | 2022-02-08T11:42:02.000Z | pnc/atlas_pnc/atlas_controller.cpp | junhyeokahn/PnC | 388440f7db7b2aedf1e397d0130d806090865c35 | [
"MIT"
] | 9 | 2018-11-20T22:37:50.000Z | 2021-09-14T17:17:27.000Z | #include <pnc/atlas_pnc/atlas_control_architecture.hpp>
#include <pnc/atlas_pnc/atlas_controller.hpp>
#include <pnc/whole_body_controllers/ihwbc/ihwbc.hpp>
#include <pnc/whole_body_controllers/ihwbc/joint_integrator.hpp>
AtlasController::AtlasController(AtlasTCIContainer *_tci_container,
RobotSystem *_robot) {
util::PrettyConstructor(2, "AtlasController");
tci_container_ = _tci_container;
robot_ = _robot;
sp_ = AtlasStateProvider::getStateProvider(robot_);
YAML::Node cfg = YAML::LoadFile(THIS_COM "config/atlas/pnc.yaml");
// Initialize WBC
std::vector<bool> act_list;
for (int i = 0; i < robot_->n_floating; ++i)
act_list.push_back(false);
for (int i = 0; i < robot_->n_a; ++i)
act_list.push_back(true);
int n_q_dot(act_list.size());
int n_active(robot_->n_a);
int n_passive(n_q_dot - n_active - robot_->n_floating);
Eigen::MatrixXd sa = Eigen::MatrixXd::Zero(n_active, n_q_dot);
Eigen::MatrixXd sv = Eigen::MatrixXd::Zero(n_passive, n_q_dot);
int j(0), k(0);
for (int i = 0; i < n_q_dot; ++i) {
if (i >= 6) {
if (act_list[i]) {
sa(j, i) = 1.;
j += 1;
} else {
sv(k, i) = 1.;
k += 1;
}
}
}
Eigen::MatrixXd sf = Eigen::MatrixXd::Zero(robot_->n_floating, n_q_dot);
sf.block(0, 0, 6, 6) = Eigen::MatrixXd::Identity(6, 6);
wbc_ = new IHWBC(sf, sa, sv);
wbc_->b_trq_limit = util::ReadParameter<bool>(cfg["wbc"], "b_trq_limit");
if (wbc_->b_trq_limit) {
wbc_->trq_limit = sa.block(0, robot_->n_floating, n_active,
n_q_dot - robot_->n_floating) *
robot_->joint_trq_limit;
}
wbc_->lambda_q_ddot =
util::ReadParameter<double>(cfg["wbc"], "lambda_q_ddot");
wbc_->lambda_rf = util::ReadParameter<double>(cfg["wbc"], "lambda_rf");
// Initialize Joint Integrator
joint_integrator_ = new JointIntegrator(robot_->n_a, sp_->servo_dt);
joint_integrator_->setVelocityFrequencyCutOff(
util::ReadParameter<double>(cfg["wbc"], "vel_cutoff_freq"));
joint_integrator_->setPositionFrequencyCutOff(
util::ReadParameter<double>(cfg["wbc"], "pos_cutoff_freq"));
joint_integrator_->setMaxPositionError(
util::ReadParameter<double>(cfg["wbc"], "max_pos_err"));
joint_integrator_->setVelocityBounds(robot_->joint_vel_limit.col(0),
robot_->joint_vel_limit.col(1));
joint_integrator_->setPositionBounds(robot_->joint_pos_limit.col(0),
robot_->joint_pos_limit.col(1));
joint_trq_cmd_ = Eigen::VectorXd::Zero(robot_->n_a);
joint_vel_cmd_ = Eigen::VectorXd::Zero(robot_->n_a);
joint_pos_cmd_ = Eigen::VectorXd::Zero(robot_->n_a);
r_rf_cmd_ = Eigen::VectorXd::Zero(6);
l_rf_cmd_ = Eigen::VectorXd::Zero(6);
}
AtlasController::~AtlasController() {
delete wbc_;
delete joint_integrator_;
}
void AtlasController::getCommand(void *cmd) {
static bool b_first_visit(true);
if (b_first_visit) {
FirstVisit();
b_first_visit = false;
}
// Dynamics properties
Eigen::MatrixXd A = robot_->get_mass_matrix();
Eigen::MatrixXd Ainv = A.inverse();
Eigen::VectorXd grav = robot_->get_gravity();
Eigen::VectorXd cori = robot_->get_coriolis();
wbc_->update_setting(A, Ainv, cori, grav);
// Task, Contact, Internal Constraint Setup
wbc_->w_hierarchy = Eigen::VectorXd::Zero(tci_container_->task_list.size());
for (int i = 0; i < tci_container_->task_list.size(); ++i) {
tci_container_->task_list[i]->update_jacobian();
tci_container_->task_list[i]->update_cmd();
wbc_->w_hierarchy[i] = tci_container_->task_list[i]->w_hierarchy;
}
int rf_dim(0);
for (int i = 0; i < tci_container_->contact_list.size(); ++i) {
tci_container_->contact_list[i]->update_contact();
rf_dim += tci_container_->contact_list[i]->dim;
}
for (int i = 0; i < tci_container_->internal_constraint_list.size(); ++i) {
tci_container_->internal_constraint_list[i]->update_internal_constraint();
}
// WBC commands
Eigen::VectorXd rf_des = Eigen::VectorXd::Zero(rf_dim);
Eigen::VectorXd joint_acc_cmd = Eigen::VectorXd::Zero(robot_->n_a);
wbc_->solve(tci_container_->task_list, tci_container_->contact_list,
tci_container_->internal_constraint_list, rf_des, joint_trq_cmd_,
joint_acc_cmd, rf_des);
if (sp_->state == AtlasStates::LFootSwing) {
l_rf_cmd_ = Eigen::VectorXd::Zero(6);
r_rf_cmd_ = rf_des;
} else if (sp_->state == AtlasStates::RFootSwing) {
r_rf_cmd_ = Eigen::VectorXd::Zero(6);
l_rf_cmd_ = rf_des;
} else {
// right foot first
r_rf_cmd_ = rf_des.head(6);
l_rf_cmd_ = rf_des.tail(6);
}
joint_integrator_->integrate(joint_acc_cmd, robot_->joint_velocities,
robot_->joint_positions, joint_vel_cmd_,
joint_pos_cmd_);
((AtlasCommand *)cmd)->joint_positions =
robot_->vector_to_map(joint_pos_cmd_);
((AtlasCommand *)cmd)->joint_velocities =
robot_->vector_to_map(joint_vel_cmd_);
((AtlasCommand *)cmd)->joint_torques = robot_->vector_to_map(joint_trq_cmd_);
}
void AtlasController::FirstVisit() {
Eigen::VectorXd jpos_ini = robot_->joint_positions;
joint_integrator_->initializeStates(Eigen::VectorXd::Zero(robot_->n_a),
jpos_ini);
}
| 37.319444 | 79 | 0.66431 | junhyeokahn |
8d23a8c54a1857e9b08a2bdd9b71bcb4036f6dbf | 831 | cc | C++ | src/connectivity/bluetooth/core/bt-host/sm/valid_packet_reader_parse_sdu_fuzztest.cc | liexusong/fuchsia | 81897680af92a1848a063e3c20ff3a4892ccff07 | [
"BSD-2-Clause"
] | 3 | 2021-09-02T07:21:06.000Z | 2022-03-12T03:20:10.000Z | src/connectivity/bluetooth/core/bt-host/sm/valid_packet_reader_parse_sdu_fuzztest.cc | liexusong/fuchsia | 81897680af92a1848a063e3c20ff3a4892ccff07 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/connectivity/bluetooth/core/bt-host/sm/valid_packet_reader_parse_sdu_fuzztest.cc | liexusong/fuchsia | 81897680af92a1848a063e3c20ff3a4892ccff07 | [
"BSD-2-Clause"
] | 2 | 2022-02-25T12:22:49.000Z | 2022-03-12T03:20:10.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "src/connectivity/bluetooth/core/bt-host/common/byte_buffer.h"
#include "src/connectivity/bluetooth/core/bt-host/sm/packet.h"
namespace bt::sm {
void fuzz(const uint8_t* data, size_t size) {
DynamicByteBuffer buf(size);
memcpy(buf.mutable_data(), data, size);
ByteBufferPtr buf_ptr = std::make_unique<DynamicByteBuffer>(buf);
fit::result<ValidPacketReader, ErrorCode> result = ValidPacketReader::ParseSdu(buf_ptr);
if (result.is_ok()) {
ZX_ASSERT(result.value().is_valid());
}
}
} // namespace bt::sm
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
bt::sm::fuzz(data, size);
return 0;
}
| 29.678571 | 90 | 0.731649 | liexusong |
8d25b14e89d354f8ff34834e576c4b5b9d01da5f | 568 | cpp | C++ | Olympiad Programs/M3/M3 Madrese/Afther M2 Results/Day 1/M3s/22/Day 2/1.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | 1 | 2020-12-08T11:21:34.000Z | 2020-12-08T11:21:34.000Z | Olympiad Programs/M3/M3 Madrese/Afther M2 Results/Day 1/M3s/22/Day 2/1.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | Olympiad Programs/M3/M3 Madrese/Afther M2 Results/Day 1/M3s/22/Day 2/1.cpp | mirtaba/ACMICPC-INOI_Archive | ea06e4e40e984f0807410e4f9b5f7042580da2e3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
#define pb push_back
#define mp make_pair
#define pf push_front
#define FOR(i,s,f) for (int i=s;i<f;i++)
typedef long long LL ;
typedef pair <int ,int > PII;
typedef pair <LL , LL > PLL;
const int Maxn = 1000 +25;
const int Mod = 1000*1000*1000 +9;
const int Del = 11117;
int main()
{
ios::sync_with_stdio(0);
cout << (1<<26) << endl;
int M=(1<<26);
M%=Del;
M*=M;
M%=Del;
M*=3;
M%=Del;
cout << M << endl;
}
| 16.228571 | 40 | 0.603873 | mirtaba |