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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25d1824fb2cbe0e9da5dbffccab59beab8e79368 | 8,892 | cpp | C++ | thormang3_step_control_module/src/robotis_online_walking_plugin.cpp | thor-mang/ROBOTIS-THORMANG-MPC | 6d5d6479ddab1bbcf0ff34e5cf6f98823da38cad | [
"BSD-3-Clause"
] | 3 | 2018-01-30T16:03:20.000Z | 2021-11-13T21:14:08.000Z | thormang3_step_control_module/src/robotis_online_walking_plugin.cpp | thor-mang/ROBOTIS-THORMANG-MPC | 6d5d6479ddab1bbcf0ff34e5cf6f98823da38cad | [
"BSD-3-Clause"
] | null | null | null | thormang3_step_control_module/src/robotis_online_walking_plugin.cpp | thor-mang/ROBOTIS-THORMANG-MPC | 6d5d6479ddab1bbcf0ff34e5cf6f98823da38cad | [
"BSD-3-Clause"
] | null | null | null | #include <thormang3_step_control_module/robotis_online_walking_plugin.h>
#include <thormang3_walking_module/thormang3_online_walking.h>
#include <thormang3_walking_module/walking_module.h>
namespace thormang3
{
using namespace vigir_footstep_planning;
THORMANG3OnlineWalkingPlugin::THORMANG3OnlineWalkingPlugin()
: StepControllerPlugin()
, last_remaining_unreserved_steps_(0)
, min_unreserved_steps_(2)
{
}
THORMANG3OnlineWalkingPlugin::~THORMANG3OnlineWalkingPlugin()
{
}
void THORMANG3OnlineWalkingPlugin::setStepPlanMsgPlugin(StepPlanMsgPlugin::Ptr plugin)
{
StepControllerPlugin::setStepPlanMsgPlugin(plugin);
boost::unique_lock<boost::shared_mutex> lock(plugin_mutex_);
thor_mang_step_plan_msg_plugin_ = boost::dynamic_pointer_cast<ThorMangStepPlanMsgPlugin>(plugin);
if (!thor_mang_step_plan_msg_plugin_)
ROS_ERROR("[THORMANG3OnlineWalkingPlugin] StepPlanMsgPlugin is not from type 'ThorMangStepPlanMsgPlugin'!");
}
bool THORMANG3OnlineWalkingPlugin::updateStepPlan(const msgs::StepPlan& step_plan)
{
if (step_plan.steps.empty())
return true;
// transform initial step plan (afterwards stitching will do that automatically for us)
if (step_queue_->empty())
{
const msgs::Step& step = step_plan.steps.front();
robotis_framework::StepData ref_step;
initStepData(ref_step);
/// TODO: use robotis reference step here?
//robotis_framework::THORMANG3OnlineWalking::GetInstance()->GetReferenceStepDatafotAddition(&ref_step);
geometry_msgs::Pose ref_pose;
if (step.foot.foot_index == msgs::Foot::LEFT)
thor_mang_footstep_planning::toRos(ref_step.position_data.left_foot_pose, ref_pose);
else if (step.foot.foot_index == msgs::Foot::RIGHT)
thor_mang_footstep_planning::toRos(ref_step.position_data.right_foot_pose, ref_pose);
else
{
ROS_ERROR("[THORMANG3OnlineWalkingPlugin] updateStepPlan: First step of input step plan has unknown foot index.");
return false;
}
// determine transformation to robotis frame
tf::Transform transform = vigir_footstep_planning::StepPlan::getTransform(step.foot.pose, ref_pose);
msgs::StepPlan step_plan_transformed = step_plan;
vigir_footstep_planning::StepPlan::transformStepPlan(step_plan_transformed, transform);
return StepControllerPlugin::updateStepPlan(step_plan_transformed);
}
else
{
/// TODO: Handle reverse spooling correctly
return StepControllerPlugin::updateStepPlan(step_plan);
}
return false;
}
void THORMANG3OnlineWalkingPlugin::initWalk()
{
thormang3::THORMANG3OnlineWalking* online_walking = thormang3::THORMANG3OnlineWalking::getInstance();
if (online_walking->isRunning())
{
ROS_ERROR("[THORMANG3OnlineWalkingPlugin] Can't start walking as walking engine is still running. This is likely a bug and should be fixed immediately!");
setState(FAILED);
return;
}
//online_walking->initialize();
//online_walking->setInitialPose();
//online_walking->setInitalWaistYawAngle();
last_remaining_unreserved_steps_ = 0;
// init feedback states
msgs::ExecuteStepPlanFeedback feedback;
feedback.header.stamp = ros::Time::now();
feedback.last_performed_step_index = -1;
feedback.currently_executing_step_index = 0;
feedback.first_changeable_step_index = 0;
setFeedbackState(feedback);
setState(ACTIVE);
online_walking->start();
ROS_INFO("[THORMANG3OnlineWalkingPlugin] Starting walking.");
}
void THORMANG3OnlineWalkingPlugin::preProcess(const ros::TimerEvent& event)
{
StepControllerPlugin::preProcess(event);
if (getState() != ACTIVE)
return;
thormang3::THORMANG3OnlineWalking* online_walking = thormang3::THORMANG3OnlineWalking::getInstance();
// first check if walking engine is still running
if (!online_walking->isRunning())
{
ROS_INFO("[THORMANG3OnlineWalkingPlugin] Walking engine has stopped unexpectedly. This is likely a bug and should be fixed immediately!");
setState(FAILED);
return;
}
// checking current state of walking engine
int remaining_unreserved_steps = online_walking->getNumofRemainingUnreservedStepData();
int executed_steps = std::max(last_remaining_unreserved_steps_ - remaining_unreserved_steps, 0);
last_remaining_unreserved_steps_ = remaining_unreserved_steps;
int needed_steps = min_unreserved_steps_ - remaining_unreserved_steps;
msgs::ExecuteStepPlanFeedback feedback = getFeedbackState();
// step(s) has been performed recently
feedback.header.stamp = ros::Time::now();
feedback.last_performed_step_index += executed_steps;
feedback.currently_executing_step_index += executed_steps;
if (needed_steps > 0)
{
step_queue_->clearDirtyFlag();
// check if further steps in queue are available
int steps_remaining = std::max(0, (step_queue_->lastStepIndex() - feedback.first_changeable_step_index) + 1);
// steps are available
if (steps_remaining > 0)
{
needed_steps = std::min(needed_steps, steps_remaining);
setNextStepIndexNeeded(getNextStepIndexNeeded()+needed_steps);
feedback.first_changeable_step_index = getNextStepIndexNeeded()+1;
}
// queue has been completely flushed out and executed
else
{
// check for successful execution of queue
if (step_queue_->lastStepIndex() == feedback.last_performed_step_index)
{
ROS_INFO("[THORMANG3OnlineWalkingPlugin] Walking finished.");
feedback.currently_executing_step_index = -1;
feedback.first_changeable_step_index = -1;
setFeedbackState(feedback);
step_queue_->reset();
updateQueueFeedback();
setState(FINISHED);
}
}
}
setFeedbackState(feedback);
}
bool THORMANG3OnlineWalkingPlugin::executeStep(const msgs::Step& step)
{
/// TODO: flush step
thormang3::THORMANG3OnlineWalking* online_walking = thormang3::THORMANG3OnlineWalking::getInstance();
// add initial step
if (step.step_index == 0)
{
robotis_framework::StepData step_data;
initStepData(step_data);
/// TODO: use robotis reference step here?
//online_walking->getReferenceStepDatafotAddition(&_refStepData);
if (!online_walking->addStepData(step_data))
{
ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding initial step.");
return false;
}
last_step_data_ = step_data;
// add final step
step_data.position_data.foot_z_swap = 0.0;
step_data.position_data.body_z_swap = 0.0;
step_data.position_data.moving_foot = thormang3_walking_module_msgs::StepPositionData::STANDING;
step_data.time_data.walking_state = thormang3_walking_module_msgs::StepTimeData::IN_WALKING_ENDING;
step_data.time_data.abs_step_time += 1.0;
if (!online_walking->addStepData(step_data))
{
ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding (temp) final step.");
return false;
}
}
else
{
// get ref data
robotis_framework::StepData ref_step_data;
online_walking->getReferenceStepDatafotAddition(&ref_step_data);
// remove final step to be updated
online_walking->eraseLastStepData();
// add step
/// TODO: use robotis reference step here?
robotis_framework::StepData step_data = last_step_data_;
step_data << step;
/// TODO: compensate drift in z
step_data.position_data.body_pose.z = ref_step_data.position_data.body_pose.z;
if (step.foot.foot_index == msgs::Foot::LEFT)
step_data.position_data.left_foot_pose.z = ref_step_data.position_data.right_foot_pose.z;
else
step_data.position_data.right_foot_pose.z = ref_step_data.position_data.left_foot_pose.z;
if (!online_walking->addStepData(step_data))
{
ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding step %i.", step.step_index);
return false;
}
last_step_data_ = step_data;
// readd updated final step
//step_data.position_data.foot_z_swap = 0.0;
step_data.position_data.body_z_swap = 0.0;
step_data.position_data.moving_foot = thormang3_walking_module_msgs::StepPositionData::STANDING;
step_data.time_data.walking_state = thormang3_walking_module_msgs::StepTimeData::IN_WALKING_ENDING;
step_data.time_data.abs_step_time += 1.6;
if (!online_walking->addStepData(step_data))
{
ROS_INFO("[THORMANG3OnlineWalkingPlugin] executeStep: Error while adding (temp) final step.");
return false;
}
}
last_remaining_unreserved_steps_ = online_walking->getNumofRemainingUnreservedStepData();
return true;
}
void THORMANG3OnlineWalkingPlugin::stop()
{
StepControllerPlugin::stop();
/// TODO: Stop when both feet on ground
thormang3::THORMANG3OnlineWalking::getInstance()->stop();
}
} // namespace
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(thormang3::THORMANG3OnlineWalkingPlugin, vigir_step_control::StepControllerPlugin)
| 33.055762 | 158 | 0.753711 | thor-mang |
25d1f31082b94445867fed6605391419691dffe0 | 899 | hpp | C++ | tasks/LedMatrixDisplay.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 1 | 2022-01-31T01:59:52.000Z | 2022-01-31T01:59:52.000Z | tasks/LedMatrixDisplay.hpp | PhischDotOrg/stm32-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | 5 | 2020-04-13T21:55:12.000Z | 2020-06-27T17:44:44.000Z | tasks/LedMatrixDisplay.hpp | PhischDotOrg/stm32f4-common | 4b6b9c436018c89d3668c6ee107e97abb930bae2 | [
"MIT"
] | null | null | null | /*-
* $Copyright$
-*/
#ifndef _TASKS_LED_MATRIX_DISPLAY_HPP_3dcb329a_694a_48b4_8249_5ca9cb2ed9b4
#define _TASKS_LED_MATRIX_DISPLAY_HPP_3dcb329a_694a_48b4_8249_5ca9cb2ed9b4
#include "tasks/Task.hpp"
#include <gpio/GpioPin.hpp>
#include <uart/UartDevice.hpp>
namespace tasks {
template<typename LedMatrixT, typename UartT = uart::UartDevice, unsigned t_width = 8, unsigned t_height = 8>
class LedMatrixDisplayT : public Task {
private:
UartT & m_uart;
LedMatrixT & m_ledMatrix;
const unsigned m_periodUs;
virtual void run(void);
public:
LedMatrixDisplayT(const char * const p_name, UartT &p_uart, LedMatrixT &p_ledMatrix, const unsigned p_priority, const unsigned p_periodUs = 500);
virtual ~LedMatrixDisplayT();
};
}; /* namespace tasks */
#include "LedMatrixDisplay.cpp"
#endif /* _TASKS_LED_MATRIX_DISPLAY_HPP_3dcb329a_694a_48b4_8249_5ca9cb2ed9b4 */
| 26.441176 | 149 | 0.765295 | PhischDotOrg |
25d39d929f95332c75d0f8c7a56f050bd408de0a | 609 | hpp | C++ | include/guidance/segregated_intersection_classification.hpp | AugustoQueiroz/pedalavel-backend | c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f | [
"BSD-2-Clause"
] | null | null | null | include/guidance/segregated_intersection_classification.hpp | AugustoQueiroz/pedalavel-backend | c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f | [
"BSD-2-Clause"
] | null | null | null | include/guidance/segregated_intersection_classification.hpp | AugustoQueiroz/pedalavel-backend | c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f | [
"BSD-2-Clause"
] | 1 | 2019-09-23T22:49:07.000Z | 2019-09-23T22:49:07.000Z | #include "util/typedefs.hpp"
#include <unordered_set>
namespace osrm
{
namespace util
{
class NameTable;
}
namespace extractor
{
class NodeBasedGraphFactory;
}
namespace guidance
{
// Find all "segregated" edges, e.g. edges that can be skipped in turn instructions.
// The main cases are:
// - middle edges between two osm ways in one logic road (U-turn)
// - staggered intersections (X-cross)
// - square/circle intersections
std::unordered_set<EdgeID> findSegregatedNodes(const extractor::NodeBasedGraphFactory &factory,
const util::NameTable &names);
}
}
| 21.75 | 95 | 0.701149 | AugustoQueiroz |
25dabbbb9c66336a8a909ef3fe31761be685940e | 1,886 | cpp | C++ | benchmarks/threadpool/benchmark.cpp | alexbriskin/taskflow | da69f8989f26f8ff7bc731dbafb2f6ce171934fc | [
"MIT"
] | null | null | null | benchmarks/threadpool/benchmark.cpp | alexbriskin/taskflow | da69f8989f26f8ff7bc731dbafb2f6ce171934fc | [
"MIT"
] | null | null | null | benchmarks/threadpool/benchmark.cpp | alexbriskin/taskflow | da69f8989f26f8ff7bc731dbafb2f6ce171934fc | [
"MIT"
] | null | null | null | #include <taskflow/taskflow.hpp>
#include <chrono>
#include "ThreadPool.hpp"
ThreadPool* ThreadPool::singleton = nullptr;
std::mutex ThreadPool::singleton_mutex;
tf::Executor executor;
class ChronoTimer {
public:
ChronoTimer(void) {
}
void start(void){
startTime = std::chrono::high_resolution_clock::now();
}
void finish(std::string msg){
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - startTime;
printf("%s : %f ms\n",msg.c_str(), elapsed.count() * 1000);
}
private:
std::chrono::high_resolution_clock::time_point startTime;
};
void benchFunc(uint64_t loopLen){
float acc = 0;
for (uint64_t k = 0; k < loopLen; ++k)
acc += k;
}
void bench(uint32_t iter){
printf("Benchmark with %d iterations\n",iter);
const uint64_t num_blocks = 1000;
const uint64_t loopLen = 100;
ChronoTimer timer;
ThreadPool *pool = ThreadPool::get();
timer.start();
for (uint64_t it = 0; it < iter; ++it) {
tf::Taskflow taskflow;
tf::Task node[num_blocks];
for (uint64_t i = 0; i < num_blocks; i++)
node[i] = taskflow.placeholder();
for (uint64_t i = 0; i < num_blocks; i++) {
node[i].work([=]() {
benchFunc(loopLen);
});
}
executor.run(taskflow).wait();
}
timer.finish("taskflow: time in ms: ");
timer.start();
for (uint64_t it = 0; it < iter; ++it) {
std::vector<std::future<int>> results;
for (uint64_t i = 0; i < num_blocks; i++) {
results.emplace_back(pool->enqueue([=]() {
benchFunc(loopLen);
return 0;
}));
}
for(auto& result : results)
{
result.get();
}
}
timer.finish("threadpool: time in ms: ");
}
int main() {
for (uint32_t i = 0; i < 5; ++i)
bench(100);
for (uint32_t i = 0; i < 5; ++i)
bench(50);
for (uint32_t i = 0; i < 5; ++i)
bench(20);
for (uint32_t i = 0; i < 5; ++i)
bench(10);
for (uint32_t i = 0; i < 5; ++i)
bench(5);
}
| 22.452381 | 61 | 0.629905 | alexbriskin |
25db6ad72a6d8a018fff90d5533d6d667604fe69 | 3,776 | hpp | C++ | src/core/exponential.hpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 11 | 2016-03-31T17:46:15.000Z | 2022-02-14T01:07:56.000Z | src/core/exponential.hpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 3 | 2016-04-04T16:40:47.000Z | 2019-10-16T22:22:54.000Z | src/core/exponential.hpp | tp-ntouran/mocc | 77d386cdf341b1a860599ff7c6e4017d46e0b102 | [
"Apache-2.0"
] | 3 | 2019-10-16T22:20:15.000Z | 2019-11-28T11:59:03.000Z | /*
Copyright 2016 Mitchell Young
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include "util/global_config.hpp"
namespace mocc {
/**
* Base class defining a class of simple utility classes for computing
* exponential functions. The base version uses the stock library call to
* exp(), while derived versions can override this with more efficient table
* lookups.
*/
class Exponential {
public:
Exponential()
{
}
inline real_t exp(real_t v) const
{
return std::exp(v);
}
virtual real_t max_error()
{
return 0.0;
}
};
/*
* This version of \ref Exponential uses a linear lookup table to speed up
* the evaluations of \ref exp(). If the argument to \ref exp() is beyond
* the domain of the table, it will fall back to the result of the standard
* library \c exp() function.
*/
template <int N> class Exponential_Linear : public Exponential {
public:
Exponential_Linear(real_t min = -10.0, real_t max = 0.0)
: min_(min),
max_(max),
space_((max - min_) / (real_t)(N)),
rspace_(1.0 / space_)
{
for (int i = 0; i <= N; i++) {
d_[i] = std::exp(min_ + i * space_);
}
}
inline real_t exp(real_t v) const
{
if (v < min_ || v > max_) {
std::cout << "Out-of-bounds exponential argument: " << v
<< std::endl;
return std::exp(v);
}
int i = (v - min_) * rspace_;
v -= space_ * i + min_;
return d_[i] + (d_[i + 1] - d_[i]) * v * rspace_;
}
real_t max_error()
{
real_t max_error = 0.0;
for (int i = 0; i < N; i++) {
real_t x = min_ + space_ * (0.5 + i);
real_t e = std::exp(x);
real_t err = std::abs((this->exp(x) - e) / e);
max_error = std::max(max_error, err);
}
return max_error;
}
/*
* \brief Return the table value for the passed point index
*
* This is mostly useful for testing and debugging purposes.
*/
real_t operator[](int i) const {
return d_[i];
}
real_t dx() const {
return space_;
}
protected:
real_t min_;
real_t max_;
real_t space_;
real_t rspace_;
std::array<real_t, N + 1> d_;
};
/**
* Same as \ref Exponential_Linear, but without the check to make sure the
* argument is within the limits of the table. This should only be used in
* situations where one knows that the arguments to \ref exp() won't spill
* the banks of the table. Even considering branch prediction, this manages
* to shave a little more time off of the \ref exp() evaluations over \ref
* Exponential_Linear.
*/
template <int N> class Exponential_UnsafeLinear : public Exponential_Linear<N> {
Exponential_UnsafeLinear(real_t min = -10.0, real_t max = 0.0)
: Exponential_Linear<N>(min, max)
{
return;
}
inline real_t exp(real_t v) const
{
int i = (v - this->min_) * this->rspace_;
v -= this->space_ * i + this->min_;
return this->d_[i] +
(this->d_[i + 1] - this->d_[i]) * v * this->rspace_;
}
};
}
| 27.362319 | 80 | 0.601165 | tp-ntouran |
25dcaa63f88e96f8b8aea70cd7e38066eaa3cd88 | 2,362 | cpp | C++ | Algorithms/0993.CousinsInBinaryTree/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0993.CousinsInBinaryTree/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0993.CousinsInBinaryTree/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <queue>
#include "TreeNode.h"
#include "TreeNodeUtils.h"
#include "gtest/gtest.h"
using CommonLib::TreeNode;
namespace
{
struct NodeData
{
NodeData(TreeNode* current, size_t depth, TreeNode* parent) : Current(current), Depth(depth), Parent(parent)
{
}
TreeNode* Current;
size_t Depth;
TreeNode* Parent;
};
class Solution
{
public:
bool isCousins(TreeNode* root, int x, int y) const
{
std::queue<NodeData> nodes;
nodes.emplace(root, 0, nullptr);
bool hasXValue = false;
bool hasYValue = false;
size_t currentDepth = 0;
TreeNode* lastParent = nullptr;
while (!nodes.empty())
{
if (currentDepth != nodes.front().Depth)
{
hasXValue = false;
hasYValue = false;
currentDepth = nodes.front().Depth;
lastParent = nullptr;
}
if (nodes.front().Current->val == x && ProcessValueEquality(nodes.front().Parent, hasXValue, hasYValue, &lastParent))
return true;
if (nodes.front().Current->val == y && ProcessValueEquality(nodes.front().Parent, hasYValue, hasXValue, &lastParent))
return true;
if (nodes.front().Current->left != nullptr)
nodes.emplace(nodes.front().Current->left, nodes.front().Depth + 1, nodes.front().Current);
if (nodes.front().Current->right != nullptr)
nodes.emplace(nodes.front().Current->right, nodes.front().Depth + 1, nodes.front().Current);
nodes.pop();
}
return false;
}
private:
bool ProcessValueEquality(TreeNode* parent, bool &hasValue, bool hasOtherValue, TreeNode** lastParent) const
{
if (hasOtherValue && *lastParent != parent)
return true;
hasValue = true;
*lastParent = parent;
return false;
}
};
}
using CommonLib::Codec;
namespace CousinsInBinaryTreeTask
{
TEST(SmallestStringStartingFromLeafTaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(false, solution.isCousins(Codec::createTree("[1,2,3,4]").get(), 4, 3));
ASSERT_EQ(true, solution.isCousins(Codec::createTree("[1,2,3,null,4,null,5]").get(), 5, 4));
ASSERT_EQ(false, solution.isCousins(Codec::createTree("[1,2,3,null,4]").get(), 2, 3));
}
} | 28.457831 | 129 | 0.600339 | stdstring |
25e0c3389da573d2eedb1433ce82a0f442dc3c7b | 881 | cpp | C++ | UOJ/Goodbye Yiwei/B/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | UOJ/Goodbye Yiwei/B/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | UOJ/Goodbye Yiwei/B/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 100010
#define maxm 200010
using namespace std;
int T,n,m;
struct Graph{
int tot,head[maxn],to[maxm],next[maxm],du[maxn],mark[maxn];
void addedge(int a,int b){to[++tot]=b;next[tot]=head[a];head[a]=tot;++du[a];}
void clear(){tot=0;memset(head,0,sizeof(head));memset(du,0,sizeof(du));memset(mark,0,sizeof(mark));}
void solve(){
for(int k=1;k<=n;++k){
if(du[k]==1){mark[k]=1;continue;}
for(int p=head[k];p;p=next[p])if(du[to[p]]==1){mark[k]=1;break;}
}
}
}G;
int main(){
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
G.clear();
for(int i=1;i<=m;++i){
int u,v;scanf("%d%d",&u,&v);
G.addedge(u,v);G.addedge(v,u);
}
G.solve();
int k=0;
for(int i=1;i<=n;++i)if(G.mark[i])++k;
printf("%d\n",k);
for(int i=1;i<=n;++i)if(G.mark[i])printf("%d ",i);printf("\n");
}
return 0;
}
| 22.589744 | 101 | 0.578888 | sjj118 |
25e3e10969df769bef5fb49031e2c4848fc1c2ea | 1,122 | hpp | C++ | sources/Notebook.hpp | LiorBreitman8234/Ex2_cpp_b | 53c8c2524d737e3121a749c3b1ff2ef4551de6cb | [
"MIT"
] | null | null | null | sources/Notebook.hpp | LiorBreitman8234/Ex2_cpp_b | 53c8c2524d737e3121a749c3b1ff2ef4551de6cb | [
"MIT"
] | null | null | null | sources/Notebook.hpp | LiorBreitman8234/Ex2_cpp_b | 53c8c2524d737e3121a749c3b1ff2ef4551de6cb | [
"MIT"
] | null | null | null | //
// Created by bravo8234 on 20/03/2022.
//
#ifndef EX2_CPP_QA_NOTEBOOK_HPP
#define EX2_CPP_QA_NOTEBOOK_HPP
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <string>
#include <stdexcept>
#include "Page.hpp"
#include "Direction.hpp"
#define ROW_LENGTH 100
#define CHAR_UP_LIMIT 126
#define CHAR_LOW_LIMIT 32
namespace ariel {
class Notebook {
std::map<int, Page> pages;
std::map<int, Page> &pagesRef;
static int checkInputWrite(int page, int row, int column, const std::string &toWrite, Direction direction);
static int checkInputReadAndErase(int page, int row, int column, int length, Direction direction);
public:
Notebook()
: pages(std::map<int, Page>()), pagesRef(pages) {};
void write(int page, int row, int column, Direction direction, std::string toWrite);
std::string read(int page, int row, int column, Direction direction, int length);
void erase(int page, int row, int column, Direction direction, int length);
void show(int page);
};
}
#endif //EX2_CPP_QA_NOTEBOOK_HPP
| 25.5 | 115 | 0.688948 | LiorBreitman8234 |
25e45e9972c42667d5f0467baaa2ab2366b980c5 | 18,719 | cpp | C++ | src/incphp.cpp | StephanGocht/incphp | d92cd186d4bfb059140278b0adc2ec47de06f704 | [
"MIT"
] | 1 | 2021-03-08T08:08:03.000Z | 2021-03-08T08:08:03.000Z | src/incphp.cpp | StephanGocht/incphp | d92cd186d4bfb059140278b0adc2ec47de06f704 | [
"MIT"
] | null | null | null | src/incphp.cpp | StephanGocht/incphp | d92cd186d4bfb059140278b0adc2ec47de06f704 | [
"MIT"
] | 1 | 2017-08-29T07:09:09.000Z | 2017-08-29T07:09:09.000Z | #include "incphp.h"
#include <array>
#include <iostream>
#include <cmath>
#include <set>
#include "SatVariable.h"
#include "LearnedClauseEvaluationDecorator.h"
#include "tclap/CmdLine.h"
#include "carj/carj.h"
#include "carj/ScopedTimer.h"
#include "ipasir/randomized_ipasir.h"
#include "ipasir/ipasir_cpp.h"
#include "ipasir/printer.h"
#include "carj/logging.h"
int neccessaryArgument = true;
int defaultIsFalse = false;
using json = nlohmann::json;
TCLAP::CmdLine cmd(
"This tool solves the pidgeon hole principle incrementally.",
' ', "0.1");
carj::CarjArg<TCLAP::SwitchArg, bool> addAssumed("A", "addAssumed",
"Add assumed clauses.", cmd, defaultIsFalse);
carj::CarjArg<TCLAP::SwitchArg, bool> fixedUpperBound("u", "fixedUpperBound",
"Add upper bound as clauses.", cmd, defaultIsFalse);
namespace CollectData {
class MakespanAndTime {
public:
MakespanAndTime(unsigned makespan) {
static auto& solves = carj::getCarj()
.data["/incphp/result/solves"_json_pointer];
solves.push_back({});
solves.back()["makespan"] = makespan;
LOG(INFO) << "makespan: " << makespan;
timer = std::make_unique<carj::ScopedTimer>(solves.back()["time"]);
}
private:
std::unique_ptr<carj::ScopedTimer> timer;
};
}
class DimSpecFixedPigeons {
private:
unsigned numPigeons;
unsigned numLiteralsPerTime;
/**
* Variable representing that pigeon p is in hole h.
* Note that hole is the same as time.
*/
int varPigeonInHole(unsigned p, unsigned h) {
return numLiteralsPerTime * h + p + 1;
}
/**
* Helper variable, which is true iff the pigeon sits in a future hole.
* i.e. step created hole h, then pigeon sits in a hole added in step later
*/
int helperFutureHole(int p, int h) {
return numLiteralsPerTime * h + numPigeons + p + 1;
}
void printClause(std::vector<int> clause) {
for (int literal: clause) {
std::cout << literal << " ";
}
std::cout << "0" << std::endl;
}
public:
DimSpecFixedPigeons(unsigned _numPigeons):
numPigeons(_numPigeons),
numLiteralsPerTime(2 * _numPigeons)
{
}
void print() {
//i, u, g, t
int numberOfClauses = 0;
numberOfClauses = numPigeons;
std::cout << "i cnf " << numLiteralsPerTime << " "
<< numberOfClauses << std::endl;
for (unsigned i = 0; i < numPigeons; i++) {
printClause({
varPigeonInHole(i, 0), helperFutureHole(i, 0)
});
}
numberOfClauses = (numPigeons - 1) * numPigeons / 2;
std::cout << "u cnf " << numLiteralsPerTime << " "
<< numberOfClauses << std::endl;
// at most one pigeon in hole of step
for (unsigned i = 0; i < numPigeons; i++) {
for (unsigned j = 0; j < i; j++) {
printClause({-varPigeonInHole(i, 0) , -varPigeonInHole(j, 0)});
}
}
numberOfClauses = numPigeons;
std::cout << "g cnf " << numLiteralsPerTime << " "
<< numberOfClauses << std::endl;
for (unsigned i = 0; i < numPigeons; i++) {
printClause({-helperFutureHole(i, 0)});
}
numberOfClauses = 3 * numPigeons;
std::cout << "t cnf " << 2 * numLiteralsPerTime << " "
<< numberOfClauses << std::endl;
for (unsigned i = 0; i < numPigeons; i++) {
// ->
printClause({
-helperFutureHole(i, 0),
varPigeonInHole(i, 1),
helperFutureHole(i, 1),
});
// <-
// printClause({
// helperFutureHole(i, 0),
// -varPigeonInHole(i, 1)
// });
// printClause({
// helperFutureHole(i, 0),
// -helperFutureHole(i, 1)
// });
}
}
};
class VariableContainer {
public:
VariableContainer(unsigned _numPigeons):
numPigeons(_numPigeons),
allocator()
{
}
virtual int pigeonInHole(unsigned pigeon, unsigned hole) = 0;
virtual SatVariableAllocator& getAllocator() {
return allocator;
}
virtual ~VariableContainer(){
}
protected:
unsigned numPigeons;
private:
SatVariableAllocator allocator;
};
class BasicVariableContainer: public virtual VariableContainer {
public:
BasicVariableContainer(unsigned numPigeons):
VariableContainer(numPigeons),
P(VariableContainer::getAllocator().newVariable(
numPigeons, numPigeons - 1)) {
}
virtual int pigeonInHole(unsigned pigeon, unsigned hole) {
return P(pigeon, hole);
}
virtual ~BasicVariableContainer(){
}
private:
SatVariable<unsigned, unsigned> P;
};
class ExtendedVariableContainer: public virtual VariableContainer {
public:
ExtendedVariableContainer(unsigned numPigeons):
VariableContainer(numPigeons),
P(VariableContainer::getAllocator().newVariable(
numPigeons + 1, numPigeons, numPigeons - 1)) {
}
virtual int pigeonInHole(unsigned pigeon, unsigned hole) {
return P(numPigeons, pigeon, hole);
}
virtual int pigeonInHole(unsigned layer, unsigned pigeon, unsigned hole) {
return P(layer, pigeon, hole);
}
virtual ~ExtendedVariableContainer(){
}
private:
SatVariable<unsigned, unsigned, unsigned> P;
};
class VariableContainer3SAT: public virtual VariableContainer {
public:
VariableContainer3SAT(unsigned numPigeons):
VariableContainer(numPigeons),
H(getAllocator().newVariable(numPigeons, numPigeons))
{
}
virtual int connector(unsigned pigeon, unsigned hole) {
return H(pigeon, hole);
}
virtual ~VariableContainer3SAT(){
}
private:
SatVariable<unsigned, unsigned> H;
};
class HelperVariableContainer: public virtual VariableContainer {
public:
HelperVariableContainer(unsigned numPigeons):
VariableContainer(numPigeons),
helperVar(getAllocator().newVariable(numPigeons))
{
}
virtual int helper(unsigned i) {
return helperVar(i);
}
virtual ~HelperVariableContainer(){
}
private:
SatVariable<unsigned> helperVar;
};
template <class T1, class T2>
class ContainerCombinator:
public virtual VariableContainer,
public virtual T1,
public virtual T2 {
public:
ContainerCombinator(unsigned numPigeons):
VariableContainer(numPigeons),
T1(numPigeons),
T2(numPigeons)
{
}
virtual ~ContainerCombinator(){
}
};
class UniversalPHPEncoder {
public:
UniversalPHPEncoder(
std::unique_ptr<ipasir::Ipasir> _solver,
unsigned _numPigeons):
UniversalPHPEncoder(
std::move(_solver),
std::make_unique<BasicVariableContainer>(_numPigeons),
_numPigeons
)
{}
UniversalPHPEncoder(
std::unique_ptr<ipasir::Ipasir> _solver,
std::unique_ptr<VariableContainer> _var,
unsigned _numPigeons):
solver(std::move(_solver)),
var(std::move(_var)),
numPigeons(_numPigeons)
{
assert(numPigeons > 1);
}
virtual void addAtMostOnePigeonInHole(unsigned hole) {
for (unsigned pigeonA = 1; pigeonA < numPigeons; pigeonA++) {
for (unsigned pigeonB = 0; pigeonB < pigeonA; pigeonB++) {
solver->addClause({
-var->pigeonInHole(pigeonA, hole),
-var->pigeonInHole(pigeonB, hole)
});
}
}
}
virtual void addAtLeastOneHolePerPigeon(
unsigned numHoles,
unsigned activationLiteral = 0) {
for (unsigned pigeon = 0; pigeon < numPigeons; pigeon++) {
for (unsigned hole = 0; hole < numHoles; hole++) {
solver->add(var->pigeonInHole(pigeon, hole));
}
if (activationLiteral != 0) {
solver->add(activationLiteral);
}
solver->add(0);
}
}
virtual void solve(){
unsigned numHoles = numPigeons - 1;
addAtLeastOneHolePerPigeon(numHoles);
for (unsigned hole = 0; hole < numHoles; hole++) {
addAtMostOnePigeonInHole(hole);
}
bool solved = (solver->solve() == ipasir::SolveResult::SAT);
assert(!solved);
}
virtual VariableContainer* getVar() {
return var.get();
}
virtual ~UniversalPHPEncoder(){
}
protected:
std::unique_ptr<ipasir::Ipasir> solver;
std::unique_ptr<VariableContainer> var;
unsigned numPigeons;
};
typedef ContainerCombinator<HelperVariableContainer, BasicVariableContainer> hvc;
class SimpleIncrementalPHPEncoder: public UniversalPHPEncoder {
public:
SimpleIncrementalPHPEncoder(
std::unique_ptr<ipasir::Ipasir> _solver,
unsigned numPigeons):
UniversalPHPEncoder(
std::move(_solver),
std::make_unique<hvc>(numPigeons),
numPigeons
)
{
hvar = dynamic_cast<hvc*>(getVar());
}
virtual void solve(){
bool solved;
for (unsigned numHoles = 1; numHoles < numPigeons; numHoles++) {
addAtMostOnePigeonInHole(numHoles - 1);
addAtLeastOneHolePerPigeon(numHoles, hvar->helper(numHoles - 1));
{
CollectData::MakespanAndTime m(numHoles);
solver->assume(-hvar->helper(numHoles - 1));
solved = (solver->solve() == ipasir::SolveResult::SAT);
assert(!solved);
}
}
}
virtual ~SimpleIncrementalPHPEncoder(){}
private:
hvc* hvar;
};
typedef ContainerCombinator<VariableContainer3SAT, BasicVariableContainer> svc;
class PHPEncoder3SAT: public UniversalPHPEncoder {
public:
PHPEncoder3SAT(
std::unique_ptr<ipasir::Ipasir> _solver,
unsigned _numPigeons):
UniversalPHPEncoder(
std::move(_solver),
std::make_unique<svc>(_numPigeons),
_numPigeons
) {
}
PHPEncoder3SAT(
std::unique_ptr<ipasir::Ipasir> _solver,
std::unique_ptr<VariableContainer3SAT> _var,
unsigned _numPigeons):
UniversalPHPEncoder(
std::move(_solver),
std::move(_var),
_numPigeons
)
{
}
virtual void addLowerBorder() {
VariableContainer3SAT* var =
dynamic_cast<VariableContainer3SAT*>(getVar());
for (unsigned p = 0; p < numPigeons; p++) {
solver->addClause({ var->connector(p, 0)});
}
}
virtual void addBorders(bool forceUppberBound = false) {
addLowerBorder();
if (forceUppberBound || fixedUpperBound.getValue()) {
addUpperBorder();
}
}
virtual void addHole(unsigned hole) {
VariableContainer3SAT* var =
dynamic_cast<VariableContainer3SAT*>(getVar());
for (unsigned p = 0; p < numPigeons; p++) {
solver->addClause({
-var->connector(p,hole),
var->pigeonInHole(p, hole),
var->connector(p, hole + 1)
});
}
addAtMostOnePigeonInHole(hole);
}
virtual void addUpperBorder() {
VariableContainer3SAT* var =
dynamic_cast<VariableContainer3SAT*>(getVar());
for (unsigned p = 0; p < numPigeons; p++) {
solver->addClause({ -var->connector(p, numPigeons - 1)});
}
}
virtual void assumeAll(unsigned i) {
VariableContainer3SAT* var =
dynamic_cast<VariableContainer3SAT*>(getVar());
for (unsigned p = 0; p < numPigeons; p++) {
solver->assume(-var->connector(p, i));
}
bool solved = (solver->solve() == ipasir::SolveResult::SAT);
assert(!solved);
}
virtual void solve() {
solve(false);
}
virtual void solveIncremental() {
solve(true);
}
virtual void solve(bool incremental){
addBorders();
for (unsigned numHoles = 1; numHoles < numPigeons; numHoles++) {
addHole(numHoles - 1);
if (incremental) {
CollectData::MakespanAndTime m(numHoles);
assumeAll(numHoles);
}
}
if (!incremental)
{
unsigned numHoles = numPigeons - 1;
CollectData::MakespanAndTime m(numHoles);
assumeAll(numHoles);
}
}
virtual ~PHPEncoder3SAT() {};
};
class AlternatePHPEncoder3SAT: public PHPEncoder3SAT {
public:
AlternatePHPEncoder3SAT(
std::unique_ptr<ipasir::Ipasir> _solver,
unsigned _numPigeons):
PHPEncoder3SAT(
std::move(_solver),
std::make_unique<svc>(_numPigeons),
_numPigeons
) {
}
virtual void assumeAll(unsigned numHoles) {
VariableContainer3SAT* var =
dynamic_cast<VariableContainer3SAT*>(getVar());
unsigned n = numPigeons;
for (unsigned k = numPigeons; k >=numHoles + 1; k--) {
// std::cout << "n: " << n << " k: " << k << std::endl;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + k, true);
do {
for (unsigned i = 0; i < n; ++i) {
if (v[i]) {
solver->assume(-var->connector(i, numHoles));
// std::cout << i << " ";
}
}
// std::cout << std::endl;
bool unsat = (solver->solve() == ipasir::SolveResult::UNSAT);
assert(unsat);
if (unsat && addAssumed.getValue()) {
for (unsigned i = 0; i < n; ++i) {
if (v[i]) {
solver->add(var->connector(i, numHoles));
// std::cout << i << " ";
}
}
solver->add(0);
}
} while (std::prev_permutation(v.begin(), v.end()));
}
}
};
typedef ContainerCombinator<ExtendedVariableContainer, VariableContainer3SAT> evc;
class ExtendedPHPEncoder3SAT: public PHPEncoder3SAT {
public:
ExtendedPHPEncoder3SAT(
std::unique_ptr<ipasir::Ipasir> _solver,
unsigned _numPigeons):
PHPEncoder3SAT(
std::move(_solver),
std::make_unique<evc>(_numPigeons),
_numPigeons
)
{
}
ExtendedPHPEncoder3SAT(
std::unique_ptr<ipasir::Ipasir> _solver,
std::unique_ptr<evc> _var,
unsigned _numPigeons):
PHPEncoder3SAT(
std::move(_solver),
std::move(_var),
_numPigeons
)
{
}
virtual void addExtendedResolutionClauses(){
ExtendedVariableContainer* var =
dynamic_cast<ExtendedVariableContainer*>(getVar());
for (unsigned n = numPigeons; n > 2; n--) {
for (unsigned i = 0; i < n - 1; i++) {
for (unsigned j = 0; j < n - 2; j++) {
solver->addClause({
var->pigeonInHole(n - 1, i, j),
-var->pigeonInHole(n, i, j)
});
solver->addClause({
var->pigeonInHole(n - 1, i, j),
-var->pigeonInHole(n, i, n - 2),
-var->pigeonInHole(n, n - 1, j)
});
solver->addClause({
-var->pigeonInHole(n - 1, i, j),
var->pigeonInHole(n, i, j),
var->pigeonInHole(n, i, n - 2)
});
solver->addClause({
-var->pigeonInHole(n - 1, i, j),
var->pigeonInHole(n, i, j),
var->pigeonInHole(n, n - 1, j)
});
}
}
}
}
virtual void learnClauses(unsigned step){
unsigned sn = numPigeons;
ExtendedVariableContainer* var =
dynamic_cast<ExtendedVariableContainer*>(getVar());
// learn at most one
for (unsigned h = 0; h < numPigeons - 1 - step; h++) {
for (unsigned p = 1; p < numPigeons - step; p++) {
for (unsigned j = 0; j < p; j++) {
//carj::ScopedTimer timer((*solves.rbegin())["time"]);
//LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << p << ", " << h << ")";
//LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << j << ", " << h << ")";
std::vector<int> clause({
-var->pigeonInHole(sn - step, p, h),
-var->pigeonInHole(sn - step, j, h)
});
for (int lit: clause) {
solver->assume(-lit);
}
std::set<int> clauseLiterals;
clauseLiterals.insert(clause.begin(),clause.end());
bool foundClause = false;
solver->set_learn(2, [&foundClause, &clauseLiterals](int* learned) {
std::set<int> learnedLiterals;
while(*learned != 0) {
learnedLiterals.insert(*learned);
learned++;
}
foundClause |= (learnedLiterals == clauseLiterals);
});
bool solved = (solver->solve() == ipasir::SolveResult::SAT);
assert(!solved);
solver->set_learn(0, [](int*){});
}
}
}
// learn at least one
for (unsigned p = 1; p < numPigeons - step; p++) {
for (unsigned h = 0; h < numPigeons - 1 - step; h++) {
//carj::ScopedTimer timer((*solves.rbegin())["time"]);
//LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << p << ", " << h << ")";
//LOG(INFO) << "var->pigeonInHole(" << sn - step << ", " << j << ", " << h << ")";
solver->assume(-var->pigeonInHole(sn - step, p, h));
}
bool solved = (solver->solve() == ipasir::SolveResult::SAT);
assert(!solved);
}
}
virtual void solve() {
solve(false);
}
virtual void solveIncremental() {
solve(true);
}
virtual void solve(bool incremental){
// solver->set_learn(10000, [](int* learned) {
// for(;*learned != 0;learned++) {
// std::cout << *learned << " ";
// }
// std::cout << std::endl;
// });
bool solved;
addBorders(true);
for (unsigned numHoles = 1; numHoles < numPigeons; numHoles++) {
addHole(numHoles - 1);
}
addExtendedResolutionClauses();
if (incremental) {
for (unsigned step = 1; step < numPigeons; step++) {
CollectData::MakespanAndTime m(step);
learnClauses(step);
}
}
solved = (solver->solve() == ipasir::SolveResult::SAT);
assert(!solved);
}
virtual ~ExtendedPHPEncoder3SAT(){
}
};
carj::TCarjArg<TCLAP::ValueArg, unsigned> numberOfPigeons("n", "numPigeons",
"Number of pigeons", !neccessaryArgument, 1, "natural number", cmd);
carj::CarjArg<TCLAP::SwitchArg, bool> dimspec("d", "dimspec", "Output dimspec.",
cmd, defaultIsFalse);
carj::CarjArg<TCLAP::SwitchArg, bool> print("p", "print", "Output as cnf.",
cmd, defaultIsFalse);
carj::CarjArg<TCLAP::SwitchArg, bool> extendedResolution("e", "extendedResolution",
"Add extended resolution formulas.", cmd, defaultIsFalse);
carj::CarjArg<TCLAP::SwitchArg, bool> incremental("i", "incremental",
"Solve formual incrementally.", cmd, defaultIsFalse);
carj::CarjArg<TCLAP::SwitchArg, bool> alternate("a", "alternate",
"alternate mode", cmd, defaultIsFalse);
carj::CarjArg<TCLAP::SwitchArg, bool> encoding3SAT("3", "3sat",
"Encode PHP in 3 SAT CNF.", cmd, defaultIsFalse);
carj::CarjArg<TCLAP::SwitchArg, bool> record("r", "record",
"Record clause learning data.", cmd, defaultIsFalse);
int incphp_main(int argc, const char **argv) {
carj::init(argc, argv, cmd, "/incphp/parameters");
if (dimspec.getValue()) {
DimSpecFixedPigeons dsfp(numberOfPigeons.getValue());
dsfp.print();
} else {
std::unique_ptr<ipasir::Ipasir> solver;
if (print.getValue()) {
solver = std::make_unique<ipasir::Printer>();
} else {
solver = std::make_unique<ipasir::Solver>();
}
solver = std::make_unique<ipasir::RandomizedSolver>(std::move(solver));
if (record.getValue()) {
solver = std::make_unique<LearnedClauseEvaluationDecorator>(std::move(solver));
}
LOG(INFO) << "Using solver: " << solver->signature();
if (encoding3SAT.getValue()) {
if (extendedResolution.getValue()) {
std::unique_ptr<ExtendedPHPEncoder3SAT> encoder =
std::make_unique<ExtendedPHPEncoder3SAT>(
std::move(solver),
numberOfPigeons.getValue());
if (incremental.getValue()) {
encoder->solveIncremental();
} else {
encoder->solve();
}
} else {
std::unique_ptr<PHPEncoder3SAT> encoder;
if (alternate.getValue()) {
encoder = std::make_unique<AlternatePHPEncoder3SAT>(
std::move(solver),
numberOfPigeons.getValue());
} else {
encoder = std::make_unique<PHPEncoder3SAT>(
std::move(solver),
numberOfPigeons.getValue());
}
if (incremental.getValue()) {
encoder->solveIncremental();
} else {
encoder->solve();
}
}
} else {
if (extendedResolution.getValue()) {
LOG(FATAL) << "Unsupported Option";
}
if (incremental.getValue()) {
SimpleIncrementalPHPEncoder encoder(
std::move(solver),
numberOfPigeons.getValue());
encoder.solve();
} else {
UniversalPHPEncoder encoder(
std::move(solver),
numberOfPigeons.getValue());
encoder.solve();
}
}
}
return 0;
}
| 23.664981 | 87 | 0.653614 | StephanGocht |
25fcf11745a446cb8ddc224fe08418b05228c89a | 16,735 | hpp | C++ | examples/cpuid/libcpuid/include/cpuid/cpuid.hpp | DrPizza/jsm | d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef | [
"MIT"
] | 1 | 2021-06-29T06:46:34.000Z | 2021-06-29T06:46:34.000Z | examples/cpuid/libcpuid/include/cpuid/cpuid.hpp | DrPizza/jsm | d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef | [
"MIT"
] | null | null | null | examples/cpuid/libcpuid/include/cpuid/cpuid.hpp | DrPizza/jsm | d5fc0a6c1e579bbb15c546aa3b76012ad93bc7ef | [
"MIT"
] | null | null | null | #ifndef CPUID_HPP
#define CPUID_HPP
#include <cstddef>
#include <array>
#include <map>
#include <gsl/gsl>
#include <fmt/format.h>
#include "suffixes.hpp"
#if defined(_MSC_VER)
#define UNREACHABLE() __assume(0)
#else
#define UNREACHABLE() __builtin_unreachable()
#endif
namespace cpuid {
enum struct leaf_type : std::uint32_t
{
basic_info = 0x0000'0000_u32,
version_info = 0x0000'0001_u32,
cache_and_tlb = 0x0000'0002_u32,
serial_number = 0x0000'0003_u32,
deterministic_cache = 0x0000'0004_u32,
monitor_mwait = 0x0000'0005_u32,
thermal_and_power = 0x0000'0006_u32,
extended_features = 0x0000'0007_u32,
reserved_1 = 0x0000'0008_u32,
direct_cache_access = 0x0000'0009_u32,
performance_monitoring = 0x0000'000a_u32,
extended_topology = 0x0000'000b_u32,
reserved_2 = 0x0000'000c_u32,
extended_state = 0x0000'000d_u32,
reserved_3 = 0x0000'000e_u32,
rdt_monitoring = 0x0000'000f_u32,
rdt_allocation = 0x0000'0010_u32,
reserved_4 = 0x0000'0011_u32,
sgx_info = 0x0000'0012_u32,
reserved_5 = 0x0000'0013_u32,
processor_trace = 0x0000'0014_u32,
time_stamp_counter = 0x0000'0015_u32,
processor_frequency = 0x0000'0016_u32,
system_on_chip_vendor = 0x0000'0017_u32,
deterministic_tlb = 0x0000'0018_u32,
reserved_6 = 0x0000'0019_u32,
reserved_7 = 0x0000'001a_u32,
pconfig = 0x0000'001b_u32,
reserved_8 = 0x0000'001c_u32,
reserved_9 = 0x0000'001d_u32,
reserved_10 = 0x0000'001e_u32,
extended_topology_v2 = 0x0000'001f_u32,
hypervisor_limit = 0x4000'0000_u32,
hyper_v_signature = 0x4000'0001_u32,
hyper_v_system_identity = 0x4000'0002_u32,
hyper_v_features = 0x4000'0003_u32,
hyper_v_enlightenment_recs = 0x4000'0004_u32,
hyper_v_implementation_limits = 0x4000'0005_u32,
hyper_v_implementation_hardware = 0x4000'0006_u32,
hyper_v_root_cpu_management = 0x4000'0007_u32,
hyper_v_shared_virtual_memory = 0x4000'0008_u32,
hyper_v_nested_hypervisor = 0x4000'0009_u32,
hyper_v_nested_features = 0x4000'000a_u32,
xen_limit = 0x4000'0000_u32, xen_limit_offset = 0x4000'0100_u32,
xen_version = 0x4000'0001_u32, xen_version_offset = 0x4000'0101_u32,
xen_features = 0x4000'0002_u32, xen_features_offset = 0x4000'0102_u32,
xen_time = 0x4000'0003_u32, xen_time_offset = 0x4000'0103_u32,
xen_hvm_features = 0x4000'0004_u32, xen_hvm_features_offset = 0x4000'0104_u32,
xen_pv_features = 0x4000'0005_u32, xen_pv_features_offset = 0x4000'0105_u32,
vmware_timing = 0x4000'0010_u32,
kvm_features = 0x4000'0001_u32,
extended_limit = 0x8000'0000_u32,
extended_signature_and_features = 0x8000'0001_u32,
brand_string_0 = 0x8000'0002_u32,
brand_string_1 = 0x8000'0003_u32,
brand_string_2 = 0x8000'0004_u32,
l1_cache_identifiers = 0x8000'0005_u32,
l2_cache_identifiers = 0x8000'0006_u32,
ras_advanced_power_management = 0x8000'0007_u32,
address_limits = 0x8000'0008_u32,
reserved_11 = 0x8000'0009_u32,
secure_virtual_machine = 0x8000'000a_u32,
extended_reserved_1 = 0x8000'000b_u32,
extended_reserved_2 = 0x8000'000c_u32,
extended_reserved_3 = 0x8000'000d_u32,
extended_reserved_4 = 0x8000'000e_u32,
extended_reserved_5 = 0x8000'000f_u32,
extended_reserved_6 = 0x8000'0010_u32,
extended_reserved_7 = 0x8000'0011_u32,
extended_reserved_8 = 0x8000'0012_u32,
extended_reserved_9 = 0x8000'0013_u32,
extended_reserved_10 = 0x8000'0014_u32,
extended_reserved_11 = 0x8000'0015_u32,
extended_reserved_12 = 0x8000'0016_u32,
extended_reserved_13 = 0x8000'0017_u32,
extended_reserved_14 = 0x8000'0018_u32,
tlb_1g_identifiers = 0x8000'0019_u32,
performance_optimization = 0x8000'001a_u32,
instruction_based_sampling = 0x8000'001b_u32,
lightweight_profiling = 0x8000'001c_u32,
cache_properties = 0x8000'001d_u32,
extended_apic = 0x8000'001e_u32,
encrypted_memory = 0x8000'001f_u32,
none = 0x0000'0000_u32,
};
constexpr inline leaf_type operator++(leaf_type& lhs) {
lhs = static_cast<leaf_type>(static_cast<std::uint32_t>(lhs) + 1);
return lhs;
}
constexpr inline leaf_type operator+=(leaf_type& lhs, std::uint32_t rhs) {
lhs = static_cast<leaf_type>(static_cast<std::uint32_t>(lhs) + rhs);
return lhs;
}
constexpr inline leaf_type operator+(const leaf_type& lhs, std::uint32_t rhs) {
return static_cast<leaf_type>(static_cast<std::uint32_t>(lhs) + rhs);
}
enum struct subleaf_type : std::uint32_t
{
main = 0x0000'0000_u32,
extended_features_main = 0x0000'0000_u32,
extended_state_main = 0x0000'0000_u32,
extended_state_sub = 0x0000'0001_u32,
rdt_monitoring_main = 0x0000'0000_u32,
rdt_monitoring_l3 = 0x0000'0001_u32,
rdt_allocation_main = 0x0000'0000_u32,
rdt_cat_l3 = 0x0000'0001_u32,
rdt_cat_l2 = 0x0000'0002_u32,
rdt_mba = 0x0000'0003_u32,
sgx_capabilities = 0x0000'0000_u32,
sgx_attributes = 0x0000'0001_u32,
processor_trace_main = 0x0000'0000_u32,
processor_trace_sub = 0x0000'0001_u32,
system_on_chip_vendor_main = 0x0000'0000_u32,
system_on_chip_vendor_sub = 0x0000'0001_u32,
deterministic_address_translation_main = 0x0000'0000_u32,
deterministic_address_translation_sub = 0x0000'0001_u32,
xen_time_main = 0x0000'0000_u32,
xen_time_tsc_offset = 0x0000'0001_u32,
xen_time_host = 0x0000'0002_u32,
none = 0x0000'0000_u32,
};
constexpr inline subleaf_type operator++(subleaf_type& lhs) {
lhs = static_cast<subleaf_type>(static_cast<std::uint32_t>(lhs) + 1);
return lhs;
}
constexpr inline subleaf_type operator+=(subleaf_type& lhs, std::uint32_t offset) {
lhs = static_cast<subleaf_type>(static_cast<std::uint32_t>(lhs) + offset);
return lhs;
}
enum register_type : std::uint8_t
{
eax,
ebx,
ecx,
edx,
};
constexpr inline register_type operator++(register_type& lhs) {
lhs = static_cast<register_type>(static_cast<std::uint8_t>(lhs) + 1);
return lhs;
}
enum vendor_type : std::uint32_t
{
unknown = 0x0000'0000_u32,
// silicon
amd = 0x0000'0001_u32,
centaur = 0x0000'0002_u32,
cyrix = 0x0000'0004_u32,
intel = 0x0000'0008_u32,
transmeta = 0x0000'0010_u32,
nat_semi = 0x0000'0020_u32,
nexgen = 0x0000'0040_u32,
rise = 0x0000'0080_u32,
sis = 0x0000'0100_u32,
umc = 0x0000'0200_u32,
via = 0x0000'0400_u32,
vortex = 0x0000'0800_u32,
// hypervisors
bhyve = 0x0001'0000_u32,
kvm = 0x0002'0000_u32,
hyper_v = 0x0004'0000_u32,
parallels = 0x0008'0000_u32,
vmware = 0x0010'0000_u32,
xen_hvm = 0x0020'0000_u32,
xen_viridian = xen_hvm | hyper_v,
qemu = 0x0040'0000_u32,
// for filtering
any_silicon = 0x0000'0fff_u32,
any_hypervisor = 0x007f'0000_u32,
any = 0xffff'ffff_u32,
};
constexpr inline vendor_type operator|(const vendor_type& lhs, const vendor_type& rhs) {
return static_cast<vendor_type>(static_cast<std::uint32_t>(lhs) | static_cast<std::uint32_t>(rhs));
}
constexpr inline vendor_type operator&(const vendor_type& lhs, const vendor_type& rhs) {
return static_cast<vendor_type>(static_cast<std::uint32_t>(lhs) & static_cast<std::uint32_t>(rhs));
}
inline std::string to_string(vendor_type vendor) {
std::string silicon;
std::string hypervisor;
switch(vendor & vendor_type::any_silicon) {
case vendor_type::amd:
silicon = "AMD";
break;
case vendor_type::centaur:
silicon = "Centaur";
break;
case vendor_type::cyrix:
silicon = "Cyrix";
break;
case vendor_type::intel:
silicon = "Intel";
break;
case vendor_type::transmeta:
silicon = "Transmeta";
break;
case vendor_type::nat_semi:
silicon = "National Semiconductor";
break;
case vendor_type::nexgen:
silicon = "NexGen";
break;
case vendor_type::rise:
silicon = "Rise";
break;
case vendor_type::sis:
silicon = "SiS";
break;
case vendor_type::umc:
silicon = "UMC";
break;
case vendor_type::via:
silicon = "VIA";
break;
case vendor_type::vortex:
silicon = "Vortex";
break;
default:
silicon = "Unknown";
break;
}
switch(vendor & vendor_type::any_hypervisor) {
case vendor_type::bhyve:
hypervisor = "bhyve";
break;
case vendor_type::kvm:
hypervisor = "KVM";
break;
case vendor_type::hyper_v:
hypervisor = "Hyper-V";
break;
case vendor_type::parallels:
hypervisor = "Parallels";
break;
case vendor_type::vmware:
hypervisor = "VMware";
break;
case vendor_type::xen_hvm:
hypervisor = "Xen HVM";
break;
case vendor_type::xen_viridian:
hypervisor = "Xen HVM with Viridian Extensions";
break;
case vendor_type::qemu:
hypervisor = "QEMU";
break;
default:
hypervisor = "";
}
return hypervisor.size() != 0 ? hypervisor + " on " + silicon : silicon;
}
using register_set_t = std::array<std::uint32_t, 4>;
using subleaves_t = std::map<subleaf_type, register_set_t>;
using leaves_t = std::map<leaf_type, subleaves_t>;
vendor_type get_vendor_from_name(const register_set_t& regs);
struct id_info_t
{
std::uint32_t brand_id : 8;
std::uint32_t cache_line_size : 8;
std::uint32_t maximum_addressable_ids : 8;
std::uint32_t initial_apic_id : 8;
};
struct split_model_t
{
std::uint32_t stepping : 4;
std::uint32_t model : 4;
std::uint32_t family : 4;
std::uint32_t type : 2;
std::uint32_t reserved_1 : 2;
std::uint32_t extended_model : 4;
std::uint32_t extended_family : 8;
std::uint32_t reserved_2 : 4;
};
struct model_t
{
std::uint32_t stepping;
std::uint32_t model;
std::uint32_t family;
};
inline bool operator==(const model_t& lhs, const model_t& rhs) noexcept {
return lhs.stepping == rhs.stepping
&& lhs.model == rhs.model
&& lhs.family == rhs.family;
}
struct cpu_t
{
std::uint32_t apic_id;
vendor_type vendor;
model_t model;
leaves_t leaves;
};
inline bool operator==(const cpu_t& lhs, const cpu_t& rhs) noexcept {
return lhs.apic_id == rhs.apic_id
&& lhs.vendor == rhs.vendor
&& lhs.model == rhs.model
&& lhs.leaves == rhs.leaves;
}
register_set_t cpuid(leaf_type leaf, subleaf_type subleaf) noexcept;
void print_generic(fmt::memory_buffer& out, const cpu_t& cpu, leaf_type leaf, subleaf_type subleaf);
enum struct file_format
{
native,
etallen,
libcpuid,
aida64,
cpuinfo
};
std::map<std::uint32_t, cpu_t> enumerate_file(std::istream& fin, file_format format);
std::map<std::uint32_t, cpu_t> enumerate_processors(bool brute_force, bool skip_vendor_check, bool skip_feature_check);
void print_dump(fmt::memory_buffer& out, std::map<std::uint32_t, cpu_t> logical_cpus, file_format format);
void print_leaf(fmt::memory_buffer& out, const cpu_t& cpu, leaf_type leaf, bool skip_vendor_check, bool skip_feature_check);
void print_leaves(fmt::memory_buffer& out, const cpu_t& cpu, bool skip_vendor_check, bool skip_feature_check);
struct flag_spec_t
{
std::uint32_t selector_eax = 0_u32;
std::uint32_t selector_ecx = 0_u32;
register_type flag_register = eax;
std::string flag_name = "";
std::uint32_t flag_start = 0xffff'ffff_u32;
std::uint32_t flag_end = 0xffff'ffff_u32;
};
void print_single_flag(fmt::memory_buffer& out, const cpu_t& cpu, const flag_spec_t& flag_description);
flag_spec_t parse_flag_spec(const std::string& flag_description);
std::string to_string(const flag_spec_t& spec);
inline bool operator==(const flag_spec_t& lhs, const flag_spec_t& rhs) noexcept {
return std::tie(lhs.selector_eax, lhs.selector_ecx, lhs.flag_register, lhs.flag_name, lhs.flag_start, lhs.flag_end)
== std::tie(rhs.selector_eax, rhs.selector_ecx, rhs.flag_register, rhs.flag_name, rhs.flag_start, rhs.flag_end);
}
struct cache_instance_t
{
std::vector<std::uint32_t> sharing_ids;
};
struct cache_t
{
std::uint32_t level;
std::uint32_t type;
std::uint32_t ways;
std::uint32_t sets;
std::uint32_t line_size;
std::uint32_t line_partitions;
std::uint32_t total_size;
bool fully_associative;
bool direct_mapped;
bool complex_addressed;
bool self_initializing;
bool invalidates_lower_levels;
bool inclusive;
std::uint32_t sharing_mask;
std::map<std::uint32_t, cache_instance_t> instances;
};
inline bool operator<(const cache_t& lhs, const cache_t& rhs) noexcept {
return lhs.level != rhs.level ? lhs.level < rhs.level
: lhs.type != rhs.type ? lhs.type < rhs.type
: lhs.total_size < rhs.total_size;
}
enum class level_type : std::uint32_t
{
invalid = 0_u32,
smt = 1_u32,
core = 2_u32,
module = 3_u32,
tile = 4_u32,
die = 5_u32,
node = 0xffff'fffe_u32,
package = 0xffff'ffff_u32
};
struct level_description_t
{
level_type level;
std::uint32_t shift_distance;
std::uint32_t select_mask;
};
struct logical_core_t
{
std::uint32_t full_apic_id;
std::uint32_t smt_id;
std::uint32_t core_id;
std::uint32_t package_id;
std::vector<std::uint32_t> non_shared_cache_ids;
std::vector<std::uint32_t> shared_cache_ids;
};
struct physical_core_t
{
std::map<std::uint32_t, logical_core_t> logical_cores;
};
struct module_t
{
std::map<std::uint32_t, physical_core_t> physical_cores;
};
struct tile_t
{
std::map<std::uint32_t, module_t> modules;
};
struct die_t
{
std::map<std::uint32_t, tile_t> tiles;
};
struct node_t
{
std::map<std::uint32_t, physical_core_t> physical_cores;
};
struct package_t
{
std::map<std::uint32_t, physical_core_t> physical_cores;
//std::map<std::uint32_t, die_t> dies;
//std::map<std::uint32_t, node_t> nodes;
};
struct system_t
{
vendor_type vendor;
std::uint32_t smt_mask_width;
std::uint32_t core_mask_width;
std::uint32_t module_mask_width;
std::uint32_t tile_mask_width;
std::uint32_t die_mask_width;
std::vector<std::uint32_t> x2_apic_ids;
std::vector<cache_t> all_caches;
std::vector<logical_core_t> all_cores;
std::map<std::uint32_t, package_t> packages;
std::set<level_type> valid_levels;
};
system_t build_topology(const std::map<std::uint32_t, cpu_t>& logical_cpus);
void print_topology(fmt::memory_buffer& out, const system_t& machine);
}
#endif
| 32.685547 | 126 | 0.612668 | DrPizza |
25fd87249c385e2b459e6d3fc0275a6b65d9b193 | 44,878 | cpp | C++ | source/backend/shape/bezier.cpp | acekiller/povray | ae6837fb8625bb9ca00830f8871c90c87dd21b75 | [
"Zlib"
] | 1 | 2015-06-21T05:27:57.000Z | 2015-06-21T05:27:57.000Z | source/backend/shape/bezier.cpp | binji/povray | ae6837fb8625bb9ca00830f8871c90c87dd21b75 | [
"Zlib"
] | null | null | null | source/backend/shape/bezier.cpp | binji/povray | ae6837fb8625bb9ca00830f8871c90c87dd21b75 | [
"Zlib"
] | null | null | null | /*******************************************************************************
* bezier.cpp
*
* This module implements the code for Bezier bicubic patch shapes
*
* This file was written by Alexander Enzmann. He wrote the code for
* bezier bicubic patches and generously provided us these enhancements.
*
* from Persistence of Vision Ray Tracer ('POV-Ray') version 3.7.
* Copyright 1991-2003 Persistence of Vision Team
* Copyright 2003-2009 Persistence of Vision Raytracer Pty. Ltd.
* ---------------------------------------------------------------------------
* NOTICE: This source code file is provided so that users may experiment
* with enhancements to POV-Ray and to port the software to platforms other
* than those supported by the POV-Ray developers. There are strict rules
* regarding how you are permitted to use this file. These rules are contained
* in the distribution and derivative versions licenses which should have been
* provided with this file.
*
* These licences may be found online, linked from the end-user license
* agreement that is located at http://www.povray.org/povlegal.html
* ---------------------------------------------------------------------------
* POV-Ray is based on the popular DKB raytracer version 2.12.
* DKBTrace was originally written by David K. Buck.
* DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
* ---------------------------------------------------------------------------
* $File: //depot/povray/smp/source/backend/shape/bezier.cpp $
* $Revision: #26 $
* $Change: 5103 $
* $DateTime: 2010/08/22 06:58:49 $
* $Author: clipka $
*******************************************************************************/
/*********************************************************************************
* NOTICE
*
* This file is part of a BETA-TEST version of POV-Ray version 3.7. It is not
* final code. Use of this source file is governed by both the standard POV-Ray
* licences referred to in the copyright header block above this notice, and the
* following additional restrictions numbered 1 through 4 below:
*
* 1. This source file may not be re-distributed without the written permission
* of Persistence of Vision Raytracer Pty. Ltd.
*
* 2. This notice may not be altered or removed.
*
* 3. Binaries generated from this source file by individuals for their own
* personal use may not be re-distributed without the written permission
* of Persistence of Vision Raytracer Pty. Ltd. Such personal-use binaries
* are not required to have a timeout, and thus permission is granted in
* these circumstances only to disable the timeout code contained within
* the beta software.
*
* 4. Binaries generated from this source file for use within an organizational
* unit (such as, but not limited to, a company or university) may not be
* distributed beyond the local organizational unit in which they were made,
* unless written permission is obtained from Persistence of Vision Raytracer
* Pty. Ltd. Additionally, the timeout code implemented within the beta may
* not be disabled or otherwise bypassed in any manner.
*
* The following text is not part of the above conditions and is provided for
* informational purposes only.
*
* The purpose of the no-redistribution clause is to attempt to keep the
* circulating copies of the beta source fresh. The only authorized distribution
* point for the source code is the POV-Ray website and Perforce server, where
* the code will be kept up to date with recent fixes. Additionally the beta
* timeout code mentioned above has been a standard part of POV-Ray betas since
* version 1.0, and is intended to reduce bug reports from old betas as well as
* keep any circulating beta binaries relatively fresh.
*
* All said, however, the POV-Ray developers are open to any reasonable request
* for variations to the above conditions and will consider them on a case-by-case
* basis.
*
* Additionally, the developers request your co-operation in fixing bugs and
* generally improving the program. If submitting a bug-fix, please ensure that
* you quote the revision number of the file shown above in the copyright header
* (see the '$Revision:' field). This ensures that it is possible to determine
* what specific copy of the file you are working with. The developers also would
* like to make it known that until POV-Ray 3.7 is out of beta, they would prefer
* to emphasize the provision of bug fixes over the addition of new features.
*
* Persons wishing to enhance this source are requested to take the above into
* account. It is also strongly suggested that such enhancements are started with
* a recent copy of the source.
*
* The source code page (see http://www.povray.org/beta/source/) sets out the
* conditions under which the developers are willing to accept contributions back
* into the primary source tree. Please refer to those conditions prior to making
* any changes to this source, if you wish to submit those changes for inclusion
* with POV-Ray.
*
*********************************************************************************/
// frame.h must always be the first POV file included (pulls in platform config)
#include "backend/frame.h"
#include "backend/math/vector.h"
#include "backend/shape/bezier.h"
#include "backend/math/matrices.h"
#include "backend/scene/objects.h"
#include "backend/scene/threaddata.h"
#include "base/pov_err.h"
#include <algorithm>
// this must be the last file included
#include "base/povdebug.h"
namespace pov
{
/*****************************************************************************
* Local preprocessor defines
******************************************************************************/
const DBL BEZIER_EPSILON = 1.0e-10;
const DBL BEZIER_TOLERANCE = 1.0e-5;
/*****************************************************************************
*
* FUNCTION
*
* create_new_bezier_node
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
BEZIER_NODE *BicubicPatch::create_new_bezier_node()
{
BEZIER_NODE *Node = (BEZIER_NODE *)POV_MALLOC(sizeof(BEZIER_NODE), "bezier node");
Node->Data_Ptr = NULL;
return (Node);
}
/*****************************************************************************
*
* FUNCTION
*
* create_bezier_vertex_block
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
BEZIER_VERTICES *BicubicPatch::create_bezier_vertex_block()
{
BEZIER_VERTICES *Vertices;
Vertices = (BEZIER_VERTICES *)POV_MALLOC(sizeof(BEZIER_VERTICES), "bezier vertices");
return (Vertices);
}
/*****************************************************************************
*
* FUNCTION
*
* create_bezier_child_block
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
BEZIER_CHILDREN *BicubicPatch::create_bezier_child_block()
{
BEZIER_CHILDREN *Children;
Children = (BEZIER_CHILDREN *)POV_MALLOC(sizeof(BEZIER_CHILDREN), "bezier children");
return (Children);
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_tree_builder
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
BEZIER_NODE *BicubicPatch::bezier_tree_builder(const VECTOR (*Patch)[4][4], DBL u0, DBL u1, DBL v0, DBL v1, int depth, int& max_depth_reached)
{
VECTOR Lower_Left[4][4], Lower_Right[4][4];
VECTOR Upper_Left[4][4], Upper_Right[4][4];
BEZIER_CHILDREN *Children;
BEZIER_VERTICES *Vertices;
BEZIER_NODE *Node = create_new_bezier_node();
if (depth > max_depth_reached)
{
max_depth_reached = depth;
}
/* Build the bounding sphere for this subpatch. */
bezier_bounding_sphere(Patch, Node->Center, &(Node->Radius_Squared));
/*
* If the patch is close to being flat, then just perform
* a ray-plane intersection test.
*/
if (flat_enough(Patch))
{
/* The patch is now flat enough to simply store the corners. */
Node->Node_Type = BEZIER_LEAF_NODE;
Vertices = create_bezier_vertex_block();
Assign_Vector(Vertices->Vertices[0], (*Patch)[0][0]);
Assign_Vector(Vertices->Vertices[1], (*Patch)[0][3]);
Assign_Vector(Vertices->Vertices[2], (*Patch)[3][3]);
Assign_Vector(Vertices->Vertices[3], (*Patch)[3][0]);
Vertices->uvbnds[0] = u0;
Vertices->uvbnds[1] = u1;
Vertices->uvbnds[2] = v0;
Vertices->uvbnds[3] = v1;
Node->Data_Ptr = (void *)Vertices;
}
else
{
if (depth >= U_Steps)
{
if (depth >= V_Steps)
{
/* We are at the max recursion depth. Just store corners. */
Node->Node_Type = BEZIER_LEAF_NODE;
Vertices = create_bezier_vertex_block();
Assign_Vector(Vertices->Vertices[0], (*Patch)[0][0]);
Assign_Vector(Vertices->Vertices[1], (*Patch)[0][3]);
Assign_Vector(Vertices->Vertices[2], (*Patch)[3][3]);
Assign_Vector(Vertices->Vertices[3], (*Patch)[3][0]);
Vertices->uvbnds[0] = u0;
Vertices->uvbnds[1] = u1;
Vertices->uvbnds[2] = v0;
Vertices->uvbnds[3] = v1;
Node->Data_Ptr = (void *)Vertices;
}
else
{
bezier_split_up_down(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left);
Node->Node_Type = BEZIER_INTERIOR_NODE;
Children = create_bezier_child_block();
Children->Children[0] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Left, u0, u1, v0, (v0 + v1) / 2.0, depth + 1, max_depth_reached);
Children->Children[1] = bezier_tree_builder((VECTOR(*)[4][4])Upper_Left, u0, u1, (v0 + v1) / 2.0, v1, depth + 1, max_depth_reached);
Node->Count = 2;
Node->Data_Ptr = (void *)Children;
}
}
else
{
if (depth >= V_Steps)
{
bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right);
Node->Node_Type = BEZIER_INTERIOR_NODE;
Children = create_bezier_child_block();
Children->Children[0] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Left, u0, (u0 + u1) / 2.0, v0, v1, depth + 1, max_depth_reached);
Children->Children[1] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Right, (u0 + u1) / 2.0, u1, v0, v1, depth + 1, max_depth_reached);
Node->Count = 2;
Node->Data_Ptr = (void *)Children;
}
else
{
bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right);
bezier_split_up_down((VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left);
bezier_split_up_down((VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Upper_Right);
Node->Node_Type = BEZIER_INTERIOR_NODE;
Children = create_bezier_child_block();
Children->Children[0] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Left, u0, (u0 + u1) / 2.0, v0, (v0 + v1) / 2.0, depth + 1, max_depth_reached);
Children->Children[1] = bezier_tree_builder((VECTOR(*)[4][4])Upper_Left, u0, (u0 + u1) / 2.0, (v0 + v1) / 2.0, v1, depth + 1, max_depth_reached);
Children->Children[2] = bezier_tree_builder((VECTOR(*)[4][4])Lower_Right, (u0 + u1) / 2.0, u1, v0, (v0 + v1) / 2.0, depth + 1, max_depth_reached);
Children->Children[3] = bezier_tree_builder((VECTOR(*)[4][4])Upper_Right, (u0 + u1) / 2.0, u1, (v0 + v1) / 2.0, v1, depth + 1, max_depth_reached);
Node->Count = 4;
Node->Data_Ptr = (void *)Children;
}
}
}
return (Node);
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_value
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* Determine the position and normal at a single coordinate
* point (u, v) on a Bezier patch.
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::bezier_value(const VECTOR (*cp)[4][4], DBL u0, DBL v0, VECTOR P, VECTOR N)
{
const DBL C[] = { 1.0, 3.0, 3.0, 1.0 };
int i, j;
DBL c, t, ut, vt;
DBL u[4], uu[4], v[4], vv[4];
DBL du[4], duu[4], dv[4], dvv[4];
DBL squared_u1, squared_v1;
VECTOR U1, V1;
/* Calculate binomial coefficients times coordinate positions. */
u[0] = 1.0; uu[0] = 1.0; du[0] = 0.0; duu[0] = 0.0;
v[0] = 1.0; vv[0] = 1.0; dv[0] = 0.0; dvv[0] = 0.0;
for (i = 1; i < 4; i++)
{
u[i] = u[i - 1] * u0; uu[i] = uu[i - 1] * (1.0 - u0);
v[i] = v[i - 1] * v0; vv[i] = vv[i - 1] * (1.0 - v0);
du[i] = i * u[i - 1]; duu[i] = -i * uu[i - 1];
dv[i] = i * v[i - 1]; dvv[i] = -i * vv[i - 1];
}
/* Now evaluate position and tangents based on control points. */
Make_Vector(P, 0, 0, 0);
Make_Vector(U1, 0, 0, 0);
Make_Vector(V1, 0, 0, 0);
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
c = C[i] * C[j];
ut = u[i] * uu[3 - i];
vt = v[j] * vv[3 - j];
t = c * ut * vt;
VAddScaledEq(P, t, (*cp)[i][j]);
t = c * vt * (du[i] * uu[3 - i] + u[i] * duu[3 - i]);
VAddScaledEq(U1, t, (*cp)[i][j]);
t = c * ut * (dv[j] * vv[3 - j] + v[j] * dvv[3 - j]);
VAddScaledEq(V1, t, (*cp)[i][j]);
}
}
/* Make the normal from the cross product of the tangents. */
VCross(N, U1, V1);
VDot(t, N, N);
squared_u1 = VSumSqr(U1);
squared_v1 = VSumSqr(V1);
if (t > (BEZIER_EPSILON * squared_u1 * squared_v1))
{
t = 1.0 / sqrt(t);
VScaleEq(N, t);
}
else
{
Make_Vector(N, 1, 0, 0);
}
}
/*****************************************************************************
*
* FUNCTION
*
* subpatch_normal
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* Calculate the normal to a subpatch (triangle) return the vector
* <1.0 0.0 0.0> if the triangle is degenerate.
*
* CHANGES
*
* -
*
******************************************************************************/
bool BicubicPatch::subpatch_normal(const VECTOR v1, const VECTOR v2, const VECTOR v3, VECTOR Result, DBL *d)
{
VECTOR V1, V2;
DBL squared_v1, squared_v2;
DBL Length;
VSub(V1, v1, v2);
VSub(V2, v3, v2);
VCross(Result, V1, V2);
Length = VSumSqr(Result);
squared_v1 = VSumSqr(V1);
squared_v2 = VSumSqr(V2);
if (Length <= (BEZIER_EPSILON * squared_v1 * squared_v2))
{
Make_Vector(Result, 1.0, 0.0, 0.0);
*d = -1.0 * v1[X];
return false;
}
else
{
Length = sqrt(Length);
VInverseScale(Result, Result, Length);
VDot(*d, Result, v1);
*d = 0.0 - *d;
return true;
}
}
/*****************************************************************************
*
* FUNCTION
*
* intersect_subpatch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
bool BicubicPatch::intersect_subpatch(const Ray &ray, const VECTOR V1[3], const DBL uu[3], const DBL vv[3], DBL *Depth, VECTOR P, VECTOR N, DBL *u, DBL *v) const
{
DBL squared_b0, squared_b1;
DBL d, n, a, b, r;
VECTOR Q, T1;
VECTOR B[3], IB[3], NN[3];
VSub(B[0], V1[1], V1[0]);
VSub(B[1], V1[2], V1[0]);
VCross(B[2], B[0], B[1]);
VDot(d, B[2], B[2]);
squared_b0 = VSumSqr(B[0]);
squared_b1 = VSumSqr(B[1]);
if (d <= (BEZIER_EPSILON * squared_b1 * squared_b0))
{
return false;
}
d = 1.0 / sqrt(d);
VScaleEq(B[2], d);
/* Degenerate triangle. */
if (!MInvers3(B, IB))
{
return false;
}
VDot(d, ray.Direction, IB[2]);
if (fabs(d) < BEZIER_EPSILON)
{
return false;
}
VSub(Q, V1[0], ray.Origin);
VDot(n, Q, IB[2]);
*Depth = n / d;
if (*Depth < BEZIER_TOLERANCE)
{
return false;
}
VScale(T1, ray.Direction, *Depth);
VAdd(P, ray.Origin, T1);
VSub(Q, P, V1[0]);
VDot(a, Q, IB[0]);
VDot(b, Q, IB[1]);
if ((a < 0.0) || (b < 0.0) || (a + b > 1.0))
{
return false;
}
r = 1.0 - a - b;
Make_Vector(N, 0.0, 0.0, 0.0);
bezier_value((VECTOR(*)[4][4])&Control_Points, uu[0], vv[0], T1, NN[0]);
bezier_value((VECTOR(*)[4][4])&Control_Points, uu[1], vv[1], T1, NN[1]);
bezier_value((VECTOR(*)[4][4])&Control_Points, uu[2], vv[2], T1, NN[2]);
VScale(T1, NN[0], r); VAddEq(N, T1);
VScale(T1, NN[1], a); VAddEq(N, T1);
VScale(T1, NN[2], b); VAddEq(N, T1);
*u = r * uu[0] + a * uu[1] + b * uu[2];
*v = r * vv[0] + a * vv[1] + b * vv[2];
VDot(d, N, N);
if (d > BEZIER_EPSILON)
{
d = 1.0 / sqrt(d);
VScaleEq(N, d);
}
else
{
Make_Vector(N, 1, 0, 0);
}
return true;
}
/*****************************************************************************
*
* FUNCTION
*
* find_average
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* Find a sphere that contains all of the points in the list "vectors".
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::find_average(int vector_count, const VECTOR *vectors, VECTOR center, DBL *radius)
{
int i;
DBL r0, r1, xc = 0, yc = 0, zc = 0;
DBL x0, y0, z0;
for (i = 0; i < vector_count; i++)
{
xc += vectors[i][X];
yc += vectors[i][Y];
zc += vectors[i][Z];
}
xc /= (DBL)vector_count;
yc /= (DBL)vector_count;
zc /= (DBL)vector_count;
r0 = 0.0;
for (i = 0; i < vector_count; i++)
{
x0 = vectors[i][X] - xc;
y0 = vectors[i][Y] - yc;
z0 = vectors[i][Z] - zc;
r1 = x0 * x0 + y0 * y0 + z0 * z0;
if (r1 > r0)
{
r0 = r1;
}
}
Make_Vector(center, xc, yc, zc);
*radius = r0;
}
/*****************************************************************************
*
* FUNCTION
*
* spherical_bounds_check
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
bool BicubicPatch::spherical_bounds_check(const Ray &ray, const VECTOR center, DBL radius)
{
DBL x, y, z, dist1, dist2;
x = center[X] - ray.Origin[X];
y = center[Y] - ray.Origin[Y];
z = center[Z] - ray.Origin[Z];
dist1 = x * x + y * y + z * z;
if (dist1 < radius)
{
/* ray starts inside sphere - assume it intersects. */
return true;
}
else
{
dist2 = x*ray.Direction[X] + y*ray.Direction[Y] + z*ray.Direction[Z];
dist2 *= dist2;
if ((dist2 > 0) && ((dist1 - dist2) <= (radius + BEZIER_EPSILON) ))
{
return true;
}
}
return false;
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_bounding_sphere
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* Find a sphere that bounds all of the control points of a Bezier patch.
* The values returned are: the center of the bounding sphere, and the
* square of the radius of the bounding sphere.
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::bezier_bounding_sphere(const VECTOR (*Patch)[4][4], VECTOR center, DBL *radius)
{
int i, j;
DBL r0, r1, xc = 0, yc = 0, zc = 0;
DBL x0, y0, z0;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
xc += (*Patch)[i][j][X];
yc += (*Patch)[i][j][Y];
zc += (*Patch)[i][j][Z];
}
}
xc /= 16.0;
yc /= 16.0;
zc /= 16.0;
r0 = 0.0;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
x0 = (*Patch)[i][j][X] - xc;
y0 = (*Patch)[i][j][Y] - yc;
z0 = (*Patch)[i][j][Z] - zc;
r1 = x0 * x0 + y0 * y0 + z0 * z0;
if (r1 > r0)
{
r0 = r1;
}
}
}
Make_Vector(center, xc, yc, zc);
*radius = r0;
}
/*****************************************************************************
*
* FUNCTION
*
* Precompute_Patch_Values
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* Precompute grid points and normals for a bezier patch.
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Precompute_Patch_Values()
{
int i, j;
VECTOR cp[16];
VECTOR(*Patch_Ptr)[4][4] = (VECTOR(*)[4][4]) Control_Points;
int max_depth_reached = 0;
/* Calculate the bounding sphere for the entire patch. */
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
Assign_Vector(cp[4*i + j], Control_Points[i][j]);
}
}
find_average(16, cp, Bounding_Sphere_Center, &Bounding_Sphere_Radius);
if (Patch_Type == 1)
{
if (Node_Tree != NULL)
{
bezier_tree_deleter(Node_Tree);
}
Node_Tree = bezier_tree_builder(Patch_Ptr, 0.0, 1.0, 0.0, 1.0, 0, max_depth_reached);
}
}
/*****************************************************************************
*
* FUNCTION
*
* point_plane_distance
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* Determine the distance from a point to a plane.
*
* CHANGES
*
* -
*
******************************************************************************/
DBL BicubicPatch::point_plane_distance(const VECTOR p, const VECTOR n, DBL d)
{
DBL temp1, temp2;
VDot(temp1, p, n);
temp1 += d;
VLength(temp2, n);
if (fabs(temp2) < EPSILON)
{
return (0.0);
}
temp1 /= temp2;
return (temp1);
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_subpatch_intersect
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
int BicubicPatch::bezier_subpatch_intersect(const Ray &ray, const VECTOR (*Patch)[4][4], DBL u0, DBL u1, DBL v0, DBL v1, IStack& Depth_Stack, TraceThreadData *Thread)
{
int cnt = 0;
VECTOR V1[3];
DBL u, v, Depth;
DBL uu[3], vv[3];
VECTOR P, N;
UV_VECT UV;
DBL uv_point[2], tpoint[2];
Assign_Vector(V1[0], (*Patch)[0][0]);
Assign_Vector(V1[1], (*Patch)[0][3]);
Assign_Vector(V1[2], (*Patch)[3][3]);
uu[0] = u0; uu[1] = u0; uu[2] = u1;
vv[0] = v0; vv[1] = v1; vv[2] = v1;
if (intersect_subpatch(ray, V1, uu, vv, &Depth, P, N, &u, &v))
{
/* transform current point from uv space to texture space */
uv_point[0] = v;
uv_point[1] = u;
Compute_Texture_UV(uv_point, ST, tpoint);
UV[U] = tpoint[0];
UV[V] = tpoint[1];
Depth_Stack->push(Intersection(Depth, P, N, UV, this));
cnt++;
}
Assign_Vector(V1[1], V1[2]);
Assign_Vector(V1[2], (*Patch)[3][0]);
uu[1] = uu[2]; uu[2] = u1;
vv[1] = vv[2]; vv[2] = v0;
if (intersect_subpatch(ray, V1, uu, vv, &Depth, P, N, &u, &v))
{
/* transform current point from uv space to texture space */
uv_point[0] = v;
uv_point[1] = u;
Compute_Texture_UV(uv_point, ST, tpoint);
UV[U] = tpoint[0];
UV[V] = tpoint[1];
Depth_Stack->push(Intersection(Depth, P, N, UV, this));
cnt++;
}
return (cnt);
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_split_left_right
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::bezier_split_left_right(const VECTOR (*Patch)[4][4], VECTOR (*Left_Patch)[4][4], VECTOR (*Right_Patch)[4][4])
{
int i, j;
VECTOR Half;
VECTOR Temp1[4], Temp2[4];
for (i = 0; i < 4; i++)
{
Assign_Vector(Temp1[0], (*Patch)[0][i]);
VHalf(Temp1[1], (*Patch)[0][i], (*Patch)[1][i]);
VHalf(Half, (*Patch)[1][i], (*Patch)[2][i]);
VHalf(Temp1[2], Temp1[1], Half);
VHalf(Temp2[2], (*Patch)[2][i], (*Patch)[3][i]);
VHalf(Temp2[1], Half, Temp2[2]);
VHalf(Temp1[3], Temp1[2], Temp2[1]);
Assign_Vector(Temp2[0], Temp1[3]);
Assign_Vector(Temp2[3], (*Patch)[3][i]);
for (j = 0; j < 4; j++)
{
Assign_Vector((*Left_Patch)[j][i], Temp1[j]);
Assign_Vector((*Right_Patch)[j][i], Temp2[j]);
}
}
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_split_up_down
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::bezier_split_up_down(const VECTOR (*Patch)[4][4], VECTOR (*Bottom_Patch)[4][4], VECTOR (*Top_Patch)[4][4])
{
int i, j;
VECTOR Temp1[4], Temp2[4];
VECTOR Half;
for (i = 0; i < 4; i++)
{
Assign_Vector(Temp1[0], (*Patch)[i][0]);
VHalf(Temp1[1], (*Patch)[i][0], (*Patch)[i][1]);
VHalf(Half, (*Patch)[i][1], (*Patch)[i][2]);
VHalf(Temp1[2], Temp1[1], Half);
VHalf(Temp2[2], (*Patch)[i][2], (*Patch)[i][3]);
VHalf(Temp2[1], Half, Temp2[2]);
VHalf(Temp1[3], Temp1[2], Temp2[1]);
Assign_Vector(Temp2[0], Temp1[3]);
Assign_Vector(Temp2[3], (*Patch)[i][3]);
for (j = 0; j < 4; j++)
{
Assign_Vector((*Bottom_Patch)[i][j], Temp1[j]);
Assign_Vector((*Top_Patch)[i][j] , Temp2[j]);
}
}
}
/*****************************************************************************
*
* FUNCTION
*
* determine_subpatch_flatness
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* See how close to a plane a subpatch is, the patch must have at least
* three distinct vertices. A negative result from this function indicates
* that a degenerate value of some sort was encountered.
*
* CHANGES
*
* -
*
******************************************************************************/
DBL BicubicPatch::determine_subpatch_flatness(const VECTOR (*Patch)[4][4])
{
int i, j;
DBL d, dist, temp1;
VECTOR n, TempV;
VECTOR vertices[4];
Assign_Vector(vertices[0], (*Patch)[0][0]);
Assign_Vector(vertices[1], (*Patch)[0][3]);
VSub(TempV, vertices[0], vertices[1]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
/*
* Degenerate in the V direction for U = 0. This is ok if the other
* two corners are distinct from the lower left corner - I'm sure there
* are cases where the corners coincide and the middle has good values,
* but that is somewhat pathalogical and won't be considered.
*/
Assign_Vector(vertices[1], (*Patch)[3][3]);
VSub(TempV, vertices[0], vertices[1]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
return (-1.0);
}
Assign_Vector(vertices[2], (*Patch)[3][0]);
VSub(TempV, vertices[0], vertices[1]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
return (-1.0);
}
VSub(TempV, vertices[1], vertices[2]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
return (-1.0);
}
}
else
{
Assign_Vector(vertices[2], (*Patch)[3][0]);
VSub(TempV, vertices[0], vertices[1]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
Assign_Vector(vertices[2], (*Patch)[3][3]);
VSub(TempV, vertices[0], vertices[2]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
return (-1.0);
}
VSub(TempV, vertices[1], vertices[2]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
return (-1.0);
}
}
else
{
VSub(TempV, vertices[1], vertices[2]);
VLength(temp1, TempV);
if (fabs(temp1) < EPSILON)
{
return (-1.0);
}
}
}
/*
* Now that a good set of candidate points has been found,
* find the plane equations for the patch.
*/
if (subpatch_normal(vertices[0], vertices[1], vertices[2], n, &d))
{
/*
* Step through all vertices and see what the maximum
* distance from the plane happens to be.
*/
dist = 0.0;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
temp1 = fabs(point_plane_distance(((*Patch)[i][j]), n, d));
if (temp1 > dist)
{
dist = temp1;
}
}
}
return (dist);
}
else
{
/*
Debug_Info("Subpatch normal failed in determine_subpatch_flatness\n");
*/
return (-1.0);
}
}
/*****************************************************************************
*
* FUNCTION
*
* flat_enough
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
bool BicubicPatch::flat_enough(const VECTOR (*Patch)[4][4]) const
{
DBL Dist;
Dist = determine_subpatch_flatness(Patch);
if (Dist < 0.0)
{
return false;
}
else
{
if (Dist < Flatness_Value)
{
return true;
}
else
{
return false;
}
}
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_subdivider
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
int BicubicPatch::bezier_subdivider(const Ray &ray, const VECTOR (*Patch)[4][4], DBL u0, DBL u1, DBL v0, DBL v1, int recursion_depth, IStack& Depth_Stack, TraceThreadData *Thread)
{
int cnt = 0;
DBL ut, vt, radius;
VECTOR Lower_Left[4][4], Lower_Right[4][4];
VECTOR Upper_Left[4][4], Upper_Right[4][4];
VECTOR center;
/*
* Make sure the ray passes through a sphere bounding
* the control points of the patch.
*/
bezier_bounding_sphere(Patch, center, &radius);
if (!spherical_bounds_check(ray, center, radius))
{
return (0);
}
/*
* If the patch is close to being flat, then just
* perform a ray-plane intersection test.
*/
if (flat_enough(Patch))
return bezier_subpatch_intersect(ray, Patch, u0, u1, v0, v1, Depth_Stack, Thread);
if (recursion_depth >= U_Steps)
{
if (recursion_depth >= V_Steps)
{
return bezier_subpatch_intersect(ray, Patch, u0, u1, v0, v1, Depth_Stack, Thread);
}
else
{
bezier_split_up_down(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left);
vt = (v1 + v0) / 2.0;
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Left, u0, u1, v0, vt, recursion_depth + 1, Depth_Stack, Thread);
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Upper_Left, u0, u1, vt, v1, recursion_depth + 1, Depth_Stack, Thread);
}
}
else
{
if (recursion_depth >= V_Steps)
{
bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right);
ut = (u1 + u0) / 2.0;
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Left, u0, ut, v0, v1, recursion_depth + 1, Depth_Stack, Thread);
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Right, ut, u1, v0, v1, recursion_depth + 1, Depth_Stack, Thread);
}
else
{
ut = (u1 + u0) / 2.0;
vt = (v1 + v0) / 2.0;
bezier_split_left_right(Patch, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Right);
bezier_split_up_down((VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Lower_Left, (VECTOR(*)[4][4])Upper_Left) ;
bezier_split_up_down((VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Lower_Right, (VECTOR(*)[4][4])Upper_Right);
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Left, u0, ut, v0, vt, recursion_depth + 1, Depth_Stack, Thread);
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Upper_Left, u0, ut, vt, v1, recursion_depth + 1, Depth_Stack, Thread);
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Lower_Right, ut, u1, v0, vt, recursion_depth + 1, Depth_Stack, Thread);
cnt += bezier_subdivider(ray, (VECTOR(*)[4][4])Upper_Right, ut, u1, vt, v1, recursion_depth + 1, Depth_Stack, Thread);
}
}
return (cnt);
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_tree_deleter
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::bezier_tree_deleter(BEZIER_NODE *Node)
{
int i;
BEZIER_CHILDREN *Children;
/* If this is an interior node then continue the descent. */
if (Node->Node_Type == BEZIER_INTERIOR_NODE)
{
Children = (BEZIER_CHILDREN *)Node->Data_Ptr;
for (i = 0; i < Node->Count; i++)
{
bezier_tree_deleter(Children->Children[i]);
}
POV_FREE(Children);
}
else
{
if (Node->Node_Type == BEZIER_LEAF_NODE)
{
/* Free the memory used for the vertices. */
POV_FREE(Node->Data_Ptr);
}
}
/* Free the memory used for the node. */
POV_FREE(Node);
}
/*****************************************************************************
*
* FUNCTION
*
* bezier_tree_walker
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
int BicubicPatch::bezier_tree_walker(const Ray &ray, const BEZIER_NODE *Node, IStack& Depth_Stack, TraceThreadData *Thread)
{
int i, cnt = 0;
DBL Depth, u, v;
DBL uu[3], vv[3];
VECTOR N, P;
VECTOR V1[3];
UV_VECT UV;
DBL uv_point[2], tpoint[2];
const BEZIER_CHILDREN *Children;
const BEZIER_VERTICES *Vertices;
/*
* Make sure the ray passes through a sphere bounding
* the control points of the patch.
*/
if (!spherical_bounds_check(ray, Node->Center, Node->Radius_Squared))
{
return (0);
}
/*
* If this is an interior node then continue the descent,
* else do a check against the vertices.
*/
if (Node->Node_Type == BEZIER_INTERIOR_NODE)
{
Children = (const BEZIER_CHILDREN *)Node->Data_Ptr;
for (i = 0; i < Node->Count; i++)
{
cnt += bezier_tree_walker(ray, Children->Children[i], Depth_Stack, Thread);
}
}
else if (Node->Node_Type == BEZIER_LEAF_NODE)
{
Vertices = (const BEZIER_VERTICES *)Node->Data_Ptr;
Assign_Vector(V1[0], Vertices->Vertices[0]);
Assign_Vector(V1[1], Vertices->Vertices[1]);
Assign_Vector(V1[2], Vertices->Vertices[2]);
uu[0] = Vertices->uvbnds[0];
uu[1] = Vertices->uvbnds[0];
uu[2] = Vertices->uvbnds[1];
vv[0] = Vertices->uvbnds[2];
vv[1] = Vertices->uvbnds[3];
vv[2] = Vertices->uvbnds[3];
/*
* Triangulate this subpatch, then check for
* intersections in the triangles.
*/
if (intersect_subpatch( ray, V1, uu, vv, &Depth, P, N, &u, &v))
{
/* transform current point from uv space to texture space */
uv_point[0] = v;
uv_point[1] = u;
Compute_Texture_UV(uv_point, ST, tpoint);
UV[U] = tpoint[0];
UV[V] = tpoint[1];
Depth_Stack->push(Intersection(Depth, P, N, UV, this));
cnt++;
}
Assign_Vector(V1[1], V1[2]);
Assign_Vector(V1[2], Vertices->Vertices[3]);
uu[1] = uu[2]; uu[2] = Vertices->uvbnds[1];
vv[1] = vv[2]; vv[2] = Vertices->uvbnds[2];
if (intersect_subpatch(ray, V1, uu, vv, &Depth, P, N, &u, &v))
{
/* transform current point from object space to texture space */
uv_point[0] = v;
uv_point[1] = u;
Compute_Texture_UV(uv_point, ST, tpoint);
UV[U] = tpoint[0];
UV[V] = tpoint[1];
Depth_Stack->push(Intersection(Depth, P, N, UV, this));
cnt++;
}
}
else
{
throw POV_EXCEPTION_STRING("Bad Node type in bezier_tree_walker().");
}
return (cnt);
}
/*****************************************************************************
*
* FUNCTION
*
* intersect_bicubic_patch0
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
int BicubicPatch::intersect_bicubic_patch0(const Ray &ray, IStack& Depth_Stack, TraceThreadData *Thread)
{
const VECTOR(*Patch)[4][4] = &Control_Points;
return (bezier_subdivider(ray, Patch, 0.0, 1.0, 0.0, 1.0, 0, Depth_Stack, Thread));
}
/*****************************************************************************
*
* FUNCTION
*
* All_Bicubic_Patch_Intersections
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
bool BicubicPatch::All_Intersections(const Ray& ray, IStack& Depth_Stack, TraceThreadData *Thread)
{
int Found, cnt = 0;
Found = false;
Thread->Stats()[Ray_Bicubic_Tests]++;
switch (Patch_Type)
{
case 0:
cnt = intersect_bicubic_patch0(ray, Depth_Stack, Thread);
break;
case 1:
cnt = bezier_tree_walker(ray, Node_Tree, Depth_Stack, Thread);
break;
default:
throw POV_EXCEPTION_STRING("Bad patch type in All_Bicubic_Patch_Intersections.");
}
if (cnt > 0)
{
Thread->Stats()[Ray_Bicubic_Tests_Succeeded]++;
Found = true;
}
return (Found);
}
/*****************************************************************************
*
* FUNCTION
*
* Inside_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* A patch is not a solid, so an inside test doesn't make sense.
*
* CHANGES
*
* -
*
******************************************************************************/
bool BicubicPatch::Inside(const VECTOR, TraceThreadData *) const
{
return false;
}
/*****************************************************************************
*
* FUNCTION
*
* Bicubic_Patch_Normal
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Normal(VECTOR Result, Intersection *Inter, TraceThreadData *Thread) const
{
/* Use preocmputed normal. */
Assign_Vector(Result, Inter->INormal);
}
/*****************************************************************************
*
* FUNCTION
*
* Translate_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Translate(const VECTOR Vector, const TRANSFORM *)
{
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
VAdd(Control_Points[i][j], Control_Points[i][j], Vector);
}
}
Precompute_Patch_Values();
Compute_BBox();
}
/*****************************************************************************
*
* FUNCTION
*
* Rotate_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Rotate(const VECTOR, const TRANSFORM *tr)
{
Transform(tr);
}
/*****************************************************************************
*
* FUNCTION
*
* Scale_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Scale(const VECTOR Vector, const TRANSFORM *)
{
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
VEvaluate(Control_Points[i][j], Control_Points[i][j], Vector);
}
}
Precompute_Patch_Values();
Compute_BBox();
}
/*****************************************************************************
*
* FUNCTION
*
* Transform_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Transform(const TRANSFORM *tr)
{
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
MTransPoint(Control_Points[i][j], Control_Points[i][j], tr);
}
}
Precompute_Patch_Values();
Compute_BBox();
}
/*****************************************************************************
*
* FUNCTION
*
* Invert_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* Inversion of a patch really doesn't make sense.
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Invert()
{
}
/*****************************************************************************
*
* FUNCTION
*
* Create_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
BicubicPatch::BicubicPatch() : ObjectBase(BICUBIC_PATCH_OBJECT)
{
Patch_Type = - 1;
U_Steps = 0;
V_Steps = 0;
Flatness_Value = 0.0;
accuracy = 0.01;
Node_Tree = NULL;
Weights = NULL;
/*
* NOTE: Control_Points[4][4] is initialized in Parse_Bicubic_Patch.
* Bounding_Sphere_Center,Bounding_Sphere_Radius, Normal_Vector[], and
* IPoint[] are initialized in Precompute_Patch_Values.
*/
/* set the default uv-mapping coordinates */
ST[0][U] = 0;
ST[0][V] = 0;
ST[1][U] = 1;
ST[1][V] = 0;
ST[2][U] = 1;
ST[2][V] = 1;
ST[3][U] = 0;
ST[3][V] = 1;
}
/*****************************************************************************
*
* FUNCTION
*
* Copy_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
ObjectPtr BicubicPatch::Copy()
{
int i, j;
BicubicPatch *New = new BicubicPatch();
int m, h;
/* Do not do *New = *Old so that Precompute works right */
New->Patch_Type = Patch_Type;
New->U_Steps = U_Steps;
New->V_Steps = V_Steps;
if ( Weights != NULL )
{
New->Weights = (WEIGHTS *)POV_MALLOC( sizeof(WEIGHTS),"bicubic patch" );
POV_MEMCPY( New->Weights, Weights, sizeof(WEIGHTS) );
}
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
Assign_Vector(New->Control_Points[i][j], Control_Points[i][j]);
}
}
New->Flatness_Value = Flatness_Value;
New->Precompute_Patch_Values();
/* copy the mapping */
for (m = 0; m < 4; m++)
{
for (h = 0; h < 3; h++)
{
New->ST[m][h] = ST[m][h];
}
}
return (New);
}
/*****************************************************************************
*
* FUNCTION
*
* Destroy_Bicubic_Patch
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Enzmann
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
BicubicPatch::~BicubicPatch()
{
if (Patch_Type == 1)
{
if (Node_Tree != NULL)
{
bezier_tree_deleter(Node_Tree);
}
}
if ( Weights != NULL ) POV_FREE(Weights);
}
/*****************************************************************************
*
* FUNCTION
*
* Compute_Bicubic_Patch_BBox
*
* INPUT
*
* Bicubic_Patch - Bicubic patch
*
* OUTPUT
*
* Bicubic_Patch
*
* RETURNS
*
* AUTHOR
*
* Dieter Bayer
*
* DESCRIPTION
*
* Calculate the bounding box of a bicubic patch.
*
* CHANGES
*
* Aug 1994 : Creation.
*
******************************************************************************/
void BicubicPatch::Compute_BBox()
{
int i, j;
VECTOR Min, Max;
Make_Vector(Min, BOUND_HUGE, BOUND_HUGE, BOUND_HUGE);
Make_Vector(Max, -BOUND_HUGE, -BOUND_HUGE, -BOUND_HUGE);
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
Min[X] = min(Min[X], Control_Points[i][j][X]);
Min[Y] = min(Min[Y], Control_Points[i][j][Y]);
Min[Z] = min(Min[Z], Control_Points[i][j][Z]);
Max[X] = max(Max[X], Control_Points[i][j][X]);
Max[Y] = max(Max[Y], Control_Points[i][j][Y]);
Max[Z] = max(Max[Z], Control_Points[i][j][Z]);
}
}
Make_BBox_from_min_max(BBox, Min, Max);
}
/*****************************************************************************
*
* FUNCTION
*
* Bicubic_Patch_UVCoord
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Nathan Kopp
*
* DESCRIPTION
*
* -
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::UVCoord(UV_VECT Result, const Intersection *Inter, TraceThreadData *Thread) const
{
/* Use preocmputed uv coordinates. */
Assign_UV_Vect(Result, Inter->Iuv);
}
/*****************************************************************************
*
* FUNCTION
*
* Compute_UV_Point
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Mike Hough
*
* DESCRIPTION
*
* Transform p from uv space to texture space (point t) using the
* shape's ST mapping
*
* CHANGES
*
* -
*
******************************************************************************/
void BicubicPatch::Compute_Texture_UV(const UV_VECT p, const UV_VECT st[4], UV_VECT t)
{
UV_VECT u1, u2;
u1[0] = st[0][0] + p[0] * (st[1][0] - st[0][0]);
u1[1] = st[0][1] + p[0] * (st[1][1] - st[0][1]);
u2[0] = st[3][0] + p[0] * (st[2][0] - st[3][0]);
u2[1] = st[3][1] + p[0] * (st[2][1] - st[3][1]);
t[0] = u1[0] + p[1] * (u2[0] - u1[0]);
t[1] = u1[1] + p[1] * (u2[1] - u1[1]);
}
}
| 19.088898 | 182 | 0.533246 | acekiller |
d308603b4cafc4b003b92fad971055b67b738aff | 5,336 | cpp | C++ | samples/stm32l011xx/command_line/main.cpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | samples/stm32l011xx/command_line/main.cpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | samples/stm32l011xx/command_line/main.cpp | JayKickliter/CML | d21061a3abc013a8386798280b9595e9d4a2978c | [
"MIT"
] | null | null | null | /*
Name: main.cpp
Copyright(c) 2019 Mateusz Semegen
This code is licensed under MIT license (see LICENSE file for details)
*/
//cml
#include <cml/collection/Vector.hpp>
#include <cml/common/cstring.hpp>
#include <cml/hal/counter.hpp>
#include <cml/hal/systick.hpp>
#include <cml/hal/peripherals/GPIO.hpp>
#include <cml/hal/peripherals/USART.hpp>
#include <cml/hal/mcu.hpp>
#include <cml/utils/Command_line.hpp>
namespace
{
using namespace cml;
using namespace cml::collection;
using namespace cml::common;
using namespace cml::hal;
using namespace cml::hal::peripherals;
using namespace cml::utils;
void led_cli_callback(const Vector<Command_line::Callback::Parameter>& a_params, void* a_p_user_data)
{
pin::Out* p_led_pin = reinterpret_cast<pin::Out*>(a_p_user_data);
if (2 == a_params.get_length())
{
bool is_on = cstring::equals(a_params[1].a_p_value, "on", a_params[1].length);
if (true == is_on)
{
p_led_pin->set_level(pin::Level::high);
}
else
{
bool is_off = cstring::equals(a_params[1].a_p_value, "off", a_params[1].length);
if (true == is_off)
{
p_led_pin->set_level(pin::Level::low);
}
}
}
}
void reset_callback(const Vector<Command_line::Callback::Parameter>& a_params, void* a_p_user_data)
{
mcu::reset();
}
uint32_t write_character(char a_character, void* a_p_user_data)
{
USART* p_console_usart = reinterpret_cast<USART*>(a_p_user_data);
return p_console_usart->transmit_bytes_polling(&a_character, 1).data_length_in_words;
}
uint32_t write_string(const char* a_p_string, uint32_t a_length, void* a_p_user_data)
{
USART* p_console_usart = reinterpret_cast<USART*>(a_p_user_data);
return p_console_usart->transmit_bytes_polling(a_p_string, a_length).data_length_in_words;
}
uint32_t read_key(char* a_p_out, uint32_t a_length, void* a_p_user_data)
{
USART* p_console_usart = reinterpret_cast<USART*>(a_p_user_data);
return p_console_usart->receive_bytes_polling(a_p_out, a_length).data_length_in_words;
}
} // namespace ::
int main()
{
using namespace cml::common;
using namespace cml::hal;
using namespace cml::utils;
mcu::enable_hsi_clock(mcu::Hsi_frequency::_16_MHz);
mcu::set_sysclk(mcu::Sysclk_source::hsi, { mcu::Bus_prescalers::AHB::_1,
mcu::Bus_prescalers::APB1::_1,
mcu::Bus_prescalers::APB2::_1 });
if (mcu::Sysclk_source::hsi == mcu::get_sysclk_source())
{
USART::Config usart_config =
{
115200u,
USART::Oversampling::_16,
USART::Stop_bits::_1,
USART::Flow_control_flag::none,
USART::Sampling_method::three_sample_bit,
USART::Mode_flag::rx | USART::Mode_flag::tx
};
USART::Frame_format usart_frame_format
{
USART::Word_length::_8_bit,
USART::Parity::none
};
USART::Clock usart_clock
{
USART::Clock::Source::sysclk,
mcu::get_sysclk_frequency_hz(),
};
pin::af::Config usart_pin_config =
{
pin::Mode::push_pull,
pin::Pull::up,
pin::Speed::low,
0x4u
};
mcu::disable_msi_clock();
systick::enable((mcu::get_sysclk_frequency_hz() / kHz(1)) - 1, 0x9u);
systick::register_tick_callback({ counter::update, nullptr });
GPIO gpio_port_a(GPIO::Id::a);
gpio_port_a.enable();
pin::af::enable(&gpio_port_a, 2u, usart_pin_config);
pin::af::enable(&gpio_port_a, 15u, usart_pin_config);
USART console_usart(USART::Id::_2);
bool usart_ready = console_usart.enable(usart_config, usart_frame_format, usart_clock, 0x1u, 10);
if (true == usart_ready)
{
GPIO gpio_port_b(GPIO::Id::b);
gpio_port_b.enable();
pin::Out led_pin;
pin::out::enable(&gpio_port_b, 3u, { pin::Mode::push_pull, pin::Pull::down, pin::Speed::low }, &led_pin);
char preamble[36];
cstring::format(preamble,
sizeof(preamble),
"\nCML CLI sample. CPU speed: %d MHz\n",
mcu::get_sysclk_frequency_hz() / MHz(1));
console_usart.transmit_bytes_polling(preamble, sizeof(preamble));
Command_line command_line({ write_character, &console_usart },
{ write_string, &console_usart },
{ read_key, &console_usart },
"cmd > ",
"Command not found");
command_line.register_callback({ "led", led_cli_callback, &led_pin });
command_line.register_callback({ "reset", reset_callback, nullptr });
command_line.write_prompt();
while (true)
{
command_line.update();
}
}
}
while (true);
} | 31.761905 | 118 | 0.572714 | JayKickliter |
d309a3a3096fdebad8cf4baf0f5fd64a39720fe9 | 673 | cpp | C++ | Leetcode/remve_duplicates_sorted.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | Leetcode/remve_duplicates_sorted.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | Leetcode/remve_duplicates_sorted.cpp | prameetu/CP_codes | 41f8cfc188d2e08a8091bc5134247d05ba8a78f5 | [
"MIT"
] | null | null | null | //leetcode - 26
#include<bits/stdc++.h>
using namespace std;
int remove_duplicate_sorteed_array(vector <int> &v)
{
if(v.size() == 0)
return 0;
int i(0);
int j(1);
while(j<v.size())
{
if(v[i] == v[j])
{
j++;
}
else
{
i++;
v[i] = v[j];
j++;
}
}
return i+1;
}
int main()
{
vector <int> v;
int n,x;
cin >> n;
while(n--)
{
cin >> x;
v.push_back(x);
}
for(int i=0;i<remove_duplicate_sorteed_array(v);i++)
{
cout << v[i] << " ";
}
} | 14.020833 | 57 | 0.358098 | prameetu |
d30e9b47aca32b97d8a7182db8fdd762709681aa | 2,451 | cpp | C++ | BinaryIO/BinaryReader.cpp | ghaffaribehdad/Preprocessor | 85165a1259f8dcb1edd92a8113343875dd6085ea | [
"MIT"
] | null | null | null | BinaryIO/BinaryReader.cpp | ghaffaribehdad/Preprocessor | 85165a1259f8dcb1edd92a8113343875dd6085ea | [
"MIT"
] | null | null | null | BinaryIO/BinaryReader.cpp | ghaffaribehdad/Preprocessor | 85165a1259f8dcb1edd92a8113343875dd6085ea | [
"MIT"
] | null | null | null |
#include "BinaryReader.h"
#include <fstream>
#include <filesystem>
// define fs namespace for convenience
namespace fs = std::experimental::filesystem;
// keep track fo instantiation
unsigned int BinaryReader::s_instances = 0;
// constructor
BinaryReader::BinaryReader(const char* _fileName)
{
//increment number of instances
s_instances += 1;
this->m_fileName = _fileName;
// extract the current path
fs::path path_currentPath = fs::current_path();
this->m_filePath = path_currentPath.u8string();
// add a backslash at the end of path
this->m_filePath += "\\";
}
// constructor
BinaryReader::BinaryReader(const char* _fileName, const char* _filePath)
: m_fileName(_fileName), m_filePath(_filePath)
{}
// getter functions
const char* BinaryReader::getfileName() const
{
return m_fileName.c_str();
}
const char* BinaryReader::getfilePath() const
{
return m_filePath.c_str();
}
// setter
void BinaryReader::setfileName(const char* _fileName)
{
m_fileName = std::string(_fileName);
}
void BinaryReader::setfilePath(const char* _filePath)
{
m_filePath = std::string(_filePath);
}
bool BinaryReader::read()
{
// define the istream
std::ifstream myFile;
std::string fullPath= m_filePath + m_fileName;
myFile = std::ifstream(fullPath, std::ios::binary);
// check whether the file is open
if (!myFile.is_open())
return false;
// get the starting position
std::streampos start = myFile.tellg();
// go to the end
myFile.seekg(0, std::ios::end);
// get the ending position
std::streampos end = myFile.tellg();
// return to starting position
myFile.seekg(0, std::ios::beg);
// size of the buffer
const int buffer_size = static_cast<int>(end - start);
// resize it to fit the dataset(MUST BE EDITED WHILE IT IS ABOVE THE RAM SIZE)
this->m_vec_buffer.resize(buffer_size);
//read file and store it into buffer
myFile.read(&(m_vec_buffer.at(0)), buffer_size);
// close the file
myFile.close();
return true;
}
std::vector<char>* BinaryReader::flush_buffer()
{
return & m_vec_buffer;
}
void BinaryReader::clean_buffer()
{
this->m_vec_buffer.clear();
}
BinaryReader::BinaryReader()
{
this->m_fileName = "";
this->m_filePath = "";
this->m_vec_buffer = {};
}
void BinaryReader::setVecBuffer(const std::vector<char> * _vec_buffer)
{
this->m_vec_buffer = *_vec_buffer;
} | 20.771186 | 80 | 0.681355 | ghaffaribehdad |
d310a52a4d42d17e75db3bcf05f0fadc483e91be | 1,076 | cpp | C++ | JTS/CF-B/CF714-D2-B/main.cpp | rahulsrma26/ol_codes | dc599f5b70c14229a001c5239c366ba1b990f68b | [
"MIT"
] | 2 | 2019-03-18T16:06:10.000Z | 2019-04-07T23:17:06.000Z | JTS/CF-B/CF714-D2-B/main.cpp | rahulsrma26/ol_codes | dc599f5b70c14229a001c5239c366ba1b990f68b | [
"MIT"
] | null | null | null | JTS/CF-B/CF714-D2-B/main.cpp | rahulsrma26/ol_codes | dc599f5b70c14229a001c5239c366ba1b990f68b | [
"MIT"
] | 1 | 2019-03-18T16:06:52.000Z | 2019-03-18T16:06:52.000Z | // Date : 2019-03-29
// Author : Rahul Sharma
// Problem : http://codeforces.com/contest/714/problem/B
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
using namespace std;
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
int a = -1, b = -1, c = -1, i = 1;
cin >> a;
for (int x; i < n; i++) {
cin >> x;
if(x != a){
b = x;
i++;
break;
}
}
for (int x; i < n; i++) {
cin >> x;
if(x != a && x != b){
c = x;
i++;
break;
}
}
bool possible = true;
for (int x; i < n; i++) {
cin >> x;
if(x != a && x != b && x != c){
possible = false;
break;
}
}
if(possible && c != -1){
if(a > b)
swap(a, b);
if(b > c)
swap(b, c);
if(a > b)
swap(a, b);
if(c - b != b - a)
possible = false;
}
cout << (possible ? "YES" : "NO") << '\n';
}
| 18.877193 | 56 | 0.358736 | rahulsrma26 |
d310f83c21ed88818d09c47575a6108e2e6884e7 | 4,603 | hpp | C++ | System.Drawing/src/Switch/System/Drawing/Png.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 4 | 2021-10-14T01:43:00.000Z | 2022-03-13T02:16:08.000Z | System.Drawing/src/Switch/System/Drawing/Png.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | null | null | null | System.Drawing/src/Switch/System/Drawing/Png.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 2 | 2022-03-13T02:16:06.000Z | 2022-03-14T14:32:57.000Z | #pragma once
#define PNG_SKIP_SETJMP_CHECK
#include <png.h>
#undef PNG_SKIP_SETJMP_CHECK
#include <zlib.h>
#include <Switch/System/Object.hpp>
#include <Switch/System/IO//BinaryReader.hpp>
#include "../../../../include/Switch/System/Drawing/Image.hpp"
#include "../../../../include/Switch/System/Drawing/Imaging/FrameDimension.hpp"
struct PngMemory {
png_structp pp;
const unsigned char* current;
const unsigned char* last;
};
extern "C" {
static void PngReadDataFromMem(png_structp png_ptr, png_bytep data, png_size_t length) {
struct PngMemory* png_mem_data = (PngMemory*)png_get_io_ptr(png_ptr);
if (png_mem_data->current + length > png_mem_data->last) {
png_error(png_mem_data->pp, "Invalid attempt to read row data");
return;
}
memcpy(data, png_mem_data->current, length);
png_mem_data->current += length;
}
} // extern "C"
namespace Switch {
namespace System {
namespace Drawing {
class Png : public object {
public:
template<typename TStream>
Png(const TStream& stream) : reader(ref_new<System::IO::BinaryReader>(stream)) {}
Png(refptr<System::IO::Stream> stream) : reader(ref_new<System::IO::BinaryReader>(stream)) {}
void Read(Image& image) {
png_infop info = null;
png_structp pp = png_create_read_struct(PNG_LIBPNG_VER_STRING, null, null, null);
if (pp)
info = png_create_info_struct(pp);
if (!pp || !info) {
if (pp)
png_destroy_read_struct(&pp, null, null);
throw OutOfMemoryException(caller_);
}
if (setjmp(png_jmpbuf(pp))) {
png_destroy_read_struct(&pp, &info, null);
throw OutOfMemoryException(caller_);
}
Array<byte> streamData((int32)reader->BaseStream().Length());
reader->Read(streamData, 0, static_cast<int32>(reader->BaseStream().Length()));
PngMemory png_mem_data;
png_mem_data.current = streamData.Data();
png_mem_data.last = streamData.Data() + reader->BaseStream().Length();
png_mem_data.pp = pp;
png_set_read_fn(pp, (png_voidp) &png_mem_data, PngReadDataFromMem);
png_read_info(pp, info);
if (png_get_color_type(pp, info) == PNG_COLOR_TYPE_PALETTE)
png_set_expand(pp);
image.size.Width((int)(png_get_image_width(pp, info)));
image.size.Height((int)(png_get_image_height(pp, info)));
switch (png_get_bit_depth(pp, info)) {
case 8: image.pixelFormat = Imaging::PixelFormat::Format8bppIndexed; break;
case 16: image.pixelFormat = Imaging::PixelFormat::Format16bppRgb555; break;
case 24: image.pixelFormat = Imaging::PixelFormat::Format24bppRgb; break;
case 32: image.pixelFormat = Imaging::PixelFormat::Format32bppRgb; break;
default: image.pixelFormat = Imaging::PixelFormat::Undefined; break;
}
if (png_get_bit_depth(pp, info) < 8) {
png_set_packing(pp);
png_set_expand(pp);
} else if (png_get_bit_depth(pp, info) == 16)
png_set_strip_16(pp);
if (png_get_valid(pp, info, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(pp);
Array<byte> rawData(image.size.Width() * image.size.Height() * (image.pixelFormat == Imaging::PixelFormat::Format32bppRgb ? 4 : 3));
Array<png_bytep> rows(image.size.Height());
for (int32 i = 0; i < image.size.Height(); i ++)
rows[i] = (png_bytep)(rawData.Data() + i * image.size.Width() * (image.pixelFormat == Imaging::PixelFormat::Format32bppRgb ? 4 : 3));
for (int32 i = png_set_interlace_handling(pp); i > 0; i --)
png_read_rows(pp, (png_bytep*)rows.Data(), null, image.size.Height());
#if defined(_WIN32)
if (image.pixelFormat == Imaging::PixelFormat::Format32bppRgb) {
byte* ptr = (byte*)rawData.Data();
for (int32 i = image.size.Width() * image.size.Height(); i > 0; i --) {
if (!ptr[3])
ptr[0] = ptr[1] = ptr[2] = 0;
ptr += 4;
}
}
#endif
png_read_end(pp, info);
png_destroy_read_struct(&pp, &info, null);
//image.rawData = Array<byte>(rawData.Data(), image.size.Width() * image.size.Height() * (image.PixelFormat() == System::Drawing::Imaging::PixelFormat::Format32bppRgb ? 4 : 3));
image.rawData = rawData;
}
private:
refptr<System::IO::BinaryReader> reader;
};
}
}
}
| 37.422764 | 187 | 0.611123 | kkptm |
d31146fb16e388b45f401cec225d5c1702cd50b7 | 2,865 | cpp | C++ | SDK/src/lgGuiExplorador.cpp | rgr0912/LibreGame | ffce4dbb3abeea1bbc64bb5bea29f76fc44b1e4f | [
"MIT"
] | null | null | null | SDK/src/lgGuiExplorador.cpp | rgr0912/LibreGame | ffce4dbb3abeea1bbc64bb5bea29f76fc44b1e4f | [
"MIT"
] | null | null | null | SDK/src/lgGuiExplorador.cpp | rgr0912/LibreGame | ffce4dbb3abeea1bbc64bb5bea29f76fc44b1e4f | [
"MIT"
] | null | null | null | #include "lgIMGUI.h"
Ogre::String objeto;
Ogre::SceneNode* _nodeImgui;
static int rb = 1;
static int rl = 1;
void lgGUI::Explorador(bool* p, Ogre::RenderWindow* win, Ogre::SceneManager* manager){
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar;
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(10,10));
//obteniendo las dimensiones de la venta para asignar tamaño
int h = win->getHeight();
int w = win->getWidth();
ImGui::SetNextWindowPos(ImVec2(0,tmenubar+tmenuherrmientas));
ImGui::SetNextWindowSize(ImVec2(200,h));
//explorador de entidades y luces
ImGui::Begin("Explorador",p, window_flags);
if (ImGui::CollapsingHeader("Entidades")){
ImGuiIO& io = ImGui::GetIO();
int contador_ent = 0;
//obteniendo entidades del SceneManager de ogre
Ogre::SceneManager::MovableObjectIterator mIterator = manager->getMovableObjectIterator("Entity");
while(mIterator.hasMoreElements()){
e = static_cast<Ogre::Entity*>(mIterator.getNext());
objeto = e->getName();
_nodeImgui = e->getParentSceneNode();
const char* c = objeto.c_str();
ImGui::RadioButton(c, &rb, contador_ent);
if(rb == contador_ent){
Propiedades(p,win,e,c);
_nodeImgui->showBoundingBox(true);
}else{
_nodeImgui->showBoundingBox(false);
}
ImGui::Separator();
contador_ent = contador_ent + 1;
}
if(!mIterator.hasMoreElements()){
}
}
if (ImGui::CollapsingHeader("Luces")){
ImGuiIO& io = ImGui::GetIO();
int contador_l = 0;
//obteniendo luces
Ogre::SceneManager::MovableObjectIterator mIterator = manager->getMovableObjectIterator("Light");
while(mIterator.hasMoreElements()){
l = static_cast<Ogre::Light*>(mIterator.getNext());
objeto = l->getName();
_nodeImgui = l->getParentSceneNode();
const char* c = objeto.c_str();
ImGui::RadioButton(c, &rb, contador_l);
if(rb == contador_l){
PropiedadesLuz(p,win,l,c);
SelectorColorLuz(l);
_nodeImgui->showBoundingBox(true);
}else{
_nodeImgui->showBoundingBox(false);
}
ImGui::Separator();
contador_l = contador_l + 1;
}
if(!mIterator.hasMoreElements()){
}
}
ImGui::End();
ImGui::PopStyleVar(2);
} | 36.730769 | 132 | 0.609773 | rgr0912 |
d312c56b74e161ad7b6c71cf7ae2bf2d04a1e8ec | 2,925 | cpp | C++ | cxx_examples/threshold_detect.cpp | kb3gtn/BladeRF_Setup_Instructions | 14f970a5d426a1909ab7d45165c808879bbb1f17 | [
"CC0-1.0"
] | 1 | 2021-12-12T15:05:25.000Z | 2021-12-12T15:05:25.000Z | cxx_examples/threshold_detect.cpp | kb3gtn/BladeRF_Setup_Instructions | 14f970a5d426a1909ab7d45165c808879bbb1f17 | [
"CC0-1.0"
] | null | null | null | cxx_examples/threshold_detect.cpp | kb3gtn/BladeRF_Setup_Instructions | 14f970a5d426a1909ab7d45165c808879bbb1f17 | [
"CC0-1.0"
] | null | null | null | ////////////////////////////////////////////
// Threshold Detect
//
// This is a simple demodulator that just tells
// if the received energy is above a threshold
// or not.
//
// You can use a UHF transmitter to transmit
// a CW or modulated signal at 446.5 MHz.
//
// This will indicate if it see the start of the signal
// and when the signal goes away..
//
// Peter Fetterer ([email protected])
//
////////////////////////////////////////////
#include <vector>
#include <string>
#include <cstdint>
#include <complex>
#include <atomic>
#include <csignal>
#include "bladeRF.hpp"
using std::atomic;
using std::cout;
using std::vector;
using std::complex;
using cplx_double = complex<double>;
using std::string;
atomic<bool> g_app_running;
void signal_handler( int signum ) {
cout << "\nReceived signal: " << signum << " from os. \n";
g_app_running = false;
}
double compute_avg_magnatude( vector<cplx_double> *samples );
int main(int argc, char **argv) {
g_app_running = true;
bladeRF::bladeRF myRadio;
bladeRF::channel_cfg_t radioConfig;
radioConfig.ch_num(0);
radioConfig.rx_freq(446500000);
radioConfig.rx_samplerate(521000);
radioConfig.rx_bandwidth(200000);
radioConfig.rx_gain(60);
radioConfig.rx_enabled(true);
string argstring("*");
if ( myRadio.open( argstring.c_str() ) != bladeRF::result_t::ok ) {
cout << "Failed to open radio..\n";
return -1;
}
if ( myRadio.configure( radioConfig ) != bladeRF::result_t::ok ) {
cout << "Failed to configure radio..\n";
return -1;
}
if ( myRadio.configure_streaming() != bladeRF::result_t::ok ) {
cout << "Faile to configure streaming on the radio..\n";
return -1;
}
// create a buffer to hold samples of the correct size for streaming to use.
vector<cplx_double> sample_buffer(myRadio.get_stream_buffer_size() );
bool above_threshold = false;
double threshold = 0.05;
double measured = 0;
int loopcnt=0;
// install signal handler
signal(SIGINT, signal_handler);
cout << "Starting Main Loop.\n";
while( g_app_running == true ) {
myRadio.receive( &sample_buffer );
measured = compute_avg_magnatude( &sample_buffer );
if ( measured > threshold ) {
if ( above_threshold == false ) {
cout << "Signal Detected..\n";
above_threshold = true;
}
} else {
// less than = threshold
if ( above_threshold == true ) {
cout << "Signal Lost..\n";
}
above_threshold = false;
}
if ( loopcnt == 30 ) {
cout << "measured: " << measured << '\n';
loopcnt = 0;
} else {
++loopcnt;
}
}
cout << "Main Loop Exit.. clean-up..\n";
myRadio.close();
return 0;
}
double compute_avg_magnatude( vector<cplx_double> *samples ) {
double avg = 0;
for (int idx=0; idx < samples->size(); ++idx) {
avg += std::abs( (*samples)[idx] );
}
avg = avg / samples->size();
return avg;
}
| 22.851563 | 78 | 0.623248 | kb3gtn |
d312ea3a6301bf51be5603d1359d3b40e59b6deb | 2,793 | hpp | C++ | include/Camera.hpp | alecwalsh/glfwogltest2 | 70224838d4851cb308834662763e51eb310f13b2 | [
"BSD-2-Clause"
] | null | null | null | include/Camera.hpp | alecwalsh/glfwogltest2 | 70224838d4851cb308834662763e51eb310f13b2 | [
"BSD-2-Clause"
] | null | null | null | include/Camera.hpp | alecwalsh/glfwogltest2 | 70224838d4851cb308834662763e51eb310f13b2 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include "GameObject.hpp"
#include "TimeManager.hpp"
#include <Physics/Collision.hpp>
#include <cstdint>
#include <glm/glm.hpp>
// TODO: Add support for roll
class Camera : public GameObject {
void UpdateViewMatrix() noexcept;
void UpdateVectors(glm::vec3 frontVector, glm::vec3 upVector) noexcept;
Physics::SimpleCubeCollider collider = {{}, {1.75, 3, 1.75}, {}};
double xSensitivity = 0.2f;
double ySensitivity = 0.2f;
double minPitch = -89.0;
double maxPitch = 89.0;
double pitch;
double yaw;
public:
Camera(glm::vec3 position, glm::vec3 target,
float speed = 1.0f,
glm::vec3 up = {0.0f, 1.0f, 0.0f} // y-axis defaults to up
);
// Runs every frame
void Tick() override;
void SetPosition(glm::vec3 position) override;
void Rotate() noexcept;
// Takes the mouse movement during the last frame and translates it into pitch and yaw
void CalculatePitchAndYaw(double deltaX, double deltaY) noexcept;
glm::mat4 viewMat{1.0f};
enum class Direction : std::uint8_t { Forward, Backward, Right, Left, Up, Down };
struct Vectors {
using vec3 = glm::vec3;
vec3 front{0.0f};
vec3 back{0.0f};
vec3 right{0.0f};
vec3 left{0.0f};
vec3 up{0.0f};
vec3 down{0.0f};
const vec3& operator[](Direction d) const noexcept;
vec3& operator[](Direction d) noexcept;
} vectors;
float speed = 1.0f;
// ParallelToGround means moving forward, back, left, and right results in movement parallel to the ground(pitch is 0)
// Up and down movement simply moves up or down
// With RelativeToCameraDirection, the camera's pitch applies to movement forward or backward
enum class MovementStyle : std::uint8_t { ParallelToGround, RelativeToCameraDirection };
MovementStyle movementStyle = MovementStyle::ParallelToGround;
bool CheckCollision(glm::vec3 translation) const;
// Create a lambda that translates the camera in a certain direction
auto TranslateCamera(Camera::Direction d) {
return [this, d] {
// TODO: Get key bindings from files
// TODO: Figure out how to use control key
auto vec = vectors[d];
if (movementStyle == MovementStyle::ParallelToGround) {
if (!(d == Camera::Direction::Up || d == Camera::Direction::Down)) {
vec.y = 0;
vec = glm::normalize(vec);
}
}
auto translation = speed * static_cast<float>(timeManager.deltaTime) * vec;
bool willCollide = CheckCollision(translation);
if (!willCollide) {
ModifyPosition(translation);
}
};
};
};
| 28.5 | 122 | 0.619764 | alecwalsh |
d3145bbc042c71a96f7ad0f02504129db950bdf6 | 3,108 | cpp | C++ | rvalue/perfect forwarding/src/Main.cpp | matt360/ModernCpp | 42ab42447d22c9e92f3da12dcb8ac16794668879 | [
"MIT"
] | null | null | null | rvalue/perfect forwarding/src/Main.cpp | matt360/ModernCpp | 42ab42447d22c9e92f3da12dcb8ac16794668879 | [
"MIT"
] | 16 | 2018-03-01T11:18:55.000Z | 2018-07-01T17:17:32.000Z | rvalue/perfect forwarding/src/Main.cpp | matzar/ModernCpp | 42ab42447d22c9e92f3da12dcb8ac16794668879 | [
"MIT"
] | null | null | null | // rvalue and perfect forwarding https://www.justsoftwaresolutions.co.uk/cplusplus/rvalue_references_and_perfect_forwarding.html
#include <iostream>
#include <vector>
class X
{
std::vector<double> data;
public:
X() :
data(100000) { std::cout << "constructed X!" << std::endl; } // lots of data
X(X const& other) : // copy constructor
data(other.data) { std::cout << "copy constructor called!" << std::endl; } // duplicate all that data
X(X&& other) : // move constructor
data(std::move(other.data)) { std::cout << "move constructor called!" << std::endl; } // move the data: no copies
X& operator=(X const& other) // copy-assignment
{
std::cout << "copy-assignement called!" << std::endl;
data = other.data; // copy all the data
return *this;
}
X& operator=(X&& other) // move-assignment
{
std::cout << "move-assignment called!" << std::endl;
data = std::move(other.data); // move the data: no copies
return *this;
}
};
// perfect forwarding
// a function template can pass its arguments through to another function whilst retaining the lvalue/rvalue nature of the function arguments
// by using std::forward. This is called "perfect forwarding", avoids excessive copying, and avoids the template author having to write
// multiple overloads for lvalue and rvalue references.
void g(X& t) { std::cout << "lvalue" << std::endl; };
void g(X&& t) { std::cout << "rvalue" << std::endl; };
template<typename T>
void f(T&& t)
{
std::cout << "template function calling: g(t) and t is ";
g(t);
std::cout << "template function calling: g(std::forward<T>(t)) and t is ";
g(std::forward<T>(t));
}
// overload
void h(X& t)
{
std::cout << "overloaded function calling: g(t) and t is ";
g(t);
}
void h(X&& t)
{
std::cout << "overloaded function calling: g(std::forward<X>(t)) and t is ";
g(std::forward<X>(t));
}
int main()
{
// copy constructor and move constructor
std::cout << "X x1; ";
X x1;
std::cout << "X x2(x1); ";
X x2(x1); // copy
std::cout << "X x3(std::move(x1)); ";
X x3(std::move(x1)); // no copy, move: x1 no longer has any data
std::cout << "X make_x; ";
X make_x; // build an X with data
std::cout << "x1 = make_x; ";
x1 = make_x; // return value is an rvalue, so move rather than copy
// perfect forwarding
std::cout << "X x; ";
X x;
std::cout << std::endl;
std::cout << "f(x) " << std::endl;
f(x); // we pass a named x object to f, so T is deducted to be an lvalue reference: x&, when T is an lvalue reference, std::forward<T> is an no-operation: it just returns its argument. We therefore call the overload of g that takes an lvalue reference [void g(X& t)]
std::cout << std::endl;
std::cout << "f(X()) " << std::endl;
f(X()); // in this case, std::forward<T>(t) is equivalent to static_cast<T&&>(t): it ensures that the argument is forwarded as an rvalue reference. This means that the overload of g that takes an rvalue refrence is selected [void g(X&& t)]
std::cout << std::endl;
std::cout << "h(x) " << std::endl;
h(x);
std::cout << std::endl;
std::cout << "h(X()) " << std::endl;
h(X());
std::cin.get();
} | 29.6 | 267 | 0.63964 | matt360 |
d3146253c3afc611d1abb7293222712fee2869d6 | 2,626 | cpp | C++ | sources/dansandu/glyph/internal/multimap.test.cpp | dansandu/glyph | d7d51bc57000d85eb4fd576e11502eeadbb0a6cf | [
"MIT"
] | null | null | null | sources/dansandu/glyph/internal/multimap.test.cpp | dansandu/glyph | d7d51bc57000d85eb4fd576e11502eeadbb0a6cf | [
"MIT"
] | null | null | null | sources/dansandu/glyph/internal/multimap.test.cpp | dansandu/glyph | d7d51bc57000d85eb4fd576e11502eeadbb0a6cf | [
"MIT"
] | null | null | null | #include "dansandu/glyph/internal/multimap.hpp"
#include "catchorg/catch/catch.hpp"
#include <set>
using dansandu::glyph::internal::multimap::Multimap;
using dansandu::glyph::symbol::Symbol;
TEST_CASE("Multimap")
{
SECTION("set values")
{
auto table = Multimap{};
table[Symbol{0}] = {Symbol{1}, Symbol{2}};
REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}});
table[Symbol{10}] = {Symbol{13}, Symbol{15}};
REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}});
REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}});
table[Symbol{20}] = {Symbol{26}, Symbol{29}, Symbol{21}};
REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}});
REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}});
REQUIRE(table[Symbol{20}] == std::vector<Symbol>{Symbol{26}, Symbol{29}, Symbol{21}});
SECTION("merge with new symbol")
{
table.merge({Symbol{0}, Symbol{40}});
REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}});
REQUIRE(table[Symbol{40}] == table[Symbol{0}]);
REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}});
REQUIRE(table[Symbol{20}] == std::vector<Symbol>{Symbol{26}, Symbol{29}, Symbol{21}});
}
SECTION("merge with existing symbols")
{
table.merge({Symbol{0}, Symbol{20}});
REQUIRE(table[Symbol{0}] == std::vector<Symbol>{Symbol{1}, Symbol{2}, Symbol{26}, Symbol{29}, Symbol{21}});
REQUIRE(table[Symbol{0}] == table[Symbol{20}]);
REQUIRE(table[Symbol{10}] == std::vector<Symbol>{Symbol{13}, Symbol{15}});
}
SECTION("iteration")
{
auto actualPartitions = std::vector<std::vector<Symbol>>{};
auto actualValues = std::vector<std::vector<Symbol>>{};
table.forEach(
[&](const auto& p, const auto& v)
{
actualPartitions.push_back(p);
actualValues.push_back(v);
});
const auto expectedPartitions = std::vector<std::vector<Symbol>>{{Symbol{0}}, {Symbol{10}}, {Symbol{20}}};
const auto expectedValues = std::vector<std::vector<Symbol>>{
{Symbol{1}, Symbol{2}}, {Symbol{13}, Symbol{15}}, {Symbol{26}, Symbol{29}, Symbol{21}}};
REQUIRE(actualPartitions == expectedPartitions);
REQUIRE(actualValues == expectedValues);
}
}
}
| 32.825 | 119 | 0.562072 | dansandu |
d319d61cf22889d604b25ed8057f3f1ff23bf12c | 4,435 | cpp | C++ | firmware/library/L1_Drivers/test/gpio_test.cpp | Adam-D-Sanchez/SJSU-Dev2 | ecb5bb01912f6f85a76b6715d0e72f2d3062ceed | [
"Apache-2.0"
] | null | null | null | firmware/library/L1_Drivers/test/gpio_test.cpp | Adam-D-Sanchez/SJSU-Dev2 | ecb5bb01912f6f85a76b6715d0e72f2d3062ceed | [
"Apache-2.0"
] | null | null | null | firmware/library/L1_Drivers/test/gpio_test.cpp | Adam-D-Sanchez/SJSU-Dev2 | ecb5bb01912f6f85a76b6715d0e72f2d3062ceed | [
"Apache-2.0"
] | null | null | null | #include "L0_LowLevel/LPC40xx.h"
#include "L1_Drivers/gpio.hpp"
#include "L4_Testing/testing_frameworks.hpp"
EMIT_ALL_METHODS(Gpio);
TEST_CASE("Testing Gpio", "[gpio]")
{
// Declared constants that are to be used within the different sections
// of this unit test
constexpr uint8_t kPin0 = 0;
constexpr uint8_t kPin7 = 7;
// Simulated local version of LPC_IOCON.
// This is necessary since a Gpio is also a Pin.
LPC_IOCON_TypeDef local_iocon;
memset(&local_iocon, 0, sizeof(local_iocon));
// Substitute the memory mapped LPC_IOCON with the local_iocon test struture
// Redirects manipulation to the 'local_iocon'
Pin::pin_map = reinterpret_cast<Pin::PinMap_t *>(&local_iocon);
// Initialized local LPC_GPIO_TypeDef objects with 0 to observe how the Gpio
// class manipulates the data in the registers
LPC_GPIO_TypeDef local_gpio_port[2];
memset(&local_gpio_port, 0, sizeof(local_gpio_port));
// Only GPIO port 1 & 2 will be used in this unit test
Gpio::gpio_port[0] = &local_gpio_port[0];
Gpio::gpio_port[1] = &local_gpio_port[1];
// Pins that are to be used in the unit test
Gpio p0_00(0, 0);
Gpio p1_07(1, 7);
SECTION("Set as Output and Input")
{
// Source: "UM10562 LPC408x/407x User manual" table 96 page 148
constexpr uint8_t kInputSet = 0b0;
constexpr uint8_t kOutputSet = 0b1;
p0_00.SetAsInput();
p1_07.SetAsOutput();
// Check bit 0 of local_gpio_port[0].DIR (port 0 pin 0)
// to see if it is cleared
CHECK(((local_gpio_port[0].DIR >> kPin0) & 1) == kInputSet);
// Check bit 7 of local_gpio_port[1].DIR (port 1 pin 7)
// to see if it is set
CHECK(((local_gpio_port[1].DIR >> kPin7) & 1) == kOutputSet);
p0_00.SetDirection(GpioInterface::kOutput);
p1_07.SetDirection(GpioInterface::kInput);
// Check bit 0 of local_gpio_port[0].DIR (port 0 pin 0)
// to see if it is set
CHECK(((local_gpio_port[0].DIR >> kPin0) & 1) == kOutputSet);
// Check bit 7 of local_gpio_port[1].DIR (port 1 pin 7)
// to see if it is cleared
CHECK(((local_gpio_port[1].DIR >> kPin7) & 1) == kInputSet);
}
SECTION("Set High")
{
// Source: "UM10562 LPC408x/407x User manual" table 99 page 149
constexpr uint8_t kHighSet = 0b1;
p0_00.SetHigh();
p1_07.Set(GpioInterface::kHigh);
// Check bit 0 of local_gpio_port[0].SET (port 0 pin 0)
// to see if it is set
CHECK(((local_gpio_port[0].SET >> kPin0) & 1) == kHighSet);
// Check bit 7 of local_gpio_port[1].SET (port 1 pin 7)
// to see if it is set
CHECK(((local_gpio_port[1].SET >> kPin7) & 1) == kHighSet);
}
SECTION("Set Low")
{
// Source: "UM10562 LPC408x/407x User manual" table 100 page 150
constexpr uint8_t kLowSet = 0b1;
p0_00.SetLow();
p1_07.Set(GpioInterface::kLow);
// Check bit 0 of local_gpio_port[0].CLR (port 0 pin 0)
// to see if it is set
CHECK(((local_gpio_port[0].CLR >> kPin0) & 1) == kLowSet);
// Check bit 7 of local_gpio_port[1].CLR (port 1 pin 7)
// to see if it is set
CHECK(((local_gpio_port[1].CLR >> kPin7) & 1) == kLowSet);
}
SECTION("Read Pin")
{
// Clearing bit 0 of local_gpio_port[0].PIN (port 0 pin 0) in order to
// read the pin value through the Read method
local_gpio_port[0].PIN &= ~(1 << kPin0);
// Setting bit 7 of local_gpio_port[1].PIN (port 1 pin 7) in order to
// read the pin value through the Read method
local_gpio_port[1].PIN |= (1 << kPin7);
CHECK(p0_00.Read() == false);
CHECK(p1_07.Read() == true);
CHECK(p0_00.Read() == Gpio::State::kLow);
CHECK(p1_07.Read() == Gpio::State::kHigh);
}
SECTION("Toggle")
{
// Clearing bit 0 of local_gpio_port[0].PIN (port 0 pin 0) in order to
// read the pin value through the Read method
local_gpio_port[0].PIN &= ~(1 << kPin0);
// Setting bit 7 of local_gpio_port[1].PIN (port 1 pin 7) in order to
// read the pin value through the Read method
local_gpio_port[1].PIN |= (1 << kPin7);
// Should change to 1
p0_00.Toggle();
// Should change to 0
p1_07.Toggle();
CHECK(p0_00.Read() == true);
CHECK(p1_07.Read() == false);
}
Gpio::gpio_port[0] = LPC_GPIO0;
Gpio::gpio_port[1] = LPC_GPIO1;
Gpio::gpio_port[2] = LPC_GPIO2;
Gpio::gpio_port[3] = LPC_GPIO3;
Gpio::gpio_port[4] = LPC_GPIO4;
Gpio::gpio_port[5] = LPC_GPIO5;
Pin::pin_map = reinterpret_cast<Pin::PinMap_t *>(LPC_IOCON);
}
| 36.056911 | 78 | 0.657046 | Adam-D-Sanchez |
d31eac89ad7b1543f83c0bded1103289ffb8d0ff | 18,370 | cpp | C++ | src/lib/rendering/descriptors/DescriptorPool.cpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | 1 | 2021-08-15T19:20:14.000Z | 2021-08-15T19:20:14.000Z | src/lib/rendering/descriptors/DescriptorPool.cpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | 17 | 2021-06-05T12:37:04.000Z | 2021-10-01T10:20:09.000Z | src/lib/rendering/descriptors/DescriptorPool.cpp | Lut99/Rasterizer | 453864506db749a93fb82fb17cc5ee88cc4ada01 | [
"MIT"
] | null | null | null | /* DESCRIPTOR POOL.cpp
* by Lut99
*
* Created:
* 26/04/2021, 14:38:48
* Last edited:
* 25/05/2021, 18:14:13
* Auto updated?
* Yes
*
* Description:
* Contains the DescriptorPool class, which serves as a memory pool for
* descriptors, which in turn describe how a certain buffer or other
* piece of memory should be accessed on the GPU.
**/
#include "tools/Logger.hpp"
#include "../auxillary/ErrorCodes.hpp"
#include "DescriptorPool.hpp"
using namespace std;
using namespace Makma3D;
using namespace Makma3D::Rendering;
/***** POPULATE FUNCTIONS *****/
/* Populates a given VkDescriptorPoolSize struct. */
static void populate_descriptor_pool_size(VkDescriptorPoolSize& descriptor_pool_size, const std::tuple<VkDescriptorType, uint32_t>& descriptor_type) {
// Initialize to default
descriptor_pool_size = {};
descriptor_pool_size.type = std::get<0>(descriptor_type);
descriptor_pool_size.descriptorCount = std::get<1>(descriptor_type);
}
/* Populates a given VkDescriptorPoolCreateInfo struct. */
static void populate_descriptor_pool_info(VkDescriptorPoolCreateInfo& descriptor_pool_info, const Tools::Array<VkDescriptorPoolSize>& descriptor_pool_sizes, uint32_t n_sets, VkDescriptorPoolCreateFlags descriptor_pool_flags) {
// Initialize to default
descriptor_pool_info = {};
descriptor_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
// Set the pool size to use
descriptor_pool_info.poolSizeCount = static_cast<uint32_t>(descriptor_pool_sizes.size());
descriptor_pool_info.pPoolSizes = descriptor_pool_sizes.rdata();
// Set the maximum number of sets allowed
descriptor_pool_info.maxSets = n_sets;
// Set the flags to use
descriptor_pool_info.flags = descriptor_pool_flags | VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
}
/* Populates a given VkDescriptorSetAllocateInfo struct. */
static void populate_descriptor_set_info(VkDescriptorSetAllocateInfo& descriptor_set_info, VkDescriptorPool vk_descriptor_pool, const Tools::Array<VkDescriptorSetLayout>& vk_descriptor_set_layouts, uint32_t n_sets) {
// Set to default
descriptor_set_info = {};
descriptor_set_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
// Set the pool that we use to allocate them
descriptor_set_info.descriptorPool = vk_descriptor_pool;
// Set the number of sets to allocate
descriptor_set_info.descriptorSetCount = n_sets;
// Set the layout for this descriptor
descriptor_set_info.pSetLayouts = vk_descriptor_set_layouts.rdata();
}
/***** DESCRIPTORPOOL CLASS *****/
/* Constructor for the DescriptorPool class, which takes the GPU to create the pool on, the number of descriptors we want to allocate in the pool, the maximum number of descriptor sets that can be allocated and optionally custom create flags. */
DescriptorPool::DescriptorPool(const Rendering::GPU& gpu, const std::pair<VkDescriptorType, uint32_t>& descriptor_type, uint32_t max_sets, VkDescriptorPoolCreateFlags flags):
gpu(gpu),
vk_descriptor_types(Tools::Array<std::pair<VkDescriptorType, uint32_t>>({ descriptor_type })),
vk_max_sets(max_sets),
vk_create_flags(flags)
{
logger.logc(Verbosity::important, DescriptorPool::channel, "Initializing with a single type...");
// First, we define how large the pool will be
logger.logc(Verbosity::details, DescriptorPool::channel, "Preparing structs...");
VkDescriptorPoolSize descriptor_pool_size;
populate_descriptor_pool_size(descriptor_pool_size, this->vk_descriptor_types[0]);
// Prepare the create info
VkDescriptorPoolCreateInfo descriptor_pool_info;
populate_descriptor_pool_info(descriptor_pool_info, Tools::Array<VkDescriptorPoolSize>({ descriptor_pool_size }), this->vk_max_sets, this->vk_create_flags);
// Actually allocate the pool
logger.logc(Verbosity::details, DescriptorPool::channel, "Allocating pool..");
VkResult vk_result;
if ((vk_result = vkCreateDescriptorPool(this->gpu, &descriptor_pool_info, nullptr, &this->vk_descriptor_pool)) != VK_SUCCESS) {
logger.fatalc(DescriptorPool::channel, "Could not allocate descriptor pool: ", vk_error_map[vk_result]);
}
// Before we leave, we can optimise by setting the map to the maximum memory size
this->descriptor_sets.reserve(this->vk_max_sets);
// D0ne
logger.logc(Verbosity::important, DescriptorPool::channel, "Init success.");
}
/* Constructor for the DescriptorPool class, which takes the GPU to create the pool on, a list of descriptor types and their counts, the maximum number of descriptor sets that can be allocated and optionally custom create flags. */
DescriptorPool::DescriptorPool(const Rendering::GPU& gpu, const Tools::Array<std::pair<VkDescriptorType, uint32_t>>& descriptor_types, uint32_t max_sets, VkDescriptorPoolCreateFlags flags) :
gpu(gpu),
vk_descriptor_types(descriptor_types),
vk_max_sets(max_sets),
vk_create_flags(flags)
{
logger.logc(Verbosity::important, DescriptorPool::channel, "Initializing with multiple types...");
// First, we define how large the pool will be
logger.logc(Verbosity::details, DescriptorPool::channel, "Preparing structs...");
Tools::Array<VkDescriptorPoolSize> descriptor_pool_sizes;
descriptor_pool_sizes.resize(this->vk_descriptor_types.size());
for (uint32_t i = 0; i < this->vk_descriptor_types.size(); i++) {
populate_descriptor_pool_size(descriptor_pool_sizes[i], this->vk_descriptor_types[i]);
}
// Prepare the create info
VkDescriptorPoolCreateInfo descriptor_pool_info;
populate_descriptor_pool_info(descriptor_pool_info, descriptor_pool_sizes, this->vk_max_sets, this->vk_create_flags);
// Actually allocate the pool
logger.logc(Verbosity::details, DescriptorPool::channel, "Allocating pool..");
VkResult vk_result;
if ((vk_result = vkCreateDescriptorPool(this->gpu, &descriptor_pool_info, nullptr, &this->vk_descriptor_pool)) != VK_SUCCESS) {
logger.fatalc(DescriptorPool::channel, "Could not allocate descriptor pool: ", vk_error_map[vk_result]);
}
// Before we leave, we can optimise by setting the map to the maximum memory size
this->descriptor_sets.reserve(this->vk_max_sets);
// D0ne
logger.logc(Verbosity::important, DescriptorPool::channel, "Init success.");
}
/* Copy constructor for the DescriptorPool. */
DescriptorPool::DescriptorPool(const DescriptorPool& other) :
gpu(other.gpu),
vk_descriptor_types(other.vk_descriptor_types),
vk_max_sets(other.vk_max_sets),
vk_create_flags(other.vk_create_flags)
{
logger.logc(Verbosity::debug, DescriptorPool::channel, "Copying...");
// First, we define how large the pool will be
Tools::Array<VkDescriptorPoolSize> descriptor_pool_sizes;
descriptor_pool_sizes.resize(this->vk_descriptor_types.size());
for (uint32_t i = 0; i < this->vk_descriptor_types.size(); i++) {
populate_descriptor_pool_size(descriptor_pool_sizes[i], this->vk_descriptor_types[0]);
}
// Prepare the create info
VkDescriptorPoolCreateInfo descriptor_pool_info;
populate_descriptor_pool_info(descriptor_pool_info, descriptor_pool_sizes, this->vk_max_sets, this->vk_create_flags);
// Actually allocate the pool
VkResult vk_result;
if ((vk_result = vkCreateDescriptorPool(this->gpu, &descriptor_pool_info, nullptr, &this->vk_descriptor_pool)) != VK_SUCCESS) {
logger.fatalc(DescriptorPool::channel, "Could not allocate descriptor pool: ", vk_error_map[vk_result]);
}
// Do not copy individual descriptors
// Before we leave, we can optimise by setting the map to the maximum memory size
this->descriptor_sets.reserve(this->vk_max_sets);
// D0ne
logger.logc(Verbosity::debug, DescriptorPool::channel, "Copy success.");
}
/* Move constructor for the DescriptorPool. */
DescriptorPool::DescriptorPool(DescriptorPool&& other):
gpu(other.gpu),
vk_descriptor_pool(other.vk_descriptor_pool),
vk_descriptor_types(other.vk_descriptor_types),
vk_max_sets(other.vk_max_sets),
vk_create_flags(other.vk_create_flags),
descriptor_sets(other.descriptor_sets)
{
// Set the other's pool & sets to nullptr to avoid deallocation
other.vk_descriptor_pool = nullptr;
other.descriptor_sets.clear();
}
/* Destructor for the DescriptorPool. */
DescriptorPool::~DescriptorPool() {
logger.logc(Verbosity::important, DescriptorPool::channel, "Cleaning...");
VkResult vk_result;
if (this->descriptor_sets.size() > 0) {
logger.logc(Verbosity::details, DescriptorPool::channel, "Deallocating descriptor sets...");
for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) {
if ((vk_result = vkFreeDescriptorSets(this->gpu, this->vk_descriptor_pool, 1, &this->descriptor_sets[i]->vulkan())) != VK_SUCCESS) {
logger.errorc(DescriptorPool::channel, "Could not deallocate descriptor sets: ", vk_error_map[vk_result]);
}
}
}
if (this->vk_descriptor_pool != nullptr) {
logger.logc(Verbosity::details, DescriptorPool::channel, "Deallocating pool...");
vkDestroyDescriptorPool(this->gpu, this->vk_descriptor_pool, nullptr);
}
logger.logc(Verbosity::important, DescriptorPool::channel, "Cleaned.");
}
/* Allocates a single descriptor set with the given layout. Will fail with errors if there's no more space. */
DescriptorSet* DescriptorPool::allocate(const Rendering::DescriptorSetLayout& descriptor_set_layout) {
// Check if we have enough space left
if (static_cast<uint32_t>(this->descriptor_sets.size()) >= this->vk_max_sets) {
logger.fatalc(DescriptorPool::channel, "Cannot allocate new DescriptorSet: already allocated maximum of ", this->vk_max_sets, " sets.");
}
// Put the layout in a struct s.t. we can pass it and keep it in memory until after the call
Tools::Array<VkDescriptorSetLayout> vk_descriptor_set_layouts({ descriptor_set_layout.vulkan() });
// Next, populate the create info
VkDescriptorSetAllocateInfo descriptor_set_info;
populate_descriptor_set_info(descriptor_set_info, this->vk_descriptor_pool, vk_descriptor_set_layouts, 1);
// We can now call the allocate function
VkResult vk_result;
VkDescriptorSet set;
if ((vk_result = vkAllocateDescriptorSets(this->gpu, &descriptor_set_info, &set)) != VK_SUCCESS) {
logger.fatalc(DescriptorPool::channel, "Failed to allocate new DescriptorSet: ", vk_error_map[vk_result]);
}
// Create the object and insert it
DescriptorSet* descriptor_set = new DescriptorSet(this->gpu, set);
this->descriptor_sets.push_back(descriptor_set);
// With that done, return the handle
return descriptor_set;
}
/* Allocates multiple descriptor sets with the given layout, returning them as an Array. Will fail with errors if there's no more space. */
Tools::Array<DescriptorSet*> DescriptorPool::nallocate(uint32_t n_sets, const Tools::Array<Rendering::DescriptorSetLayout>& descriptor_set_layouts) {
#ifndef NDEBUG
// If n_sets if null, nothing to do
if (n_sets == 0) {
logger.warningc(DescriptorPool::channel, "Request to allocate 0 sets received; nothing to do.");
return {};
}
// If we aren't passed enough layouts, then tell us
if (n_sets != descriptor_set_layouts.size()) {
logger.fatalc(DescriptorPool::channel, "Not enough descriptor set layouts passed: got ", descriptor_set_layouts.size(), ", expected ", n_sets);
}
#endif
// Check if we have enough space left
if (static_cast<uint32_t>(this->descriptor_sets.size()) + n_sets > this->vk_max_sets) {
logger.fatalc(DescriptorPool::channel, "Cannot allocate ", n_sets, " new DescriptorSets: only space for ", this->vk_max_sets - static_cast<uint32_t>(this->descriptor_sets.size()), " sets");
}
// Get the VkDescriptorSetLayout objects behind the layouts
Tools::Array<VkDescriptorSetLayout> vk_descriptor_set_layouts(descriptor_set_layouts.size());
for (uint32_t i = 0; i < descriptor_set_layouts.size(); i++) {
vk_descriptor_set_layouts.push_back(descriptor_set_layouts[i]);
}
// Create a temporary list of result sets to which we can allocate
Tools::Array<VkDescriptorSet> sets(n_sets);
// Next, populate the create info
VkDescriptorSetAllocateInfo descriptor_set_info;
populate_descriptor_set_info(descriptor_set_info, this->vk_descriptor_pool, vk_descriptor_set_layouts, n_sets);
// We can now call the allocate function
VkResult vk_result;
if ((vk_result = vkAllocateDescriptorSets(this->gpu, &descriptor_set_info, sets.wdata(n_sets))) != VK_SUCCESS) {
logger.fatalc(DescriptorPool::channel, "Failed to allocate ", n_sets, " new DescriptorSets: ", vk_error_map[vk_result]);
}
// Create the resulting DescriptorSet object for each pair, then return
Tools::Array<DescriptorSet*> result(n_sets);
for (uint32_t i = 0; i < n_sets; i++) {
result.push_back(new DescriptorSet(this->gpu, sets[i]));
this->descriptor_sets.push_back(result.last());
}
// We're done, so return the set of handles
return result;
}
/* Allocates multiple descriptor sets with the given layout (repeating it), returning them as an Array. Will fail with errors if there's no more space. */
Tools::Array<DescriptorSet*> DescriptorPool::nallocate(uint32_t n_sets, const Rendering::DescriptorSetLayout& descriptor_set_layout) {
#ifndef NDEBUG
// If n_sets if null, nothing to do
if (n_sets == 0) {
logger.warningc(DescriptorPool::channel, "Request to allocate 0 sets received; nothing to do.");
return {};
}
#endif
// Check if we have enough space left
if (static_cast<uint32_t>(this->descriptor_sets.size()) + n_sets > this->vk_max_sets) {
logger.fatalc(DescriptorPool::channel, "Cannot allocate ", n_sets, " new DescriptorSets: only space for ", this->vk_max_sets - static_cast<uint32_t>(this->descriptor_sets.size()), " sets");
}
// Get the VkDescriptorSetLayout object behind the layout as an array
Tools::Array<VkDescriptorSetLayout> vk_descriptor_set_layout(descriptor_set_layout.vulkan(), n_sets);
// Create a temporary list of result sets to which we can allocate
Tools::Array<VkDescriptorSet> sets(n_sets);
// Next, populate the create info
VkDescriptorSetAllocateInfo descriptor_set_info;
populate_descriptor_set_info(descriptor_set_info, this->vk_descriptor_pool, vk_descriptor_set_layout, n_sets);
// We can now call the allocate function
VkResult vk_result;
if ((vk_result = vkAllocateDescriptorSets(this->gpu, &descriptor_set_info, sets.wdata(n_sets))) != VK_SUCCESS) {
logger.fatalc(DescriptorPool::channel, "Failed to allocate ", n_sets, " new DescriptorSets: ", vk_error_map[vk_result]);
}
// Create the resulting DescriptorSet object for each pair, then return
Tools::Array<DescriptorSet*> result(n_sets);
for (uint32_t i = 0; i < n_sets; i++) {
result.push_back(new DescriptorSet(this->gpu, sets[i]));
this->descriptor_sets.push_back(result.last());
}
// We're done, so return the set of handles
return result;
}
/* Deallocates the descriptor set with the given handle. */
void DescriptorPool::free(const DescriptorSet* set) {
// Try to remove the pointer from the list
bool found = false;
for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) {
if (this->descriptor_sets[i] == set) {
this->descriptor_sets.erase(i);
found = true;
break;
}
}
if (!found) {
logger.fatalc(DescriptorPool::channel, "Tried to free DescriptorSet that was not allocated with this pool.");
}
// Destroy the VkCommandBuffer
vkFreeDescriptorSets(this->gpu, this->vk_descriptor_pool, 1, &set->vulkan());
// Destroy the pointer itself
delete set;
}
/* Deallocates an array of given descriptors sets. */
void DescriptorPool::nfree(const Tools::Array<DescriptorSet*>& sets) {
// First, we check if all handles exist
Tools::Array<VkDescriptorSet> to_remove(sets.size());
for (uint32_t i = 0; i < sets.size(); i++) {
bool found = false;
for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) {
if (this->descriptor_sets[i] == sets[i]) {
this->descriptor_sets.erase(i);
found = true;
break;
}
}
if (!found) {
logger.fatalc(DescriptorPool::channel, "Tried to free DescriptorSet that was not allocated with this pool.");
}
// Mark the Vk object for removal
to_remove.push_back(sets[i]->vulkan());
// Delete the pointer
delete sets[i];
}
// All that's left is to actually remove the handles; do that
VkResult vk_result;
if ((vk_result = vkFreeDescriptorSets(this->gpu, this->vk_descriptor_pool, to_remove.size(), to_remove.rdata())) != VK_SUCCESS) {
logger.fatalc(DescriptorPool::channel, "Could not deallocate descriptor sets: ", vk_error_map[vk_result]);
}
}
/* Resets the pool in its entirety, quickly deallocating everything. */
void DescriptorPool::reset() {
// Call the reset quickly (note the 0, the flags, is reserved for future use and thus fixed for us)
vkResetDescriptorPool(this->gpu, this->vk_descriptor_pool, 0);
// Delete all internal pointers
for (uint32_t i = 0; i < this->descriptor_sets.size(); i++) {
delete this->descriptor_sets[i];
}
this->descriptor_sets.clear();
}
/* Swap operator for the DescriptorPool class. */
void Rendering::swap(DescriptorPool& dp1, DescriptorPool& dp2) {
#ifndef NDEBUG
// If the GPU is not the same, then initialize to all nullptrs and everything
if (dp1.gpu != dp2.gpu) { logger.fatalc(DescriptorPool::channel, "Cannot swap descriptor pools with different GPUs"); }
#endif
// Swap all fields
using std::swap;
swap(dp1.vk_descriptor_pool, dp2.vk_descriptor_pool);
swap(dp1.vk_descriptor_types, dp2.vk_descriptor_types);
swap(dp1.vk_max_sets, dp2.vk_max_sets);
swap(dp1.vk_create_flags, dp2.vk_create_flags);
swap(dp1.descriptor_sets, dp2.descriptor_sets);
}
| 42.62181 | 245 | 0.721121 | Lut99 |
d31f64e26267dc1b13491335ff3dd9b5b5f51e28 | 3,313 | cpp | C++ | hi_snex/snex_parser/snex_jit_SymbolParser.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_snex/snex_parser/snex_jit_SymbolParser.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | hi_snex/snex_parser/snex_jit_SymbolParser.cpp | Matt-Dub/HISE | ae2dd1653e1c8d749a9088edcd573de6252b0b96 | [
"Intel"
] | null | null | null | /* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE 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.
*
* HISE 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 HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licences for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licencing:
*
* http://www.hartinstruments.net/hise/
*
* HISE is based on the JUCE library,
* which also must be licenced for commercial applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace snex {
namespace jit {
using namespace juce;
using namespace asmjit;
void NamespaceResolver::CanExist::resolve(NamespaceHandler& n, NamespacedIdentifier& c, const ParserHelpers::CodeLocation& l)
{
auto r = n.resolve(c, true);
if (!r.wasOk())
l.throwError(r.getErrorMessage());
}
SymbolParser::SymbolParser(ParserHelpers::TokenIterator& other_, NamespaceHandler& handler_) :
ParserHelpers::TokenIterator(other_),
handler(handler_),
other(other_)
{
}
snex::jit::Symbol SymbolParser::parseExistingSymbol(bool needsStaticTyping)
{
parseNamespacedIdentifier<NamespaceResolver::MustExist>();
auto type = handler.getVariableType(currentNamespacedIdentifier);
location.test(handler.checkVisiblity(currentNamespacedIdentifier));
auto s = Symbol(currentNamespacedIdentifier, type);
if (needsStaticTyping && s.typeInfo.isDynamic())
location.throwError("Can't resolve symbol type");
return s;
}
snex::jit::Symbol SymbolParser::parseNewDynamicSymbolSymbol(NamespaceHandler::SymbolType t)
{
jassert(other.currentTypeInfo.isDynamic());
parseNamespacedIdentifier<NamespaceResolver::MustBeNew>();
auto s = Symbol(currentNamespacedIdentifier, other.currentTypeInfo);
return s;
}
snex::jit::Symbol SymbolParser::parseNewSymbol(NamespaceHandler::SymbolType t)
{
auto type = other.currentTypeInfo;
parseNamespacedIdentifier<NamespaceResolver::MustBeNew>();
auto s = Symbol(currentNamespacedIdentifier, type);
BlockParser::CommentAttacher ca(*this);
if (t != NamespaceHandler::Unknown)
handler.addSymbol(s.id, type, t, ca.getInfo());
#if 0
if (s.typeInfo.isDynamic() && t != NamespaceHandler::UsingAlias)
location.throwError("Can't resolve symbol type");
#endif
return s;
}
void NamespaceResolver::MustExist::resolve(NamespaceHandler& n, NamespacedIdentifier& c, const ParserHelpers::CodeLocation& l)
{
auto r = n.resolve(c);
if (!r.wasOk())
{
DBG(n.dump());
l.throwError(r.getErrorMessage());
}
}
void NamespaceResolver::MustBeNew::resolve(NamespaceHandler& n, NamespacedIdentifier& c, const ParserHelpers::CodeLocation& l)
{
}
}
} | 27.380165 | 126 | 0.715967 | Matt-Dub |
d3210fd0c26b61c2ef387e112f839acbc13abf16 | 4,988 | cc | C++ | src/ImgProc.cc | abhishekdewan101/RealTimeFaceTracking | 393dfd9418bf53e006d6c1fe533ecaca82c80e08 | [
"MIT"
] | 2 | 2019-02-20T00:37:57.000Z | 2019-02-20T00:38:32.000Z | node_modules/opencv/src/ImgProc.cc | nolim1t/opencv-aws-lambda | 744d2cc1e9ac257e24c8a1a33e8a0d53dd8aff56 | [
"MIT"
] | null | null | null | node_modules/opencv/src/ImgProc.cc | nolim1t/opencv-aws-lambda | 744d2cc1e9ac257e24c8a1a33e8a0d53dd8aff56 | [
"MIT"
] | 4 | 2015-03-29T19:50:06.000Z | 2021-03-31T18:55:35.000Z | #include "ImgProc.h"
#include "Matrix.h"
void ImgProc::Init(Handle<Object> target)
{
Persistent<Object> inner;
Local<Object> obj = NanNew<Object>();
NanAssignPersistent(inner, obj);
NODE_SET_METHOD(obj, "undistort", Undistort);
NODE_SET_METHOD(obj, "initUndistortRectifyMap", InitUndistortRectifyMap);
NODE_SET_METHOD(obj, "remap", Remap);
target->Set(NanNew("imgproc"), obj);
}
// cv::undistort
NAN_METHOD(ImgProc::Undistort)
{
NanEscapableScope();
try {
// Get the arguments
// Arg 0 is the image
Matrix* m0 = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
cv::Mat inputImage = m0->mat;
// Arg 1 is the camera matrix
Matrix* m1 = ObjectWrap::Unwrap<Matrix>(args[1]->ToObject());
cv::Mat K = m1->mat;
// Arg 2 is the distortion coefficents
Matrix* m2 = ObjectWrap::Unwrap<Matrix>(args[2]->ToObject());
cv::Mat dist = m2->mat;
// Make an mat to hold the result image
cv::Mat outputImage;
// Undistort
cv::undistort(inputImage, outputImage, K, dist);
// Wrap the output image
Local<Object> outMatrixWrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance();
Matrix *outMatrix = ObjectWrap::Unwrap<Matrix>(outMatrixWrap);
outMatrix->mat = outputImage;
// Return the output image
NanReturnValue(outMatrixWrap);
} catch (cv::Exception &e) {
const char *err_msg = e.what();
NanThrowError(err_msg);
NanReturnUndefined();
}
}
// cv::initUndistortRectifyMap
NAN_METHOD(ImgProc::InitUndistortRectifyMap)
{
NanEscapableScope();
try {
// Arg 0 is the camera matrix
Matrix* m0 = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
cv::Mat K = m0->mat;
// Arg 1 is the distortion coefficents
Matrix* m1 = ObjectWrap::Unwrap<Matrix>(args[1]->ToObject());
cv::Mat dist = m1->mat;
// Arg 2 is the recification transformation
Matrix* m2 = ObjectWrap::Unwrap<Matrix>(args[2]->ToObject());
cv::Mat R = m2->mat;
// Arg 3 is the new camera matrix
Matrix* m3 = ObjectWrap::Unwrap<Matrix>(args[3]->ToObject());
cv::Mat newK = m3->mat;
// Arg 4 is the image size
cv::Size imageSize;
if (args[4]->IsArray()) {
Local<Object> v8sz = args[4]->ToObject();
imageSize = cv::Size(v8sz->Get(1)->IntegerValue(), v8sz->Get(0)->IntegerValue());
} else {
JSTHROW_TYPE("Must pass image size");
}
// Arg 5 is the first map type, skip for now
int m1type = args[5]->IntegerValue();
// Make matrices to hold the output maps
cv::Mat map1, map2;
// Compute the rectification map
cv::initUndistortRectifyMap(K, dist, R, newK, imageSize, m1type, map1, map2);
// Wrap the output maps
Local<Object> map1Wrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance();
Matrix *map1Matrix = ObjectWrap::Unwrap<Matrix>(map1Wrap);
map1Matrix->mat = map1;
Local<Object> map2Wrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance();
Matrix *map2Matrix = ObjectWrap::Unwrap<Matrix>(map2Wrap);
map2Matrix->mat = map2;
// Make a return object with the two maps
Local<Object> ret = NanNew<Object>();
ret->Set(NanNew<String>("map1"), map1Wrap);
ret->Set(NanNew<String>("map2"), map2Wrap);
// Return the maps
NanReturnValue(ret);
} catch (cv::Exception &e) {
const char *err_msg = e.what();
NanThrowError(err_msg);
NanReturnUndefined();
}
}
// cv::remap
NAN_METHOD(ImgProc::Remap)
{
NanEscapableScope();
try {
// Get the arguments
// Arg 0 is the image
Matrix* m0 = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
cv::Mat inputImage = m0->mat;
// Arg 1 is the first map
Matrix* m1 = ObjectWrap::Unwrap<Matrix>(args[1]->ToObject());
cv::Mat map1 = m1->mat;
// Arg 2 is the second map
Matrix* m2 = ObjectWrap::Unwrap<Matrix>(args[2]->ToObject());
cv::Mat map2 = m2->mat;
// Arg 3 is the interpolation mode
int interpolation = args[3]->IntegerValue();
// Args 4, 5 border settings, skipping for now
// Output image
cv::Mat outputImage;
// Remap
cv::remap(inputImage, outputImage, map1, map2, interpolation);
// Wrap the output image
Local<Object> outMatrixWrap = NanNew(Matrix::constructor)->GetFunction()->NewInstance();
Matrix *outMatrix = ObjectWrap::Unwrap<Matrix>(outMatrixWrap);
outMatrix->mat = outputImage;
// Return the image
NanReturnValue(outMatrixWrap);
} catch (cv::Exception &e) {
const char *err_msg = e.what();
NanThrowError(err_msg);
NanReturnUndefined();
}
}
| 29.341176 | 96 | 0.596231 | abhishekdewan101 |
d323d663b46feee228700e1768c809c4d1307c19 | 1,100 | cpp | C++ | source/rho/crypt/tSHA224.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | 1 | 2016-09-22T03:27:33.000Z | 2016-09-22T03:27:33.000Z | source/rho/crypt/tSHA224.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | null | null | null | source/rho/crypt/tSHA224.cpp | Rhobota/librho | d540cba6227e15ac6ef3dcb6549ed9557f6fee04 | [
"BSD-3-Clause"
] | null | null | null | #include <rho/crypt/tSHA224.h>
#include <rho/crypt/hash_utils.h>
#include "sha.h"
namespace rho
{
namespace crypt
{
tSHA224::tSHA224()
: m_context(NULL)
{
m_context = new SHA256_CTX;
SHA224_Init((SHA256_CTX*)m_context);
}
tSHA224::~tSHA224()
{
delete ((SHA256_CTX*)m_context);
m_context = NULL;
}
i32 tSHA224::write(const u8* buffer, i32 length)
{
return this->writeAll(buffer, length);
}
i32 tSHA224::writeAll(const u8* buffer, i32 length)
{
if (length <= 0)
throw eInvalidArgument("Stream read/write length must be >0");
SHA224_Update(((SHA256_CTX*)m_context), buffer, (u32)length);
return length;
}
std::vector<u8> tSHA224::getHash() const
{
u8 dg[SHA256_DIGEST_LENGTH];
SHA256_CTX context = *((SHA256_CTX*)m_context);
SHA224_Final(dg, &context);
std::vector<u8> v(SHA224_DIGEST_LENGTH, 0);
for (size_t i = 0; i < v.size(); i++) v[i] = dg[i];
return v;
}
std::string tSHA224::getHashString() const
{
std::vector<u8> hash = getHash();
return hashToString(hash);
}
} // namespace crypt
} // namespace rho
| 18.333333 | 70 | 0.653636 | Rhobota |
d32630e21e4b2010a28a11dce1b2982c461e29fc | 243 | cpp | C++ | src/modules/lib/OrderPositionController.cpp | Thorsten-Geppert/Warehouse | b064e5b422d0b484ca702cc4433cbda90f40e009 | [
"BSD-3-Clause"
] | null | null | null | src/modules/lib/OrderPositionController.cpp | Thorsten-Geppert/Warehouse | b064e5b422d0b484ca702cc4433cbda90f40e009 | [
"BSD-3-Clause"
] | null | null | null | src/modules/lib/OrderPositionController.cpp | Thorsten-Geppert/Warehouse | b064e5b422d0b484ca702cc4433cbda90f40e009 | [
"BSD-3-Clause"
] | null | null | null | #include "OrderPositionController.h"
OrderPositionController::OrderPositionController(
RuntimeInformationType *rit
) : Controller(
rit,
_N("orders_positions"), // Table
_N("orderPositionId"), // Primary key
_N("rank") // Sorting
) {
}
| 20.25 | 49 | 0.73251 | Thorsten-Geppert |
d326f30e97bbe3c6b214736073ea6175cdb5fc6c | 1,113 | cpp | C++ | src/python_bindings.cpp | risteon/voxel-traversal | 331f390025d23fdc2d6f6e33292625bf42b3264c | [
"MIT"
] | 3 | 2022-03-02T17:17:52.000Z | 2022-03-25T09:03:43.000Z | src/python_bindings.cpp | risteon/voxel-traversal | 331f390025d23fdc2d6f6e33292625bf42b3264c | [
"MIT"
] | null | null | null | src/python_bindings.cpp | risteon/voxel-traversal | 331f390025d23fdc2d6f6e33292625bf42b3264c | [
"MIT"
] | null | null | null | #include "python_bindings.h"
#include <pybind11/stl.h>
#include "voxel_traversal.h"
namespace py = pybind11;
using namespace voxel_traversal;
namespace pytraversal {
py::array_t<int64_t, py::array::c_style> traverse(
const grid_type& grid, const grid_type::Vector3d& ray_origin,
const grid_type::Vector3d& ray_end) {
TraversedVoxels<double> traversed_voxels{};
const auto ray = Ray<double>::fromOriginEnd(ray_origin, ray_end);
const bool hit = traverseVoxelGrid(ray, grid, traversed_voxels);
if (hit) {
return py::cast(traversed_voxels);
} else {
// make sure to return empty array with correct shape [0, 3]
const py::array::ShapeContainer shape({0, 3});
return py::array_t<int64_t, py::array::c_style>(shape);
}
}
} // namespace pytraversal
PYBIND11_MODULE(pytraversal, m) {
using namespace pytraversal;
m.doc() = "pytraversal bindings";
py::class_<grid_type>(m, "Grid3D")
.def(py::init<>())
.def(py::init<const grid_type::Vector3d&, const grid_type::Vector3d&,
const grid_type::Index3d&>())
.def("traverse", traverse);
}
| 27.825 | 75 | 0.68823 | risteon |
d32d1de1a820b1b8bfc0d9799320170b7033bf32 | 3,351 | cpp | C++ | packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/core/src/MonteCarlo_AdjointPhotonProbeState.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_AdjointPhotonProbeState.cpp
//! \author Alex Robinson
//! \brief Adjoint photon probe state class declaration
//!
//---------------------------------------------------------------------------//
// FRENSIE Includes
#include "MonteCarlo_AdjointPhotonProbeState.hpp"
#include "Utility_ArchiveHelpers.hpp"
#include "Utility_ContractException.hpp"
namespace MonteCarlo{
// Constructor
AdjointPhotonProbeState::AdjointPhotonProbeState()
: AdjointPhotonState(),
d_active( false )
{ /* ... */ }
// Constructor
AdjointPhotonProbeState::AdjointPhotonProbeState(
const ParticleState::historyNumberType history_number )
: AdjointPhotonState( history_number, ADJOINT_PHOTON_PROBE ),
d_active( false )
{ /* ... */ }
// Copy constructor (with possible creation of new generation)
AdjointPhotonProbeState::AdjointPhotonProbeState(
const ParticleState& existing_base_state,
const bool increment_generation_number,
const bool reset_collision_number )
: AdjointPhotonState( existing_base_state,
ADJOINT_PHOTON_PROBE,
increment_generation_number,
reset_collision_number ),
d_active( false )
{ /* ... */ }
// Copy constructor (with possible creation of new generation)
AdjointPhotonProbeState::AdjointPhotonProbeState(
const AdjointPhotonProbeState& existing_base_state,
const bool increment_generation_number,
const bool reset_collision_number )
: AdjointPhotonState( existing_base_state,
ADJOINT_PHOTON_PROBE,
increment_generation_number,
reset_collision_number ),
d_active( false )
{ /* ... */ }
// Set the energy of the particle (MeV)
/*! \details An active probe particle gets killed when its energy changes. A
* probe particle should only be activated after its initial energy has been
* set.
*/
void AdjointPhotonProbeState::setEnergy( const energyType energy )
{
ParticleState::setEnergy( energy );
if( d_active )
this->setAsGone();
}
// Check if this is a probe
bool AdjointPhotonProbeState::isProbe() const
{
return true;
}
// Activate the probe
/*! \details Once a probe has been activated the next call to set energy
* will cause is to be killed.
*/
void AdjointPhotonProbeState::activate()
{
d_active = true;
}
// Returns if the probe is active
bool AdjointPhotonProbeState::isActive() const
{
return d_active;
}
// Clone the particle state (do not use to generate new particles!)
AdjointPhotonProbeState* AdjointPhotonProbeState::clone() const
{
return new AdjointPhotonProbeState( *this, false, false );
}
// Print the adjoint photon state
void AdjointPhotonProbeState::print( std::ostream& os ) const
{
os << "Particle Type: ";
if( d_active )
os << "Active ";
else
os << "Inactive ";
os << "Adjoint Photon Probe" << std::endl;
this->printImplementation<AdjointPhotonProbeState>( os );
}
} // end MonteCarlo namespace
UTILITY_CLASS_EXPORT_IMPLEMENT_SERIALIZE( MonteCarlo::AdjointPhotonProbeState);
BOOST_CLASS_EXPORT_IMPLEMENT( MonteCarlo::AdjointPhotonProbeState );
//---------------------------------------------------------------------------//
// end MonteCarlo_AdjointPhotonProbeState.cpp
//---------------------------------------------------------------------------//
| 28.887931 | 79 | 0.670248 | lkersting |
d32dfef64b2ca3e8da4825a88a07ae9a60a709fb | 5,485 | cpp | C++ | src/currency/Currency.cpp | MiKlTA/Lust_The_Game | aabe4a951ffd7305526466d378ba8b6769c555e8 | [
"MIT"
] | null | null | null | src/currency/Currency.cpp | MiKlTA/Lust_The_Game | aabe4a951ffd7305526466d378ba8b6769c555e8 | [
"MIT"
] | null | null | null | src/currency/Currency.cpp | MiKlTA/Lust_The_Game | aabe4a951ffd7305526466d378ba8b6769c555e8 | [
"MIT"
] | null | null | null | #include "Currency.h"
namespace lust {
Currency::Currency(const Fraction *owner, AmountType amount)
: m_fraction(owner),
m_amount(amount)
{
}
Currency::AmountType Currency::getAmount() const
{
return m_amount;
}
const Fraction * Currency::getFraction() const
{
return m_fraction;
}
const Currency Currency::operator+(Currency::AmountType cr) const
{
if (m_amount + cr > 0)
{
return Currency(m_fraction, m_amount + cr);
}
return Currency(m_fraction, 0);
}
const Currency Currency::operator-(Currency::AmountType cr) const
{
if (m_amount - cr > 0)
{
return Currency(m_fraction, m_amount - cr);
}
return Currency(m_fraction, 0);
}
const Currency Currency::operator*(Currency::AmountType cr) const
{
if (m_amount * cr > 0)
{
return Currency(m_fraction, m_amount * cr);
}
return Currency(m_fraction, 0);
}
const Currency Currency::operator%(Currency::AmountType cr) const
{
if (m_amount % cr > 0)
{
return Currency(m_fraction, m_amount % cr);
}
return Currency(m_fraction, 0);
}
const Currency Currency::operator/(Currency::AmountType cr) const
{
if (m_amount / cr > 0)
{
return Currency(m_fraction, m_amount / cr);
}
return Currency(m_fraction, 0);
}
const Currency Currency::operator+(const Currency &cr) const
{
return (*this) + cr.m_amount;
}
const Currency Currency::operator-(const Currency &cr) const
{
return (*this) - cr.m_amount;
}
const Currency Currency::operator*(const Currency &cr) const
{
return (*this) * cr.m_amount;
}
const Currency Currency::operator%(const Currency &cr) const
{
return (*this) % cr.m_amount;
}
const Currency Currency::operator/(const Currency &cr) const
{
return (*this) / cr.m_amount;
}
Currency & Currency::operator=(const Currency &cr)
{
m_amount = cr.m_amount;
return (*this);
}
Currency & Currency::operator=(AmountType num)
{
m_amount = num;
return (*this);
}
Currency & Currency::operator+=(AmountType cr)
{
(*this) = (*this) + cr;
return (*this);
}
Currency & Currency::operator-=(AmountType cr)
{
(*this) = (*this) - cr;
return (*this);
}
Currency & Currency::operator*=(AmountType cr)
{
(*this) = (*this) * cr;
return (*this);
}
Currency & Currency::operator%=(AmountType cr)
{
(*this) = (*this) % cr;
return (*this);
}
Currency & Currency::operator/=(AmountType cr)
{
(*this) = (*this) / cr;
return (*this);
}
Currency & Currency::operator+=(const Currency &cr)
{
(*this) = (*this) + cr.m_amount;
return (*this);
}
Currency & Currency::operator-=(const Currency &cr)
{
(*this) = (*this) - cr.m_amount;
return (*this);
}
Currency & Currency::operator*=(const Currency &cr)
{
(*this) = (*this) * cr.m_amount;
return (*this);
}
Currency & Currency::operator%=(const Currency &cr)
{
(*this) = (*this) % cr.m_amount;
return (*this);
}
Currency & Currency::operator/=(const Currency &cr)
{
(*this) = (*this) / cr.m_amount;
return (*this);
}
// private
bool Currency::isEqualFractions(const Currency &cr) const
{
return m_fraction == cr.m_fraction;
}
// global functions
const Currency operator+(Currency::AmountType lhs, const Currency &rhs)
{
return Currency(rhs + lhs);
}
const Currency operator-(Currency::AmountType lhs, const Currency &rhs)
{
return Currency(rhs * -1 + lhs);
}
const Currency operator*(Currency::AmountType lhs, const Currency &rhs)
{
return Currency(rhs * lhs);
}
const Currency operator%(Currency::AmountType lhs, const Currency &rhs)
{
return Currency(Currency(rhs.m_fraction, lhs) % rhs.m_amount);
}
const Currency operator/(Currency::AmountType lhs, const Currency &rhs)
{
return Currency(Currency(rhs.m_fraction, lhs) / rhs.m_amount);
}
bool operator==(const Currency &lhs, Currency::AmountType rhs)
{
return lhs.m_amount == rhs;
}
bool operator!=(const Currency &lhs, Currency::AmountType rhs)
{
return lhs.m_amount != rhs;
}
bool operator>(const Currency &lhs, Currency::AmountType rhs)
{
return lhs.m_amount > rhs;
}
bool operator<(const Currency &lhs, Currency::AmountType rhs)
{
return lhs.m_amount < rhs;
}
bool operator>=(const Currency &lhs, Currency::AmountType rhs)
{
return lhs.m_amount >= rhs;
}
bool operator<=(const Currency &lhs, Currency::AmountType rhs)
{
return lhs.m_amount <= rhs;
}
bool operator==(const Currency &lhs, const Currency &rhs)
{
if (lhs.isEqualFractions(rhs))
{
return lhs.m_amount == rhs.m_amount;
}
return false;
}
bool operator!=(const Currency &lhs, const Currency &rhs)
{
if (lhs.isEqualFractions(rhs))
{
return lhs.m_amount != rhs.m_amount;
}
return true;
}
bool operator>(const Currency &lhs, const Currency &rhs)
{
if (lhs.isEqualFractions(rhs))
{
return lhs.m_amount > rhs.m_amount;
}
return false;
}
bool operator<(const Currency &lhs, const Currency &rhs)
{
if (lhs.isEqualFractions(rhs))
{
return lhs.m_amount == rhs.m_amount;
}
return false;
}
bool operator>=(const Currency &lhs, const Currency &rhs)
{
if (lhs.isEqualFractions(rhs))
{
return lhs.m_amount == rhs.m_amount;
}
return false;
}
bool operator<=(const Currency &lhs, const Currency &rhs)
{
if (lhs.isEqualFractions(rhs))
{
return lhs.m_amount == rhs.m_amount;
}
return false;
}
}
| 17.693548 | 71 | 0.643938 | MiKlTA |
d33bb133a1fdb90b06f49c838296a88b112c8ecc | 925 | cpp | C++ | test/scheme.cpp | syoliver/url | 7a992f6aa758807bbcd2e92e413453da98ee0c3d | [
"BSL-1.0"
] | null | null | null | test/scheme.cpp | syoliver/url | 7a992f6aa758807bbcd2e92e413453da98ee0c3d | [
"BSL-1.0"
] | null | null | null | test/scheme.cpp | syoliver/url | 7a992f6aa758807bbcd2e92e413453da98ee0c3d | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2019 Vinnie Falco ([email protected])
//
// 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)
//
// Official repository: https://github.com/vinniefalco/url
//
// Test that header file is self-contained.
#include <boost/url/scheme.hpp>
#include "test_suite.hpp"
namespace boost {
namespace urls {
class scheme_test
{
public:
void
run()
{
BOOST_TEST(is_special("ftp"));
BOOST_TEST(is_special("file"));
BOOST_TEST(is_special("http"));
BOOST_TEST(is_special("https"));
BOOST_TEST(is_special("ws"));
BOOST_TEST(is_special("wss"));
BOOST_TEST(! is_special("gopher"));
BOOST_TEST(! is_special("magnet"));
BOOST_TEST(! is_special("mailto"));
}
};
TEST_SUITE(scheme_test, "boost.url.scheme");
} // urls
} // boost
| 22.560976 | 79 | 0.652973 | syoliver |
d3418780b49099787da948635bce7903710005cc | 1,853 | cpp | C++ | src/arguments.cpp | tsoding/ray-tracer | c8d189cc53445cae56bfb5e4f76926b93d0e67d5 | [
"MIT"
] | 16 | 2016-05-25T10:33:41.000Z | 2019-09-02T22:09:00.000Z | src/arguments.cpp | tsoding/ray-tracer | c8d189cc53445cae56bfb5e4f76926b93d0e67d5 | [
"MIT"
] | 67 | 2018-07-16T10:34:20.000Z | 2018-10-23T16:02:43.000Z | src/arguments.cpp | tsoding/ray-tracer | c8d189cc53445cae56bfb5e4f76926b93d0e67d5 | [
"MIT"
] | 5 | 2018-07-31T19:09:08.000Z | 2018-08-21T21:31:44.000Z | #include "./arguments.hpp"
#include <iostream>
#include <string>
Arguments::Arguments(int argc, char **argv):
m_argc(argc),
m_argv(argv),
m_threadCount(1),
m_width(800),
m_height(600) {
}
std::string Arguments::sceneFile() const {
return m_sceneFile;
}
std::string Arguments::outputFile() const {
return m_outputFile;
}
size_t Arguments::threadCount() const {
return m_threadCount;
}
size_t Arguments::width() const {
return m_width;
}
size_t Arguments::height() const {
return m_height;
}
bool Arguments::verify() {
int i = 1;
for (; i < m_argc; ++i) {
if (m_argv[i][0] == '-') {
if (m_argv[i] == std::string("-j")) {
// TODO(#83): Arguments option parsing doesn't check if the parameter of option is available
m_threadCount = std::stoul(m_argv[++i]);
} else if (m_argv[i] == std::string("-w")) {
m_width = std::stoul(m_argv[++i]);
} else if (m_argv[i] == std::string("-h")) {
m_height = std::stoul(m_argv[++i]);
} else {
std::cerr << "Unexpected option: "
<< m_argv[i]
<< std::endl;
return false;
}
} else {
break;
}
}
if (i < m_argc) {
m_sceneFile = m_argv[i++];
} else {
std::cerr << "Expected scene file"
<< std::endl;
return false;
}
if (i < m_argc) {
m_outputFile = m_argv[i++];
}
return true;
}
void Arguments::help() const {
std::cerr << "./ray-tracer "
<< "[-j <thread-count>] "
<< "[-w <width>] "
<< "[-h <height>]"
<< "<scene-file> "
<< "[output-file] "
<< std::endl;
}
| 22.876543 | 108 | 0.474366 | tsoding |
d34b9891822c636074a61aba3466baa8db63339d | 1,577 | tpp | C++ | src/base/program_options.tpp | heshu-by/likelib-ws | 85987d328dc274622f4b758afa1b6af43d15564f | [
"Apache-2.0"
] | 1 | 2020-10-23T19:09:27.000Z | 2020-10-23T19:09:27.000Z | src/base/program_options.tpp | heshu-by/likelib-ws | 85987d328dc274622f4b758afa1b6af43d15564f | [
"Apache-2.0"
] | null | null | null | src/base/program_options.tpp | heshu-by/likelib-ws | 85987d328dc274622f4b758afa1b6af43d15564f | [
"Apache-2.0"
] | 1 | 2020-12-08T11:16:30.000Z | 2020-12-08T11:16:30.000Z | #pragma once
#include "program_options.hpp"
#include "base/error.hpp"
namespace base
{
template<typename ValueType>
void ProgramOptionsParser::addOption(const std::string& flag, const std::string& help)
{
_options_description.add_options()(flag.c_str(), boost::program_options::value<ValueType>(), help.c_str());
}
template<typename ValueType>
void ProgramOptionsParser::addOption(const std::string& flag, ValueType defaultValue, const std::string& help)
{
_options_description.add_options()(
flag.c_str(), boost::program_options::value<ValueType>()->default_value(defaultValue), help.c_str());
}
template<typename ValueType>
void ProgramOptionsParser::addRequiredOption(const std::string& flag, const std::string& help)
{
_options_description.add_options()(
flag.c_str(), boost::program_options::value<ValueType>()->required(), help.c_str());
}
template<typename ValueType>
ValueType ProgramOptionsParser::getValue(const std::string& flag_name) const
{
if (!hasOption(flag_name)) {
RAISE_ERROR(base::ParsingError, std::string("No option with name: ") + flag_name);
}
try {
auto option = _options[flag_name].as<ValueType>();
return option;
}
catch (const boost::program_options::error& e) {
RAISE_ERROR(base::InvalidArgument, std::string("Incorrect option type: String"));
}
catch (const std::exception& e) {
RAISE_ERROR(base::InvalidArgument, e.what());
}
catch (...) {
RAISE_ERROR(base::InvalidArgument, "[unexpected error]");
}
}
} // namespace base
| 28.160714 | 111 | 0.700698 | heshu-by |
d34dd7b776401c3e51a2779909c902253f3aaf29 | 10,645 | cpp | C++ | ex2_ISALErasurecodeandrecovery/src/main.cpp | ingdex/isa-l | f487627d49441036fd0d40a04257745a9cb8fab0 | [
"BSD-3-Clause"
] | null | null | null | ex2_ISALErasurecodeandrecovery/src/main.cpp | ingdex/isa-l | f487627d49441036fd0d40a04257745a9cb8fab0 | [
"BSD-3-Clause"
] | null | null | null | ex2_ISALErasurecodeandrecovery/src/main.cpp | ingdex/isa-l | f487627d49441036fd0d40a04257745a9cb8fab0 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) <2017>, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "measurements.hpp"
#include "options.h"
#include "prealloc.h"
#include "random_number_generator.h"
#include "utils.hpp"
#include <algorithm>
#include <chrono>
#include <cstring>
#include <iostream>
#include <isa-l.h>
// Create the source data buffers with random data, plus extra room for the error correction codes.
// We create a total of 'm' buffers of lenght 'len'.
// The 'k' first buffers contain the data.
// The 'm-k' remaining buffer are left uninitialized, and will store the error correction codes.
uint8_t** create_source_data(int m, int k, int len)
{
uint8_t** sources = (uint8_t**)malloc(m * sizeof(uint8_t*));
random_number_generator<uint8_t> data_generator;
for (int i = 0; i < m; ++i)
{
sources[i] = (uint8_t*)malloc(len * sizeof(uint8_t));
if (i < k)
{
int j = 0;
for (; j < len / 64 * 64; j += 64)
{
memset(&sources[i][j], data_generator.get(), 64);
}
for (; j < len; ++j)
{
sources[i][j] = (uint8_t)data_generator.get();
}
}
}
return sources;
}
// Create the error correction codes, and store them alongside the data.
std::vector<uint8_t> encode_data(int m, int k, uint8_t** sources, int len, prealloc_encode prealloc)
{
// Generate encode matrix
gf_gen_cauchy1_matrix(prealloc.encode_matrix.data(), m, k);
// Generates the expanded tables needed for fast encoding
ec_init_tables(k, m - k, &prealloc.encode_matrix[k * k], prealloc.table.data());
// Actually generated the error correction codes
ec_encode_data(
len, k, m - k, prealloc.table.data(), (uint8_t**)sources, (uint8_t**)&sources[k]);
return prealloc.encode_matrix;
}
// We randomly choose up to 2 buffers to "lose", and return the indexes of those buffers.
// Note that we can lose both part of the data or part of the error correction codes indifferently.
std::vector<int> generate_errors(int m, int errors_count)
{
random_number_generator<int> idx_generator(0, m - 1);
std::vector<int> errors{idx_generator.get(), 0};
if (errors_count == 2)
{
do
{
errors[1] = idx_generator.get();
} while (errors[1] == errors[0]);
std::sort(errors.begin(), errors.end());
}
return errors;
}
// We arrange a new array of buffers that skip the ones we "lost"
uint8_t** create_erroneous_data(int k, uint8_t** source_data, std::vector<int> errors)
{
uint8_t** erroneous_data;
erroneous_data = (uint8_t**)malloc(k * sizeof(uint8_t*));
for (int i = 0, r = 0; i < k; ++i, ++r)
{
while (std::find(errors.cbegin(), errors.cend(), r) != errors.cend())
++r;
for (int j = 0; j < k; j++)
{
erroneous_data[i] = source_data[r];
}
}
return erroneous_data;
}
// Recover the contents of the "lost" buffers
// - m : the total number of buffer, containint both the source data and the error
// correction codes
// - k : the number of buffer that contain the source data
// - erroneous_data : the original buffers without the ones we "lost"
// - errors : the indexes of the buffers we "lost"
// - encode_matrix : the matrix used to generate the error correction codes
// - len : the length (in bytes) of each buffer
// Return the recovered "lost" buffers
uint8_t** recover_data(
int m,
int k,
uint8_t** erroneous_data,
const std::vector<int>& errors,
const std::vector<uint8_t>& encode_matrix,
int len,
prealloc_recover prealloc)
{
for (int i = 0, r = 0; i < k; ++i, ++r)
{
while (std::find(errors.cbegin(), errors.cend(), r) != errors.cend())
++r;
for (int j = 0; j < k; j++)
{
prealloc.errors_matrix[k * i + j] = encode_matrix[k * r + j];
}
}
gf_invert_matrix(prealloc.errors_matrix.data(), prealloc.invert_matrix.data(), k);
for (int e = 0; e < errors.size(); ++e)
{
int idx = errors[e];
if (idx < k) // We lost one of the buffers containing the data
{
for (int j = 0; j < k; j++)
{
prealloc.decode_matrix[k * e + j] = prealloc.invert_matrix[k * idx + j];
}
}
else // We lost one of the buffer containing the error correction codes
{
for (int i = 0; i < k; i++)
{
uint8_t s = 0;
for (int j = 0; j < k; j++)
s ^= gf_mul(prealloc.invert_matrix[j * k + i], encode_matrix[k * idx + j]);
prealloc.decode_matrix[k * e + i] = s;
}
}
}
ec_init_tables(k, m - k, prealloc.decode_matrix.data(), prealloc.table.data());
ec_encode_data(len, k, (m - k), prealloc.table.data(), erroneous_data, prealloc.decoding);
return prealloc.decoding;
}
// Performs 1 storage/recovery cycle, and returns the storage and recovery time.
// - m : the total number of buffer, that will contain both the source data and the
// error correction codes
// - k : the number of buffer that will contain the source data
// - len : the length (in bytes) of each buffer
// - errors_count : the number of buffer to lose (must be equal to m-k)
measurements iteration(int m, int k, int len, int errors_count)
{
uint8_t** source_data = create_source_data(m, k, len);
prealloc_encode prealloc_encode(m, k);
auto start_storage = std::chrono::steady_clock::now();
std::vector<uint8_t> encode_matrix =
encode_data(m, k, source_data, len, std::move(prealloc_encode));
auto end_storage = std::chrono::steady_clock::now();
std::vector<int> errors = generate_errors(m, errors_count);
uint8_t** erroneous_data = create_erroneous_data(k, source_data, errors);
prealloc_recover prealloc_recover(m, k, errors.size(), len);
auto start_recovery = std::chrono::steady_clock::now();
uint8_t** decoding =
recover_data(m, k, erroneous_data, errors, encode_matrix, len, std::move(prealloc_recover));
auto end_recovery = std::chrono::steady_clock::now();
bool success = false;
for (int i = 0; i < errors.size(); ++i)
{
int ret = memcmp(source_data[errors[i]], decoding[i], len);
success = (ret == 0);
}
free(erroneous_data);
for (int i = 0; i < m; ++i)
{
free(source_data[i]);
}
free(source_data);
for (int i = 0; i < errors_count; ++i)
{
free(decoding[i]);
}
free(decoding);
if (!success)
return {std::chrono::nanoseconds{0}, std::chrono::nanoseconds{0}};
return {end_storage - start_storage, end_recovery - start_recovery};
}
int main(int argc, char* argv[])
{
using namespace std::chrono_literals;
options options = options::parse(argc, argv);
utils::display_info(options);
int m = options.buffer_count;
int k = options.buffer_count - options.lost_buffers;
int len = options.dataset_size / (options.buffer_count - options.lost_buffers);
int errors_count = options.lost_buffers;
std::cout << "[Info ] Perfoming benchmark...\n";
std::cout << "[Info ] 0 % done" << std::flush;
measurements total_measurements;
int iterations = 0;
auto start_time = std::chrono::steady_clock::now();
do
{
measurements new_measurement = iteration(m, k, len, errors_count);
if (new_measurement.storage > 0s && new_measurement.recovery > 0s)
{
++iterations;
total_measurements += new_measurement;
if (std::chrono::steady_clock::now() - start_time > 1s)
{
auto estimated_iterations =
std::min(10000l, (1s / (total_measurements.recovery / iterations)));
auto estimated_runtime =
estimated_iterations *
((std::chrono::steady_clock::now() - start_time) / iterations);
if (estimated_runtime > 5s && iterations % (estimated_iterations / 10) == 0)
std::cout << "\r[Info ] "
<< (int)(((double)iterations / estimated_iterations) * 100)
<< " % done" << std::flush;
}
}
} while (iterations < 10000 &&
(total_measurements.storage < 1s || total_measurements.recovery < 1s));
std::cout << "\r[Info ] 100 % done\n";
if (iterations > 1)
std::cout << "[Info ] Average results over " << iterations << " iterations:\n";
std::cout << "[Info ] Storage time: "
<< utils::duration_to_string(total_measurements.storage / iterations) << "\n";
std::cout << "[Info ] Recovery time: "
<< utils::duration_to_string(total_measurements.recovery / iterations) << "\n";
}
| 37.882562 | 100 | 0.607609 | ingdex |
d3590896e0df90b8defc4bcdd125e8879cad1434 | 5,290 | cpp | C++ | src/routine.cpp | gcp/CLBlast | 7c13bacf129291e3e295ecb6e833788477085fa0 | [
"Apache-2.0"
] | 1 | 2021-01-01T05:20:33.000Z | 2021-01-01T05:20:33.000Z | src/routine.cpp | gcp/CLBlast | 7c13bacf129291e3e295ecb6e833788477085fa0 | [
"Apache-2.0"
] | null | null | null | src/routine.cpp | gcp/CLBlast | 7c13bacf129291e3e295ecb6e833788477085fa0 | [
"Apache-2.0"
] | null | null | null |
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This file implements the Routine base class (see the header for information about the class).
//
// =================================================================================================
#include <string>
#include <vector>
#include "routine.hpp"
namespace clblast {
// =================================================================================================
// Constructor: not much here, because no status codes can be returned
Routine::Routine(Queue &queue, EventPointer event, const std::string &name,
const std::vector<std::string> &routines, const Precision precision):
precision_(precision),
routine_name_(name),
queue_(queue),
event_(event),
context_(queue_.GetContext()),
device_(queue_.GetDevice()),
device_name_(device_.Name()),
db_(queue_, routines, precision_) {
}
// =================================================================================================
// Separate set-up function to allow for status codes to be returned
StatusCode Routine::SetUp() {
// Queries the cache to see whether or not the program (context-specific) is already there
if (ProgramIsInCache(context_, precision_, routine_name_)) { return StatusCode::kSuccess; }
// Queries the cache to see whether or not the binary (device-specific) is already there. If it
// is, a program is created and stored in the cache
if (BinaryIsInCache(device_name_, precision_, routine_name_)) {
try {
auto& binary = GetBinaryFromCache(device_name_, precision_, routine_name_);
auto program = Program(device_, context_, binary);
auto options = std::vector<std::string>();
program.Build(device_, options);
StoreProgramToCache(program, context_, precision_, routine_name_);
} catch (...) { return StatusCode::kBuildProgramFailure; }
return StatusCode::kSuccess;
}
// Otherwise, the kernel will be compiled and program will be built. Both the binary and the
// program will be added to the cache.
// Inspects whether or not cl_khr_fp64 is supported in case of double precision
const auto extensions = device_.Capabilities();
if (precision_ == Precision::kDouble || precision_ == Precision::kComplexDouble) {
if (extensions.find(kKhronosDoublePrecision) == std::string::npos) {
return StatusCode::kNoDoublePrecision;
}
}
// As above, but for cl_khr_fp16 (half precision)
if (precision_ == Precision::kHalf) {
if (extensions.find(kKhronosHalfPrecision) == std::string::npos) {
return StatusCode::kNoHalfPrecision;
}
}
// Loads the common header (typedefs and defines and such)
std::string common_header =
#include "kernels/common.opencl"
;
// Collects the parameters for this device in the form of defines, and adds the precision
auto defines = db_.GetDefines();
defines += "#define PRECISION "+ToString(static_cast<int>(precision_))+"\n";
// Adds the name of the routine as a define
defines += "#define ROUTINE_"+routine_name_+"\n";
// For specific devices, use the non-IEE754 compilant OpenCL mad() instruction. This can improve
// performance, but might result in a reduced accuracy.
if (device_.IsAMD() && device_.IsGPU()) {
defines += "#define USE_CL_MAD 1\n";
}
// For specific devices, use staggered/shuffled workgroup indices.
if (device_.IsAMD() && device_.IsGPU()) {
defines += "#define USE_STAGGERED_INDICES 1\n";
}
// For specific devices add a global synchronisation barrier to the GEMM kernel to optimize
// performance through better cache behaviour
if (device_.IsARM() && device_.IsGPU()) {
defines += "#define GLOBAL_MEM_FENCE 1\n";
}
// Combines everything together into a single source string
const auto source_string = defines + common_header + source_string_;
// Compiles the kernel
try {
auto program = Program(context_, source_string);
auto options = std::vector<std::string>();
const auto build_status = program.Build(device_, options);
// Checks for compiler crashes/errors/warnings
if (build_status == BuildStatus::kError) {
const auto message = program.GetBuildInfo(device_);
fprintf(stdout, "OpenCL compiler error/warning: %s\n", message.c_str());
return StatusCode::kBuildProgramFailure;
}
if (build_status == BuildStatus::kInvalid) { return StatusCode::kInvalidBinary; }
// Store the compiled binary and program in the cache
const auto binary = program.GetIR();
StoreBinaryToCache(binary, device_name_, precision_, routine_name_);
StoreProgramToCache(program, context_, precision_, routine_name_);
} catch (...) { return StatusCode::kBuildProgramFailure; }
// No errors, normal termination of this function
return StatusCode::kSuccess;
}
// =================================================================================================
} // namespace clblast
| 40.075758 | 100 | 0.644423 | gcp |
d35c8e3ba7c5010219d211d66032fc183eafb3a6 | 7,551 | cc | C++ | src/pf_manager.cc | jinzy15/CourseDataBaseTHU | af3a9abc1d887c674064ab823c4b9a1dcb810630 | [
"MIT"
] | 190 | 2015-01-08T14:26:25.000Z | 2022-03-21T17:43:52.000Z | src/pf_manager.cc | jinzy15/CourseDataBaseTHU | af3a9abc1d887c674064ab823c4b9a1dcb810630 | [
"MIT"
] | 4 | 2018-11-07T17:42:31.000Z | 2018-11-22T16:23:17.000Z | src/pf_manager.cc | jinzy15/CourseDataBaseTHU | af3a9abc1d887c674064ab823c4b9a1dcb810630 | [
"MIT"
] | 91 | 2015-01-07T08:13:38.000Z | 2022-03-10T04:35:44.000Z | //
// File: pf_manager.cc
// Description: PF_Manager class implementation
// Authors: Hugo Rivero ([email protected])
// Dallan Quass ([email protected])
//
#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "pf_internal.h"
#include "pf_buffermgr.h"
//
// PF_Manager
//
// Desc: Constructor - intended to be called once at begin of program
// Handles creation, deletion, opening and closing of files.
// It is associated with a PF_BufferMgr that manages the page
// buffer and executes the page replacement policies.
//
PF_Manager::PF_Manager()
{
// Create Buffer Manager
pBufferMgr = new PF_BufferMgr(PF_BUFFER_SIZE);
}
//
// ~PF_Manager
//
// Desc: Destructor - intended to be called once at end of program
// Destroys the buffer manager.
// All files are expected to be closed when this method is called.
//
PF_Manager::~PF_Manager()
{
// Destroy the buffer manager objects
delete pBufferMgr;
}
//
// CreateFile
//
// Desc: Create a new PF file named fileName
// In: fileName - name of file to create
// Ret: PF return code
//
RC PF_Manager::CreateFile (const char *fileName)
{
int fd; // unix file descriptor
int numBytes; // return code form write syscall
// Create file for exclusive use
if ((fd = open(fileName,
#ifdef PC
O_BINARY |
#endif
O_CREAT | O_EXCL | O_WRONLY,
CREATION_MASK)) < 0)
return (PF_UNIX);
// Initialize the file header: must reserve FileHdrSize bytes in memory
// though the actual size of FileHdr is smaller
char hdrBuf[PF_FILE_HDR_SIZE];
// So that Purify doesn't complain
memset(hdrBuf, 0, PF_FILE_HDR_SIZE);
PF_FileHdr *hdr = (PF_FileHdr*)hdrBuf;
hdr->firstFree = PF_PAGE_LIST_END;
hdr->numPages = 0;
// Write header to file
if((numBytes = write(fd, hdrBuf, PF_FILE_HDR_SIZE))
!= PF_FILE_HDR_SIZE) {
// Error while writing: close and remove file
close(fd);
unlink(fileName);
// Return an error
if(numBytes < 0)
return (PF_UNIX);
else
return (PF_HDRWRITE);
}
// Close file
if(close(fd) < 0)
return (PF_UNIX);
// Return ok
return (0);
}
//
// DestroyFile
//
// Desc: Delete a PF file named fileName (fileName must exist and not be open)
// In: fileName - name of file to delete
// Ret: PF return code
//
RC PF_Manager::DestroyFile (const char *fileName)
{
// Remove the file
if (unlink(fileName) < 0)
return (PF_UNIX);
// Return ok
return (0);
}
//
// OpenFile
//
// Desc: Open the paged file whose name is "fileName". It is possible to open
// a file more than once, however, it will be treated as 2 separate files
// (different file descriptors; different buffers). Thus, opening a file
// more than once for writing may corrupt the file, and can, in certain
// circumstances, crash the PF layer. Note that even if only one instance
// of a file is for writing, problems may occur because some writes may
// not be seen by a reader of another instance of the file.
// In: fileName - name of file to open
// Out: fileHandle - refer to the open file
// this function modifies local var's in fileHandle
// to point to the file data in the file table, and to point to the
// buffer manager object
// Ret: PF_FILEOPEN or other PF return code
//
RC PF_Manager::OpenFile (const char *fileName, PF_FileHandle &fileHandle)
{
int rc; // return code
// Ensure file is not already open
if (fileHandle.bFileOpen)
return (PF_FILEOPEN);
// Open the file
if ((fileHandle.unixfd = open(fileName,
#ifdef PC
O_BINARY |
#endif
O_RDWR)) < 0)
return (PF_UNIX);
// Read the file header
{
int numBytes = read(fileHandle.unixfd, (char *)&fileHandle.hdr,
sizeof(PF_FileHdr));
if (numBytes != sizeof(PF_FileHdr)) {
rc = (numBytes < 0) ? PF_UNIX : PF_HDRREAD;
goto err;
}
}
// Set file header to be not changed
fileHandle.bHdrChanged = FALSE;
// Set local variables in file handle object to refer to open file
fileHandle.pBufferMgr = pBufferMgr;
fileHandle.bFileOpen = TRUE;
// Return ok
return 0;
err:
// Close file
close(fileHandle.unixfd);
fileHandle.bFileOpen = FALSE;
// Return error
return (rc);
}
//
// CloseFile
//
// Desc: Close file associated with fileHandle
// The file should have been opened with OpenFile().
// Also, flush all pages for the file from the page buffer
// It is an error to close a file with pages still fixed in the buffer.
// In: fileHandle - handle of file to close
// Out: fileHandle - no longer refers to an open file
// this function modifies local var's in fileHandle
// Ret: PF return code
//
RC PF_Manager::CloseFile(PF_FileHandle &fileHandle)
{
RC rc;
// Ensure fileHandle refers to open file
if (!fileHandle.bFileOpen)
return (PF_CLOSEDFILE);
// Flush all buffers for this file and write out the header
if ((rc = fileHandle.FlushPages()))
return (rc);
// Close the file
if (close(fileHandle.unixfd) < 0)
return (PF_UNIX);
fileHandle.bFileOpen = FALSE;
// Reset the buffer manager pointer in the file handle
fileHandle.pBufferMgr = NULL;
// Return ok
return 0;
}
//
// ClearBuffer
//
// Desc: Remove all entries from the buffer manager.
// This routine will be called via the system command and is only
// really useful if the user wants to run some performance
// comparison starting with an clean buffer.
// In: Nothing
// Out: Nothing
// Ret: Returns the result of PF_BufferMgr::ClearBuffer
// It is a code: 0 for success, something else for a PF error.
//
RC PF_Manager::ClearBuffer()
{
return pBufferMgr->ClearBuffer();
}
//
// PrintBuffer
//
// Desc: Display all of the pages within the buffer.
// This routine will be called via the system command.
// In: Nothing
// Out: Nothing
// Ret: Returns the result of PF_BufferMgr::PrintBuffer
// It is a code: 0 for success, something else for a PF error.
//
RC PF_Manager::PrintBuffer()
{
return pBufferMgr->PrintBuffer();
}
//
// ResizeBuffer
//
// Desc: Resizes the buffer manager to the size passed in.
// This routine will be called via the system command.
// In: The new buffer size
// Out: Nothing
// Ret: Returns the result of PF_BufferMgr::ResizeBuffer
// It is a code: 0 for success, PF_TOOSMALL when iNewSize
// would be too small.
//
RC PF_Manager::ResizeBuffer(int iNewSize)
{
return pBufferMgr->ResizeBuffer(iNewSize);
}
//------------------------------------------------------------------------------
// Three Methods for manipulating raw memory buffers. These memory
// locations are handled by the buffer manager, but are not
// associated with a particular file. These should be used if you
// want memory that is bounded by the size of the buffer pool.
//
// The PF_Manager just passes the calls down to the Buffer manager.
//------------------------------------------------------------------------------
RC PF_Manager::GetBlockSize(int &length) const
{
return pBufferMgr->GetBlockSize(length);
}
RC PF_Manager::AllocateBlock(char *&buffer)
{
return pBufferMgr->AllocateBlock(buffer);
}
RC PF_Manager::DisposeBlock(char *buffer)
{
return pBufferMgr->DisposeBlock(buffer);
}
| 26.588028 | 80 | 0.649186 | jinzy15 |
d35f6cd973ec7a2b3bdab72b31db67f7fb5e4a5c | 680 | hpp | C++ | Object.hpp | Xiangze-Li/CG_Final | 6dc33457d6890e6cff8e327b004f76e9ed7d9615 | [
"MIT"
] | 2 | 2020-07-22T01:56:41.000Z | 2022-01-08T14:59:40.000Z | Object.hpp | Xiangze-Li/CG_Final | 6dc33457d6890e6cff8e327b004f76e9ed7d9615 | [
"MIT"
] | null | null | null | Object.hpp | Xiangze-Li/CG_Final | 6dc33457d6890e6cff8e327b004f76e9ed7d9615 | [
"MIT"
] | 1 | 2021-08-04T05:03:26.000Z | 2021-08-04T05:03:26.000Z | #pragma once
#include "utils.hpp"
#include "Texture.hpp"
#include "Ray.hpp"
#include "Hit.hpp"
class Object
{
protected:
Texture *_texture;
public:
Object() : _texture(nullptr) {}
explicit Object(Texture *texture) : _texture(texture) {}
virtual ~Object() = default;
virtual bool intersect(const Ray &, Hit &) const = 0;
// @return GUARANTEE that first.x/y/z < second.x/y/z respectively.
virtual AABBcord AABB() const = 0;
Texture *texture() const { return _texture; }
};
#include "Obj_Geometry.hpp"
#include "Obj_BVH.hpp"
#include "Obj_Mesh.hpp"
#include "Obj_Group.hpp"
// #include "Obj_Bezier.hpp" CANCELLED
| 21.935484 | 72 | 0.648529 | Xiangze-Li |
d36606f218f0a139490b7efa4cfa186372a5018e | 5,637 | cpp | C++ | unicode_back/character_categories/other_format.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | unicode_back/character_categories/other_format.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | unicode_back/character_categories/other_format.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | #include "other_format.hpp"
namespace {
constexpr std::pair<char32_t, char32_t> make_point(char32_t point)
{
return std::pair<char32_t, char32_t>(point, point);
}
static const std::vector<std::pair<char32_t, char32_t>> characters
{
make_point(0xAD),
{0x600, 0x605},
make_point(0x61C),
make_point(0x6DD),
make_point(0x70F),
make_point(0x180E),
{0x200B, 0x200F},
{0x202A, 0x202E},
{0x2060, 0x2064},
{0x2066, 0x206F},
make_point(0xFEFF),
{0xFFF9, 0xFFFB},
make_point(0x110BD),
{0x1BCA0, 0x1BCA3},
{0x1D173, 0x1D17A},
make_point(0xE0001),
{0xE0020, 0xE007F}
};
}
/*
Character Name
U+00AD SOFT HYPHEN
U+0600 ARABIC NUMBER SIGN
U+0601 ARABIC SIGN SANAH
U+0602 ARABIC FOOTNOTE MARKER
U+0603 ARABIC SIGN SAFHA
U+0604 ARABIC SIGN SAMVAT
U+0605 ARABIC NUMBER MARK ABOVE
U+061C ARABIC LETTER MARK
U+06DD ARABIC END OF AYAH
U+070F SYRIAC ABBREVIATION MARK
U+180E MONGOLIAN VOWEL SEPARATOR
U+200B ZERO WIDTH SPACE
U+200C ZERO WIDTH NON-JOINER
U+200D ZERO WIDTH JOINER
U+200E LEFT-TO-RIGHT MARK
U+200F RIGHT-TO-LEFT MARK
U+202A LEFT-TO-RIGHT EMBEDDING
U+202B RIGHT-TO-LEFT EMBEDDING
U+202C POP DIRECTIONAL FORMATTING
U+202D LEFT-TO-RIGHT OVERRIDE
U+202E RIGHT-TO-LEFT OVERRIDE
U+2060 WORD JOINER
U+2061 FUNCTION APPLICATION
U+2062 INVISIBLE TIMES
U+2063 INVISIBLE SEPARATOR
U+2064 INVISIBLE PLUS
U+2066 LEFT-TO-RIGHT ISOLATE
U+2067 RIGHT-TO-LEFT ISOLATE
U+2068 FIRST STRONG ISOLATE
U+2069 POP DIRECTIONAL ISOLATE
U+206A INHIBIT SYMMETRIC SWAPPING
U+206B ACTIVATE SYMMETRIC SWAPPING
U+206C INHIBIT ARABIC FORM SHAPING
U+206D ACTIVATE ARABIC FORM SHAPING
U+206E NATIONAL DIGIT SHAPES
U+206F NOMINAL DIGIT SHAPES
U+FEFF ZERO WIDTH NO-BREAK SPACE
U+FFF9 INTERLINEAR ANNOTATION ANCHOR
U+FFFA INTERLINEAR ANNOTATION SEPARATOR
U+FFFB INTERLINEAR ANNOTATION TERMINATOR
U+110BD KAITHI NUMBER SIGN
U+1BCA0 SHORTHAND FORMAT LETTER OVERLAP
U+1BCA1 SHORTHAND FORMAT CONTINUING OVERLAP
U+1BCA2 SHORTHAND FORMAT DOWN STEP
U+1BCA3 SHORTHAND FORMAT UP STEP
U+1D173 MUSICAL SYMBOL BEGIN BEAM
U+1D174 MUSICAL SYMBOL END BEAM
U+1D175 MUSICAL SYMBOL BEGIN TIE
U+1D176 MUSICAL SYMBOL END TIE
U+1D177 MUSICAL SYMBOL BEGIN SLUR
U+1D178 MUSICAL SYMBOL END SLUR
U+1D179 MUSICAL SYMBOL BEGIN PHRASE
U+1D17A MUSICAL SYMBOL END PHRASE
U+E0001 LANGUAGE TAG
U+E0020 TAG SPACE
U+E0021 TAG EXCLAMATION MARK
U+E0022 TAG QUOTATION MARK
U+E0023 TAG NUMBER SIGN
U+E0024 TAG DOLLAR SIGN
U+E0025 TAG PERCENT SIGN
U+E0026 TAG AMPERSAND
U+E0027 TAG APOSTROPHE
U+E0028 TAG LEFT PARENTHESIS
U+E0029 TAG RIGHT PARENTHESIS
U+E002A TAG ASTERISK
U+E002B TAG PLUS SIGN
U+E002C TAG COMMA
U+E002D TAG HYPHEN-MINUS
U+E002E TAG FULL STOP
U+E002F TAG SOLIDUS
U+E0030 TAG DIGIT ZERO
U+E0031 TAG DIGIT ONE
U+E0032 TAG DIGIT TWO
U+E0033 TAG DIGIT THREE
U+E0034 TAG DIGIT FOUR
U+E0035 TAG DIGIT FIVE
U+E0036 TAG DIGIT SIX
U+E0037 TAG DIGIT SEVEN
U+E0038 TAG DIGIT EIGHT
U+E0039 TAG DIGIT NINE
U+E003A TAG COLON
U+E003B TAG SEMICOLON
U+E003C TAG LESS-THAN SIGN
U+E003D TAG EQUALS SIGN
U+E003E TAG GREATER-THAN SIGN
U+E003F TAG QUESTION MARK
U+E0040 TAG COMMERCIAL AT
U+E0041 TAG LATIN CAPITAL LETTER A
U+E0042 TAG LATIN CAPITAL LETTER B
U+E0043 TAG LATIN CAPITAL LETTER C
U+E0044 TAG LATIN CAPITAL LETTER D
U+E0045 TAG LATIN CAPITAL LETTER E
U+E0046 TAG LATIN CAPITAL LETTER F
U+E0047 TAG LATIN CAPITAL LETTER G
U+E0048 TAG LATIN CAPITAL LETTER H
U+E0049 TAG LATIN CAPITAL LETTER I
U+E004A TAG LATIN CAPITAL LETTER J
U+E004B TAG LATIN CAPITAL LETTER K
U+E004C TAG LATIN CAPITAL LETTER L
U+E004D TAG LATIN CAPITAL LETTER M
U+E004E TAG LATIN CAPITAL LETTER N
U+E004F TAG LATIN CAPITAL LETTER O
U+E0050 TAG LATIN CAPITAL LETTER P
U+E0051 TAG LATIN CAPITAL LETTER Q
U+E0052 TAG LATIN CAPITAL LETTER R
U+E0053 TAG LATIN CAPITAL LETTER S
U+E0054 TAG LATIN CAPITAL LETTER T
U+E0055 TAG LATIN CAPITAL LETTER U
U+E0056 TAG LATIN CAPITAL LETTER V
U+E0057 TAG LATIN CAPITAL LETTER W
U+E0058 TAG LATIN CAPITAL LETTER X
U+E0059 TAG LATIN CAPITAL LETTER Y
U+E005A TAG LATIN CAPITAL LETTER Z
U+E005B TAG LEFT SQUARE BRACKET
U+E005C TAG REVERSE SOLIDUS
U+E005D TAG RIGHT SQUARE BRACKET
U+E005E TAG CIRCUMFLEX ACCENT
U+E005F TAG LOW LINE
U+E0060 TAG GRAVE ACCENT
U+E0061 TAG LATIN SMALL LETTER A
U+E0062 TAG LATIN SMALL LETTER B
U+E0063 TAG LATIN SMALL LETTER C
U+E0064 TAG LATIN SMALL LETTER D
U+E0065 TAG LATIN SMALL LETTER E
U+E0066 TAG LATIN SMALL LETTER F
U+E0067 TAG LATIN SMALL LETTER G
U+E0068 TAG LATIN SMALL LETTER H
U+E0069 TAG LATIN SMALL LETTER I
U+E006A TAG LATIN SMALL LETTER J
U+E006B TAG LATIN SMALL LETTER K
U+E006C TAG LATIN SMALL LETTER L
U+E006D TAG LATIN SMALL LETTER M
U+E006E TAG LATIN SMALL LETTER N
U+E006F TAG LATIN SMALL LETTER O
U+E0070 TAG LATIN SMALL LETTER P
U+E0071 TAG LATIN SMALL LETTER Q
U+E0072 TAG LATIN SMALL LETTER R
U+E0073 TAG LATIN SMALL LETTER S
U+E0074 TAG LATIN SMALL LETTER T
U+E0075 TAG LATIN SMALL LETTER U
U+E0076 TAG LATIN SMALL LETTER V
U+E0077 TAG LATIN SMALL LETTER W
U+E0078 TAG LATIN SMALL LETTER X
U+E0079 TAG LATIN SMALL LETTER Y
U+E007A TAG LATIN SMALL LETTER Z
U+E007B TAG LEFT CURLY BRACKET
U+E007C TAG VERTICAL LINE
U+E007D TAG RIGHT CURLY BRACKET
U+E007E TAG TILDE
U+E007F CANCEL TAG
*/
| 30.47027 | 68 | 0.716516 | do-m-en |
d36c891c8cba712fb90e067aa9173c862c8ba09a | 1,003 | cpp | C++ | BOJ/boj10871.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | BOJ/boj10871.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | BOJ/boj10871.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <climits>
#include <algorithm>
using namespace std;
int w[10][10];
int route[10];
int mn = INT_MAX;
int main()
{
int n, tmp, src, dest;
bool possible, necessary;
scanf("%d", &n);
for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) scanf("%d", &w[i][j]);
for(int i = 0; i < n; i++) route[i] = i;
do
{
tmp = 0;
possible = true;
necessary = true;
for(int i = 1; i <= n; i++)
{
src = route[i - 1 % n];
dest = route[i % n];
if(!w[src][dest])
{
possible = false;
break;
}
tmp += w[src][dest];
if(tmp > mn)
{
necessary = false;
break;
}
}
if(!possible || !necessary) continue;
mn = min(mn, tmp);
} while (next_permutation(route, route + n));
printf("%d\n", mn);
return 0;
} | 19.288462 | 82 | 0.401795 | SukJinKim |
d36e937a9dcdf0811fcdb26b65fa1591b5ea25fc | 39 | hpp | C++ | src/boost_numeric_ublas_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_numeric_ublas_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_numeric_ublas_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/numeric/ublas/fwd.hpp>
| 19.5 | 38 | 0.769231 | miathedev |
d37668c5c67a86224709a7f9157c3b17028e6c1d | 829 | cpp | C++ | Intro_a_C++/codcad-5-questao01.cpp | taylorkcantalice/intro_a_programacao | 141e33f0b6cc227a4cc7b75701b603fcf53e2378 | [
"MIT"
] | null | null | null | Intro_a_C++/codcad-5-questao01.cpp | taylorkcantalice/intro_a_programacao | 141e33f0b6cc227a4cc7b75701b603fcf53e2378 | [
"MIT"
] | null | null | null | Intro_a_C++/codcad-5-questao01.cpp | taylorkcantalice/intro_a_programacao | 141e33f0b6cc227a4cc7b75701b603fcf53e2378 | [
"MIT"
] | null | null | null | /**
============================================================================
Nome : codcad-5-questao01.cpp
Autor : Taylor Klaus Cantalice Nobrega - 20200004268 (UFPB)
Versao : 1.0
Copyright : Your copyright notice
Descricao : Titulo
============================================================================
**/
#include <iostream>
using namespace std;
string title(string F){
int i;
if(F[0] >= 'a' && F[0] <= 'z'){
F[0] = (char)(F[0]-32);
}
for(i = 1; i <= F.size(); i++){
if(F[i-1] != ' ' && F[i] >= 'A' && F[i] <= 'Z'){
F[i] = (char)(F[i]+32);
}
if(F[i-1] == ' ' && F[i] >= 'a' && F[i] <= 'z'){
F[i] = (char)(F[i]-32);
}
}
return F;
}
int main(){
string F;
getline(cin, F);
cout << title(F) << "\n";
}
| 20.725 | 77 | 0.349819 | taylorkcantalice |
c96b1fd93b62c37e2aac83768642b471e45b5e59 | 2,820 | cpp | C++ | src/SharpProj/CoordinateReferenceSystemInfo.cpp | AmpScm/ProjSharp | d112527174a3e5f9864b9f94e12c288322a5765e | [
"Apache-2.0"
] | 5 | 2021-02-15T13:56:34.000Z | 2022-03-22T10:49:01.000Z | src/SharpProj/CoordinateReferenceSystemInfo.cpp | AmpScm/SharpProj | ab16164635930d357bcbc81b8bd71d308b6b105e | [
"Apache-2.0"
] | 9 | 2021-03-05T15:32:58.000Z | 2022-02-24T08:44:16.000Z | src/SharpProj/CoordinateReferenceSystemInfo.cpp | FObermaier/SharpProj | d112527174a3e5f9864b9f94e12c288322a5765e | [
"Apache-2.0"
] | 4 | 2021-02-16T12:41:54.000Z | 2022-02-25T09:34:22.000Z | #include "pch.h"
#include "ProjObject.h"
#include "CoordinateReferenceSystem.h"
#include "CoordinateReferenceSystemInfo.h"
private ref class CRSComparer : System::Collections::Generic::IComparer<CoordinateReferenceSystemInfo^>
{
public:
// Inherited via IComparer
virtual int Compare(SharpProj::Proj::CoordinateReferenceSystemInfo^ x, SharpProj::Proj::CoordinateReferenceSystemInfo^ y)
{
int n = StringComparer::OrdinalIgnoreCase->Compare(x->Authority, y->Authority);
if (n != 0)
return n;
int xi, yi;
if (int::TryParse(x->Code, xi) && int::TryParse(y->Code, yi))
{
n = xi - yi;
if (n != 0)
return n;
}
return StringComparer::OrdinalIgnoreCase->Compare(x->Name, y->Name);
}
static initonly CRSComparer^ Instance = gcnew CRSComparer();
};
ReadOnlyCollection<CoordinateReferenceSystemInfo^>^ ProjContext::GetCoordinateReferenceSystems(CoordinateReferenceSystemFilter^ filter)
{
if (!filter)
throw gcnew ArgumentNullException("filter");
std::string auth_name;
if (filter->Authority)
auth_name = ::utf8_string(filter->Authority);
PROJ_CRS_LIST_PARAMETERS* params = proj_get_crs_list_parameters_create();
try
{
auto types = filter->Types->ToArray();
pin_ptr<ProjType> pTypes;
if (types->Length)
{
pTypes = &types[0];
params->typesCount = types->Length;
params->types = reinterpret_cast<PJ_TYPE*>(pTypes);
}
params->allow_deprecated = filter->AllowDeprecated;
if (filter->CoordinateArea)
{
params->bbox_valid = true;
params->west_lon_degree = filter->CoordinateArea->WestLongitude;
params->south_lat_degree = filter->CoordinateArea->SouthLatitude;
params->east_lon_degree = filter->CoordinateArea->EastLongitude;
params->north_lat_degree = filter->CoordinateArea->NorthLatitude;
params->crs_area_of_use_contains_bbox = filter->CompletelyContainsArea;
}
int count;
array<CoordinateReferenceSystemInfo^> ^result;
PROJ_CRS_INFO** infoList = proj_get_crs_info_list_from_database(this, auth_name.length() ? auth_name.c_str() : nullptr, params, &count);
try
{
result = gcnew array<CoordinateReferenceSystemInfo^>(count);
for (int i = 0; i < count; i++)
result[i] = gcnew CoordinateReferenceSystemInfo(infoList[i], this);
}
finally
{
proj_crs_info_list_destroy(infoList);
}
Array::Sort(result, CRSComparer::Instance);
return Array::AsReadOnly(result);
}
finally
{
proj_get_crs_list_parameters_destroy(params);
}
}
ReadOnlyCollection<CoordinateReferenceSystemInfo^>^ ProjContext::GetCoordinateReferenceSystems()
{
return GetCoordinateReferenceSystems(gcnew CoordinateReferenceSystemFilter());
}
CoordinateReferenceSystem^ CoordinateReferenceSystemInfo::Create(ProjContext^ ctx)
{
if (!ctx)
ctx = _ctx;
return CoordinateReferenceSystem::CreateFromDatabase(Authority, Code, ctx);
}
| 26.857143 | 138 | 0.746454 | AmpScm |
c96c3f49204bcdb41a405d09d5fc5ffe1e4bb7a0 | 410 | hxx | C++ | src/ast/var-dec.hxx | MrMaDGaME/Tiger | f31f73cd386b3ccb3e02abe7b23a3de09d70bd0f | [
"MIT"
] | null | null | null | src/ast/var-dec.hxx | MrMaDGaME/Tiger | f31f73cd386b3ccb3e02abe7b23a3de09d70bd0f | [
"MIT"
] | null | null | null | src/ast/var-dec.hxx | MrMaDGaME/Tiger | f31f73cd386b3ccb3e02abe7b23a3de09d70bd0f | [
"MIT"
] | null | null | null | /**
** \file ast/var-dec.hxx
** \brief Inline methods of ast::VarDec.
*/
#pragma once
#include <ast/var-dec.hh>
namespace ast
{
inline const NameTy* VarDec::type_name_get() const { return type_name_; }
inline NameTy* VarDec::type_name_get() { return type_name_; }
inline const Exp* VarDec::init_get() const { return init_; }
inline Exp* VarDec::init_get() { return init_; }
} // namespace ast
| 20.5 | 75 | 0.680488 | MrMaDGaME |
c96cee3eba689d43bbd8a0995b96497062a7ed47 | 1,188 | cpp | C++ | hashtable.cpp | AbhinavDutta/syncmer | 38c67e858143b12ea44817d581607703738aabd0 | [
"MIT"
] | 3 | 2020-10-01T12:47:06.000Z | 2021-02-10T19:51:33.000Z | hashtable.cpp | AbhinavDutta/syncmer | 38c67e858143b12ea44817d581607703738aabd0 | [
"MIT"
] | null | null | null | hashtable.cpp | AbhinavDutta/syncmer | 38c67e858143b12ea44817d581607703738aabd0 | [
"MIT"
] | 2 | 2020-10-09T08:42:18.000Z | 2021-04-12T10:12:52.000Z | #include "myutils.h"
#include "syncmerindex.h"
#include "alpha.h"
void SyncmerIndex::CountPlus()
{
asserta(m_PlusCounts == 0);
m_PlusCounts = myalloc(byte, m_SlotCount);
zero(m_PlusCounts, m_SlotCount);
const uint K = GetKmerCount();
for (uint SeqPos = 0; SeqPos < K; ++SeqPos)
{
if (IsSyncmer(SeqPos))
{
uint64 Kmer = m_Kmers[SeqPos];
uint64 Hash = KmerToHash(Kmer);
uint64 Slot = Hash%m_SlotCount;
if (m_PlusCounts[Slot] < 255)
++m_PlusCounts[Slot];
}
}
}
void SyncmerIndex::SetHashTable(uint SlotCount)
{
m_SlotCount = SlotCount;
m_HashTable.clear();
m_HashTable.resize(m_SlotCount, UINT32_MAX);
CountPlus();
const uint K = GetKmerCount();
for (uint SeqPos = 0; SeqPos < K; ++SeqPos)
{
if (IsSyncmer(SeqPos))
{
uint64 Kmer = m_Kmers[SeqPos];
uint64 Hash = KmerToHash(Kmer);
uint64 Slot = Hash%m_SlotCount;
if (m_PlusCounts[Slot] == 1)
{
asserta(Slot < SIZE(m_HashTable));
m_HashTable[Slot] = SeqPos;
}
}
}
}
uint32 SyncmerIndex::GetPos(uint64 Slot) const
{
asserta(Slot < SIZE(m_HashTable));
uint32 Pos = m_HashTable[Slot];
return Pos;
}
| 21.6 | 48 | 0.635522 | AbhinavDutta |
c9716b287ca13a6b2409202474074533a40e2a67 | 1,924 | cpp | C++ | engine/game/helpers/CallbackObject.cpp | ClayHanson/B4v21-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | 1 | 2020-08-18T19:45:34.000Z | 2020-08-18T19:45:34.000Z | engine/game/helpers/CallbackObject.cpp | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | engine/game/helpers/CallbackObject.cpp | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | #include "game/helpers/CallbackObject.h"
IMPLEMENT_CONOBJECT(CallbackObject);
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CallbackObject::CallbackObject()
{
}
CallbackObject::~CallbackObject()
{
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void CallbackObject::Reset()
{
mEvent.ClearListeners();
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ConsoleMethod(CallbackObject, AddListener, bool, 3, 3, "(string func)")
{
return object->mEvent.AddListener(CALLBACK_EVENT_LFUNC() {
const char** newArgv = new const char*[argc + 1];
newArgv[0] = (const char*)userData;
// Read the arguments
for (int i = 0; i < argc; i++)
newArgv[i + 1] = CALLBACK_EVENT_ARG(const char*);
Con::execute(argc + 1, newArgv);
delete[] newArgv;
}, (void*)StringTable->insert(argv[2]));
}
ConsoleMethod(CallbackObject, RemoveListener, bool, 3, 3, "(string func)")
{
for (U32 i = 0; i < object->mEvent.GetListenerCount(); i++)
{
CallbackEvent::EventAction* aObj = object->mEvent.GetListener(i);
if (aObj->userData == NULL || dStricmp((StringTableEntry)aObj->userData, argv[2]))
continue;
// Remove it!
CallbackEvent::EventFunction func = aObj->funcPtr;
object->mEvent.RemoveListener(func);
return true;
}
// Fail
return false;
}
ConsoleMethod(CallbackObject, Invoke, void, 3, 2, "([args])")
{
object->mEvent.Invoke(argc - 2, argv + 2);
} | 32.066667 | 228 | 0.43763 | ClayHanson |
c973846e06c6fb3bd8684ac920902619a14478ad | 3,469 | cpp | C++ | nwol/label.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | 3 | 2017-06-05T13:49:43.000Z | 2017-06-19T22:31:58.000Z | nwol/label.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | 1 | 2017-06-19T12:36:46.000Z | 2017-06-30T22:34:06.000Z | nwol/label.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | null | null | null | /// Copyright 2016-2017 - asm128
//#pragma warning(disable:4005)
#include "nwol_label.h"
#include "nwol_label_manager.h"
#include "stype.h"
#include <string>
//------------------------------------------------------------------- gsyslabel ---------------------------------------------------------------------------------------------------------
nwol::gsyslabel::gsyslabel (const char_t* label, uint32_t size) {
LabelManager = getSystemLabelManager();
error_if(errored(LabelManager->AddLabel(label, size, *this)), "Failed to store label!");
}
//------------------------------------------------------------------- glabel ---------------------------------------------------------------------------------------------------------
nwol::glabel::glabel (const char_t* label, uint32_t size) : LabelManager(getLabelManager()) { error_if(errored(LabelManager->AddLabel(label, size, *this)), "Failed to store label!"); }
bool nwol::glabel::operator == (const nwol::glabel& other) const noexcept {
if(Count != other.Count ) return false;
else if(0 == Count && Count == other.Count ) return true; // Empty labels are always equal regardless the Data pointer
else if(Data == other.Data ) return true;
else if(LabelManager == other.LabelManager ) return false;
else return 0 == memcmp(Data, other.Data, Count);
}
uint32_t nwol::glabel::save (byte_t* out_pMemoryBuffer) const {
static constexpr const uint32_t headerBytes = (uint32_t)sizeof(uint32_t);
const uint32_t arrayBytes = (uint32_t)(Count * sizeof(char_t));
if(out_pMemoryBuffer) {
*(uint32_t*)out_pMemoryBuffer = Count;
if(arrayBytes)
::memcpy(&out_pMemoryBuffer[headerBytes], Data, arrayBytes);
}
return headerBytes + arrayBytes;
}
::nwol::error_t nwol::glabel::load (const byte_t* in_pMemoryBuffer) {
ree_if(0 == in_pMemoryBuffer, "Cannot load label from a null pointer!");
const uint32_t headerBytes = (uint32_t)sizeof(uint32_t);
const uint32_t labelSize = *(const uint32_t*)in_pMemoryBuffer;
*this = labelSize ? ::nwol::glabel((const char_t*)&in_pMemoryBuffer[headerBytes], labelSize) : ::nwol::glabel::statics().empty;
return headerBytes + labelSize;
}
::nwol::error_t nwol::glabel::save (FILE* out_pMemoryBuffer) const {
nwol_necall(sint32(Count).write(out_pMemoryBuffer), "Failed to write label to file! Label: '%s'.", begin());
if(Count) {
ree_if(Count != (int32_t)fwrite(begin(), sizeof(char_t), Count, out_pMemoryBuffer), "Failed to write label to file! Label: '%s'.", begin());
}
return 0;
}
::nwol::error_t nwol::glabel::load (FILE* in_pMemoryBuffer) {
sint32 labelSize = {};
nwol_necall(labelSize.read(in_pMemoryBuffer), "%s", "Failed to read label from file!");
if(labelSize) {
::nwol::auto_nwol_free a;
a.Handle = (char_t*)::nwol::nwol_malloc(labelSize);
ree_if(0 == a, "Failed to allocate memory for label of size %u.", (uint32_t)labelSize);
if(labelSize != (int32_t)fread(a, sizeof(char_t), labelSize, in_pMemoryBuffer), "%s", "Failed to read label from file!") {
error_printf("Failed to read from file label of size: %u bytes.", labelSize);
*this = ::nwol::glabel::statics().empty;
return -1;
}
*this = ::nwol::glabel((const char_t*)a.Handle, labelSize);
}
return 0;
} | 51.014706 | 201 | 0.586913 | asm128 |
c974dc64623b9ddae78acb9d3b4c44b9bc5a6355 | 1,543 | hpp | C++ | plugins/d3d9/include/sge/d3d9/texture/planar.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/d3d9/include/sge/d3d9/texture/planar.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/d3d9/include/sge/d3d9/texture/planar.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_D3D9_TEXTURE_PLANAR_HPP_INCLUDED
#define SGE_D3D9_TEXTURE_PLANAR_HPP_INCLUDED
#include <sge/d3d9/d3dinclude.hpp>
#include <sge/d3d9/surface/d3d_unique_ptr.hpp>
#include <sge/d3d9/texture/basic.hpp>
#include <sge/d3d9/texture/planar_basic.hpp>
#include <sge/renderer/texture/planar.hpp>
#include <sge/renderer/texture/planar_parameters.hpp>
#include <sge/renderer/texture/mipmap/level.hpp>
#include <fcppt/noncopyable.hpp>
#include <fcppt/unique_ptr_decl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <vector>
#include <fcppt/config/external_end.hpp>
namespace sge
{
namespace d3d9
{
namespace texture
{
class planar : public sge::d3d9::texture::planar_basic
{
FCPPT_NONCOPYABLE(planar);
public:
planar(IDirect3DDevice9 &, sge::renderer::texture::planar_parameters const &);
~planar() override;
private:
sge::renderer::texture::planar::nonconst_buffer &
level(sge::renderer::texture::mipmap::level) override;
sge::renderer::texture::planar::const_buffer const &
level(sge::renderer::texture::mipmap::level) const override;
sge::d3d9::surface::d3d_unique_ptr get_level(sge::renderer::texture::mipmap::level);
typedef std::vector<fcppt::unique_ptr<sge::renderer::texture::planar::nonconst_buffer>>
level_vector;
level_vector const levels_;
};
}
}
}
#endif
| 26.603448 | 89 | 0.751782 | cpreh |
c97ab7aaeacb44c4bf54b7b2431f33a7c07d7a2f | 2,359 | cpp | C++ | Lab-Assignments/Data-Structure-Lab/Assignment-8/Question-5.cpp | Hics0000/Console-Based-Cpp-Programs | 6a7658a302d19b9d623ff7c5de5bc456c2d5ab69 | [
"MIT"
] | null | null | null | Lab-Assignments/Data-Structure-Lab/Assignment-8/Question-5.cpp | Hics0000/Console-Based-Cpp-Programs | 6a7658a302d19b9d623ff7c5de5bc456c2d5ab69 | [
"MIT"
] | 1 | 2021-10-05T17:00:52.000Z | 2021-10-05T17:00:52.000Z | Lab-Assignments/Data-Structure-Lab/Assignment-8/Question-5.cpp | Hics0000/Console-Based-Cpp-Programs | 6a7658a302d19b9d623ff7c5de5bc456c2d5ab69 | [
"MIT"
] | 7 | 2021-06-13T08:15:26.000Z | 2021-10-05T17:02:10.000Z | #include <bits/stdc++.h>
#include <climits>
using namespace std;
void swap(int *x, int *y);
class MinHeap
{
int *harr;
int capacity;
int heap_size;
public:
MinHeap(int capacity);
void MinHeapify(int);
int parent(int i) { return (i - 1) / 2; }
int left(int i) { return (2 * i + 1); }
int right(int i) { return (2 * i + 2); }
int DeleteMin();
void ChangeKey(int i, int new_val);
int getMin() { return harr[0]; }
void DeleteKey(int i);
void Insert(int k);
int Size()
{
return heap_size;
}
};
MinHeap::MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
harr = new int[cap];
}
void MinHeap::Insert(int k)
{
if (heap_size == capacity)
{
cout << "\nOverflow: Could not Insert\n";
return;
}
heap_size++;
int i = heap_size - 1;
harr[i] = k;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
void MinHeap::ChangeKey(int i, int new_val)
{
harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
int MinHeap::DeleteMin()
{
if (heap_size <= 0)
return INT_MAX;
if (heap_size == 1)
{
heap_size--;
return harr[0];
}
int root = harr[0];
harr[0] = harr[heap_size - 1];
heap_size--;
MinHeapify(0);
return root;
}
void MinHeap::DeleteKey(int i)
{
ChangeKey(i, INT_MIN);
DeleteMin();
}
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
void swap(int *x, int *y)
{
int Temp = *x;
*x = *y;
*y = Temp;
}
int main()
{
int n = 100;
cin >> n;
int arr[n];
MinHeap MHeap(n);
n = 100;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
MHeap.Insert(arr[i]);
}
cout << "enter number of small elements you want to print";
int k;
cin >> k;
for (int i = 0; i < k; i++)
{
cout << MHeap.DeleteMin() << " ";
}
return 0;
}
| 16.268966 | 63 | 0.50106 | Hics0000 |
c97b3c821773dee94f10dd4361d672edbe6199ad | 35,387 | cpp | C++ | Source/AllProjects/Drivers/IR/USBUIRT/USBUIRTS_DriverImpl.cpp | DeanRoddey/CQC | 3c494db7cf89c6ba73c2c1bd9327b7a8d061072a | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Drivers/IR/USBUIRT/USBUIRTS_DriverImpl.cpp | DeanRoddey/CQC | 3c494db7cf89c6ba73c2c1bd9327b7a8d061072a | [
"MIT"
] | null | null | null | Source/AllProjects/Drivers/IR/USBUIRT/USBUIRTS_DriverImpl.cpp | DeanRoddey/CQC | 3c494db7cf89c6ba73c2c1bd9327b7a8d061072a | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: USBUIRTS_DriverImpl.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 09/12/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the bulk of the driver implementation. Some of it
// is provided by the common IR server driver base class.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "USBUIRTS.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TUSBUIRTSDriver,TBaseIRSrvDriver)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace USBUIRTS_DriverImpl
{
// Our file format version marker
const tCIDLib::TCard4 c4FmtVersion = 1;
//
// Most button presses will cause multiple IR events, which is a problem,
// because we only can deal with one of them. So we set a minimum
// interval and will throw away events until this minimum interval has
// passed. So we define here the interval.
//
const tCIDLib::TCard4 c4MinEventInterval = 250;
}
// ---------------------------------------------------------------------------
// Local callback methods that we tell the UIRT to call
// ---------------------------------------------------------------------------
extern "C" tCIDLib::TVoid __stdcall
USBUIRTRecCallback( const tCIDLib::TSCh* const pszIREventStr
, tCIDLib::TVoid* const pUserData)
{
// The user data is a pointer to the driver impl object
TUSBUIRTSDriver* psdrvTar = static_cast<TUSBUIRTSDriver*>(pUserData);
//
// If the current time is not past the next event time, we just assume
// this is a bogus 2nd, 3rd, etc... event, and we ignore it. Else, we
// take it and reset the next event time.
//
const tCIDLib::TCard4 c4CurTime = TTime::c4Millis();
if (c4CurTime < psdrvTar->c4NextEventTime())
return;
// We are keeping this one, so set the next event time
psdrvTar->c4NextEventTime(c4CurTime + USBUIRTS_DriverImpl::c4MinEventInterval);
//
// Tell the driver about it. He will either store it as training data
// if in training mode, or queue it for processing if not in training
// mode.
//
psdrvTar->HandleRecEvent(TString(pszIREventStr));
}
extern "C" tCIDLib::TVoid __stdcall
ProgressCallback(const tCIDLib::TCard4
, const tCIDLib::TCard4
, const tCIDLib::TCard4
, tCIDLib::TVoid* const)
{
// We aren't using the progress callback at this time
}
// ---------------------------------------------------------------------------
// CLASS: THostMonSDriver
// PREFIX: drv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// THostMonSDriver: Constructors and Destructor
// ---------------------------------------------------------------------------
TUSBUIRTSDriver::TUSBUIRTSDriver(const TCQCDriverObjCfg& cqcdcToLoad) :
TBaseIRSrvDriver(cqcdcToLoad)
, m_bGotBlastTrainingData(kCIDLib::False)
, m_bGotRecTrainingData(kCIDLib::False)
, m_bBlastTrainingMode(kCIDLib::False)
, m_bRecTrainingMode(kCIDLib::False)
, m_c4FldIdFirmwareVer(kCIDLib::c4MaxCard)
, m_c4FldIdInvoke(kCIDLib::c4MaxCard)
, m_c4FldIdTrainingMode(kCIDLib::c4MaxCard)
, m_c4NextEventTime(0)
, m_c4PollCount(0)
, m_colRecKeyQ(tCIDLib::EMTStates::Unsafe)
, m_hUIRT(kUSBUIRT::hInvalid)
, m_pfnGetInfoProc(nullptr)
, m_pfnGetUIRTInfoProc(nullptr)
, m_pfnLearnProc(nullptr)
, m_pfnOpenProc(nullptr)
, m_pfnSetCfgProc(nullptr)
, m_pfnSetRecCBProc(nullptr)
, m_pfnTransmitProc(nullptr)
, m_pmodSupport(nullptr)
, m_strErr_NoDevice(kUIRTSErrs::errcDev_NoDevice, facUSBUIRTS())
, m_strErr_NoResp(kUIRTSErrs::errcDev_NoResp, facUSBUIRTS())
, m_strErr_NoDLL(kUIRTSErrs::errcDev_NoDLL, facUSBUIRTS())
, m_strErr_Version(kUIRTSErrs::errcDev_Version, facUSBUIRTS())
, m_strErr_Unknown(kUIRTSErrs::errcDev_Unknown, facUSBUIRTS())
, m_thrLearn
(
TString(L"USB-UIRTLearnThread_") + cqcdcToLoad.strMoniker()
, TMemberFunc<TUSBUIRTSDriver>(this, &TUSBUIRTSDriver::eLearnThread)
)
{
//
// Make sure that we were configured for an 'other' connection. Otherwise,
// its a bad configuration.
//
if (cqcdcToLoad.conncfgReal().clsIsA() != TCQCOtherConnCfg::clsThis())
{
// Note that we are throwing a CQCKit error here!
facCQCKit().ThrowErr
(
CID_FILE
, CID_LINE
, kKitErrs::errcDrv_BadConnCfgType
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Config
, cqcdcToLoad.conncfgReal().clsIsA()
, clsIsA()
, TCQCOtherConnCfg::clsThis()
);
}
}
TUSBUIRTSDriver::~TUSBUIRTSDriver()
{
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Public, inherited methods
// ---------------------------------------------------------------------------
//
// If it's one we posted to ourself, store the data. Else just pass it to
// the base IR driver class.
//
tCIDLib::TCard4
TUSBUIRTSDriver::c4SendCmd(const TString& strCmdId, const TString& strParms)
{
if (strCmdId == kUSBUIRTS::pszCmd_UIRTData)
{
//
// If we are in receiver training mode we have to store it as
// training data. Else, if we aren't in blaster training mode, we
// want to queue it as an event to process.
//
if (m_bRecTrainingMode)
{
m_bGotRecTrainingData = kCIDLib::True;
m_strRecTrainData = strParms;
}
else
{
if (!m_bBlastTrainingMode)
m_colRecKeyQ.objPut(strParms);
}
return 0;
}
return TParent::c4SendCmd(strCmdId, strParms);
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TCard4 TUSBUIRTSDriver::c4NextEventTime() const
{
return m_c4NextEventTime;
}
tCIDLib::TCard4 TUSBUIRTSDriver::c4NextEventTime(const tCIDLib::TCard4 c4ToSet)
{
m_c4NextEventTime = c4ToSet;
return m_c4NextEventTime;
}
//
// NOTE!!!!!
//
// This is called from the USB UIRT callback. It is NOT a CQC thread, so
// we have to do the minimum work possible just to queue up the passed
// event string because, if anything goes wrong, it will inevitably invoke
// some code that assumes it is running in a CQC thread.
//
// Since it does come asynchronously from the UIRT calling us back, we
// just post ourself an async command using the existing async driver command
// infrastructure.
//
tCIDLib::TVoid TUSBUIRTSDriver::HandleRecEvent(const TString& strEventStr)
{
pdcmdQSendCmd
(
kUSBUIRTS::pszCmd_UIRTData, strEventStr, tCQCKit::EDrvCmdWaits::NoWait
);
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TUSBUIRTSDriver::bBlastTrainingMode()
{
// No need to lock for this simple check
return m_bBlastTrainingMode;
}
tCIDLib::TBoolean
TUSBUIRTSDriver::bCheckBlastTrainingData(tCIDLib::TCard4& c4DataBytes
, THeapBuf& mbufToFill)
{
// If we aren't online, then throw
CheckOnline(CID_FILE, CID_LINE);
if (m_bGotBlastTrainingData)
{
//
// We got something, so copy it over and clear the flags. Be sure
// to copy the nul, so that when the data is returned later, we can
// just send it as is.
//
c4DataBytes = TRawStr::c4StrLen(m_pchBlastTrainData) + 1;
mbufToFill.CopyIn(m_pchBlastTrainData, c4DataBytes);
m_bBlastTrainingMode = kCIDLib::False;
m_bGotBlastTrainingData = kCIDLib::False;
bStoreBoolFld(m_c4FldIdTrainingMode, kCIDLib::False, kCIDLib::True);
return kCIDLib::True;
}
c4DataBytes = 0;
return kCIDLib::False;
}
tCIDLib::TBoolean
TUSBUIRTSDriver::bCheckRecTrainingData(TString& strKeyToFill)
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
if (m_bGotRecTrainingData)
{
// We have some, so copy to output and clear our stuff
strKeyToFill = m_strRecTrainData;
m_bGotRecTrainingData = kCIDLib::False;
m_strRecTrainData.Clear();
return kCIDLib::True;
}
return kCIDLib::False;
}
tCIDLib::TBoolean
TUSBUIRTSDriver::bCvtManualBlastData(const TString& strText
, tCIDLib::TCard4& c4DataBytes
, THeapBuf& mbufToFill
, TString& strError)
{
//
// Use a regular expression to validate the data, which must be a
// sequence of one or more sets of 4 hex digits, separated by spaces
// but the last one doesn't have to have any space after it, and
// should not because the client should streaming leading and trailng
// space.
//
if (!facCQCIR().bIsValidUIRTBlastData(strText))
{
strError.LoadFromMsg
(
kIRErrs::errcFmt_BadIRDataFormat, facCQCIR(), TString(L"UIRT")
);
return kCIDLib::False;
}
//
// For us, it has to be in Pronto format, since that's our native
// format and the only alternative format that this method has to
// accept. So we just convert it to the desired ultimate format,
// which is single byte ASCII characters with a null terminator. So
// we just do a simple transcode by taking the low byte of each char.
//
const tCIDLib::TCard4 c4Len = strText.c4Length();
CIDAssert(c4Len != 0, L"The incoming IR data length was zero");
for (c4DataBytes = 0; c4DataBytes< c4Len; c4DataBytes++)
mbufToFill.PutCard1(tCIDLib::TCard1(strText[c4DataBytes]), c4DataBytes);
// Add the null terminator
mbufToFill.PutCard1(0, c4DataBytes++);
return kCIDLib::True;
}
tCIDLib::TBoolean TUSBUIRTSDriver::bGetCommResource(TThread&)
{
// Try to find the UIRT library if not done so far
if (m_hUIRT == kUSBUIRT::hInvalid)
m_hUIRT = m_pfnOpenProc();
return (m_hUIRT != kUSBUIRT::hInvalid);
}
tCIDLib::TBoolean TUSBUIRTSDriver::bRecTrainingMode()
{
// No need to lock for this simple check
return m_bRecTrainingMode;
}
tCIDLib::TBoolean TUSBUIRTSDriver::bResetConnection()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
//
// The device doesn't require anything, but we want to get ourselves
// out of any training modes and clear the event queue.
//
ExitBlastTrainingMode();
ExitRecTrainingMode();
ClearEventQ();
return kCIDLib::True;
}
tCIDLib::TCard4 TUSBUIRTSDriver::c4InvokeFldId() const
{
return m_c4FldIdInvoke;
}
//
// The later UIRTs have three zones, with the open air one being
// zone one, a second one being on the back and third one that you
// can access as well.
//
tCIDLib::TCard4 TUSBUIRTSDriver::c4ZoneCount() const
{
return 3;
}
tCIDLib::TVoid TUSBUIRTSDriver::ClearBlastTrainingData()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
m_bGotBlastTrainingData = kCIDLib::False;
}
tCIDLib::TVoid TUSBUIRTSDriver::ClearRecTrainingData()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
m_bGotRecTrainingData = kCIDLib::False;
m_strRecTrainData.Clear();
}
tCQCKit::ECommResults TUSBUIRTSDriver::eConnectToDevice(TThread&)
{
//
// If we got the comm resource, we are connected, but get the firmware
// info and set that field now. If this fails, then something really
// bad has happened, since it should be doable even if there's no
// hardware attached, so return lostcommres.
//
TUIRTInfo Info;
if (!m_pfnGetUIRTInfoProc(m_hUIRT, &Info))
return tCQCKit::ECommResults::LostCommRes;
TString strFW(L"USB-UIRT FWVer=");
strFW.AppendFormatted(Info.c4FWVersion >> 8);
strFW.Append(kCIDLib::chPeriod);
strFW.AppendFormatted(Info.c4FWVersion & 0xFF);
strFW.Append(L", ProtoVer=");
strFW.AppendFormatted(Info.c4ProtVersion >> 8);
strFW.Append(kCIDLib::chPeriod);
strFW.AppendFormatted(Info.c4ProtVersion & 0xFF);
strFW.Append(L", Date=");
strFW.AppendFormatted(tCIDLib::TCard4(Info.c1Year + 2000));
strFW.Append(kCIDLib::chForwardSlash);
strFW.AppendFormatted(Info.c1Month);
strFW.Append(kCIDLib::chForwardSlash);
strFW.AppendFormatted(Info.c1Day);
// Lock for field write and set the field
bStoreStringFld(m_c4FldIdFirmwareVer, strFW, kCIDLib::True);
// Set the receiver callback
m_pfnSetRecCBProc(m_hUIRT, USBUIRTRecCallback, this);
// And set the flags
m_pfnSetCfgProc(m_hUIRT, kUSBUIRT::c4Cfg_LEDRX | kUSBUIRT::c4Cfg_LEDTX);
return tCQCKit::ECommResults::Success;
}
tCQCKit::EDrvInitRes TUSBUIRTSDriver::eInitializeImpl()
{
// Call the base IR driver first
TParent::eInitializeImpl();
//
// We have to load the USB-UIRT interface DLL dynamically, and look
// up the APIs we are going to call. We need to build the path to
// the DLL and check that it exists before we try to load it. It
// will be in the bin directory.
//
// This is not one of our facilities, so we have to just build up
// the raw name ourself, we can't use the CIDlib methods. We just
// find it in the system path.
//
TPathStr pathLibName;
TFindBuf fndbUULib;
if (!TFileSys::bExistsInSysPath(kUSBUIRTS::pszSupportDLL, fndbUULib))
{
// Log this so that they'll know why
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_DLLNotFound
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
//
// And try to load this module if we haven't already. It's a third party
// module, so we use the ctor that takes the path to load from specifically
// and no CIDLib stuff.
//
if (!m_pmodSupport)
{
try
{
m_pmodSupport = new TModule(fndbUULib.pathFileName(), kCIDLib::True);
}
catch(const TError& errToCatch)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Medium);
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_DLLNotLoaded
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
catch(...)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_DLLNotLoaded
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
}
// Load up all of the entry points we need to use
try
{
m_pfnCloseProc = reinterpret_cast<TUUIRTClose>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTClose")
);
m_pfnGetInfoProc = reinterpret_cast<TUUIRTGetDrvInfo>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTGetDrvInfo")
);
m_pfnGetUIRTInfoProc = reinterpret_cast<TUUIRTGetUUIRTInfo>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTGetUUIRTInfo")
);
m_pfnLearnProc = reinterpret_cast<TUUIRTLearnIR>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTLearnIR")
);
m_pfnOpenProc = reinterpret_cast<TUUIRTOpen>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTOpen")
);
m_pfnSetCfgProc = reinterpret_cast<TUUIRTSetUUIRTConfig>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTSetUUIRTConfig")
);
m_pfnSetRecCBProc = reinterpret_cast<TUUIRTSetRecCB>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTSetReceiveCallback")
);
m_pfnTransmitProc = reinterpret_cast<TUUIRTTransmitIR>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTTransmitIR")
);
}
catch(...)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_FuncsNotLoaded
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
//
// Register our couple of fields. We just provide one that indicates
// the training mode state, so that the client can display an
// indicator that shows whether the driver is in training mode or not.
//
tCQCKit::TFldDefList colFlds(8);
TCQCFldDef flddCmd;
//
// Do readable fields for the standard fields that an IR driver
// has to provide. The invoke field must be an 'always write' field
// since it exists just to invoke IR data sending.
//
flddCmd.Set
(
TFacCQCIR::strFldName_FirmwareVer
, tCQCKit::EFldTypes::String
, tCQCKit::EFldAccess::Read
);
colFlds.objAdd(flddCmd);
flddCmd.Set
(
TFacCQCIR::strFldName_Invoke
, tCQCKit::EFldTypes::String
, tCQCKit::EFldAccess::Write
);
flddCmd.bAlwaysWrite(kCIDLib::True);
colFlds.objAdd(flddCmd);
flddCmd.Set
(
TFacCQCIR::strFldName_TrainingState
, tCQCKit::EFldTypes::Boolean
, tCQCKit::EFldAccess::Read
);
colFlds.objAdd(flddCmd);
// Tell our base class about our fields
SetFields(colFlds);
// Look up the ids of our fields, for efficiency
m_c4FldIdFirmwareVer = pflddFind
(
TFacCQCIR::strFldName_FirmwareVer, kCIDLib::True
)->c4Id();
m_c4FldIdInvoke = pflddFind
(
TFacCQCIR::strFldName_Invoke, kCIDLib::True
)->c4Id();
m_c4FldIdTrainingMode = pflddFind
(
TFacCQCIR::strFldName_TrainingState, kCIDLib::True
)->c4Id();
//
// Set the poll time a little faster than normal. This is a very
// interactive device, and it has a good fast speed. Set the recon
// time pretty slow since we would only ever fail if the hardware is
// not present, so no need to keep banging away fast.
//
SetPollTimes(50, 10000);
//
// Crank up the actions processing thread if not already running. It
// runs until we are unloaded pulling events out of the queue and
// processing them.
//
StartActionsThread();
//
// In our case we want to go to 'wait for config' mode, not wait for
// comm res, since we need to get configuration before we can go online.
//
return tCQCKit::EDrvInitRes::WaitConfig;
}
tCQCKit::ECommResults TUSBUIRTSDriver::ePollDevice(TThread&)
{
tCQCKit::ECommResults eRetVal = tCQCKit::ECommResults::Success;
//
// If we aren't in blaster or training mode, then let's bump the poll
// count, and every so many times through, ping the device to make
// sure it's still there.
//
if (!m_bBlastTrainingMode && !m_bRecTrainingMode)
{
//
// Every so many times through, we ping the device to make sure
// it's still there. This should be about every 10 seconds at
// our poll rate.
//
m_c4PollCount++;
if (m_c4PollCount > 200)
{
TUIRTInfo Info;
if (!m_pfnGetUIRTInfoProc(m_hUIRT, &Info))
eRetVal = tCQCKit::ECommResults::LostCommRes;
m_c4PollCount = 0;
}
}
const tCIDLib::TCard4 c4RecKeyCnt = m_colRecKeyQ.c4ElemCount();
if (eRetVal != tCQCKit::ECommResults::Success)
{
// We are losing the connection so flush the queue
m_colRecKeyQ.RemoveAll();
}
else if (c4RecKeyCnt)
{
//
// If there are any queued receiver keys, queue them up on
// our parent class.
//
// BEAR in mind we have a lock above. But all we are doing here
// is just passing in soem data to be queued up.
//
TString strKey;
while (m_colRecKeyQ.bGetNextMv(strKey, 0))
QueueRecEvent(strKey);
}
return eRetVal;
}
tCIDLib::TVoid TUSBUIRTSDriver::EnterBlastTrainingMode()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
// If we are already in training mode, then that's an error
if (m_bBlastTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_AlreadyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Already
);
}
//
// We make them wait until all the queued events are processed before
// they can do any training.
//
WaitForActions();
//
// Go into training mode. Since it's a blocking call on the USB-UIRT,
// we spin off a thread to do the work. When it exits, it'll set
// the got data flag appropriately.
//
m_bGotBlastTrainingData = kCIDLib::False;
m_bBlastTrainingMode = kCIDLib::True;
m_thrLearn.Start();
// Look for field access and update the training mode field
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
}
tCIDLib::TVoid TUSBUIRTSDriver::EnterRecTrainingMode()
{
// Can't already be in training mode
if (m_bRecTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_AlreadyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Already
, strMoniker()
);
}
//
// We make them wait until all the queued events are processed before
// they can do any training.
//
WaitForActions();
// Set the record training mode flag and clear the data flags
m_bRecTrainingMode = kCIDLib::True;
m_bGotRecTrainingData = kCIDLib::False;
m_strRecTrainData.Clear();
// And then update the training mode field
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
}
tCIDLib::TVoid TUSBUIRTSDriver::ExitBlastTrainingMode()
{
//
// Set the flag that the learn procedure uses as an abort flag. This
// will cause the thread to exit.
//
m_c4CancelLearn = 1;
// Wait for the learning thread to exit
try
{
if (m_thrLearn.bIsRunning())
m_thrLearn.eWaitForDeath(2000);
}
catch(const TError& errToCatch)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Low)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Low);
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_StopTrainThread
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, strMoniker()
);
}
}
// Clear the flags first, then update the training mode field
m_bBlastTrainingMode = kCIDLib::False;
m_bGotBlastTrainingData = kCIDLib::False;
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
}
tCIDLib::TVoid TUSBUIRTSDriver::ExitRecTrainingMode()
{
// Clear our own flags
m_bRecTrainingMode = kCIDLib::False;
m_bGotRecTrainingData = kCIDLib::False;
// And then update the training mode field
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
// The UIRT is not in any special mode for this, so nothing more to do
}
// We have to format the data for the indicated command to text
tCIDLib::TVoid
TUSBUIRTSDriver::FormatBlastData(const TIRBlasterCmd& irbcFmt
, TString& strToFill)
{
//
// The data is just the text as ASCII, so we can do a cheap transcode
// to the string by just expanding each byte.
//
// In our case it has a null on it, so don't copy that.
//
const tCIDLib::TCard4 c4Count = irbcFmt.c4DataLen();
strToFill.Clear();
if (c4Count)
{
const tCIDLib::TCard1* pc1Src = irbcFmt.mbufData().pc1Data();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count - 1; c4Index++)
strToFill.Append(tCIDLib::TCh(*pc1Src++));
}
}
tCIDLib::TVoid
TUSBUIRTSDriver::InvokeBlastCmd(const TString& strDevice
, const TString& strCmd
, const tCIDLib::TCard4 c4ZoneNum)
{
//
// We can check the zone number up front without locking. They are
// zero based.
//
if (c4ZoneNum >= c4ZoneCount())
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcBlast_BadZone
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TCardinal(c4ZoneNum + 1)
, strMoniker()
);
}
// If we aren't online, then throw
CheckOnline(CID_FILE, CID_LINE);
// We can't allow this if either training mode is active
if (m_bRecTrainingMode || m_bBlastTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_BusyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, strMoniker()
);
}
// Look up the command
tCIDLib::TCard4 c4Repeat;
const TIRBlasterCmd& irbcInvoke = irbcFromName(strDevice, strCmd, c4Repeat);
// And send it
SendIRData(irbcInvoke.mbufData(), irbcInvoke.c4DataLen(), c4Repeat, c4ZoneNum);
// Reset the poll counter since we ust verified that it's alive
m_c4PollCount = 0;
}
tCIDLib::TVoid TUSBUIRTSDriver::ReleaseCommResource()
{
try
{
// If we have a handle, then try to close it
if (m_hUIRT != kUSBUIRT::hInvalid)
{
m_pfnCloseProc(m_hUIRT);
m_hUIRT = kUSBUIRT::hInvalid;
}
}
catch(TError& errToCatch)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Medium, CID_FILE, CID_LINE);
}
}
tCIDLib::TVoid
TUSBUIRTSDriver::SendBlasterData(const tCIDLib::TCard4 c4DataBytes
, const TMemBuf& mbufToSend
, const tCIDLib::TCard4 c4ZoneNum
, const tCIDLib::TCard4 c4RepeatCount)
{
// We can check the zone number up front without locking
if (c4ZoneNum >= c4ZoneCount())
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcBlast_BadZone
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TCardinal(c4ZoneNum + 1)
, strMoniker()
);
}
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
// We can't allow this if either training mode is active
if (m_bRecTrainingMode || m_bBlastTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_BusyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, strMoniker()
);
}
// Send the data
SendIRData(mbufToSend, c4DataBytes, c4RepeatCount, c4ZoneNum);
}
tCIDLib::TVoid TUSBUIRTSDriver::TerminateImpl()
{
// If we are in blaster training mode, we have to get out
if (m_bBlastTrainingMode && !m_c4CancelLearn)
{
m_c4CancelLearn = 1;
// Wait for the thread to exit
try
{
if (m_thrLearn.bIsRunning())
m_thrLearn.eWaitForDeath(2000);
}
catch(TError& errToCatch)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Low)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Low, CID_FILE, CID_LINE);
facCQCIR().LogMsg
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_StopTrainThread
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Term
, strMoniker()
);
}
}
}
// Unload the module if we loaded it
if (m_pmodSupport)
{
try
{
delete m_pmodSupport;
m_pmodSupport = 0;
}
catch(TError& errToCatch)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Low, CID_FILE, CID_LINE);
}
}
// And call the base IR driver class last
TParent::TerminateImpl();
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::EExitCodes
TUSBUIRTSDriver::eLearnThread(TThread& thrThis, tCIDLib::TVoid*)
{
// Let the calling thread go
thrThis.Sync();
//
// We don't have to loop or anything here. We are just going to make
// one blocking call.
//
try
{
m_c4CancelLearn = 0;
const tCIDLib::TSInt iRes = m_pfnLearnProc
(
m_hUIRT
, kUSBUIRT::c4IRFmt_Pronto
, m_pchBlastTrainData
, ProgressCallback
, 0
, &m_c4CancelLearn
, 0
, 0
, 0
);
if (iRes)
{
//
// If we didn't get out due to a cancel, then set the flag
// indicating we have data, and set the next event time so
// that if they don't react quickly, we won't pick up any
// other events that come in due to the button they are
// pressing.
//
if (!m_c4CancelLearn)
m_bGotBlastTrainingData = kCIDLib::True;
m_c4NextEventTime = TTime::c4Millis() + 1000;
}
else
{
// We got an error so log it
TKrnlError kerrUUIRT = TKrnlError::kerrLast();
facCQCIR().LogKrnlErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_TrainError
, kerrUUIRT
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strMoniker()
, strUUIRTErr(kerrUUIRT.errcHostId())
);
}
}
catch(...)
{
facCQCIR().LogMsg
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_TrainUExcept
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strMoniker()
);
}
return tCIDLib::EExitCodes::Normal;
}
const TString&
TUSBUIRTSDriver::strUUIRTErr(const tCIDLib::TOSErrCode errcToLoad)
{
switch(errcToLoad)
{
case kUSBUIRT::c4Err_NoDevice :
return m_strErr_NoDevice;
break;
case kUSBUIRT::c4Err_NoResp :
return m_strErr_NoResp;
break;
case kUSBUIRT::c4Err_NoDLL :
return m_strErr_NoDLL;
break;
case kUSBUIRT::c4Err_Version :
return m_strErr_Version;
break;
};
return m_strErr_Unknown;
}
tCIDLib::TVoid
TUSBUIRTSDriver::SendIRData(const TMemBuf& mbufData
, const tCIDLib::TCard4 c4Bytes
, const tCIDLib::TCard4 c4RepeatCount
, const tCIDLib::TCard4 c4ZoneNum)
{
//
// Map the zone number to the UIRT's zone number. We have to map
// our Zone 0 to its Z3 (which is the front open air blaster), so
// that we maintain backwards compability with the pre-zone support
// version of this driver.
//
// Our mapping is:
//
// Zone 0 : Z3
// Zone 1 : Z1
// Zone 2 : Z2
//
tCIDLib::TSCh chZone;
switch(c4ZoneNum)
{
case 1 :
chZone = '1';
break;
case 2 :
chZone = '2';
break;
default :
chZone = '3';
break;
};
//
// Our data is an ASCII string, but it's stored as binary data and
// the null cannot be stored on it, so we have to put on on, which
// requires making a local buffer. We have to prepend the zone stuff
// before it.
//
tCIDLib::TSCh* pszData = new tCIDLib::TSCh[c4Bytes + 3];
pszData[0] = kCIDLib::chLatin_Z;
pszData[1] = chZone;
TRawMem::CopyMemBuf(pszData + 2, mbufData.pc1Data(), c4Bytes);
pszData[c4Bytes + 2] = 0;
TArrayJanitor<tCIDLib::TSCh> janBuf(pszData);
// And send the data
tCIDLib::TSInt iRet = m_pfnTransmitProc
(
m_hUIRT
, pszData
, kUSBUIRT::c4IRFmt_Pronto
, c4RepeatCount
, 0
, 0
, 0
, 0
);
if (!iRet)
{
TKrnlError kerrUUIRT = TKrnlError::kerrLast();
facCQCIR().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcDev_DevError
, kerrUUIRT
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strMoniker()
, strUUIRTErr(kerrUUIRT.errcHostId())
);
}
}
| 28.934587 | 85 | 0.574137 | DeanRoddey |
c97c9a5cc4291dae894effa8b9782c4ea2d12dd5 | 483 | cpp | C++ | Source/KInk/Private/Hangar/Lifesteal.cpp | DanySpin97/KInk | e9f65cfe20aab39a09467bf8e96e0cc06697a29f | [
"MIT"
] | 4 | 2016-11-30T04:39:51.000Z | 2018-06-29T06:38:27.000Z | Source/KInk/Private/Hangar/Lifesteal.cpp | DanySpin97/KInk | e9f65cfe20aab39a09467bf8e96e0cc06697a29f | [
"MIT"
] | null | null | null | Source/KInk/Private/Hangar/Lifesteal.cpp | DanySpin97/KInk | e9f65cfe20aab39a09467bf8e96e0cc06697a29f | [
"MIT"
] | null | null | null | // Copyright (c) 2016 WiseDragonStd
#include "KInk.h"
#include "Lifesteal.h"
ALifesteal::ALifesteal()
{
Weapon = EWeapon::WFireGun;
}
void ALifesteal::ActivatePowerUp()
{
Super::ActivatePowerUp();
Cast<ACustomPlayerState>(GetWorld()->GetFirstPlayerController()->PlayerState)->Lifesteal += LifestealAdded;
}
void ALifesteal::DeactivatePowerUp()
{
Cast<ACustomPlayerState>(GetWorld()->GetFirstPlayerController()->PlayerState)->Lifesteal -= LifestealAdded;
K2_DestroyActor();
} | 23 | 108 | 0.761905 | DanySpin97 |
c981f5818431a97aad440abe3d029195e7cb5872 | 4,395 | cpp | C++ | src/solidity-frontend/pattern_check.cpp | maktheus/esbmc | 26c2a1e9e45f737e8423aaa1a2cadbc832d17fbe | [
"BSD-3-Clause"
] | null | null | null | src/solidity-frontend/pattern_check.cpp | maktheus/esbmc | 26c2a1e9e45f737e8423aaa1a2cadbc832d17fbe | [
"BSD-3-Clause"
] | null | null | null | src/solidity-frontend/pattern_check.cpp | maktheus/esbmc | 26c2a1e9e45f737e8423aaa1a2cadbc832d17fbe | [
"BSD-3-Clause"
] | null | null | null | #include <solidity-frontend/pattern_check.h>
#include <stdlib.h>
pattern_checker::pattern_checker(
const nlohmann::json &_ast_nodes,
const std::string &_target_func,
const messaget &msg)
: ast_nodes(_ast_nodes), target_func(_target_func), msg(msg)
{
}
bool pattern_checker::do_pattern_check()
{
// TODO: add more functions here to perform more pattern-based checks
msg.status(fmt::format("Checking function {} ...", target_func.c_str()));
unsigned index = 0;
for(nlohmann::json::const_iterator itr = ast_nodes.begin();
itr != ast_nodes.end();
++itr, ++index)
{
if(
(*itr).contains("kind") && (*itr).contains("nodeType") &&
(*itr).contains("name"))
{
// locate the target function
if(
(*itr)["kind"].get<std::string>() == "function" &&
(*itr)["nodeType"].get<std::string>() == "FunctionDefinition" &&
(*itr)["name"].get<std::string>() == target_func)
return start_pattern_based_check(*itr);
}
}
return false;
}
bool pattern_checker::start_pattern_based_check(const nlohmann::json &func)
{
// SWC-115: Authorization through tx.origin
check_authorization_through_tx_origin(func);
return false;
}
void pattern_checker::check_authorization_through_tx_origin(
const nlohmann::json &func)
{
// looking for the pattern require(tx.origin == <VarDeclReference>)
const nlohmann::json &body_stmt = func["body"]["statements"];
msg.progress(
" - Pattern-based checking: SWC-115 Authorization through tx.origin");
msg.debug("statements in function body array ... \n");
unsigned index = 0;
for(nlohmann::json::const_iterator itr = body_stmt.begin();
itr != body_stmt.end();
++itr, ++index)
{
msg.status(fmt::format(" checking function body stmt {}", index));
if(itr->contains("nodeType"))
{
if((*itr)["nodeType"].get<std::string>() == "ExpressionStatement")
{
const nlohmann::json &expr = (*itr)["expression"];
if(expr["nodeType"] == "FunctionCall")
{
if(expr["kind"] == "functionCall")
{
check_require_call(expr);
}
}
}
}
}
}
void pattern_checker::check_require_call(const nlohmann::json &expr)
{
// Checking the authorization argument of require() function
if(expr["expression"]["nodeType"].get<std::string>() == "Identifier")
{
if(expr["expression"]["name"].get<std::string>() == "require")
{
const nlohmann::json &call_args = expr["arguments"];
// Search for tx.origin in BinaryOperation (==) as used in require(tx.origin == <VarDeclReference>)
// There should be just one argument, the BinaryOpration expression.
// Checking 1 argument as in require(<leftExpr> == <rightExpr>)
if(call_args.size() == 1)
{
check_require_argument(call_args);
}
}
}
}
void pattern_checker::check_require_argument(const nlohmann::json &call_args)
{
// This function is used to check the authorization argument of require() funciton
const nlohmann::json &arg_expr = call_args[0];
// look for BinaryOperation "=="
if(arg_expr["nodeType"].get<std::string>() == "BinaryOperation")
{
if(arg_expr["operator"].get<std::string>() == "==")
{
const nlohmann::json &left_expr = arg_expr["leftExpression"];
// Search for "tx", "." and "origin". First, confirm the nodeType is MemeberAccess
// If the nodeType was NOT MemberAccess, accessing "memberName" would throw an exception !
if(
left_expr["nodeType"].get<std::string>() ==
"MemberAccess") // tx.origin is of the type MemberAccess expression
{
check_tx_origin(left_expr);
}
} // end of "=="
} // end of "BinaryOperation"
}
void pattern_checker::check_tx_origin(const nlohmann::json &left_expr)
{
// This function is used to check the Tx.origin pattern used in BinOp expr
if(left_expr["memberName"].get<std::string>() == "origin")
{
if(left_expr["expression"]["nodeType"].get<std::string>() == "Identifier")
{
if(left_expr["expression"]["name"].get<std::string>() == "tx")
{
//assert(!"Found vulnerability SWC-115 Authorization through tx.origin");
msg.error(
"Found vulnerability SWC-115 Authorization through tx.origin");
msg.error("VERIFICATION FAILED");
exit(EXIT_SUCCESS);
}
}
}
}
| 31.847826 | 105 | 0.636633 | maktheus |
c98408bf2920f46c134c379826dc10e57f1d109a | 152 | hpp | C++ | higan/processor/arm/disassembler.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 3 | 2016-03-23T01:17:36.000Z | 2019-10-25T06:41:09.000Z | higan/processor/arm/disassembler.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | higan/processor/arm/disassembler.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | auto disassemble_arm_instruction(uint32 pc) -> string;
auto disassemble_thumb_instruction(uint32 pc) -> string;
auto disassemble_registers() -> string;
| 38 | 56 | 0.809211 | ameer-bauer |
c9871c91855e4eb966b8fe3d07a7362f569b0aed | 594 | hpp | C++ | include/depthai/common/CameraBoardSocket.hpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | null | null | null | include/depthai/common/CameraBoardSocket.hpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | null | null | null | include/depthai/common/CameraBoardSocket.hpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | null | null | null | #pragma once
#include <ostream>
#include "depthai-shared/common/CameraBoardSocket.hpp"
namespace dai {
inline std::ostream& operator<<(std::ostream& out, const CameraBoardSocket& socket) {
switch(socket) {
case CameraBoardSocket::AUTO:
out << "AUTO";
break;
case CameraBoardSocket::RGB:
out << "RGB";
break;
case CameraBoardSocket::LEFT:
out << "LEFT";
break;
case CameraBoardSocket::RIGHT:
out << "RIGHT";
break;
}
return out;
}
} // namespace dai | 22 | 85 | 0.552189 | SpectacularAI |
c98921e4c917408cb2305561d730e9d24c06342c | 233 | cpp | C++ | cplusplus/cplusplus/main.cpp | youshihou/art | 7921dd58d303baef12de1558dace342e3dcdb924 | [
"MIT"
] | null | null | null | cplusplus/cplusplus/main.cpp | youshihou/art | 7921dd58d303baef12de1558dace342e3dcdb924 | [
"MIT"
] | null | null | null | cplusplus/cplusplus/main.cpp | youshihou/art | 7921dd58d303baef12de1558dace342e3dcdb924 | [
"MIT"
] | null | null | null | //
// main.cpp
// cplusplus-learning
//
// Created by Ankui on 6/12/20.
// Copyright © 2020 Ankui. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
return 0;
}
| 14.5625 | 48 | 0.626609 | youshihou |
c98922f898ddda43aa5c1b282d9c5446d1b9e7ff | 2,562 | cpp | C++ | src/software/geom/spline.cpp | matthewberends/Software | 4681c7cffc9c1ca8f739ea692daffc490a8c1910 | [
"MIT"
] | null | null | null | src/software/geom/spline.cpp | matthewberends/Software | 4681c7cffc9c1ca8f739ea692daffc490a8c1910 | [
"MIT"
] | null | null | null | src/software/geom/spline.cpp | matthewberends/Software | 4681c7cffc9c1ca8f739ea692daffc490a8c1910 | [
"MIT"
] | null | null | null | #include "software/geom/spline.h"
Spline::Spline(const std::vector<Point>& points) : knots(points)
{
initLinearSegments(points);
}
Spline::Spline(const std::initializer_list<Point>& points) : knots(points)
{
initLinearSegments(points);
}
Point Spline::valueAt(double val) const
{
if (val < 0.0 || val > 1.0)
{
std::stringstream ss;
ss << "Tried to evaluate spline at " << val
<< ", which is outside of domain of the spline: [0,1]";
throw std::invalid_argument(ss.str());
}
Point retval;
if (segments.empty())
{
retval = knots.front();
}
else
{
// Note: this could be more performant with binary search
auto seg_it = std::find_if(segments.begin(), segments.end(),
[&](const SplineSegment& sseg) {
return (val >= sseg.start && val <= sseg.end);
});
if (seg_it == segments.end())
{
std::stringstream ss;
ss << "Tried to evaluate spline at " << val
<< ", which was not in any interval of any segment";
throw std::runtime_error(ss.str());
}
retval = Point(seg_it->x.valueAt(val), seg_it->y.valueAt(val));
}
return retval;
}
size_t Spline::size(void) const
{
return knots.size();
}
const std::vector<Point> Spline::getKnots(void) const
{
return knots;
}
const Point Spline::startPoint(void) const
{
return knots.front();
}
const Point Spline::endPoint(void) const
{
return knots.back();
}
void Spline::initLinearSegments(const std::vector<Point>& points)
{
if (points.size() == 0)
{
throw std::runtime_error("Cannot create spline with no points");
}
else if (points.size() > 1)
{
// only splines with more than one point can have segments
for (size_t i = 1; i < points.size(); i++)
{
double input_start = (i - 1) / ((double)points.size() - 1);
double input_end = (i) / ((double)points.size() - 1);
Polynomial poly_x = Polynomial(std::make_pair(input_start, points[i - 1].x()),
std::make_pair(input_end, points[i].x()));
Polynomial poly_y = Polynomial(std::make_pair(input_start, points[i - 1].y()),
std::make_pair(input_end, points[i].y()));
segments.push_back(SplineSegment(poly_x, poly_y, input_start, input_end));
}
}
}
| 27.548387 | 90 | 0.546838 | matthewberends |
c98b00bb80bfbf6b9c21c3faa781990cf2d19139 | 7,081 | cpp | C++ | IGC/VectorCompiler/unittests/SPIRVConversions/SPIRVConversionsTest.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 440 | 2018-01-30T00:43:22.000Z | 2022-03-24T17:28:37.000Z | IGC/VectorCompiler/unittests/SPIRVConversions/SPIRVConversionsTest.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 225 | 2018-02-02T03:10:47.000Z | 2022-03-31T10:50:37.000Z | IGC/VectorCompiler/unittests/SPIRVConversions/SPIRVConversionsTest.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 138 | 2018-01-30T08:15:11.000Z | 2022-03-22T14:16:39.000Z | /*========================== begin_copyright_notice ============================
Copyright (C) 2019-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "llvm/ADT/StringRef.h"
#include "llvm/GenXIntrinsics/GenXIntrinsics.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Error.h"
#include "LLVMSPIRVLib.h"
#include "llvm/Target/TargetMachine.h"
#include "gtest/gtest.h"
#include "llvmWrapper/IR/DerivedTypes.h"
#include <strstream>
#include <memory>
using namespace llvm;
namespace {
static GenXIntrinsic::ID BeginGenXID = llvm::GenXIntrinsic::genx_3d_load;
static GenXIntrinsic::ID EndGenXID = llvm::GenXIntrinsic::genx_zzzzend;
// Currently returns some fixed types.
Type *generateAnyType(Intrinsic::IITDescriptor::ArgKind AK, LLVMContext &Ctx) {
using namespace Intrinsic;
switch (AK) {
case IITDescriptor::AK_Any:
case IITDescriptor::AK_AnyInteger:
return Type::getInt32Ty(Ctx);
case IITDescriptor::AK_AnyFloat:
return Type::getDoubleTy(Ctx);
case IITDescriptor::AK_AnyPointer:
return Type::getInt32PtrTy(Ctx);
case IITDescriptor::AK_AnyVector:
return IGCLLVM::FixedVectorType::get(Type::getInt32Ty(Ctx), 8);
}
llvm_unreachable("All types should be handled");
}
void generateOverloadedTypes(GenXIntrinsic::ID Id, LLVMContext &Ctx,
SmallVectorImpl<Type *> &Tys) {
using namespace Intrinsic;
SmallVector<IITDescriptor, 8> Table;
GenXIntrinsic::getIntrinsicInfoTableEntries(Id, Table);
for (unsigned i = 0, e = Table.size(); i != e; ++i) {
auto Desc = Table[i];
if (Desc.Kind != IITDescriptor::Argument)
continue;
size_t ArgNum = Desc.getArgumentNumber();
Tys.resize(std::max(ArgNum + 1, Tys.size()));
Tys[ArgNum] = generateAnyType(Desc.getArgumentKind(), Ctx);
}
}
static std::string ty2s(Type* ty) {
std::string type_str;
llvm::raw_string_ostream rso(type_str);
ty->print(rso, true);
return rso.str();
}
static std::string k2s(std::map<std::string, Attribute::AttrKind>& s,
Attribute::AttrKind kkk) {
for (const auto& i: s) {
if (i.second == kkk)
return i.first;
}
return "n/a";
}
class SpirvConvertionsTest : public testing::Test {
protected:
void SetUp() override {
M_.reset(new Module("Test_Module", Ctx_));
M_->setTargetTriple("spir64-unknown-unknown");
}
void TearDown() override {
M_.reset();
}
Module* Retranslate(LLVMContext& ctx, std::string& err) {
err.clear();
std::stringstream ss;
writeSpirv(M_.get(), ss, err);
if (!err.empty())
return nullptr;
std::string s_sv_ir = ss.str();
std::istrstream ir_stream(s_sv_ir.data(), s_sv_ir.size());
Module* result = nullptr;
readSpirv(ctx, ir_stream, result, err);
if (!err.empty())
return nullptr;
return result;
}
LLVMContext Ctx_;
std::unique_ptr<Module> M_;
std::set<std::string> FN_;
};
TEST_F(SpirvConvertionsTest, IntrinsicAttrs) {
Type *FArgTy[] = {Type::getInt32PtrTy(Ctx_)};
FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx_), FArgTy, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, "", M_.get());
BasicBlock *BB = BasicBlock::Create(Ctx_, "", F);
IRBuilder<> Builder(BB);
for (unsigned id = BeginGenXID; id < EndGenXID; ++id) {
GenXIntrinsic::ID XID = static_cast<GenXIntrinsic::ID>(id);
SmallVector<Type *, 8> Tyss;
generateOverloadedTypes(XID, Ctx_, Tyss);
Function* f = GenXIntrinsic::getGenXDeclaration(M_.get(), XID, Tyss);
SmallVector<Value *, 8> Args;
for (Type* ty: f->getFunctionType()->params()) {
Value* arg = llvm::Constant::getNullValue(ty);
Args.push_back(arg);
FN_.insert(f->getName().str());
/*
std::cout << "name: " << f->getName().str() << "\n";
Type* aty = arg->getType();
std::cout << " param_type: " << ty2s(ty) << ' ' << (void*)ty << "\n";
std::cout << " arg_type: " << ty2s(aty) << ' ' << (void*)aty << "\n";
*/
}
Builder.CreateCall(f, Args);
}
llvm::Error merr = M_->materializeAll();
if (merr)
FAIL() << "materialization a module resulted in failure: " << merr << "\n";
std::string err;
LLVMContext C;
Module* M = Retranslate(C, err);
if (!M) {
FAIL() << "failure during retranslation: " << err << "\n";
return;
}
// M_->dump();
// M->dump();
for (const std::string& fname :FN_) {
// std::cout << "processing <" << fname << ">" << "\n";
Function* fl = M->getFunction(fname);
Function* fr = M_->getFunction(fname);
if (!fl)
FAIL() << "could not find <" << fname << "> in the converted Module\n";
if (!fr)
FAIL() << "could not find <" << fname << "> in the original Module\n";
// fl->getAttributes().dump();
// fr->getAttributes().dump();
for (unsigned i = Attribute::None; i < Attribute::EndAttrKinds; ++i) {
Attribute::AttrKind att = (Attribute::AttrKind)i;
EXPECT_TRUE(fl->hasFnAttribute(att) == fr->hasFnAttribute(att));
}
}
}
TEST_F(SpirvConvertionsTest, FunctionAttrs) {
// TODO: think about how one can test all attributes. Right now the problem
// is that I don't know how to diffirentiate between attributes which require
// a value from those that don't.
std::map<std::string, Attribute::AttrKind> kinds = {
{ "Convergent", Attribute::Convergent },
{ "NoReturn", Attribute::NoReturn },
{ "NoInline", Attribute::NoInline },
{ "NoUnwind", Attribute::NoUnwind },
{ "ReadNone", Attribute::ReadNone },
{ "SafeStack", Attribute::SafeStack },
{ "WriteOnly", Attribute::WriteOnly },
};
for (const auto& k : kinds) {
Type *FArgTy[] = {Type::getInt32PtrTy(Ctx_)};
FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx_), FArgTy, false);
Function* test_f =
Function::Create(FT, Function::ExternalLinkage, k.first, M_.get());
for (unsigned i = Attribute::None; i < Attribute::EndAttrKinds; ++i) {
if (test_f->hasFnAttribute((Attribute::AttrKind)i)) {
test_f->removeFnAttr((Attribute::AttrKind)i);
}
}
test_f->addFnAttr(k.second);
BasicBlock *aux_BB = BasicBlock::Create(Ctx_, "", test_f);
IRBuilder<> aux_Builder(aux_BB);
}
std::string err;
LLVMContext C;
Module* M = Retranslate(C, err);
if (!M) {
FAIL() << "failure during retranslation: " << err << "\n";
return;
}
for (const auto& k : kinds) {
Function* fl = M->getFunction(k.first);
Function* fr = M_->getFunction(k.first);
for (unsigned i = Attribute::None; i < Attribute::EndAttrKinds; ++i) {
Attribute::AttrKind att = (Attribute::AttrKind)i;
if ((fl->hasFnAttribute(att) != fr->hasFnAttribute(att))) {
FAIL() << "Attriubute mismatch for <" << k.first << "> at attr:" <<
i << " (" << k2s(kinds, att) << ")\n";
}
}
}
// M_->dump();
// M->dump();
}
} // namespace
| 29.627615 | 80 | 0.622511 | kurapov-peter |
c995886ef90dfe5fec483adb02c06dde94ecedd9 | 4,750 | cpp | C++ | src/solutions/untexturedobjects/gl/drawloop.cpp | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 172 | 2015-01-05T15:36:14.000Z | 2022-03-11T10:57:23.000Z | src/solutions/untexturedobjects/gl/drawloop.cpp | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 19 | 2015-02-19T00:48:36.000Z | 2020-02-21T01:23:26.000Z | src/solutions/untexturedobjects/gl/drawloop.cpp | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 28 | 2015-01-08T12:16:18.000Z | 2020-05-30T18:07:36.000Z | #include "pch.h"
#include "drawloop.h"
#include "framework/gfx_gl.h"
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
UntexturedObjectsGLDrawLoop::UntexturedObjectsGLDrawLoop()
: m_ib()
, m_vb()
, m_varray()
, m_drawid()
, m_prog()
, m_transform_buffer()
{ }
// --------------------------------------------------------------------------------------------------------------------
bool UntexturedObjectsGLDrawLoop::Init(const std::vector<UntexturedObjectsProblem::Vertex>& _vertices,
const std::vector<UntexturedObjectsProblem::Index>& _indices,
size_t _objectCount)
{
if (!UntexturedObjectsSolution::Init(_vertices, _indices, _objectCount)) {
return false;
}
// Program
const char* kUniformNames[] = { "ViewProjection", nullptr };
m_prog = CreateProgramT("cubes_gl_multi_draw_vs.glsl",
"cubes_gl_multi_draw_fs.glsl",
kUniformNames, &mUniformLocation);
if (m_prog == 0) {
console::warn("Unable to initialize solution '%s', shader compilation/linking failed.", GetName().c_str());
return false;
}
glGenVertexArrays(1, &m_varray);
glBindVertexArray(m_varray);
// Buffers
glGenBuffers(1, &m_vb);
glBindBuffer(GL_ARRAY_BUFFER, m_vb);
glBufferData(GL_ARRAY_BUFFER, _vertices.size() * sizeof(UntexturedObjectsProblem::Vertex), &*_vertices.begin(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(UntexturedObjectsProblem::Vertex), (void*) offsetof(UntexturedObjectsProblem::Vertex, pos));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(UntexturedObjectsProblem::Vertex), (void*) offsetof(UntexturedObjectsProblem::Vertex, color));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
std::vector<uint32_t> drawids(_objectCount);
for (uint32_t i = 0; i < _objectCount; ++i) {
drawids[i] = i;
}
glGenBuffers(1, &m_drawid);
glBindBuffer(GL_ARRAY_BUFFER, m_drawid);
glBufferData(GL_ARRAY_BUFFER, drawids.size() * sizeof(uint32_t), drawids.data(), GL_STATIC_DRAW);
glVertexAttribIPointer(2, 1, GL_UNSIGNED_INT, sizeof(uint32_t), 0);
glVertexAttribDivisor(2, 1);
glEnableVertexAttribArray(2);
glGenBuffers(1, &m_ib);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ib);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indices.size() * sizeof(UntexturedObjectsProblem::Index), &*_indices.begin(), GL_STATIC_DRAW);
glGenBuffers(1, &m_transform_buffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_transform_buffer);
return GLRenderer::GetApiError() == GL_NO_ERROR;
}
// --------------------------------------------------------------------------------------------------------------------
void UntexturedObjectsGLDrawLoop::Render(const std::vector<Matrix>& _transforms)
{
size_t count = _transforms.size();
assert(count <= mObjectCount);
// Program
Vec3 dir = { -0.5f, -1, 1 };
Vec3 at = { 0, 0, 0 };
Vec3 up = { 0, 0, 1 };
dir = normalize(dir);
Vec3 eye = at - 250 * dir;
Matrix view = matrix_look_at(eye, at, up);
Matrix view_proj = mProj * view;
glUseProgram(m_prog);
glUniformMatrix4fv(mUniformLocation.ViewProjection, 1, GL_TRUE, &view_proj.x.x);
// Rasterizer State
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glDisable(GL_SCISSOR_TEST);
// Blend State
glDisable(GL_BLEND);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
// Depth Stencil State
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_transform_buffer);
glBufferData(GL_SHADER_STORAGE_BUFFER, _transforms.size() * sizeof(Matrix), &*_transforms.begin(), GL_DYNAMIC_DRAW);
for (size_t u = 0; u < count; ++u) {
glDrawElementsInstancedBaseInstance(GL_TRIANGLES, mIndexCount, GL_UNSIGNED_SHORT, nullptr, 1, u);
}
}
// --------------------------------------------------------------------------------------------------------------------
void UntexturedObjectsGLDrawLoop::Shutdown()
{
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glDeleteBuffers(1, &m_ib);
glDeleteBuffers(1, &m_vb);
glDeleteVertexArrays(1, &m_varray);
glDeleteBuffers(1, &m_drawid);
glDeleteBuffers(1, &m_transform_buffer);
glDeleteProgram(m_prog);
}
| 37.698413 | 153 | 0.584632 | michaelmarks |
c99a63623f4ce3fa4894067ee5b48bfac0f876d4 | 555 | cc | C++ | simctty/main_web.cc | skip2/simctty | 0de7a58f77a14367361637601816bf6c657f96a2 | [
"MIT"
] | 4 | 2016-10-01T00:13:13.000Z | 2020-06-10T10:09:56.000Z | simctty/main_web.cc | skip2/simctty | 0de7a58f77a14367361637601816bf6c657f96a2 | [
"MIT"
] | null | null | null | simctty/main_web.cc | skip2/simctty | 0de7a58f77a14367361637601816bf6c657f96a2 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "simctty/system.h"
int main(int argc, char** argv) {
System system;
uint64 cycle_count = 0;
const uint64 cycles_per_iteration = 20000000 / 1000;
fprintf(stdout, "Running\n");
if (!system.LoadImageFile("vmlinux.bin", 0x100)) {
fprintf(stderr, "Unable to load image\n");
return EXIT_FAILURE;
}
while (system.Run(cycles_per_iteration)) {
cycle_count += cycles_per_iteration;
while (system.GetUART()->CanRead()) {
fprintf(stderr, "%c", system.GetUART()->Read());
}
}
return 1;
}
| 19.821429 | 54 | 0.654054 | skip2 |
c99c85a7c469b6f6329eacc2be26f3cb09a856ee | 928 | cpp | C++ | src/videowidget.cpp | radzevich/VSPlayer | b645589460cfc0ca4e5eae6ad4b0b1c1d4fc5c87 | [
"Apache-2.0"
] | 1 | 2020-07-07T01:41:22.000Z | 2020-07-07T01:41:22.000Z | src/videowidget.cpp | radzevich/VSPlayer | b645589460cfc0ca4e5eae6ad4b0b1c1d4fc5c87 | [
"Apache-2.0"
] | null | null | null | src/videowidget.cpp | radzevich/VSPlayer | b645589460cfc0ca4e5eae6ad4b0b1c1d4fc5c87 | [
"Apache-2.0"
] | null | null | null | #include "videowidget.h"
#include <QMouseEvent>
VideoWidget::VideoWidget(QWidget *parent)
: QVideoWidget(parent)
{
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
QPalette p = palette();
p.setColor(QPalette::Window, Qt::black);
setPalette(p);
setAttribute(Qt::WA_OpaquePaintEvent);
}
void VideoWidget::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape && isFullScreen()) {
setFullScreen(false);
event->accept();
} else if (event->key() == Qt::Key_Enter && event->modifiers() & Qt::Key_Alt) {
setFullScreen(!isFullScreen());
event->accept();
} else {
QVideoWidget::keyPressEvent(event);
}
}
void VideoWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
setFullScreen(!isFullScreen());
event->accept();
}
void VideoWidget::mousePressEvent(QMouseEvent *event)
{
QVideoWidget::mousePressEvent(event);
}
| 23.2 | 83 | 0.665948 | radzevich |
c9a782c1fe1c1af5b9627e30bd010014d0854c75 | 443 | cpp | C++ | src/backends/sdl/system/event/wait.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | src/backends/sdl/system/event/wait.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | src/backends/sdl/system/event/wait.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | #include <awl/backends/sdl/exception.hpp>
#include <awl/backends/sdl/system/event/wait.hpp>
#include <fcppt/text.hpp>
#include <fcppt/config/external_begin.hpp>
#include <SDL_events.h>
#include <fcppt/config/external_end.hpp>
SDL_Event awl::backends::sdl::system::event::wait()
{
SDL_Event result;
if (SDL_WaitEvent(&result) == 0)
{
throw awl::backends::sdl::exception{FCPPT_TEXT("SDL_WaitEvent failed!")};
}
return result;
}
| 23.315789 | 77 | 0.724605 | freundlich |
c9a97d9e835fd97a63f4622a646a0355d279fd56 | 4,660 | cpp | C++ | app/lib/gt_core/src/trainer.cpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | 3 | 2018-10-11T13:37:42.000Z | 2021-03-23T21:54:02.000Z | app/lib/gt_core/src/trainer.cpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | null | null | null | app/lib/gt_core/src/trainer.cpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | null | null | null | #include <gt_core/trainer.hpp>
#include <gt_os/window-finder.hpp>
#include <gt_os/window-enumerator.hpp>
namespace gt::core {
Trainer::Trainer(std::string&& trainerTitle, os::OsApi *osApi)
: title(trainerTitle) {
os::setConsoleTitle(this->title.c_str());
this->osApi = osApi;
}
Trainer::~Trainer() = default;
bool Trainer::trainerIsRunning() const {
os::WindowEnumerator windowEnumerator(this->osApi);
os::WindowFinder windowFinder(&windowEnumerator);
os::WindowManager windowManager(this->osApi, &windowFinder);
return windowManager.isOpened(this->title);
}
void Trainer::showOpenedWindow() const {
os::WindowEnumerator windowEnumerator(this->osApi);
os::WindowFinder windowFinder(&windowEnumerator);
os::WindowManager windowManager(this->osApi, &windowFinder);
windowManager.show(this->title);
}
void Trainer::start() const {
lua::LuaWrapper lua;
void (*lambada)(xml::CheatEntry *, float) = [](xml::CheatEntry *entry,
float valueToAdd) {
DWORD processId = os::getProcessIdByName("KillingFloor.exe");
Game game(processId, &os::OsApi::getInstance());
game.updateValue(entry, valueToAdd);
};
lua.registerFunction("addValueTo", lambada);
// TODO: remove unused parameter for stopMP3.
lua.registerFunction("stopMP3", os::stopMP3);
lua.registerFunction("playMP3", os::playMP3);
lua.registerFunction("playWAV", os::playWAV);
lua.registerFunction("readFile", lua::LuaWrapper::createUserData);
loadLuaState(lua);
const auto registeredKeys = lua.getVector<int>((char *)"registeredKeys");
const char *processName = *lua.getValue<char *>((char *)"processName");
std::cout << processName << std::endl;
os::KeyboardWatcher keyboardWatcher(registeredKeys, this->osApi);
for (;; os::sleep(50)) {
// TODO: remove it!
if (keyboardWatcher.isKeyDown(VK_F12)) {
break;
}
// TODO: uncomment it!
// Close Trainer IF GAME is NOT RUNNING
// if (!gameIsRunning())
// {
// break;
// }
// TODO: uncomment it!
// // Continue IF GAME is not active || PLAYER is DEAD
// if (!GameOnFocus() || game->PlayerIsDead())
// {
// Sleep(1000);
// continue;
// }
// // Rewrite data if FREEZE FLAG enabled
// if (bGodMode)
// {
// game->UpdateData1();
// }
// if (bNoReload)
// {
// game->UpdateData2();
// }
for (const int key : registeredKeys) {
if (keyboardWatcher.isKeyPressed(key)) {
lua.callFunction("handleKey", key,
keyboardWatcher.isKeyDown(VK_SHIFT),
keyboardWatcher.isKeyDown(VK_CONTROL),
keyboardWatcher.isKeyDown(VK_MENU));
}
}
}
}
bool Trainer::chooseConfig() const {
std::cout << "method 'Trainer::chooseConfig' is not implemented yet!"
<< std::endl;
return true;
}
bool Trainer::gameIsRunning() const {
std::cout << "method 'Trainer::gameIsRunning' is not implemented yet!"
<< std::endl;
return true;
}
void loadLuaState(lua::LuaWrapper &lua) {
#if DEBUG
constexpr char *script = (char *)R"(
keyCodes = {
VK_F5 = 0x74,
VK_F6 = 0x75,
VK_F7 = 0x76,
VK_F8 = 0x77,
VK_F9 = 0x78
}
api = {
playSound = playSound,
addValueTo = addValueTo,
readFile = readFile
}
processName = 'KillingFloor.exe'
entries = api.readFile('KillingFloor.CT')
registeredKeys = {
keyCodes.VK_F6,
keyCodes.VK_F7,
keyCodes.VK_F8,
keyCodes.VK_F9
}
function handleKey (key, shift, ctrl, alt)
if key == keyCodes.VK_F6 then
print('god mode')
api.playSound('sounds/on.wav')
elseif key == keyCodes.VK_F7 then
print('no reload')
api.playSound('sounds/on.wav')
elseif key == keyCodes.VK_F8 then
api.addValueTo(entries.money, 1000)
print('increase money')
api.playSound('sounds/money.wav')
elseif key == keyCodes.VK_F9 and shift and ctrl and alt then
print('level up for all perks')
api.playSound('sounds/experience.wav')
end
end
function tick()
-- addValueTo(entries.armor, 100)
end
)";
lua.loadString(script);
#else
lua.loadFile("scripts/KillingFloor.lua");
#endif
}
} // namespace gt::core
| 28.072289 | 77 | 0.583262 | my-repositories |
c9ac6d0aff5e734df80b8d02b9bc3dad3e1b610a | 1,308 | cpp | C++ | src/main.cpp | ithamsteri/homework_05 | 713cb2558bd66fbbbaea656d96f430ed3be0551a | [
"MIT"
] | null | null | null | src/main.cpp | ithamsteri/homework_05 | 713cb2558bd66fbbbaea656d96f430ed3be0551a | [
"MIT"
] | 2 | 2018-09-22T13:27:08.000Z | 2018-10-16T16:42:52.000Z | src/main.cpp | ithamsteri/homework_05 | 713cb2558bd66fbbbaea656d96f430ed3be0551a | [
"MIT"
] | null | null | null | #include "DocumentController.h"
#include "DocumentModel.h"
#include "DocumentView.h"
#include "storages/SVG_Storage.h"
#include <iostream>
#include <string>
int main(int, char *[]) {
// ***************************
// * Setup MVC components *
// ***************************
DocumentModel model;
DocumentView view(model);
DocumentController controller(model, view);
// ****************************
// * Work with empty document *
// ****************************
controller.addShape(Shape::Circle, "x=100;y=323;radius=3");
controller.addShape(Shape::Rectangle, "x=10;y=30;width=100;height=390");
controller.clear();
// *****************************************
// * Load from storage and modify document *
// *****************************************
SVGStorage storage;
controller.load(&storage, "filename: funny.svg");
auto rect_id = controller.addShape(Shape::Rectangle, "x=100;y=10;width=140;height=30");
auto circle_id = controller.addShape(Shape::Circle, "x=10;y=5;radius=12");
controller.removeShape(rect_id);
std::clog << "Serialized data of Circle: " << controller.getShape(circle_id) << '\n';
// save to storage with new filename
controller.save(&storage, "filename: funny_new.svg");
return 0;
}
| 33.538462 | 91 | 0.560398 | ithamsteri |
c9af0bc0a6b59a70ac6d8389b7936f9559638e00 | 212 | cpp | C++ | chapter-7/7.39.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-7/7.39.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-7/7.39.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // Illegal
// it will introduce a ambiguous-like call, when there is a statememt trying to define a object of Sales_data class type but without arguments, compiler does not know which one is better to be called.
| 70.666667 | 200 | 0.787736 | zero4drift |
c9b0645c63044fa0174cbf257e6a4a1e32bf15df | 1,152 | cpp | C++ | Codeforces Round #303 (Div. 2)/B. Equidistant String/B. Equidistant String/main.cpp | anirudha-ani/Codeforces | 6c7f64257939d44b1c2ec9dd202f1c9f899f1cad | [
"Apache-2.0"
] | null | null | null | Codeforces Round #303 (Div. 2)/B. Equidistant String/B. Equidistant String/main.cpp | anirudha-ani/Codeforces | 6c7f64257939d44b1c2ec9dd202f1c9f899f1cad | [
"Apache-2.0"
] | null | null | null | Codeforces Round #303 (Div. 2)/B. Equidistant String/B. Equidistant String/main.cpp | anirudha-ani/Codeforces | 6c7f64257939d44b1c2ec9dd202f1c9f899f1cad | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// B. Equidistant String
//
// Created by Anirudha Paul on 5/21/15.
// Copyright (c) 2015 Anirudha Paul. All rights reserved.
//
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
string first ;
string second ;
cin.clear();
getline(cin,first);
cin.clear();
getline(cin,second);
char answer[100000];
long long length = first.length();
int same = 0 ;
int notSame = 0;
for (int i = 0 ; i < length ; i++)
{
if (first[i] == second[i])
{
same++;
answer[i] = first[i];
}
else
{
notSame++;
if (notSame%2 == 0)
{
answer[i] = first[i];
}
else
{
answer[i] = second[i];
}
}
}
if (notSame % 2 != 0)
{
printf("impossible");
}
else
{
for (int i = 0 ; i < length ; i++)
printf("%c" , answer[i]);
}
printf("\n");
return 0;
}
| 16.695652 | 58 | 0.422743 | anirudha-ani |
c9b1b9994010f3e31021925d781504d7a507db83 | 2,813 | hpp | C++ | include/lz_end_toolkit/construct_lcp.hpp | dkempa/lz-end-toolkit | d0a0bd0fd3ec6adc1df198190d588fbaa8ae7496 | [
"MIT"
] | 1 | 2021-06-24T07:27:41.000Z | 2021-06-24T07:27:41.000Z | include/lz_end_toolkit/construct_lcp.hpp | dkempa/lz-end-toolkit | d0a0bd0fd3ec6adc1df198190d588fbaa8ae7496 | [
"MIT"
] | null | null | null | include/lz_end_toolkit/construct_lcp.hpp | dkempa/lz-end-toolkit | d0a0bd0fd3ec6adc1df198190d588fbaa8ae7496 | [
"MIT"
] | null | null | null | /**
* @file construct_lcp.hpp
* @section LICENCE
*
* This file is part of LZ-End Toolkit v0.1.0
* See: https://github.com/dominikkempa/lz-end-toolkit
*
* Published in:
* Dominik Kempa and Dmitry Kosolobov:
* LZ-End Parsing in Compressed Space.
* Data Compression Conference (DCC), IEEE, 2017.
*
* Copyright (C) 2016-2021
* Dominik Kempa <dominik.kempa (at) gmail.com>
* Dmitry Kosolobov <dkosolobov (at) mail.ru>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**/
#ifndef __LZ_END_TOOLKIT_CONSTRUCT_LCP_HPP_INCLUDED
#define __LZ_END_TOOLKIT_CONSTRUCT_LCP_HPP_INCLUDED
#include <cstdint>
#include "../utils/utils.hpp"
namespace lz_end_toolkit_private {
template<typename char_type,
typename sa_int_type,
typename lcp_int_type>
void construct_lcp(
const char_type *text,
std::uint64_t text_length,
const sa_int_type *sa,
lcp_int_type *lcp_array) {
lcp_int_type *phi = lcp_array;
lcp_int_type *plcp = utils::allocate_array<lcp_int_type>(text_length);
std::uint64_t phi_undefined_index = sa[0];
for (std::uint64_t i = 1; i < text_length; ++i) {
std::uint64_t addr = sa[i];
phi[addr] = sa[i - 1];
}
std::uint64_t lcp = 0;
for (std::uint64_t i = 0; i < text_length; ++i) {
if (i == phi_undefined_index) {
plcp[i] = 0;
continue;
}
std::uint64_t j = phi[i];
while (i + lcp < text_length && j + lcp < text_length
&& text[i + lcp] == text[j + lcp]) ++lcp;
plcp[i] = (lcp_int_type)lcp;
if (lcp > 0)
--lcp;
}
for (std::uint64_t i = 0; i < text_length; ++i) {
std::uint64_t addr = sa[i];
lcp_array[i] = plcp[addr];
}
utils::deallocate(plcp);
}
} // namespace lz_end_toolkit_private
#endif // __LZ_END_TOOLKIT_CONSTRUCT_LCP_HPP_INCLUDED
| 29.925532 | 72 | 0.697476 | dkempa |
c9ba58d381284e7e4438af2d088127afbc94aa8f | 6,191 | cc | C++ | tensorflow/core/kernels/remote_fused_graph_execute_utils_test.cc | Dashhh/tensorflow | 1708b92bb923e420d746a56baafc7d4ddcd5e05e | [
"Apache-2.0"
] | 5 | 2017-10-02T05:56:47.000Z | 2022-03-25T04:31:19.000Z | tensorflow/core/kernels/remote_fused_graph_execute_utils_test.cc | Dashhh/tensorflow | 1708b92bb923e420d746a56baafc7d4ddcd5e05e | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/remote_fused_graph_execute_utils_test.cc | Dashhh/tensorflow | 1708b92bb923e420d746a56baafc7d4ddcd5e05e | [
"Apache-2.0"
] | 8 | 2016-05-09T15:08:29.000Z | 2020-06-11T18:04:52.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/remote_fused_graph_execute_utils.h"
#include "tensorflow/cc/framework/scope.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
const string NAME_A = "a";
const string NAME_B = "b";
const string NAME_A_PLUS_B = "a_plus_b";
constexpr float NODE_A_VAL = 2.0f;
constexpr float NODE_B_VAL = 3.0f;
constexpr float VALUE_TOLERANCE_FLOAT = 1e-8f;
static Output BuildAddOps(const Scope& scope, const Input& x, const Input& y) {
EXPECT_TRUE(scope.ok());
auto _x = ops::AsNodeOut(scope, x);
EXPECT_TRUE(scope.ok());
auto _y = ops::AsNodeOut(scope, y);
EXPECT_TRUE(scope.ok());
Node* ret;
const auto unique_name = scope.GetUniqueNameForOp("Add");
auto builder = NodeBuilder(unique_name, "Add").Input(_x).Input(_y);
scope.UpdateBuilder(&builder);
scope.UpdateStatus(builder.Finalize(scope.graph(), &ret));
EXPECT_TRUE(scope.ok());
return Output(ret, 0);
}
static GraphDef CreateAddGraphDef() {
Scope root = Scope::NewRootScope();
Output node_a = ops::Const(root.WithOpName(NAME_A), NODE_A_VAL);
Output node_b = ops::Const(root.WithOpName(NAME_B), NODE_B_VAL);
Output node_add = BuildAddOps(root.WithOpName(NAME_A_PLUS_B), node_a, node_b);
GraphDef def;
TF_CHECK_OK(root.ToGraphDef(&def));
return def;
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphA) {
GraphDef def = CreateAddGraphDef();
std::pair<string, Tensor> input_node_info;
input_node_info.first = NAME_A;
input_node_info.second = Tensor(DT_FLOAT, {});
input_node_info.second.scalar<float>()() = 1.0f;
const std::vector<std::pair<string, Tensor>> inputs{input_node_info};
std::vector<string> outputs = {NAME_B, NAME_A_PLUS_B};
std::vector<tensorflow::Tensor> output_tensors;
Status status = RemoteFusedGraphExecuteUtils::DryRunInference(
def, inputs, outputs, false /* initialize_by_zero */, &output_tensors);
ASSERT_TRUE(status.ok()) << status;
EXPECT_EQ(outputs.size(), output_tensors.size());
EXPECT_NEAR(NODE_B_VAL, output_tensors.at(0).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
EXPECT_NEAR(1.0f + NODE_B_VAL, output_tensors.at(1).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphAUninitialized) {
GraphDef def = CreateAddGraphDef();
std::pair<string, Tensor> input_node_info;
input_node_info.first = NAME_A;
input_node_info.second = Tensor(DT_FLOAT, {});
const std::vector<std::pair<string, Tensor>> inputs{input_node_info};
std::vector<string> outputs = {NAME_B, NAME_A_PLUS_B};
std::vector<tensorflow::Tensor> output_tensors;
Status status = RemoteFusedGraphExecuteUtils::DryRunInference(
def, inputs, outputs, true /* initialize_by_zero */, &output_tensors);
ASSERT_TRUE(status.ok()) << status;
EXPECT_EQ(outputs.size(), output_tensors.size());
EXPECT_NEAR(NODE_B_VAL, output_tensors.at(0).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
EXPECT_NEAR(NODE_B_VAL, output_tensors.at(1).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphAB) {
GraphDef def = CreateAddGraphDef();
std::pair<string, Tensor> input_node_info_a;
input_node_info_a.first = NAME_A;
input_node_info_a.second = Tensor(DT_FLOAT, {});
input_node_info_a.second.scalar<float>()() = NODE_A_VAL;
std::pair<string, Tensor> input_node_info_b;
input_node_info_b.first = NAME_B;
input_node_info_b.second = Tensor(DT_FLOAT, {});
input_node_info_b.second.scalar<float>()() = NODE_B_VAL;
const std::vector<std::pair<string, Tensor>> inputs{input_node_info_a,
input_node_info_b};
std::vector<string> outputs = {NAME_A_PLUS_B};
std::vector<tensorflow::Tensor> output_tensors;
Status status = RemoteFusedGraphExecuteUtils::DryRunInference(
def, inputs, outputs, false /* initialize_by_zero */, &output_tensors);
ASSERT_TRUE(status.ok()) << status;
EXPECT_EQ(outputs.size(), output_tensors.size());
EXPECT_NEAR(NODE_A_VAL + NODE_B_VAL, output_tensors.at(0).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphForAllNodes) {
// Set Node "a" as an input with value (= 1.0f)
std::pair<string, Tensor> input_node_info_a;
input_node_info_a.first = NAME_A;
input_node_info_a.second = Tensor(DT_FLOAT, {});
input_node_info_a.second.scalar<float>()() = 1.0f;
// Setup dryrun arguments
const std::vector<std::pair<string, Tensor>> inputs{input_node_info_a};
RemoteFusedGraphExecuteUtils::TensorShapeMap output_tensor_info;
GraphDef def = CreateAddGraphDef();
// dryrun
const Status status = RemoteFusedGraphExecuteUtils::DryRunInferenceForAllNode(
def, inputs, false /* initialize_by_zero */, &output_tensor_info);
ASSERT_TRUE(status.ok()) << status;
// Assert output node count
ASSERT_EQ(3, output_tensor_info.size());
ASSERT_EQ(1, output_tensor_info.count(NAME_A));
ASSERT_EQ(1, output_tensor_info.count(NAME_B));
ASSERT_EQ(1, output_tensor_info.count(NAME_A_PLUS_B));
EXPECT_EQ(DT_FLOAT, output_tensor_info.at(NAME_B).first);
EXPECT_EQ(DT_FLOAT, output_tensor_info.at(NAME_A_PLUS_B).first);
const TensorShape& shape_b = output_tensor_info.at(NAME_B).second;
const TensorShape& shape_a_b = output_tensor_info.at(NAME_A_PLUS_B).second;
EXPECT_EQ(0, shape_b.dims());
EXPECT_EQ(0, shape_a_b.dims());
}
} // namespace tensorflow
| 41.831081 | 80 | 0.730738 | Dashhh |
c9bcd662975e6308d22fd1ae527e282d25623673 | 1,342 | cpp | C++ | src/All2DEngine/All2D/All2D_Controller.cpp | ldornbusch/All2D_Base | c790293b3030de97f65d62f6617222c42d18fa6a | [
"Apache-2.0"
] | null | null | null | src/All2DEngine/All2D/All2D_Controller.cpp | ldornbusch/All2D_Base | c790293b3030de97f65d62f6617222c42d18fa6a | [
"Apache-2.0"
] | null | null | null | src/All2DEngine/All2D/All2D_Controller.cpp | ldornbusch/All2D_Base | c790293b3030de97f65d62f6617222c42d18fa6a | [
"Apache-2.0"
] | null | null | null | #include "All2D_Controller.h"
#include "All2D_System.h"
All2D_Controller::All2D_Controller(std::string name) :xContainer("name"){
imgFrameBuffer.resize(All2D_System::fixedX,All2D_System::fixedY);
requestLoad();
}
All2D_Controller::~All2D_Controller(){
imgFrameBuffer.finish();
}
void All2D_Controller::init()
{
// init sound engine instance
All2D_System::sound->init();
}
bool All2D_Controller::masterPaint(Image& backBuffer)
{
bool retVal=false;
retVal=paint(backBuffer);
All2D_System::spriteManager.paint(backBuffer);
All2D_System::spriteManager.clear();
return retVal;
}
bool All2D_Controller::handleEvent(Event *evt)
{
switch (evt->Type)
{
case MM_KEYDOWN:
{
char a=(char)evt->wData;
switch (a) {
case sf::Keyboard::BackSpace:
case sf::Keyboard::Escape:
case sf::Keyboard::F12:
isExit = true;
break;
case sf::Keyboard::F:
isFullscreen=!isFullscreen;
MessageManager::handleEvent(new Event(MM_SETFULLSCREEN,(int)isFullscreen,0));
break;
default:
break;
}
}
break;
default:
break;
}
return xContainer::handleEvent(evt);
}
| 23.137931 | 97 | 0.586438 | ldornbusch |
c9c018adb71a3e5f0990a8daad2ab057a02adb3c | 3,742 | cpp | C++ | src/designer/formdesigner/formwindowsettings.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | 1 | 2021-03-16T21:47:41.000Z | 2021-03-16T21:47:41.000Z | src/designer/formdesigner/formwindowsettings.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | src/designer/formdesigner/formwindowsettings.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 1992-2006 Trolltech ASA. All rights reserved.
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.trolltech.com/products/qt/opensource.html
**
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://www.trolltech.com/products/qt/licensing.html or contact the
** sales department at [email protected].
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include "formwindowsettings.h"
#include <QtDesigner/QtDesigner>
#include <QtGui/QStyle>
FormWindowSettings::FormWindowSettings(QDesignerFormWindowInterface *parent)
: QDialog(parent), m_formWindow(parent)
{
ui.setupUi(this);
int defaultMargin = INT_MIN, defaultSpacing = INT_MIN;
formWindow()->layoutDefault(&defaultMargin, &defaultSpacing);
QStyle *style = formWindow()->style();
ui.defaultMarginSpinBox->setValue(style->pixelMetric(QStyle::PM_DefaultChildMargin, 0));
ui.defaultSpacingSpinBox->setValue(style->pixelMetric(QStyle::PM_DefaultLayoutSpacing, 0));
if (defaultMargin != INT_MIN || defaultMargin != INT_MIN) {
ui.layoutDefaultGroupBox->setChecked(true);
if (defaultMargin != INT_MIN)
ui.defaultMarginSpinBox->setValue(defaultMargin);
if (defaultSpacing != INT_MIN)
ui.defaultSpacingSpinBox->setValue(defaultSpacing);
} else {
ui.layoutDefaultGroupBox->setChecked(false);
}
QString marginFunction, spacingFunction;
formWindow()->layoutFunction(&marginFunction, &spacingFunction);
if (!marginFunction.isEmpty() || !spacingFunction.isEmpty()) {
ui.layoutFunctionGroupBox->setChecked(true);
ui.marginFunctionLineEdit->setText(marginFunction);
ui.spacingFunctionLineEdit->setText(spacingFunction);
} else {
ui.layoutFunctionGroupBox->setChecked(false);
}
QString pixFunction = formWindow()->pixmapFunction();
ui.pixmapFunctionGroupBox->setChecked(!pixFunction.isEmpty());
ui.pixmapFunctionLineEdit->setText(pixFunction);
ui.authorLineEdit->setText(formWindow()->author());
foreach (QString includeHint, formWindow()->includeHints()) {
if (includeHint.isEmpty())
continue;
ui.includeHintsTextEdit->append(includeHint);
}
}
FormWindowSettings::~FormWindowSettings()
{
}
QDesignerFormWindowInterface *FormWindowSettings::formWindow() const
{
return m_formWindow;
}
void FormWindowSettings::accept()
{
formWindow()->setAuthor(ui.authorLineEdit->text());
if (ui.pixmapFunctionGroupBox->isChecked())
formWindow()->setPixmapFunction(ui.pixmapFunctionLineEdit->text());
if (ui.layoutDefaultGroupBox->isChecked())
formWindow()->setLayoutDefault(ui.defaultMarginSpinBox->value(), ui.defaultSpacingSpinBox->value());
if (ui.layoutFunctionGroupBox->isChecked())
formWindow()->setLayoutFunction(ui.marginFunctionLineEdit->text(), ui.spacingFunctionLineEdit->text());
formWindow()->setIncludeHints(ui.includeHintsTextEdit->toPlainText().split(QLatin1String("\n")));
formWindow()->setDirty(true);
QDialog::accept();
}
| 35.980769 | 111 | 0.696152 | leaderit |
c9c1aa4f19e6498de34a61175dd7cf8af1f60929 | 9,006 | cpp | C++ | src/sample.cpp | reedacartwright/emdel | 58ea9d4db89c4a1852ba5405ef73c2eca6539ce3 | [
"MIT"
] | null | null | null | src/sample.cpp | reedacartwright/emdel | 58ea9d4db89c4a1852ba5405ef73c2eca6539ce3 | [
"MIT"
] | 1 | 2020-12-03T16:50:15.000Z | 2021-03-23T22:51:19.000Z | src/sample.cpp | reedacartwright/emdel | 58ea9d4db89c4a1852ba5405ef73c2eca6539ce3 | [
"MIT"
] | null | null | null | /***************************************************************************
* Copyright (C) 2007 by Reed A. Cartwright *
* [email protected] *
* *
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR *
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
* OTHER DEALINGS IN THE SOFTWARE. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#define _USE_MATH_DEFINES
#include <iostream>
#include <boost/math/special_functions/zeta.hpp>
#include "sample.h"
#include "sample_k2p.h"
#include "ccvector.h"
#include "series.h"
#include "invert_matrix.h"
#include "table.h"
#include "emdel.h"
using namespace std;
void sample_k2p_zeta::preallocate(size_t maxa, size_t maxd)
{
p.resize(maxa+1,maxd+1,0.0);
}
void sample_k2p_zeta::presample_step(const params_type ¶ms, const sequence &seq_a, const sequence &seq_d)
{
size_t sz_max = std::max(sz_height, sz_width);
size_t sz_anc = seq_a.size();
size_t sz_dec = seq_d.size();
sa = seq_a;
sd = seq_d;
const model_type &model = get_model();
p(0,0) = prob_scale;
for(size_t d = 1; d <= sz_dec; ++d) {
p(0,d) = 0.0;
for(size_t k = d; k > 0; --k)
p(0,d) += p(0,d-k)*model.p_indel_size[k];
}
for(size_t a = 1; a <= sz_anc; ++a) {
p(a,0) = 0.0;
for(size_t k = a; k > 0; --k)
p(a,0) += p(a-k,0)*model.p_indel_size[k];
}
for(size_t a=1;a<=sz_anc;++a) {
for(size_t d=1;d<= sz_dec;++d) {
double pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];
for(size_t k = d; k > 0; --k)
pt += p(a,d-k)*model.p_indel_size[k];
for(size_t k = a; k > 0; --k)
pt += p(a-k,d)*model.p_indel_size[k];
p(a,d) = pt;
}
}
}
void sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)
{
size_t a = sa.size();
size_t d = sd.size();
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
while(a != 0 || d != 0) {
double u = p(a,d)*myrand.uniform01();
double t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;
if(u < t) {
// match
a = a-1;
d = d-1;
seq_a.append(1, ccNuc[sa[a]]);
seq_d.append(1, ccNuc[sd[d]]);
} else {
for(size_t k = 1; k <= a || k <= d; ++k) {
if(k <= a) {
t += p(a-k,d)*model.p_indel_size[k];
if(u < t) {
// gap in d
seq_d.append(k, '-');
while(k--) seq_a.append(1, ccNuc[sa[--a]]);
break;
}
}
if(k <= d)
{
t += p(a,d-k)*model.p_indel_size[k];
if(u < t) {
// gap in a
seq_a.append(k, '-');
while(k--) seq_d.append(1, ccNuc[sd[--d]]);
break;
}
}
}
}
//seq_a.append(1,',');
//seq_d.append(1,',');
}
reverse(seq_a.begin(), seq_a.end());
reverse(seq_d.begin(), seq_d.end());
}
void sample_k2p_geo::preallocate(size_t maxa, size_t maxd)
{
p.resize(maxa+1,maxd+1,0.0);
}
void sample_k2p_geo::presample_step(const params_type ¶ms, const sequence &seq_a, const sequence &seq_d)
{
size_t sz_max = std::max(sz_height, sz_width);
size_t sz_anc = seq_a.size();
size_t sz_dec = seq_d.size();
sa = seq_a;
sd = seq_d;
const model_type &model = get_model();
double row_cache = 0.0;
vector<double> col_cache(sz_dec+1, 0.0);
p(0,0) = prob_scale;
for(size_t d = 1; d <= sz_dec; ++d) {
row_cache *= model.p_extend;
row_cache += p(0,d-1)*model.p_open;
p(0,d) = row_cache;
}
row_cache = 0.0;
for(size_t a = 1; a <= sz_anc; ++a) {
row_cache *= model.p_extend;
row_cache += p(a-1,0)*model.p_open;
p(a,0) = row_cache;
}
for(size_t a=1;a<=sz_anc;++a) {
row_cache = 0.0;
for(size_t d=1;d<= sz_dec;++d) {
double pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];
row_cache *= model.p_extend;
row_cache += p(a,d-1)*model.p_open;
pt += row_cache;
col_cache[d] *= model.p_extend;
col_cache[d] += p(a-1,d)*model.p_open;
pt += col_cache[d];
p(a,d) = pt;
}
}
}
void sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)
{
size_t a = sa.size();
size_t d = sd.size();
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
while(a != 0 || d != 0) {
double u = p(a,d)*myrand.uniform01();
double t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;
if(u < t) {
// match
a = a-1;
d = d-1;
seq_a.append(1, ccNuc[sa[a]]);
seq_d.append(1, ccNuc[sd[d]]);
} else {
for(size_t k = 1; k <= a || k <= d; ++k) {
if(k <= a) {
t += p(a-k,d)*model.p_indel_size[k];
if(u < t) {
// gap in d
seq_d.append(k, '-');
while(k--) seq_a.append(1, ccNuc[sa[--a]]);
break;
}
}
if(k <= d)
{
t += p(a,d-k)*model.p_indel_size[k];
if(u < t) {
// gap in a
seq_a.append(k, '-');
while(k--) seq_d.append(1, ccNuc[sd[--d]]);
break;
}
}
}
}
//seq_a.append(1,',');
//seq_d.append(1,',');
}
reverse(seq_a.begin(), seq_a.end());
reverse(seq_d.begin(), seq_d.end());
}
// Draw from Zipf distribution, with parameter a > 1.0
// Devroye Luc (1986) Non-uniform random variate generation.
// Springer-Verlag: Berlin. p551
inline unsigned int rand_zipf(double a)
{
double b = pow(2.0, a-1.0);
double x,t;
do {
x = floor(pow(myrand.uniform01(), -1.0/(a-1.0)));
t = pow(1.0+1.0/x, a-1.0);
} while( myrand.uniform01()*x*(t-1.0)*b >= t*(b-1.0));
return (unsigned int)x;
}
const char g_nuc[] = "ACGT";
const char g_nuc2[] = "ACGT" "GTAC" "TGCA" "CATG";
void gen_sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)
{
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
const double z = get_params()[model_k2p_zeta::pZ];
while(1) {
double p = myrand.uniform01();
if(p < model.p_2h) {
// M
unsigned int x = myrand.uniform(4);
seq_a.append(1, g_nuc[x]);
p = myrand.uniform01();
if(p < model.p_match) {
seq_d.append(1, g_nuc2[x]);
} else if(p < model.p_match+model.p_ts) {
seq_d.append(1, g_nuc2[x+4]);
} else if(p < 1.0 - 0.5*model.p_ts) {
seq_d.append(1, g_nuc2[x+8]);
} else {
seq_d.append(1, g_nuc2[x+12]);
}
} else if(p < model.p_2h+model.p_2g) {
// U
unsigned int x;
do {
x = rand_zipf(z);
} while(x > nmax);
seq_d.append(x, '-');
while(x--) {
seq_a.append(1, g_nuc[myrand.uniform(4)]);
}
} else if(p < 1.0-model.p_end) {
// V
unsigned int x;
do {
x = rand_zipf(z);
} while(x > nmax);
seq_a.append(x, '-');
while(x--) {
seq_d.append(1, g_nuc[myrand.uniform(4)]);
}
} else {
// E
break;
}
}
}
void gen_sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)
{
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
const double q = 1.0/get_params()[model_k2p_geo::pQ];
while(1) {
double p = myrand.uniform01();
if(p < model.p_2h) {
// M
unsigned int x = myrand.uniform(4);
seq_a.append(1, g_nuc[x]);
p = myrand.uniform01();
if(p < model.p_match) {
seq_d.append(1, g_nuc2[x]);
} else if(p < model.p_match+model.p_ts) {
seq_d.append(1, g_nuc2[x+4]);
} else if(p < 1.0 - 0.5*model.p_ts) {
seq_d.append(1, g_nuc2[x+8]);
} else {
seq_d.append(1, g_nuc2[x+12]);
}
} else if(p < model.p_2h+model.p_2g) {
// U
unsigned int x = myrand.geometric(q);
seq_d.append(x, '-');
while(x--) {
seq_a.append(1, g_nuc[myrand.uniform(4)]);
}
} else if(p < 1.0-model.p_end) {
// V
unsigned int x = myrand.geometric(q);
seq_a.append(x, '-');
while(x--) {
seq_d.append(1, g_nuc[myrand.uniform(4)]);
}
} else {
// E
break;
}
}
}
| 26.333333 | 109 | 0.550411 | reedacartwright |
c9d45367809e61a9700e32cda325817e9055661f | 1,590 | cpp | C++ | src/RNN.cpp | Lehdari/EvolutionSimulator | 432da1c1f5bae389b6e785d1c7e47eca8dca9698 | [
"MIT"
] | 1 | 2018-03-22T07:52:03.000Z | 2018-03-22T07:52:03.000Z | src/RNN.cpp | Lehdari/EvolutionSimulator | 432da1c1f5bae389b6e785d1c7e47eca8dca9698 | [
"MIT"
] | null | null | null | src/RNN.cpp | Lehdari/EvolutionSimulator | 432da1c1f5bae389b6e785d1c7e47eca8dca9698 | [
"MIT"
] | null | null | null | #include "RNN.hpp"
#include <cstdio>
RNN::RNN(uint64_t nInputs, uint64_t nOutputs, const RNN::Genome& genome) :
_nInputs(nInputs), _nOutputs(nOutputs)
{
for (auto i=0llu; i<_nInputs; ++i)
_neurons.emplace_back();
for (auto i=0llu; i<_nOutputs; ++i)
_neurons.emplace_back();
for (auto& cg : genome) {
uint64_t maxId = std::max(cg.from, cg.to);
if (maxId >= _neurons.size())
_neurons.resize(maxId+1);
_neurons[cg.to].conns.emplace_back(cg.from, cg.weight);
}
}
void RNN::setInput(uint64_t inputId, float val)
{
if (inputId > _nInputs)
return;
_neurons[inputId].i = val;
}
float RNN::getOutput(uint64_t outputId) const
{
if (outputId > _nOutputs)
return 0.0f;
return _neurons[_nInputs+outputId].a;
}
uint64_t RNN::getNumInputs(void) const
{
return _nInputs;
}
uint64_t RNN::getNumOutputs(void) const
{
return _nOutputs;
}
const std::vector<RNN::Neuron>& RNN::getNeurons(void) const
{
return _neurons;
}
void RNN::tick(void)
{
for (auto& n : _neurons) {
for (auto& c : n.conns)
n.i += _neurons[c.from].a*c.w;
}
for (auto& n : _neurons) {
n.a = activationLogistic(n.i);
n.i = 0.0f;
}
}
void RNN::print(bool printConns) const
{
for (auto i=0u; i<_neurons.size(); ++i) {
auto& n = _neurons[i];
printf("Neuron %u\ti: %0.3f\ta: %0.3f\n", i, n.i, n.a);
if (printConns)
for (auto& c : n.conns)
printf(" Conn from neuron %llu\tw: %0.3f\n", c.from, c.w);
}
}
| 20.649351 | 75 | 0.579874 | Lehdari |
c9d843e9c2af6209232f2faab470f508eb00895f | 1,091 | cpp | C++ | test/std/utilities/optional/optional.nullopt/nullopt_t.pass.cpp | ontio/libcxx-mirror | 4b4f32ea383deb28911f5618126c6ea6c110b5e4 | [
"Apache-2.0"
] | null | null | null | test/std/utilities/optional/optional.nullopt/nullopt_t.pass.cpp | ontio/libcxx-mirror | 4b4f32ea383deb28911f5618126c6ea6c110b5e4 | [
"Apache-2.0"
] | 1 | 2019-04-21T16:53:33.000Z | 2019-04-21T17:15:25.000Z | test/std/utilities/optional/optional.nullopt/nullopt_t.pass.cpp | ontio/libcxx-mirror | 4b4f32ea383deb28911f5618126c6ea6c110b5e4 | [
"Apache-2.0"
] | 1 | 2020-09-09T07:40:32.000Z | 2020-09-09T07:40:32.000Z | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <optional>
// struct nullopt_t{see below};
// inline constexpr nullopt_t nullopt(unspecified);
// [optional.nullopt]/2:
// Type nullopt_t shall not have a default constructor or an initializer-list
// constructor, and shall not be an aggregate.
#include <optional>
#include <type_traits>
using std::nullopt_t;
using std::nullopt;
constexpr bool test()
{
nullopt_t foo{nullopt};
(void)foo;
return true;
}
int main(int, char**)
{
static_assert(std::is_empty_v<nullopt_t>);
static_assert(!std::is_default_constructible_v<nullopt_t>);
static_assert(std::is_same_v<const nullopt_t, decltype(nullopt)>);
static_assert(test());
return 0;
}
| 25.97619 | 80 | 0.60495 | ontio |
c9d9649a41931432c8737a9bf9cdd88977d0893d | 8,608 | cpp | C++ | test/scenegraph/test_visualization3d.cpp | UCCS-Social-Robotics/libalmath | 608475eced68452eb19ef09c46e1916ac597ed88 | [
"BSD-3-Clause"
] | 4 | 2016-03-14T20:34:05.000Z | 2021-02-14T05:53:00.000Z | test/scenegraph/test_visualization3d.cpp | UCCS-Social-Robotics/libalmath | 608475eced68452eb19ef09c46e1916ac597ed88 | [
"BSD-3-Clause"
] | 1 | 2021-02-14T05:52:04.000Z | 2022-03-16T11:18:20.000Z | test/scenegraph/test_visualization3d.cpp | UCCS-Social-Robotics/libalmath | 608475eced68452eb19ef09c46e1916ac597ed88 | [
"BSD-3-Clause"
] | 9 | 2017-07-11T16:01:27.000Z | 2022-02-13T20:41:05.000Z | /*
* Copyright 2015 Aldebaran. All rights reserved.
*
*/
#include <almath/scenegraph/mesh.h>
#include <almath/scenegraph/scenebuilder.h>
#include <almath/scenegraph/meshfactory.h>
#include <almath/scenegraph/colladascenebuilder.h>
#include <almath/geometrics/shapes3d.h>
#include <gtest/gtest.h>
#include <almath/types/altransform.h>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/scoped_ptr.hpp>
using namespace AL;
boost::filesystem::path mktmpdir(const std::string &prefix) {
using namespace boost::filesystem;
path p = temp_directory_path() / unique_path(prefix + "%%%%-%%%%-%%%%-%%%%");
create_directory(p);
return p;
}
TEST(Mesh, init) {
Mesh m;
ASSERT_EQ(0u, m.polygonsNb());
ASSERT_EQ(0u, m.positionsNb());
ASSERT_EQ(0u, m.normalsNb());
ASSERT_EQ(0u, m.texCoordsNb());
}
TEST(Mesh, double_begin) {
Mesh m;
m.begin(Mesh::POLYGON);
// double begin
EXPECT_ANY_THROW(m.begin(Mesh::POLYGON));
}
TEST(Mesh, no_begin) {
Mesh m;
EXPECT_ANY_THROW(m.vertex(0.f, 0.f, 0.f));
ASSERT_EQ(0u, m.positionsNb());
EXPECT_ANY_THROW(m.end());
}
TEST(Mesh, no_normal) {
Mesh m;
m.begin(Mesh::POLYGON);
EXPECT_ANY_THROW(m.vertex(0.f, 0.f, 0.f));
m.end();
}
TEST(Mesh, no_texcoord_ok) {
Mesh m;
EXPECT_EQ(2u, m.verticesStride());
m.normal(0.f, 0.f, 1.f);
m.begin(Mesh::POLYGON);
m.vertex(0.f, 0.f, 0.f);
m.end();
}
TEST(Mesh, no_texcoord_ko) {
Mesh m(true);
EXPECT_EQ(3u, m.verticesStride());
m.normal(0.f, 0.f, 1.f);
m.begin(Mesh::POLYGON);
EXPECT_ANY_THROW(m.vertex(0.f, 0.f, 0.f));
m.end();
}
TEST(Mesh, accessors) {
Mesh m;
m.position(0.f, 1.f, 2.f);
m.position(3.f, 4.f, 5.f);
EXPECT_EQ(0.f, *m.positionPtrAt(0));
EXPECT_EQ(1.f, *(m.positionPtrAt(0) + 1));
EXPECT_EQ(2.f, *(m.positionPtrAt(0) + 2));
EXPECT_EQ(3.f, *m.positionPtrAt(1));
EXPECT_EQ(4.f, *(m.positionPtrAt(1) + 1));
EXPECT_EQ(5.f, *(m.positionPtrAt(1) + 2));
m.normal(0.f, 0.f, 1.f);
m.normal(0.f, 1.f, 0.f);
EXPECT_EQ(0.f, *m.normalPtrAt(0));
EXPECT_EQ(0.f, *(m.normalPtrAt(0) + 1));
EXPECT_EQ(1.f, *(m.normalPtrAt(0) + 2));
EXPECT_EQ(0.f, *m.normalPtrAt(1));
EXPECT_EQ(1.f, *(m.normalPtrAt(1) + 1));
EXPECT_EQ(0.f, *(m.normalPtrAt(1) + 2));
m.texCoord(0.f, 1.f);
m.texCoord(2.f, 3.f);
EXPECT_EQ(0.f, *m.texCoordPtrAt(0));
EXPECT_EQ(1.f, *(m.texCoordPtrAt(0) + 1));
EXPECT_EQ(2.f, *m.texCoordPtrAt(1));
EXPECT_EQ(3.f, *(m.texCoordPtrAt(1) + 1));
m.begin(Mesh::POLYGON);
m.vertex(0);
m.vertex(1);
m.vertex(0);
m.end();
m.begin(Mesh::POLYGON);
m.vertex(0);
m.vertex(1);
m.vertex(0);
m.vertex(1);
m.end();
EXPECT_EQ(0u, *m.vertexPtrAt(0));
EXPECT_EQ(1u, *(m.vertexPtrAt(0) + 1));
EXPECT_EQ(1u, *m.vertexPtrAt(1));
EXPECT_EQ(1u, *(m.vertexPtrAt(1) + 1));
EXPECT_EQ(0u, *m.vertexPtrAt(2));
EXPECT_EQ(1u, *(m.vertexPtrAt(2) + 1));
EXPECT_EQ(3, m.polygonVerticesCountAt(0));
EXPECT_EQ(4, m.polygonVerticesCountAt(1));
}
TEST(Mesh, vertex) {
Mesh m;
size_t n = m.polygonsNb();
size_t p = m.position(0.f, 0.f, 0.f);
ASSERT_EQ(0u, p);
ASSERT_EQ(1u, m.positionsNb());
m.normal(0.f, 0.f, 1.f);
m.texCoord(0.f, 0.f);
m.begin(Mesh::POLYGON);
m.end();
// empty polygon is a no-op
ASSERT_EQ(n, m.polygonsNb());
m.begin(Mesh::POLYGON);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.end();
ASSERT_EQ(n + 1u, m.polygonsNb());
ASSERT_EQ(3u, m.polygonVerticesCountAt(n));
m.begin(Mesh::POLYGON);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.end();
ASSERT_EQ(n + 2u, m.polygonsNb());
ASSERT_EQ(4u, m.polygonVerticesCountAt(n + 1u));
m.begin(Mesh::TRIANGLES);
m.end();
// empty triangles set is a no-op
ASSERT_EQ(n + 2u, m.polygonsNb());
m.begin(Mesh::TRIANGLES);
m.vertex(p);
m.vertex(p);
m.vertex(p);
// the triangle is not added before the end() call
ASSERT_EQ(n + 2u, m.polygonsNb());
m.vertex(p);
m.vertex(p);
// unfinished triangle
EXPECT_ANY_THROW(m.end());
// the first triangle was not added before the failed end() call
ASSERT_EQ(n + 2u, m.polygonsNb());
m.vertex(p);
m.end();
ASSERT_EQ(n + 4u, m.polygonsNb());
ASSERT_EQ(3u, m.polygonVerticesCountAt(n + 2u));
ASSERT_EQ(3u, m.polygonVerticesCountAt(n + 3u));
m.begin(Mesh::QUADS);
m.end();
// empty quads set is a no-op
ASSERT_EQ(n + 4, m.polygonsNb());
m.begin(Mesh::QUADS);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.vertex(p);
ASSERT_EQ(n + 4u, m.polygonsNb());
m.vertex(p);
m.vertex(p);
m.vertex(p);
// unfinished quad
EXPECT_ANY_THROW(m.end());
// the first triangle was not added before the failed end() call
ASSERT_EQ(n + 4u, m.polygonsNb());
m.vertex(p);
m.end();
ASSERT_EQ(n + 6u, m.polygonsNb());
ASSERT_EQ(4u, m.polygonVerticesCountAt(n + 4u));
ASSERT_EQ(4u, m.polygonVerticesCountAt(n + 5u));
}
class ColladaSceneBuilderTest : public ::testing::Test {
public:
static boost::filesystem::path tmpdir;
static void SetUpTestCase() {
// tmpdir = "/tmp"; return;
tmpdir = mktmpdir("test_visualization3d");
}
static void writeScene(const ColladaSceneBuilder &scene,
const std::string &filename) {
boost::filesystem::path path = tmpdir / filename;
std::cout << "writing collada scene to: " << path << "\n";
boost::filesystem::ofstream os(path.c_str());
os << scene;
}
};
boost::filesystem::path ColladaSceneBuilderTest::tmpdir;
#define WRITE_SCENE(scene) writeScene(scene, #scene ".dae")
TEST_F(ColladaSceneBuilderTest, rule_of_three) {
SceneBuilder::Config config0, config1;
config1.color.r = 1.f - config0.color.r;
ColladaSceneBuilder sc0;
EXPECT_EQ(config0.color.r, sc0.getConfig().color.r);
ColladaSceneBuilder sc1(config1);
sc1.add(createBoxMesh(1.f, 1.f, 1.f), Math::Transform());
EXPECT_EQ(config1.color.r, sc1.getConfig().color.r);
ColladaSceneBuilder sc2(sc1);
sc2.add(createBoxMesh(.5f, .5f, .5f), Math::Transform(2.f, 0.f, 0.f));
EXPECT_EQ(config1.color.r, sc2.getConfig().color.r);
ColladaSceneBuilder sc3;
sc3 = sc1;
sc3.add(createBoxMesh(.5f, .5f, .5f), Math::Transform(2.f, 0.f, 0.f));
EXPECT_EQ(config1.color.r, sc0.getConfig().color.r);
WRITE_SCENE(sc0);
WRITE_SCENE(sc1);
WRITE_SCENE(sc2);
WRITE_SCENE(sc3);
}
TEST_F(ColladaSceneBuilderTest, shapes) {
ColladaSceneBuilder sc;
float d = 3.f;
float x = -d;
float y = 0.f;
float z = 0.f;
// add a box to m0
Mesh m0 = createBoxMesh(1.1f, 1.2f, 1.3f);
sc.add(m0, Eigen::Affine3f(Eigen::Translation3f(x += d, y, z)));
// add another box to m0
addBoxMesh(0.55f, 0.6f, 1.9f, m0);
sc.add(m0, Math::Transform(x += d, y, z));
x = -d;
y += 3.f;
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.9f, 0.4f, 0),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.9f, 0.4f, 1),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.3f, 0.4f, 0.5f, 0.8f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.8f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.8f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.f, 0.f, 0.4f, 11),
Math::Transform(x += d, y, z));
// fall back to a box
sc.add(createRoundedBoxMesh(1.1f, 1.2f, 1.3f, 0.f, 2),
Eigen::Affine3f(Eigen::Translation3f(x += d, y, z)));
x = -d;
y += 3.f;
// use a ptr to "forget" the concrete type of the shape and test the
// visitor
boost::scoped_ptr<Math::Shape3D> shape;
shape.reset(new Math::Sphere(1.f));
sc.add(*shape, Math::Transform(x += d, y, z));
shape.reset(new Math::RoundedRectangle(0.7f, 0.8f, 0.4f));
sc.add(*shape, Math::Transform(x += d, y, z));
shape.reset(new Math::Pill(0.9f, 0.4f));
sc.add(*shape, Math::Transform(x += d, y, z));
shape.reset(new Math::Plane);
EXPECT_ANY_THROW(sc.add(*shape, Math::Transform()));
WRITE_SCENE(sc);
}
| 27.414013 | 79 | 0.628369 | UCCS-Social-Robotics |
c9da357b490cb3140a8ed47c4083cc5336315b16 | 643 | hpp | C++ | libs/core/input/include/bksge/core/input/mouse_manager.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/input/include/bksge/core/input/mouse_manager.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/input/include/bksge/core/input/mouse_manager.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file mouse_manager.hpp
*
* @brief MouseManager の定義
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_INPUT_MOUSE_MANAGER_HPP
#define BKSGE_CORE_INPUT_MOUSE_MANAGER_HPP
#include <bksge/core/input/config.hpp>
#if defined(BKSGE_CORE_INPUT_MOUSE_MANAGER_HEADER)
# include BKSGE_CORE_INPUT_MOUSE_MANAGER_HEADER
#else
# if defined(BKSGE_PLATFORM_WIN32)
# include <bksge/core/input/win32/win32_mouse_manager.hpp>
# else
# include <bksge/core/input/null/null_mouse_manager.hpp>
# endif
#endif
namespace bksge
{
using input::MouseManager;
} // namespace bksge
#endif // BKSGE_CORE_INPUT_MOUSE_MANAGER_HPP
| 20.09375 | 60 | 0.752722 | myoukaku |
c9dd5ff102ed943e0434b9e6f4cd312f826df46d | 383 | cpp | C++ | chapter_07/Replace.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | chapter_07/Replace.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | 31 | 2021-05-14T03:37:24.000Z | 2022-03-13T17:38:32.000Z | chapter_07/Replace.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | // Exercise 7.30 - Replace: space with underscore
#include <iostream>
#include <string>
int main()
{
std::string words;
std::cout << "Enter a string: ";
std::getline(std::cin, words);
for (int i = 0; i < words.length(); i++)
{
if (words[i] == ' ')
{
words[i] = '_';
}
}
std::cout << words << std::endl;
return 0;
} | 20.157895 | 49 | 0.490862 | Kevin-Oudai |
518b6befcd1cbcfa32f8b53241faebf1c19957cd | 14,567 | cpp | C++ | src/func-pilo/core/string/functional_test_module_class_fixed_wstring.cpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | 1 | 2019-07-31T06:44:46.000Z | 2019-07-31T06:44:46.000Z | src/func-pilo/core/string/functional_test_module_class_fixed_wstring.cpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | null | null | null | src/func-pilo/core/string/functional_test_module_class_fixed_wstring.cpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | null | null | null |
#include "core/string/string_util.hpp"
#include "core/string/fixed_wstring.hpp"
#include "core/io/format_output.hpp"
#include "functional_test_module_class_fixed_wstring.hpp"
#include <string>
#define MC_STR0_SIZE 8192
namespace pilo
{
namespace test
{
static pilo::i32_t functional_test_constructor_0_wchar(void* param);
static pilo::i32_t functional_test_constructor_1_wchar(void* param);
static pilo::i32_t functional_test_constructor_2_wchar(void* param);
static pilo::i32_t functional_test_constructor_3_wchar(void* param);
static pilo::i32_t functional_test_constructor_4_wchar(void* param);
static pilo::i32_t functional_test_constructor_5_wchar(void* param);
static pilo::i32_t functional_test_constructor_6_wchar(void* param);
static pilo::i32_t functional_test_copy_operator_0(void* param);
static pilo::i32_t functional_test_copy_operator_1(void* param);
static pilo::i32_t functional_test_copy_operator_2(void* param);
static pilo::i32_t functional_test_copy_operator_3(void* param);
static pilo::i32_t functional_test_copy_operator_4(void* param);
static pilo::i32_t functional_test_assign_0(void* param);
static pilo::i32_t functional_test_assign_1(void* param);
static pilo::i32_t functional_test_assign_2(void* param);
static pilo::i32_t functional_test_assign_3(void* param);
pilo::test::testing_case g_functional_cases_fixed_wstring[] =
{
/*---"---------------------------------------------"*/
{ 1, "fixed_wstring<wchar>() ", nullptr, functional_test_constructor_0_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 2, "fixed_wstring<char>(const wchar_t*) ", nullptr, functional_test_constructor_1_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 3, "fixed_wstring<wchar>(const whar_t*, size_t) ", nullptr, functional_test_constructor_2_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 4, "fixed_wstring<wchar>(const fixed_wstring&) ", nullptr, functional_test_constructor_3_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 4, "fixed_wstring<wchar>(const std::wstring &) ", nullptr, functional_test_constructor_4_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 5, "fixed_wstring<wchar>(int) ", nullptr, functional_test_constructor_5_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 6, "fixed_astring<char>(float) ", nullptr, functional_test_constructor_6_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 7, "operator=<fixed_wstring>(fixed_wstring) ", nullptr, functional_test_copy_operator_0, 0, -1, (pilo::u32_t) - 1 },
{ 7, "operator=(std::wstring) ", nullptr, functional_test_copy_operator_1, 0, -1, (pilo::u32_t) - 1 },
{ 8, "operator=(const wchar_t* ", nullptr, functional_test_copy_operator_2, 0, -1, (pilo::u32_t) - 1 },
{ 9, "operator=(wchar_t) ", nullptr, functional_test_copy_operator_3, 0, -1, (pilo::u32_t) - 1 },
{10, "operator=<number>(wchar_t) ", nullptr, functional_test_copy_operator_4, 0, -1, (pilo::u32_t) - 1 },
{11, "assign(size_t, wchar_t) ", nullptr, functional_test_assign_0, 0, -1, (pilo::u32_t) - 1 },
{12, "assign(const std::string&) ", nullptr, functional_test_assign_1, 0, -1, (pilo::u32_t) - 1 },
{13, "assign(const wchar_t*) ", nullptr, functional_test_assign_2, 0, -1, (pilo::u32_t) - 1 },
{14, "assign(const fixed_string&) ", nullptr, functional_test_assign_3, 0, -1, (pilo::u32_t) - 1 },
{ -1, "end", nullptr, nullptr, 0, -1, 0 },
};
pilo::i32_t functional_test_constructor_0_wchar(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring< MC_STR0_SIZE> str0;
if (str0.length() != 0)
{
return -1;
}
if (str0[0] != 0)
{
return -2;
}
if (str0.capacity() != MC_STR0_SIZE)
{
return -3;
}
if (!str0.empty())
{
return -4;
}
return 0;
}
pilo::i32_t functional_test_constructor_1_wchar(void* param)
{
M_UNUSED(param);
wchar_t str_buffer[MC_STR0_SIZE];
pilo::core::string::string_util::m_set(str_buffer, 0, MF_COUNT_OF(str_buffer));
pilo::core::string::string_util::m_set(str_buffer, 1, MF_COUNT_OF(str_buffer) - 1);
str_buffer[0] = '$';
str_buffer[MC_STR0_SIZE - 2] = '#';
pilo::core::string::fixed_wstring< MC_STR0_SIZE> str0(str_buffer);
if (str0.length() != 8191)
{
return -1;
}
if (str0.size() != 8191)
{
return -2;
}
if (str0.empty())
{
return -4;
}
if (str0.front() != '$')
{
return -5;
}
if (str0.back() != '#')
{
return -6;
}
if (::memcmp(str0.c_str(), str_buffer, MC_STR0_SIZE) != 0)
{
return -7;
}
return 0;
}
pilo::i32_t functional_test_constructor_2_wchar(void* param)
{
M_UNUSED(param);
wchar_t str_buffer[MC_STR0_SIZE + 1];
pilo::core::string::string_util::set(str_buffer, '1', MC_STR0_SIZE);
pilo::core::string::fixed_wstring< MC_STR0_SIZE + 1> str0(str_buffer, MC_STR0_SIZE);
if (str0.size() != MC_STR0_SIZE)
{
return -1;
}
if (::memcmp(str_buffer, str0.c_str(), sizeof(str_buffer) != 0))
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_constructor_3_wchar(void* param)
{
M_UNUSED(param);
const wchar_t* str = L"1234567890";
size_t len = pilo::core::string::string_util::length(str);
pilo::core::string::fixed_wstring< 32> str0(str, len);
pilo::core::string::fixed_wstring< 64> str1(str0);
if (str0.size() != str1.length())
{
return -1;
}
if (::memcmp(str0.c_str(), str1.c_str(), (len + 1)*sizeof(wchar_t)) != 0)
{
return -2;
}
const wchar_t* cstr2 = L"012345678901234567890123456789";
len = pilo::core::string::string_util::length(cstr2);
pilo::core::string::fixed_wstring< 112> str2(cstr2);
pilo::core::string::fixed_wstring< 32> str3(str2);
if (str3.size() != len)
{
return -3;
}
if (::memcmp(str3.c_str(), str2.c_str(), (len + 1) * sizeof(wchar_t)) != 0)
{
return -4;
}
return 0;
}
pilo::i32_t functional_test_constructor_4_wchar(void* param)
{
M_UNUSED(param);
std::wstring stdstr0 = L"012345678901234567890123456789";
pilo::core::string::fixed_wstring<31> str0(stdstr0);
if (stdstr0.length() != stdstr0.length())
{
return -1;
}
if (::memcmp(stdstr0.c_str(), str0.c_str(), str0.size()*sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_constructor_5_wchar(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring< 10> str0(123456789);
if (str0.size() != 9)
{
return -1;
}
pilo::core::string::fixed_wstring< 10> str1 = 987654321;
if (str1.size() != 9)
{
return -3;
}
pilo::core::string::fixed_wstring<11> stri64(9876543210LL);
if (stri64.size() != 10)
{
return -1;
}
pilo::u64_t u64vv = 19876543210U;
pilo::core::string::fixed_wstring<12> stru64(u64vv);
if (stru64.size() != 11)
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_constructor_6_wchar(void* param)
{
M_UNUSED(param);
float fv1 = -789.123f;
pilo::core::string::fixed_wstring<32> str0(fv1);
#ifdef WINDOWS
float fv2 = (float) ::_wtof(str0.c_str());
#else
float fv2 = (float) ::wcstof(str0, 0);
#endif
if (fv1 != fv2)
{
return -1;
}
double dv1 = -789.123456f;
pilo::core::string::fixed_wstring<32> str1(dv1);
#ifdef WINDOWS
double dv2 = (float) ::_wtof(str1.c_str());
#else
double dv2 = (float) ::wcstof(str1, 0);
#endif
if (dv1 != dv2)
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_0(void* param)
{
M_UNUSED(param);
const wchar_t* cstr0 = L"012345678901234567890123456789";
pilo::core::string::fixed_wstring<64> tstr0 = cstr0;
pilo::core::string::fixed_wstring<32> tstr1;
tstr1 = tstr0;
if (tstr1.size() != 30)
{
return -1;
}
if (::memcmp(tstr1.c_str(), cstr0, (pilo::core::string::string_util::length(cstr0) + 1)*sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_1(void* param)
{
M_UNUSED(param);
std::wstring stdstr0 = L"0123456789";
pilo::core::string::fixed_wstring<32> fastr;
fastr = stdstr0;
if (fastr.length() != stdstr0.length())
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_2(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<32> fastr;
fastr = L"0123456789";
if (fastr.length() != 10)
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_3(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<32> fastr;
fastr = 'x';
if (fastr.length() != 1)
{
return -1;
}
if (fastr[0] != 'x' || fastr[1] != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_4(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<MC_STR0_SIZE> str0;
pilo::i32_t vi32 = -12345678;
str0 = vi32;
pilo::i64_t vi64 = -1234567890;
str0 = vi64;
pilo::u32_t vu32 = 82345678;
str0 = vu32;
pilo::u64_t vu64 = 11234567890;
str0 = vu64;
float fv = -235.238f;
str0 = fv;
#ifdef WINDOWS
float fv2 = (float) ::_wtof(str0.c_str());
#else
float fv2 = (float) ::wcstof(str0, 0);
#endif
if (fv != fv2)
{
return -5;
}
double dv = 123.683909;
str0 = dv;
#ifdef WINDOWS
double dv2 = ::_wtof(str0.c_str());
#else
double dv2 = (double) ::wcstof(str0, 0);
#endif
if (abs(dv - dv2) >= 0.000001)
{
pilo::core::io::console_format_output("dv=%f, dv2=%f diff=%f\n", dv, dv2, dv-dv2);
return -6;
}
return 0;
}
pilo::i32_t functional_test_assign_0(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(12, (wchar_t)'x');
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), L"xxxxxxxxxxxx", 13) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_assign_1(void* param)
{
M_UNUSED(param);
std::wstring stdstr = L"xxxxxxxxxxxx";
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(stdstr);
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), stdstr.c_str(), 13 * sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_assign_2(void* param)
{
M_UNUSED(param);
const wchar_t* cstr = L"xxxxxxxxxxxx";
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(cstr);
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), L"xxxxxxxxxxxx", 13 * sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_assign_3(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<1024> fstr = L"xxxxxxxxxxxx";
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(fstr);
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), fstr.c_str(), 13 * sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
}
} | 33.106818 | 151 | 0.483353 | picofox |
518b9a78c5ae45dcfc8ac2a695d551e72050bf8e | 338 | cpp | C++ | halfnetwork/HalfNetwork/ACE_wrappers/ace/Connection_Recycling_Strategy.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 25 | 2019-05-20T08:07:39.000Z | 2021-08-17T11:25:02.000Z | halfnetwork/HalfNetwork/ACE_wrappers/ace/Connection_Recycling_Strategy.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | null | null | null | halfnetwork/HalfNetwork/ACE_wrappers/ace/Connection_Recycling_Strategy.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 17 | 2019-07-07T12:20:16.000Z | 2022-01-11T08:27:44.000Z | #include "ace/Connection_Recycling_Strategy.h"
ACE_RCSID(ace, Connection_Recycling_Strategy, "$Id: Connection_Recycling_Strategy.cpp 80826 2008-03-04 14:51:23Z wotte $")
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_Connection_Recycling_Strategy::~ACE_Connection_Recycling_Strategy (void)
{
}
ACE_END_VERSIONED_NAMESPACE_DECL
| 24.142857 | 123 | 0.816568 | cjwcjswo |
518c8538c87fb9c19d1f0e319a6a030c3f1dd55f | 20,785 | cpp | C++ | src/MdCharm/baseeditor/baseeditor.cpp | MonkeyMo/MdCharm | 78799f0bd85603aae9361b4fca05384a69f690e6 | [
"BSD-3-Clause"
] | 387 | 2015-01-01T17:51:59.000Z | 2021-06-13T19:40:15.000Z | src/MdCharm/baseeditor/baseeditor.cpp | MonkeyMo/MdCharm | 78799f0bd85603aae9361b4fca05384a69f690e6 | [
"BSD-3-Clause"
] | 26 | 2015-01-09T08:36:26.000Z | 2020-04-02T12:51:01.000Z | src/MdCharm/baseeditor/baseeditor.cpp | heefan/MdCharm | 78799f0bd85603aae9361b4fca05384a69f690e6 | [
"BSD-3-Clause"
] | 145 | 2015-01-10T18:07:45.000Z | 2021-09-14T07:39:35.000Z | #include <QtGui>
#include <QtCore>
#ifdef QT_V5
#include <QtPrintSupport>
#endif
#include "baseeditor.h"
#include "util/spellcheck/spellchecker.h"
#include "configuration.h"
#include "utils.h"
BaseEditor::BaseEditor(QWidget *parent) :
QPlainTextEdit(parent)
{
conf = Configuration::getInstance();
mdCharmGlobal = MdCharmGlobal::getInstance();
lineNumberArea = new LineNumberArea(this);
displayLineNumber = false;
finded = false;
replacing = false;
if(conf->isCheckSpell())
spellCheckLanguage=conf->getSpellCheckLanguage();
connect(this, SIGNAL(textChanged()),
this, SLOT(ensureAtTheLast()));
}
BaseEditor::~BaseEditor(){}
void BaseEditor::initSpellCheckMatter()//triggered by setDocument()
{
if(!conf->isCheckSpell())
return;
connect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
checkWholeContent();
}
void BaseEditor::enableSpellCheck()
{
spellCheckErrorSelection.clear();
disconnect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
updateExtraSelection();
if(spellCheckLanguage.isEmpty())
spellCheckLanguage=conf->getSpellCheckLanguage();
if(mdCharmGlobal->getSpellChecker(spellCheckLanguage)==NULL){
Q_ASSERT(0 && "This should not be happen");
spellCheckLanguage.clear();
return;
}
connect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
checkWholeContent();
}
void BaseEditor::disableSpellCheck()
{
spellCheckErrorSelection.clear();
spellCheckLanguage.clear();
disconnect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
updateExtraSelection();;
}
void BaseEditor::setDocument(QTextDocument *doc)
{
QPlainTextEdit::setDocument(doc);
initSpellCheckMatter();
}
void BaseEditor::enableHighlightCurrentLine()
{
highlightCurrentLine();
connect(this, SIGNAL(cursorPositionChanged()),
this, SLOT(highlightCurrentLine()));
}
void BaseEditor::disableHighlightCurrentLine()
{
disconnect(this, SIGNAL(cursorPositionChanged()),
this, SLOT(highlightCurrentLine()));
currentLineSelection.clear();
updateExtraSelection();
}
void BaseEditor::enableDisplayLineNumber()
{
displayLineNumber = true;
connect(this, SIGNAL(blockCountChanged(int)),
this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)),
this, SLOT(updateLineNumberArea(QRect,int)));
updateLineNumberAreaWidth(0);
lineNumberArea->setVisible(true);
}
void BaseEditor::disableDisplayLineNumber()
{
displayLineNumber = false;
disconnect(this, SIGNAL(updateRequest(QRect,int)),
this, SLOT(updateLineNumberArea(QRect,int)));
disconnect(this, SIGNAL(blockCountChanged(int)),
this, SLOT(updateLineNumberAreaWidth(int)));
updateLineNumberAreaWidth(0);
lineNumberArea->setVisible(false);
}
int BaseEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while(max >= 10)
{
max /= 10;
++digits;
}
int space = 3 + QFontMetrics(document()->defaultFont()).width(QLatin1Char('9')) * digits;
return space;
}
int BaseEditor::firstVisibleLineNumber()
{
return firstVisibleBlock().blockNumber()+1;
}
void BaseEditor::findAndHighlightText(const QString &text, QTextDocument::FindFlags qff,
bool isRE, bool isSetTextCursor)
{
if(replacing)
return;
if(text.isEmpty())
{
findTextSelection.clear();
currentFindSelection.clear();
updateExtraSelection();
return;
}
if(findAllOccurrance(text, qff, isRE))
{
finded = true;
findFirstOccurrance(text, qff, isRE, true, isSetTextCursor);
}
}
bool BaseEditor::findAllOccurrance(const QString &text, QTextDocument::FindFlags qff, bool isRE)
{
QTextDocument *doc = document();
findTextSelection.clear();
bool finded=false;
if(text.isEmpty())
{
prevFindCursor = QTextCursor();
return finded;
} else {
QTextEdit::ExtraSelection es;
QTextCursor highlightCursor(doc);
QTextCharFormat plainFormat(highlightCursor.charFormat());
QTextCharFormat colorFormat = plainFormat;
colorFormat.setBackground(Qt::yellow);
es.format = colorFormat;
QRegExp re(text);
while(!highlightCursor.isNull() && !highlightCursor.atEnd())
{
highlightCursor = isRE ? doc->find(re, highlightCursor, qff) :
doc->find(text, highlightCursor, qff);
if(!highlightCursor.isNull())
{
finded = true;
es.cursor = highlightCursor;
findTextSelection.append(es);
}
}
if(!finded)
{
prevFindCursor = highlightCursor;
}
return finded;
}
}
void BaseEditor::findFirstOccurrance(const QString &text, QTextDocument::FindFlags qff,
bool isRE, bool init, bool isSetTextCusor)
{
if (!finded)
return;
QRegExp re(text);
QTextDocument *doc = document();
QTextCursor currentCursor = textCursor();
QTextCursor firstCursor;
QTextEdit::ExtraSelection es;
if(!init || prevFindCursor.isNull())
{
QTextCursor startCursor;
if(qff&QTextDocument::FindBackward && !prevFindCursor.isNull())
{
prevFindCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor,
abs(prevFindCursor.selectionStart()-prevFindCursor.selectionEnd()));
}
if(prevFindCursor.isNull())
startCursor = currentCursor;
else
startCursor = prevFindCursor;
firstCursor = isRE ? doc->find(re, startCursor, qff):
doc->find(text, startCursor, qff);
} else {
firstCursor = isRE ? doc->find(re, prevFindCursor.selectionStart(), qff):
doc->find(text, prevFindCursor.selectionStart(), qff);
}
if(firstCursor.isNull())
{
QTextCursor wholeCursor(doc);
if(qff & QTextDocument::FindBackward)
wholeCursor.movePosition(QTextCursor::End);
firstCursor = isRE ? doc->find(re, wholeCursor, qff):
doc->find(text, wholeCursor, qff);
}
if(firstCursor.isNull())
{
prevFindCursor = firstCursor;
return;
}
es.cursor = firstCursor;
QTextCharFormat f;
f.setBackground(Qt::blue);
f.setForeground(Qt::white);
es.format = f;
currentFindSelection.clear();
currentFindSelection.append(es);
prevFindCursor = firstCursor;
firstCursor.clearSelection();
if(isSetTextCusor)
setTextCursor(firstCursor);
ensureCursorVisible();
updateExtraSelection();
}
void BaseEditor::updateLineNumberAreaWidth(int newBlockCount)
{
Q_UNUSED(newBlockCount)
setViewportMargins(displayLineNumber ? lineNumberAreaWidth() : 0, 0, 0, 0);
}
void BaseEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void BaseEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
if(!displayLineNumber)
return;
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void BaseEditor::keyPressEvent(QKeyEvent *e)
{
QPlainTextEdit::keyPressEvent(e);
if(!e->isAccepted()&&e->key()==Qt::Key_Insert)//FIXME: crashrpt 8135582f-6f1c-46db-b3be-85ee2702a88d
{
emit overWriteModeChanged();
}
}
void BaseEditor::focusInEvent(QFocusEvent *e)
{
emit focusInSignal();
QPlainTextEdit::focusInEvent(e);
}
static void fillBackground(QPainter *p, const QRectF &rect, QBrush brush, QRectF gradientRect = QRectF())//copy from QPlainTextEditor from 4.8.1
{
p->save();
if (brush.style() >= Qt::LinearGradientPattern && brush.style() <= Qt::ConicalGradientPattern) {
if (!gradientRect.isNull()) {
QTransform m = QTransform::fromTranslate(gradientRect.left(), gradientRect.top());
m.scale(gradientRect.width(), gradientRect.height());
brush.setTransform(m);
const_cast<QGradient *>(brush.gradient())->setCoordinateMode(QGradient::LogicalMode);
}
} else {
p->setBrushOrigin(rect.topLeft());
}
p->fillRect(rect, brush);
p->restore();
}
static QColor blendColors(const QColor &a, const QColor &b, int alpha)//copy from QPlainTextEditor from 4.8.1
{
return QColor((a.red() * (256 - alpha) + b.red() * alpha) / 256,
(a.green() * (256 - alpha) + b.green() * alpha) / 256,
(a.blue() * (256 - alpha) + b.blue() * alpha) / 256);
}
void BaseEditor::paintEvent(QPaintEvent *e)
{
//copy from QPlainTextEditor
QPainter painter(viewport());
Q_ASSERT(qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout()));
QPointF offset(contentOffset());
QRect er = e->rect();
QRect viewportRect = viewport()->rect();
bool editable = !isReadOnly();
QTextBlock block = firstVisibleBlock();
qreal maximumWidth = document()->documentLayout()->documentSize().width();
//margin
qreal lineX = 0;
if (conf->isDisplayRightColumnMargin()) {
// Don't use QFontMetricsF::averageCharWidth here, due to it returning
// a fractional size even when this is not supported by the platform.
lineX = QFontMetricsF(document()->defaultFont()).width(QLatin1Char('X')) * conf->getRightMarginColumn() + offset.x() + 4;
if (lineX < viewportRect.width()) {
const QBrush background = QBrush(QColor(239, 239, 239));
painter.fillRect(QRectF(lineX, er.top(), viewportRect.width() - lineX, er.height()),
background);
const QColor col = (palette().base().color().value() > 128) ? Qt::black : Qt::white;
const QPen pen = painter.pen();
painter.setPen(blendColors(background.isOpaque() ? background.color() : palette().base().color(),
col, 32));
painter.drawLine(QPointF(lineX, er.top()), QPointF(lineX, er.bottom()));
painter.setPen(pen);
}
}
// Set a brush origin so that the WaveUnderline knows where the wave started
painter.setBrushOrigin(offset);
// keep right margin clean from full-width selection
int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth)
- document()->documentMargin();
er.setRight(qMin(er.right(), maxX));
painter.setClipRect(er);
QAbstractTextDocumentLayout::PaintContext context = getPaintContext();
while (block.isValid()) {
QRectF r = blockBoundingRect(block).translated(offset);
QTextLayout *layout = block.layout();
if (!block.isVisible()) {
offset.ry() += r.height();
block = block.next();
continue;
}
if (r.bottom() >= er.top() && r.top() <= er.bottom()) {
QTextBlockFormat blockFormat = block.blockFormat();
QBrush bg = blockFormat.background();
if (bg != Qt::NoBrush) {
QRectF contentsRect = r;
contentsRect.setWidth(qMax(r.width(), maximumWidth));
fillBackground(&painter, contentsRect, bg);
}
QVector<QTextLayout::FormatRange> selections;
int blpos = block.position();
int bllen = block.length();
for (int i = 0; i < context.selections.size(); ++i) {
const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
const int selStart = range.cursor.selectionStart() - blpos;
const int selEnd = range.cursor.selectionEnd() - blpos;
if (selStart < bllen && selEnd > 0
&& selEnd > selStart) {
QTextLayout::FormatRange o;
o.start = selStart;
o.length = selEnd - selStart;
o.format = range.format;
selections.append(o);
} else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
&& block.contains(range.cursor.position())) {
// for full width selections we don't require an actual selection, just
// a position to specify the line. that's more convenience in usage.
QTextLayout::FormatRange o;
QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos);
o.start = l.textStart();
o.length = l.textLength();
if (o.start + o.length == bllen - 1)
++o.length; // include newline
o.format = range.format;
selections.append(o);
}
}
bool drawCursor = ((editable || (textInteractionFlags() & Qt::TextSelectableByKeyboard))
&& context.cursorPosition >= blpos
&& context.cursorPosition < blpos + bllen);
bool drawCursorAsBlock = drawCursor && overwriteMode() ;
if (drawCursorAsBlock) {
if (context.cursorPosition == blpos + bllen - 1) {
drawCursorAsBlock = false;
} else {
QTextLayout::FormatRange o;
o.start = context.cursorPosition - blpos;
o.length = 1;
o.format.setForeground(palette().base());
o.format.setBackground(palette().text());
selections.append(o);
}
}
layout->draw(&painter, offset, selections, er);
if ((drawCursor && !drawCursorAsBlock)
|| (editable && context.cursorPosition < -1
&& !layout->preeditAreaText().isEmpty())) {
int cpos = context.cursorPosition;
if (cpos < -1)
cpos = layout->preeditAreaPosition() - (cpos + 2);
else
cpos -= blpos;
layout->drawCursor(&painter, offset, cpos, cursorWidth());
}
}
offset.ry() += r.height();
if (offset.y() > viewportRect.height())
break;
block = block.next();
}
if (backgroundVisible() && !block.isValid() && offset.y() <= er.bottom()
&& (centerOnScroll() || verticalScrollBar()->maximum() == verticalScrollBar()->minimum())) {
painter.fillRect(QRect(QPoint((int)er.left(), (int)offset.y()), er.bottomRight()), palette().background());
}
}
void BaseEditor::highlightCurrentLine()
{
currentLineSelection.clear();
if (!isReadOnly())
{
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor::fromRgb(0xC6, 0xE2, 0xFF);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();;
currentLineSelection.append(selection);
}
updateExtraSelection();
}
void BaseEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), QColor::fromRgb(0xEA,0xEA,0xEA));
painter.setFont(document()->defaultFont());
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
int height = QFontMetrics(document()->defaultFont()).height();
while(block.isValid() && top <= event->rect().bottom())
{
if (block.isVisible() && bottom >= event->rect().top())
{
QString number = QString::number(blockNumber+1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width(), height,
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
void BaseEditor::updateExtraSelection()
{
setExtraSelections(findTextSelection+currentLineSelection+currentFindSelection+spellCheckErrorSelection);
}
void BaseEditor::findFinished()
{
findTextSelection.clear();
currentFindSelection.clear();
updateExtraSelection();
prevFindCursor = QTextCursor();
finded = false;
}
void BaseEditor::replace(const QString &rt)
{
if(prevFindCursor.isNull())
return;
prevFindCursor.beginEditBlock();
prevFindCursor.insertText(rt);
prevFindCursor.endEditBlock();
}
void BaseEditor::replaceAll(const QString &ft, const QString &rt,
QTextDocument::FindFlags qff, bool isRE)
{
QTextDocument *doc = document();
QTextCursor tc(doc);
QRegExp re(ft);
replacing = true;
while(!tc.isNull() && !tc.atEnd())
{
tc = isRE ? doc->find(re, tc, qff) :
doc->find(ft, tc, qff);
if(!tc.isNull())
{
tc.beginEditBlock();
tc.insertText(rt);
tc.endEditBlock();
}
}
replacing = false;
findAndHighlightText(ft, qff, isRE);
}
void BaseEditor::ensureAtTheLast()
{
QTextCursor tc = textCursor();
if(tc.atEnd())
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
void BaseEditor::spellCheck(int start, int unused, int length)
{
Q_UNUSED(unused)
if(length==0)
return;
// qDebug("start %d, length %d", start, length);;
int end = start+length;
bool isInSameBlock=false;
if(start==end)
isInSameBlock = true;
QTextBlock startBlock = document()->findBlock(start);
QTextBlock endBlock = document()->findBlock(end);
if(!endBlock.isValid())
endBlock = document()->lastBlock();
// qDebug("start block %d, end block %d", startBlock.blockNumber(), endBlock.blockNumber());
if(startBlock.blockNumber()==endBlock.blockNumber())
isInSameBlock = true;
spellCheckAux(startBlock);
if(!isInSameBlock){
for(int i=0; i<endBlock.blockNumber()-startBlock.blockNumber(); i++){
spellCheckAux(document()->findBlockByNumber(startBlock.blockNumber()+i+1));
}
}
updateExtraSelection();
}
void BaseEditor::spellCheckAux(const QTextBlock &block)
{
removeExtraSelectionInRange(spellCheckErrorSelection, block.position(), block.position()+block.length());
SpellChecker *spellChecker = mdCharmGlobal->getSpellChecker(spellCheckLanguage);
if(spellChecker==NULL)
return;
SpellCheckResultList resultList = spellChecker->checkString(block.text());
QTextCharFormat spellErrorCharFormat;
spellErrorCharFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
spellErrorCharFormat.setUnderlineColor(Qt::darkRed);
for(int i=0; i<resultList.length(); i++){
SpellCheckResult result = resultList.at(i);
QTextCursor errorCursor(block);
errorCursor.setPosition(block.position()+result.start);
errorCursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, result.end-result.start);//select wrong words
QTextEdit::ExtraSelection es;
es.cursor = errorCursor;
es.format = spellErrorCharFormat;
spellCheckErrorSelection.append(es);
}
}
void BaseEditor::checkWholeContent()
{
for(int i=0; i<blockCount(); i++)
spellCheckAux(document()->findBlockByNumber(i));
updateExtraSelection();
}
void BaseEditor::removeExtraSelectionInRange(QList<QTextEdit::ExtraSelection> &extraList, int start, int end)
{
QStack<int> toRemove;
for(int i=0; i<extraList.length(); i++)
{
QTextEdit::ExtraSelection es = extraList.at(i);
QTextCursor tc= es.cursor;
if(tc.selectionStart()>=start && tc.selectionEnd()<=end)
toRemove.push(i);
}
//remove from end to begin
while(!toRemove.isEmpty())
extraList.removeAt(toRemove.pop());
}
| 33.470209 | 144 | 0.613279 | MonkeyMo |
518e20203bcc8f9d82cb17e797fc3152b00959f3 | 860 | cpp | C++ | PAT/A/1046.cpp | zhi2xin1/pat-ans | 740ee6b4d5a8c354bdff012750a615c738d5013e | [
"MIT"
] | null | null | null | PAT/A/1046.cpp | zhi2xin1/pat-ans | 740ee6b4d5a8c354bdff012750a615c738d5013e | [
"MIT"
] | null | null | null | PAT/A/1046.cpp | zhi2xin1/pat-ans | 740ee6b4d5a8c354bdff012750a615c738d5013e | [
"MIT"
] | null | null | null | //#include <iostream>
#include <cstdio>
void writex(int x)
{
if(x>9)
writex(x/10);
putchar(x%10+'0');
}
void readx(int &x)
{
x=0;
char s=getchar();
while(s<'0'||s>'9')
s=getchar();
while(s>='0'&&s<='9'){
x=x*10+s-'0';
s=getchar();
}
}
int main(){
int N,testN,dis[100000],ori,des;
int sum=0,sum_2=0,temp;
readx(N);
for(int i=0;i<N;++i){
readx(temp);
dis[i]=sum;
sum+=temp;
}
sum_2=sum/2;
readx(testN);
for(int i=0;i<testN;++i){
temp=0;
readx(ori);
readx(des);
--ori;
--des;
if(ori<des){
temp=dis[des]-dis[ori];
}
else{
temp=dis[ori]-dis[des];
}
if(temp>sum_2)
temp=sum-temp;
writex(temp);
putchar(10);
}
}
| 16.538462 | 36 | 0.426744 | zhi2xin1 |
518f2b8a9782e9625a56852e3082683a4abb6a53 | 1,811 | cpp | C++ | snowman.cpp | shaiBonfil/CPP-Ex1 | ec9a82b8de9b99e3dd4488781b363ec36c95509e | [
"MIT"
] | null | null | null | snowman.cpp | shaiBonfil/CPP-Ex1 | ec9a82b8de9b99e3dd4488781b363ec36c95509e | [
"MIT"
] | null | null | null | snowman.cpp | shaiBonfil/CPP-Ex1 | ec9a82b8de9b99e3dd4488781b363ec36c95509e | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <stdexcept>
#include <exception>
#include <array>
#include "snowman.hpp"
using namespace std;
using namespace ariel;
const int DEC = 10;
namespace ariel
{
int charToInt(char c) { return c - '0' -1;}
string snowman(long num)
{
// if the input number not equal to 8 digits, this is a invalid input
if (to_string(num).length() != VALID_LEN) { throw invalid_argument("error: invalid input!");}
// if the input is 8 digits, than we check it in the while loop
long tmp = num;
while (tmp != 0)
{
if ((tmp % DEC < 1) || (tmp % DEC > 4))
{
throw invalid_argument("error: invalid input!");
}
tmp /= DEC;
}
string ans;
array <string, VALID_LEN> res;
string str = to_string(num);
int j = 0;
for (int i = 0; i < VALID_LEN; i++)
{
j = charToInt(str.at(i));
res.at(i) = presets.at(i).at(j);
}
ans += res[HAT] + "\n"; // Hat
ans += res[LEFT_ARM].at(up); // Upper Left Arm
ans += "(" + res[LEFT_EYE] + res[NOSE] + res[RIGHT_EYE] + ")"; // Eyes and Nose
ans += res[RIGHT_ARM].at(up); // Upper Right Arm
ans += "\n";
ans += res[LEFT_ARM].at(down); // Lower Left Arm
ans += "(" + res[TORSO] + ")"; // Torso
ans += res[RIGHT_ARM].at(down); // Lower Right Arm
ans += "\n";
ans += space + "(" + res[BASE] + ")" + "\n"; // Base
return ans;
}
}
| 31.224138 | 101 | 0.437327 | shaiBonfil |
519a541e25f3b56b8474e43831e07c6e2093de86 | 6,635 | cpp | C++ | src/alns/SRP-Utils/ArgParser.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/alns/SRP-Utils/ArgParser.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/alns/SRP-Utils/ArgParser.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | // ***************************************************************************************
// * ArgParser.cpp
// *
// * Author: Stefan Ropke
// ***************************************************************************************
#include "ArgParser.h"
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
// ***************************************************************************************
// * void ArgParser::parseCmdLine(const string &strExpectedArgs, int argc, char *argv[ ])
// *
// * Parses the "command line" given as parameters <argc> and <argv> (it is expected that
// * <argc> and <argv> are the std. "main(...)" parameters), and stores the result internally
// * in the object.
// *
// * The method is inspired by the "getopts" method in Perl. The function parses
// * command lines like:
// * myprogram -f 10 -p5 -F -r help.txt
// *
// * --- input parameters ---
// * strExpectedArgs : A string that specifies the flags or switches to look for. In the example
// * <strExpectedArgs> could be "f:p:r:F" which is interpretted as:
// * look for "-f" followed by a parameter, look for "-p" followed by a parameter
// * look for "-r" followed by a parameter, look for "-F" _not_ followed by a parameter
// * (notice that there are no ":" after F in "f:p:r:F").
// * The method is quite stupid so you should probably be carefull with "-" characters
// * in the parameters following a switch.
// * If the method is called with <strExpectedArgs> = "f:p:r:F" and <argc> and <argv>
// * is defined by the example command line shown above then an internal map is built
// * that would contain the following bindings:
// *
// * 'f' -> "10"
// * 'p' -> "5"
// * 'F' -> ""
// * 'r' -> "help.txt"
// *
// * Notice that the switches must be single-characters.
// * --- return values ---
// ***************************************************************************************
void ArgParser::parseCmdLine(const string& strExpectedArgs, int argc, char* argv[]) {
mapArguments.clear();
int i = 0;
while(i < (int)strExpectedArgs.size()) {
bool bParameterExpected = false;
char cSwitch = strExpectedArgs[i];
i++;
if(i < (int)strExpectedArgs.size() && strExpectedArgs[i] == ':') {
bParameterExpected = true;
i++;
}
// search after the switch:
for(int j = 1; j < argc; j++) {
// Notice that we do not run into problems when argv[j] only contain one char (we might fear array-out-of-bound errors)
// The reason is that the argv[j] strings are zero terminated.
if((argv[j])[0] == '-' && (argv[j])[1] == cSwitch) {
string strPar = "";
// switch found:
if(bParameterExpected) {
if((argv[j])[2] != 0)
strPar = string(argv[j] + 2);
else {
if(j + 1 < argc)
strPar = string(argv[j + 1]);
}
}
mapArguments.insert(pair<char, string>(cSwitch, strPar));
}
}
}
}
void ArgParser::writeParams(ostream& os, int argc, char* argv[]) const {
for(int j = 1; j < argc; j++)
os << argv[j] << " ";
}
// ***************************************************************************************
// * bool ArgParser::getArg(char cArg, string &strValue) const
// *
// * gets a parameter from the parsed command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * strValue : The parameter is returned through this parameter (nice sentence eh?).
// * --- return value: ---
// * true => the switch was found.
// * false => switch not found.
// ***************************************************************************************
bool ArgParser::getArg(char cArg, string& strValue) const {
map<char, string>::const_iterator itMap = mapArguments.find(cArg);
if(itMap != mapArguments.end()) {
strValue = itMap->second;
return true;
} else
return false;
}
// ***************************************************************************************
// * bool ArgParser::getArg(char cArg, int &iValue) const
// *
// * gets an integer parameter from the parsed command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * iValue : The parameter is returned through this parameter (nice sentence eh?).
// * --- return value: ---
// * true => the parameter was found.
// * false => parameter not found.
// ***************************************************************************************
bool ArgParser::getIntArg(char cArg, int& iValue) const {
string str;
if(getArg(cArg, str)) {
iValue = atoi(str.c_str());
return true;
} else
return false;
}
// ***************************************************************************************
// * bool ArgParser::getArg(char cArg, double &dValue) const
// *
// * gets a double parameter from the parsed command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * dValue : The parameter is returned through this parameter.
// * --- return value: ---
// * true => the parameter was found.
// * false => parameter not found.
// ***************************************************************************************
bool ArgParser::getDoubleArg(char cArg, double& dValue) const {
string str;
if(getArg(cArg, str)) {
dValue = atof(str.c_str());
return true;
} else
return false;
}
// ***************************************************************************************
// * bool ArgParser::hasArg(char cArg) const
// *
// * Checks if a specific argument was used on the command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * --- return value: ---
// * true => the parameter was found.
// * false => parameter not found.
// ***************************************************************************************
bool ArgParser::hasArg(char cArg) const {
string str;
if(getArg(cArg, str))
return true;
else
return false;
}
| 38.575581 | 132 | 0.468124 | alberto-santini |
519c8414d40a3fa45c2df6ce968f3963980d1edd | 2,252 | cpp | C++ | Kernel/FileSystem/Custody.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | 3 | 2020-05-01T02:39:03.000Z | 2021-11-26T08:34:54.000Z | Kernel/FileSystem/Custody.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | 8 | 2019-08-25T12:52:40.000Z | 2019-09-08T14:46:11.000Z | Kernel/FileSystem/Custody.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | 1 | 2021-08-03T13:04:49.000Z | 2021-08-03T13:04:49.000Z | #include <AK/HashTable.h>
#include <AK/StringBuilder.h>
#include <Kernel/FileSystem/Custody.h>
#include <Kernel/FileSystem/Inode.h>
#include <Kernel/Lock.h>
static Lockable<InlineLinkedList<Custody>>& all_custodies()
{
static Lockable<InlineLinkedList<Custody>>* list;
if (!list)
list = new Lockable<InlineLinkedList<Custody>>;
return *list;
}
Custody* Custody::get_if_cached(Custody* parent, const StringView& name)
{
LOCKER(all_custodies().lock());
for (auto& custody : all_custodies().resource()) {
if (custody.is_deleted())
continue;
if (custody.is_mounted_on())
continue;
if (custody.parent() == parent && custody.name() == name)
return &custody;
}
return nullptr;
}
NonnullRefPtr<Custody> Custody::get_or_create(Custody* parent, const StringView& name, Inode& inode)
{
if (RefPtr<Custody> cached_custody = get_if_cached(parent, name)) {
if (&cached_custody->inode() != &inode) {
dbg() << "WTF! Cached custody for name '" << name << "' has inode=" << cached_custody->inode().identifier() << ", new inode=" << inode.identifier();
}
ASSERT(&cached_custody->inode() == &inode);
return *cached_custody;
}
return create(parent, name, inode);
}
Custody::Custody(Custody* parent, const StringView& name, Inode& inode)
: m_parent(parent)
, m_name(name)
, m_inode(inode)
{
LOCKER(all_custodies().lock());
all_custodies().resource().append(this);
}
Custody::~Custody()
{
LOCKER(all_custodies().lock());
all_custodies().resource().remove(this);
}
String Custody::absolute_path() const
{
Vector<const Custody*, 32> custody_chain;
for (auto* custody = this; custody; custody = custody->parent())
custody_chain.append(custody);
StringBuilder builder;
for (int i = custody_chain.size() - 2; i >= 0; --i) {
builder.append('/');
builder.append(custody_chain[i]->name().characters());
}
return builder.to_string();
}
void Custody::did_delete(Badge<VFS>)
{
m_deleted = true;
}
void Custody::did_mount_on(Badge<VFS>)
{
m_mounted_on = true;
}
void Custody::did_rename(Badge<VFS>, const String& name)
{
m_name = name;
}
| 27.13253 | 160 | 0.641208 | JamiKettunen |
51a893e8356e179e9f3ec430ccbeb4428588cdca | 3,004 | cpp | C++ | test/ZDAMessageParse_Test.cpp | neuralsandwich/NMEAParser | 3bd29601b048b091745312f8a214ab454335c94c | [
"MIT"
] | 1 | 2020-07-19T15:25:57.000Z | 2020-07-19T15:25:57.000Z | test/ZDAMessageParse_Test.cpp | neuralsandwich/NMEAParser | 3bd29601b048b091745312f8a214ab454335c94c | [
"MIT"
] | null | null | null | test/ZDAMessageParse_Test.cpp | neuralsandwich/NMEAParser | 3bd29601b048b091745312f8a214ab454335c94c | [
"MIT"
] | 1 | 2020-07-19T15:33:28.000Z | 2020-07-19T15:33:28.000Z | //===-- ZDAMessageParse_Test.cpp --------------------------------*- C++ -*-===//
//
// This file is distributed uner the MIT license. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Functional tests for Parsing ZDA Messages
///
//===----------------------------------------------------------------------===//
#include "NMEAParser.h"
#include "gtest/gtest.h"
namespace NMEA {
TEST(ZDAMessageParse, Valid_Message) {
const std::string RawMessage = "$GPZDA,082710.00,16,09,2002,00,00*64";
time_t ExpectedTimestamp = 0;
struct tm *TimeInfo;
std::time(&ExpectedTimestamp);
TimeInfo = gmtime(&ExpectedTimestamp);
TimeInfo->tm_hour = 8;
TimeInfo->tm_min = 27;
TimeInfo->tm_sec = 10;
TimeInfo->tm_mday = 16;
TimeInfo->tm_mon = 8;
TimeInfo->tm_year = 102;
ExpectedTimestamp = mktime(TimeInfo);
GPZDA Message = {
.TimeStamp = ExpectedTimestamp, .LocalHours = 0, .LocalMinutes = 0};
NMEAMessage Expected = {NMEA_TALKER_ID::GPS, NMEA_MESSAGE_TYPE::ZDA, 1,
.ZDA = &Message};
auto Parser = NMEAParser{};
auto Result = Parser.Parse(RawMessage);
// Compare Headers
EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect";
EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect";
EXPECT_EQ(Expected.Valid, Result->Valid)
<< "Message valid status is incorrect";
// Compate Messages
EXPECT_EQ(Expected.ZDA->TimeStamp, Result->ZDA->TimeStamp);
EXPECT_EQ(Expected.ZDA->LocalHours, Result->ZDA->LocalHours);
EXPECT_EQ(Expected.ZDA->LocalMinutes, Result->ZDA->LocalMinutes);
}
TEST(ZDAMessageParse, Invalid_Message) {
const std::string RawMessage =
"$GPZDA,082710.00,16,09,,12,4,123401924,00,00*64";
NMEAMessage Expected = {NMEA_TALKER_ID::UNKNOWN_TALKER_ID,
NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE,
0,
{}};
auto Parser = NMEAParser{};
auto Result = Parser.Parse(RawMessage);
// Compare Headers
EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect";
EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect";
EXPECT_EQ(Expected.Valid, Result->Valid)
<< "Message valid status is incorrect";
// Compare Message
EXPECT_EQ(Expected.ZDA, Result->ZDA);
}
TEST(ZDAMessageParse, Empty_Message) {
const std::string RawMessage = "";
NMEAMessage Expected = {NMEA_TALKER_ID::UNKNOWN_TALKER_ID,
NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE,
0,
{}};
auto Parser = NMEAParser{};
auto Result = Parser.Parse(RawMessage);
// Compare Headers
EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect";
EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect";
EXPECT_EQ(Expected.Valid, Result->Valid)
<< "Message valid status is incorrect";
// Compare Message
EXPECT_EQ(Expected.ZDA, Result->ZDA);
}
};
| 31.957447 | 80 | 0.616844 | neuralsandwich |
51a964727efe7d4f643c07a0e40b1e3f327b6152 | 4,518 | cc | C++ | course/test/src/isometry_TEST.cc | Lobotuerk/cppl1_q12020 | b93cf3adbd153fe6747a7bcf44dd8fea081ec26a | [
"Apache-2.0"
] | null | null | null | course/test/src/isometry_TEST.cc | Lobotuerk/cppl1_q12020 | b93cf3adbd153fe6747a7bcf44dd8fea081ec26a | [
"Apache-2.0"
] | 3 | 2020-03-12T12:58:58.000Z | 2020-04-27T01:56:30.000Z | course/test/src/isometry_TEST.cc | Lobotuerk/cppl1_q12020 | b93cf3adbd153fe6747a7bcf44dd8fea081ec26a | [
"Apache-2.0"
] | null | null | null | // This file describes a challenge of a C++ L1 Padawan. The goal
// of this unit test is to suggest an API and the abstractions
// needed to implement an isometry.
// Consider including other header files if needed.
// Copyright 2020 <Jose Tomas Lorente>
#include <cmath>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
#include <isometry/isometry.hpp>
namespace ekumen {
namespace math {
namespace test {
namespace {
testing::AssertionResult areAlmostEqual(const Isometry & obj1,
const Isometry & obj2, const double tolerance) {
if (std::abs(obj1.translation()[0] - obj2.translation()[0]) > tolerance ||
std::abs(obj1.translation()[1] - obj2.translation()[1]) > tolerance ||
std::abs(obj1.translation()[2] - obj2.translation()[2]) > tolerance ||
std::abs(obj1.rotation()[0][0] - obj2.rotation()[0][0]) > tolerance ||
std::abs(obj1.rotation()[0][1] - obj2.rotation()[0][1]) > tolerance ||
std::abs(obj1.rotation()[0][2] - obj2.rotation()[0][2]) > tolerance ||
std::abs(obj1.rotation()[1][0] - obj2.rotation()[1][0]) > tolerance ||
std::abs(obj1.rotation()[1][1] - obj2.rotation()[1][1]) > tolerance ||
std::abs(obj1.rotation()[1][2] - obj2.rotation()[1][2]) > tolerance ||
std::abs(obj1.rotation()[2][0] - obj2.rotation()[2][0]) > tolerance ||
std::abs(obj1.rotation()[2][1] - obj2.rotation()[2][1]) > tolerance ||
std::abs(obj1.rotation()[2][2] - obj2.rotation()[2][2]) > tolerance) {
return testing::AssertionFailure() <<
"The isometrys are not almost equal";
}
return testing::AssertionSuccess();
}
testing::AssertionResult areAlmostEqual(const Matrix3 & obj1,
const Matrix3 & obj2, const double tolerance) {
if (std::abs(obj1[0][0] - obj2[0][0]) > tolerance ||
std::abs(obj1[0][1] - obj2[0][1]) > tolerance ||
std::abs(obj1[0][2] - obj2[0][2]) > tolerance ||
std::abs(obj1[1][0] - obj2[1][0]) > tolerance ||
std::abs(obj1[1][1] - obj2[1][1]) > tolerance ||
std::abs(obj1[1][2] - obj2[1][2]) > tolerance ||
std::abs(obj1[2][0] - obj2[2][0]) > tolerance ||
std::abs(obj1[2][1] - obj2[2][1]) > tolerance ||
std::abs(obj1[2][2] - obj2[2][2]) > tolerance) {
return testing::AssertionFailure() <<
"The isometrys are not almost equal";
}
return testing::AssertionSuccess();
}
GTEST_TEST(IsometryTest, IsometryFullTests) {
const double kTolerance{1e-12};
const Isometry t1 = Isometry::FromTranslation(Vector3{1., 2., 3.});
const Isometry t2{Vector3{1., 2., 3.}, Matrix3::kIdentity};
EXPECT_EQ(t1, t2);
// This is not mathematically correct but it could be a nice to have.
EXPECT_EQ(t1 * Vector3(1., 1., 1.), Vector3(2., 3., 4.));
EXPECT_EQ(t1.transform(Vector3(std::initializer_list<double>({1., 1., 1.}))),
Vector3(2., 3., 4.));
EXPECT_EQ(t1.inverse() * Vector3(2., 3., 4.), Vector3(1., 1., 1.));
EXPECT_EQ(t1 * t2 * Vector3(1., 1., 1.), Vector3(3., 5., 7.));
EXPECT_EQ(t1.compose(t2) * Vector3(1., 1., 1.), Vector3(3., 5., 7.));
// Composes rotations.
const Isometry t3{Isometry::RotateAround(Vector3::kUnitX, M_PI / 2.)};
const Isometry t4{Isometry::RotateAround(Vector3::kUnitY, M_PI / 4.)};
const Isometry t5{Isometry::RotateAround(Vector3::kUnitZ, M_PI / 8.)};
const Isometry t6{Isometry::FromEulerAngles(M_PI / 2., M_PI / 4., M_PI / 8.)};
EXPECT_TRUE(areAlmostEqual(t6, t3 * t4 * t5, kTolerance));
EXPECT_EQ(t3.translation(), Vector3::kZero);
const double pi_8{M_PI / 8.};
const double cpi_8{std::cos(pi_8)}; // 0.923879532
const double spi_8{std::sin(pi_8)}; // 0.382683432
EXPECT_TRUE(areAlmostEqual(t5.rotation(),
Matrix3{cpi_8, -spi_8, 0., spi_8, cpi_8, 0., 0., 0., 1.}, kTolerance));
std::stringstream ss;
ss << t5;
std::string answer = "[T: (x: 0, y: 0, z: 0), ";
answer += "R:[[0.923879533, -0.382683432, 0],";
answer += " [0.382683432, 0.923879533, 0], [0, 0, 1]]]";
EXPECT_EQ(ss.str(), answer);
Isometry t7;
EXPECT_EQ(t7.rotation()[2][2], 0);
EXPECT_EQ(t7.translation()[2], 0);
Isometry t8 = Isometry();
EXPECT_EQ(t8.rotation()[2][2], 0);
EXPECT_EQ(t8.translation()[2], 0);
Isometry t9 = Isometry::FromTranslation(Vector3{1., 2., 3.});
const Isometry t10{Vector3{2., 4., 6.}, Matrix3::kIdentity};
EXPECT_EQ(t9 *= t2, t10);
EXPECT_EQ(t9 * Vector3(1., 1., 1.), Vector3(3., 5., 7.));
}
} // namespace
} // namespace test
} // namespace math
} // namespace ekumen
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 38.615385 | 80 | 0.629925 | Lobotuerk |
51b0b992e3e5aca3632a14fef04fb59f1e78ab55 | 2,388 | hpp | C++ | WICWIU_src/Module/GRULayer.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | WICWIU_src/Module/GRULayer.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | WICWIU_src/Module/GRULayer.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | #ifndef __GRU_LAYER__
#define __GRU_LAYER__ value
#include "../Module.hpp"
template<typename DTYPE> class GRULayer : public Module<DTYPE>{
private:
public:
GRULayer(Operator<DTYPE> *pInput, int inputsize, int hiddensize, int outputsize, int use_bias = TRUE, std::string pName = "No Name") : Module<DTYPE>(pName) {
Alloc(pInput, inputsize, hiddensize, outputsize, use_bias, pName);
}
virtual ~GRULayer() {}
int Alloc(Operator<DTYPE> *pInput, int inputsize, int hiddensize, int outputsize, int use_bias, std::string pName) {
this->SetInput(pInput);
Operator<DTYPE> *out = pInput;
//weight
Tensorholder<DTYPE> *pWeightIG = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, 2*hiddensize, inputsize, 0.0, 0.01), "LSTMLayer_pWeight_IG_" + pName);
Tensorholder<DTYPE> *pWeightHG = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, 2*hiddensize, hiddensize, 0.0, 0.01), "LSTMLayer_pWeight_HG_" + pName);
Tensorholder<DTYPE> *pWeightICH = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, hiddensize, inputsize, 0.0, 0.01), "LSTMLayer_pWeight_HG_" + pName);
Tensorholder<DTYPE> *pWeightHCH = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, hiddensize, hiddensize, 0.0, 0.01), "LSTMLayer_pWeight_HG_" + pName);
//Hidden to output weight
Tensorholder<DTYPE> *pWeight_h2o = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, outputsize, hiddensize, 0.0, 0.01), "LSTMLayer_pWeight_HO_" + pName);
//bias
Tensorholder<DTYPE> *gBias = new Tensorholder<DTYPE>(Tensor<DTYPE>::Constants(1, 1, 1, 1, 2*hiddensize, 0.f), "RNN_Bias_f" + pName);
Tensorholder<DTYPE> *chBias = new Tensorholder<DTYPE>(Tensor<DTYPE>::Constants(1, 1, 1, 1, hiddensize, 0.f), "RNN_Bias_f" + pName);
out = new GRU<DTYPE>(out, pWeightIG, pWeightHG, pWeightICH, pWeightHCH, gBias, chBias);
out = new MatMul<DTYPE>(pWeight_h2o, out, "rnn_matmul_ho");
if (use_bias) {
Tensorholder<DTYPE> *pBias = new Tensorholder<DTYPE>(Tensor<DTYPE>::Constants(1, 1, 1, 1, outputsize, 0.f), "Add_Bias_" + pName);
out = new AddColWise<DTYPE>(out, pBias, "Layer_Add_" + pName);
}
this->AnalyzeGraph(out);
return TRUE;
}
};
#endif
| 47.76 | 175 | 0.657035 | ChanhyoLee |
51b4a7eacab4f9c03d9a1229d8b71afb3286bf5e | 4,280 | hh | C++ | Shared/BrainCloudCompletionBlocks.hh | davidstl/braincloud-objc | 42e9376cba1c3ef1231a5f74e1c5c66442a34779 | [
"Apache-2.0"
] | null | null | null | Shared/BrainCloudCompletionBlocks.hh | davidstl/braincloud-objc | 42e9376cba1c3ef1231a5f74e1c5c66442a34779 | [
"Apache-2.0"
] | 1 | 2019-11-30T17:08:15.000Z | 2019-11-30T17:08:15.000Z | Shared/BrainCloudCompletionBlocks.hh | OrbiLabs/braincloud-objc | b5b63f98e339582e7819e1b765abfb28bcaccbeb | [
"Apache-2.0"
] | null | null | null | //
// BrainCloudCompletionBlocks.h
// brainCloudClientObjc
//
// Created by Ryan Homer on 30/4/2015.
// Copyright (c) 2016 bitHeads. All rights reserved.
//
#ifndef brainCloudClientObjc_BrainCloudCompletionBlocks_h
#define brainCloudClientObjc_BrainCloudCompletionBlocks_h
#import <Foundation/Foundation.h>
typedef NSObject *BCCallbackObject;
/**
* Completion block called when an api completes successfully.
*
* @param serviceName The service name of the api call (see ServiceName.hh)
* @param serviceOperation The service operation of the api call (see ServiceOperation.hh)
* @param jsonData The returned JSON data from the api call.
* @param cbObject The passed in callback object. If nil is passed in to the api, nil will
* be returned in the completion block.
*/
typedef void (^BCCompletionBlock)(NSString *serviceName, NSString *serviceOperation,
NSString *jsonData, BCCallbackObject cbObject);
/**
* Completion block called when an api call returns an error.
*
* @param serviceName The service name of the api call.
* @param serviceOperation The service operation of the api call.
* @param statusCode The status code of the error (see StatusCodes.hh)
* @param reasonCode The reason code of the error (see ReasonCodes.hh)
* @param jsonError The returned JSON data from the api call.
* @param cbObject The passed in callback object. If nil is passed in to the api, nil will
* be returned in the completion block.
*/
typedef void (^BCErrorCompletionBlock)(NSString *serviceName, NSString *serviceOperation,
NSInteger statusCode, NSInteger reasonCode,
NSString *jsonError, BCCallbackObject cbObject);
/**
* Completion block called when an event is returned from brainCloud
*
* @param jsonData Returned data from the server
*/
typedef void (^BCEventCompletionBlock)(NSString *jsonData);
/**
* Completion block called whenever an api call returns rewards data.
*
* @param jsonData The rewards JSON data. The format is as follows:
* {
* "status": 200,
* "apiRewards": [
* {
* "service": "authenticationV2",
* "operation": "AUTHENTICATE",
* "rewards": {
* "rewardDetails": {
* // the reward depending on type (see docs)
* }
* }
* }
* ]
* }
*/
typedef void (^BCRewardCompletionBlock)(NSString *jsonData);
/**
* Completion block called when a file upload has completed.
*
* @param in_fileUploadId The file upload id
* @param in_jsonResponse The json response describing the file details similar to this
* {
* "status": 200,
* "data": {
* "fileList": [
* {
* "updatedAt": 1452603368201,
* "uploadedAt": null,
* "fileSize": 85470,
* "shareable": true,
* "createdAt": 1452603368201,
* "profileId": "bf8a1433-62d2-448e-b396-f3dbffff44",
* "gameId": "99999",
* "path": "test2",
* "filename": "testup.dat",
* "downloadUrl": "https://sharedprod.braincloudservers.com/s3/bc/g/99999/u/bf8a1433-62d2-448e-b396-f3dbffff44/f/test2/testup.dat"
* "cloudLocation": "bc/g/99999/u/bf8a1433-62d2-448e-b396-f3dbffff44/f/test2/testup.dat"
* }
* ]
* }
* }
*/
typedef void (^BCFileUploadCompletedCompletionBlock)(NSString *fileUploadId, NSString *json);
/**
* Completion block called when a file upload has failed.
*
* @param in_fileUploadId The file upload id
* @param in_statusCode The http status of the operation (see StatusCode.hh)
* @param in_reasonCode The reason code of the operation (see ReasonCodes.hh)
* @param in_jsonResponse The json response describing the failure. This uses the usual brainCloud error
* format similar to this:
* {
* "status": 403,
* "reason_code": 40300,
* "status_message": "Message describing failure",
* "severity": "ERROR"
* }
*/
typedef void (^BCFileUploadFailedCompletionBlock)(NSString *fileUploadId, NSInteger statusCode, NSInteger returnCode, NSString *json);
/**
* The networkError method is invoked whenever a network error is encountered
* communicating to the brainCloud server.
*
* Note this method is *not* invoked when FlushCachedMessages(true) is called.
*/
typedef void (^BCNetworkErrorCompletionBlock)();
#endif
| 34.24 | 134 | 0.692991 | davidstl |
51b81d57427905c7f7afda489f398593374c12bb | 25,712 | hpp | C++ | src/include/polo/utility/blas.hpp | aytekinar/polo | da682618e98755738905fd19e55e5271af937661 | [
"MIT"
] | 8 | 2018-10-12T09:54:25.000Z | 2020-06-18T12:04:44.000Z | src/include/polo/utility/blas.hpp | aytekinar/polo | da682618e98755738905fd19e55e5271af937661 | [
"MIT"
] | 10 | 2018-10-10T10:28:23.000Z | 2019-03-14T11:36:03.000Z | src/include/polo/utility/blas.hpp | aytekinar/polo | da682618e98755738905fd19e55e5271af937661 | [
"MIT"
] | null | null | null | #ifndef POLO_UTILITY_BLAS_HPP_
#define POLO_UTILITY_BLAS_HPP_
extern "C" {
// Single-precision, L1
void srotg_(const float *, const float *, float *, float *);
void srotmg_(float *, float *, float *, const float *, float *);
void srot_(const int *, float *, const int *, float *, const int *,
const float *, const float *);
void srotm_(const int *, float *, const int *, float *, const int *,
const int *);
void sswap_(const int *, float *, const int *, float *, const int *);
void sscal_(const int *, const float *, float *, const int *);
void scopy_(const int *, const float *, const int *, float *, const int *);
void saxpy_(const int *, const float *, const float *, const int *, float *,
const int *);
float sdot_(const int *, const float *, const int *, const float *,
const int *);
float sdsdot_(const int *, const float *, const float *, const int *,
const float *, const int *);
float snrm2_(const int *, const float *, const int *);
float sasum_(const int *, const float *, const int *);
int isamax_(const int *, const float *, const int *);
// Single-precision, L2
void sgemv_(const char *, const int *, const int *, const float *,
const float *, const int *, const float *, const int *,
const float *, float *, const int *);
void sgbmv_(const char *, const int *, const int *, const int *, const int *,
const float *, const float *, const int *, const float *,
const int *, const float *, float *, const int *);
void ssymv_(const char *, const int *, const float *, const float *,
const int *, const float *, const int *, const float *, float *,
const int *);
void ssbmv_(const char *, const int *, const int *, const float *,
const float *, const int *, const int *, const int *, const float *,
float *, const int *);
void sspmv_(const char *, const int *, const float *, const float *,
const float *, const int *, const float *, float *, const int *);
void strmv_(const char *, const char *, const char *, const int *,
const float *, const int *, float *, const int *);
void stbmv_(const char *, const char *, const char *, const int *, const int *,
const float *, const int *, float *, const int *);
void stpmv_(const char *, const char *, const char *, const int *,
const float *, float *, const int *);
void strsv_(const char *, const char *, const char *, const int *,
const float *, const int *, float *, const int *);
void stbsv_(const char *, const char *, const char *, const int *, const int *,
const float *, const int *, float *, const int *);
void stpsv_(const char *, const char *, const char *, const int *,
const float *, float *, const int *);
void sger_(const int *, const int *, const float *, const float *, const int *,
const float *, const int *, float *, const int *);
void ssyr_(const char *, const int *, const float *, const float *, const int *,
float *, const int *);
void sspr_(const char *, const int *, const float *, const float *, const int *,
float *);
void ssyr2_(const char *, const int *, const float *, const float *,
const int *, const float *, const int *, float *, const int *);
void sspr2_(const char *, const int *, const float *, const float *,
const int *, const float *, const int *, float *);
// Single-precision, L3
void sgemm_(const char *, const char *, const int *, const int *, const int *,
const float *, const float *, const int *, const float *,
const int *, const float *, float *, const int *);
void ssymm_(const char *, const char *, const int *, const int *, const float *,
const float *, const int *, const float *, const int *,
const float *, float *, const int *);
void ssyrk_(const char *, const char *, const int *, const int *, const float *,
const float *, const int *, const float *, float *, const int *);
void ssyr2k_(const char *, const char *, const int *, const int *,
const float *, const float *, const int *, const float *,
const int *, const float *, float *, const int *);
void strmm_(const char *, const char *, const char *, const char *, const int *,
const int *, const float *, const float *, const int *, float *,
const int *);
void strsm_(const char *, const char *, const char *, const char *, const int *,
const int *, const float *, const float *, const int *, float *,
const int *);
// Double-precision, L1
void drotg_(const double *, const double *, double *, double *);
void drotmg_(double *, double *, double *, const double *, double *);
void drot_(const int *, double *, const int *, double *, const int *,
const double *, const double *);
void drotm_(const int *, double *, const int *, double *, const int *,
const int *);
void dswap_(const int *, double *, const int *, double *, const int *);
void dscal_(const int *, const double *, double *, const int *);
void dcopy_(const int *, const double *, const int *, double *, const int *);
void daxpy_(const int *, const double *, const double *, const int *, double *,
const int *);
double ddot_(const int *, const double *, const int *, const double *,
const int *);
double dsdot_(const int *, const double *, const double *, const int *,
const double *, const int *);
double dnrm2_(const int *, const double *, const int *);
double dasum_(const int *, const double *, const int *);
int idamax_(const int *, const double *, const int *);
// Double-precision, L2
void dgemv_(const char *, const int *, const int *, const double *,
const double *, const int *, const double *, const int *,
const double *, double *, const int *);
void dgbmv_(const char *, const int *, const int *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dsymv_(const char *, const int *, const double *, const double *,
const int *, const double *, const int *, const double *, double *,
const int *);
void dsbmv_(const char *, const int *, const int *, const double *,
const double *, const int *, const int *, const int *,
const double *, double *, const int *);
void dspmv_(const char *, const int *, const double *, const double *,
const double *, const int *, const double *, double *, const int *);
void dtrmv_(const char *, const char *, const char *, const int *,
const double *, const int *, double *, const int *);
void dtbmv_(const char *, const char *, const char *, const int *, const int *,
const double *, const int *, double *, const int *);
void dtpmv_(const char *, const char *, const char *, const int *,
const double *, double *, const int *);
void dtrsv_(const char *, const char *, const char *, const int *,
const double *, const int *, double *, const int *);
void dtbsv_(const char *, const char *, const char *, const int *, const int *,
const double *, const int *, double *, const int *);
void dtpsv_(const char *, const char *, const char *, const int *,
const double *, double *, const int *);
void dger_(const int *, const int *, const double *, const double *,
const int *, const double *, const int *, double *, const int *);
void dsyr_(const char *, const int *, const double *, const double *,
const int *, double *, const int *);
void dspr_(const char *, const int *, const double *, const double *,
const int *, double *);
void dsyr2_(const char *, const int *, const double *, const double *,
const int *, const double *, const int *, double *, const int *);
void dspr2_(const char *, const int *, const double *, const double *,
const int *, const double *, const int *, double *);
// Double-precision, L3
void dgemm_(const char *, const char *, const int *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dsymm_(const char *, const char *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dsyrk_(const char *, const char *, const int *, const int *,
const double *, const double *, const int *, const double *,
double *, const int *);
void dsyr2k_(const char *, const char *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dtrmm_(const char *, const char *, const char *, const char *, const int *,
const int *, const double *, const double *, const int *, double *,
const int *);
void dtrsm_(const char *, const char *, const char *, const char *, const int *,
const int *, const double *, const double *, const int *, double *,
const int *);
}
namespace polo {
namespace utility {
namespace matrix {
template <class value_t> struct blas;
template <> struct blas<float> {
// Level 1
static void rotg(const float sa, const float sb, float &c, float &s) {
srotg_(&sa, &sb, &c, &s);
}
static void rotmg(float &sd1, float &sd2, float &sx1, const float sy1,
float *sparam) {
srotmg_(&sd1, &sd2, &sx1, &sy1, sparam);
}
static void rot(const int n, float *sx, const int incx, float *sy,
const int incy, const float c, const float s) {
srot_(&n, sx, &incx, sy, &incy, &c, &s);
}
static void rotm(const int n, float *sx, const int incx, float *sy,
const int incy, const int *sparam) {
srotm_(&n, sx, &incx, sy, &incy, sparam);
}
static void swap(const int n, float *sx, const int incx, float *sy,
const int incy) {
sswap_(&n, sx, &incx, sy, &incy);
}
static void scal(const int n, const float sa, float *sx, const int incx) {
sscal_(&n, &sa, sx, &incx);
}
static void copy(const int n, const float *sx, const int incx, float *sy,
const int incy) {
scopy_(&n, sx, &incx, sy, &incy);
}
static void axpy(const int n, const float sa, const float *sx, const int incx,
float *sy, const int incy) {
saxpy_(&n, &sa, sx, &incx, sy, &incy);
}
static float dot(const int n, const float *sx, const int incx,
const float *sy, const int incy) {
return sdot_(&n, sx, &incx, sy, &incy);
}
static float dsdot(const int n, const float sb, const float *sx,
const int incx, const float *sy, const int incy) {
return sdsdot_(&n, &sb, sx, &incx, sy, &incy);
}
static float nrm2(const int n, const float *x, const int incx) {
return snrm2_(&n, x, &incx);
}
static float asum(const int n, const float *sx, const int incx) {
return sasum_(&n, sx, &incx);
}
static int iamax(const int n, const float *sx, const int incx) {
return isamax_(&n, sx, &incx);
}
// Level 2
static void gemv(const char trans, const int m, const int n,
const float alpha, const float *a, const int lda,
const float *x, const int incx, const float beta, float *y,
const int incy) {
sgemv_(&trans, &m, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void gbmv(const char trans, const int m, const int n, const int kl,
const int ku, const float alpha, const float *a,
const int lda, const float *x, const int incx,
const float beta, float *y, const int incy) {
sgbmv_(&trans, &m, &n, &kl, &ku, &alpha, a, &lda, x, &incx, &beta, y,
&incy);
}
static void symv(const char uplo, const int n, const float alpha,
const float *a, const int lda, const float *x,
const int incx, const float beta, float *y, const int incy) {
ssymv_(&uplo, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void sbmv(const char uplo, const int n, const int k, const float alpha,
const float *a, const int lda, const int *x, const int incx,
const float beta, float *y, const int incy) {
ssbmv_(&uplo, &n, &k, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void spmv(const char uplo, const int n, const float alpha,
const float *a, const float *x, const int incx,
const float beta, float *y, const int incy) {
sspmv_(&uplo, &n, &alpha, a, x, &incx, &beta, y, &incy);
}
static void trmv(const char uplo, const char trans, const char diag,
const int n, const float *a, const int lda, float *x,
const int incx) {
strmv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbmv(const char uplo, const char trans, const char diag,
const int n, const int k, const float *a, const int lda,
float *x, const int incx) {
stbmv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpmv(const char uplo, const char trans, const char diag,
const int n, const float *ap, float *x, const int incx) {
stpmv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void trsv(const char uplo, const char trans, const char diag,
const int n, const float *a, const int lda, float *x,
const int incx) {
strsv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbsv(const char uplo, const char trans, const char diag,
const int n, const int k, const float *a, const int lda,
float *x, const int incx) {
stbsv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpsv(const char uplo, const char trans, const char diag,
const int n, const float *ap, float *x, const int incx) {
stpsv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void ger(const int m, const int n, const float alpha, const float *x,
const int incx, const float *y, const int incy, float *a,
const int lda) {
sger_(&m, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void syr(const char uplo, const int n, const float alpha,
const float *x, const int incx, float *a, const int lda) {
ssyr_(&uplo, &n, &alpha, x, &incx, a, &lda);
}
static void spr(const char uplo, const int n, const float alpha,
const float *x, const int incx, float *ap) {
sspr_(&uplo, &n, &alpha, x, &incx, ap);
}
static void syr2(const char uplo, const int n, const float alpha,
const float *x, const int incx, const float *y,
const int incy, float *a, const int lda) {
ssyr2_(&uplo, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void spr2(const char uplo, const int n, const float alpha,
const float *x, const int incx, const float *y,
const int incy, float *ap) {
sspr2_(&uplo, &n, &alpha, x, &incx, y, &incy, ap);
}
// Level 3
static void gemm(const char transa, const char transb, const int m,
const int n, const int k, const float alpha, const float *a,
const int lda, const float *b, const int ldb,
const float beta, float *c, const int ldc) {
sgemm_(&transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c,
&ldc);
}
static void symm(const char side, const char uplo, const int m, const int n,
const float alpha, const float *a, const int lda,
const float *b, const int ldb, const float beta, float *c,
const int ldc) {
ssymm_(&side, &uplo, &m, &n, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void syrk(const char uplo, const char trans, const int n, const int k,
const float alpha, const float *a, const int lda,
const float beta, float *c, const int ldc) {
ssyrk_(&uplo, &trans, &n, &k, &alpha, a, &lda, &beta, c, &ldc);
}
static void syr2k(const char uplo, const char trans, const int n, const int k,
const float alpha, const float *a, const int lda,
const float *b, const int ldb, const float beta, float *c,
const int ldc) {
ssyr2k_(&uplo, &trans, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void trmm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n, const float alpha,
const float *a, const int lda, float *b, const int ldb) {
strmm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
static void trsm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n, const float alpha,
const float *a, const int lda, float *b, const int ldb) {
strsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
};
template <> struct blas<double> {
// Level 1
static void rotg(const double sa, const double sb, double &c, double &s) {
drotg_(&sa, &sb, &c, &s);
}
static void rotmg(double &sd1, double &sd2, double &sx1, const double sy1,
double *sparam) {
drotmg_(&sd1, &sd2, &sx1, &sy1, sparam);
}
static void rot(const int n, double *sx, const int incx, double *sy,
const int incy, const double c, const double s) {
drot_(&n, sx, &incx, sy, &incy, &c, &s);
}
static void rotm(const int n, double *sx, const int incx, double *sy,
const int incy, const int *sparam) {
drotm_(&n, sx, &incx, sy, &incy, sparam);
}
static void swap(const int n, double *sx, const int incx, double *sy,
const int incy) {
dswap_(&n, sx, &incx, sy, &incy);
}
static void scal(const int n, const double sa, double *sx, const int incx) {
dscal_(&n, &sa, sx, &incx);
}
static void copy(const int n, const double *sx, const int incx, double *sy,
const int incy) {
dcopy_(&n, sx, &incx, sy, &incy);
}
static void axpy(const int n, const double sa, const double *sx,
const int incx, double *sy, const int incy) {
daxpy_(&n, &sa, sx, &incx, sy, &incy);
}
static double dot(const int n, const double *sx, const int incx,
const double *sy, const int incy) {
return ddot_(&n, sx, &incx, sy, &incy);
}
static double dsdot(const int n, const double sb, const double *sx,
const int incx, const double *sy, const int incy) {
return dsdot_(&n, &sb, sx, &incx, sy, &incy);
}
static double nrm2(const int n, const double *x, const int incx) {
return dnrm2_(&n, x, &incx);
}
static double asum(const int n, const double *sx, const int incx) {
return dasum_(&n, sx, &incx);
}
static int iamax(const int n, const double *sx, const int incx) {
return idamax_(&n, sx, &incx);
}
// Level 2
static void gemv(const char trans, const int m, const int n,
const double alpha, const double *a, const int lda,
const double *x, const int incx, const double beta,
double *y, const int incy) {
dgemv_(&trans, &m, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void gbmv(const char trans, const int m, const int n, const int kl,
const int ku, const double alpha, const double *a,
const int lda, const double *x, const int incx,
const double beta, double *y, const int incy) {
dgbmv_(&trans, &m, &n, &kl, &ku, &alpha, a, &lda, x, &incx, &beta, y,
&incy);
}
static void symv(const char uplo, const int n, const double alpha,
const double *a, const int lda, const double *x,
const int incx, const double beta, double *y,
const int incy) {
dsymv_(&uplo, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void sbmv(const char uplo, const int n, const int k,
const double alpha, const double *a, const int lda,
const int *x, const int incx, const double beta, double *y,
const int incy) {
dsbmv_(&uplo, &n, &k, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void spmv(const char uplo, const int n, const double alpha,
const double *a, const double *x, const int incx,
const double beta, double *y, const int incy) {
dspmv_(&uplo, &n, &alpha, a, x, &incx, &beta, y, &incy);
}
static void trmv(const char uplo, const char trans, const char diag,
const int n, const double *a, const int lda, double *x,
const int incx) {
dtrmv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbmv(const char uplo, const char trans, const char diag,
const int n, const int k, const double *a, const int lda,
double *x, const int incx) {
dtbmv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpmv(const char uplo, const char trans, const char diag,
const int n, const double *ap, double *x, const int incx) {
dtpmv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void trsv(const char uplo, const char trans, const char diag,
const int n, const double *a, const int lda, double *x,
const int incx) {
dtrsv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbsv(const char uplo, const char trans, const char diag,
const int n, const int k, const double *a, const int lda,
double *x, const int incx) {
dtbsv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpsv(const char uplo, const char trans, const char diag,
const int n, const double *ap, double *x, const int incx) {
dtpsv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void ger(const int m, const int n, const double alpha, const double *x,
const int incx, const double *y, const int incy, double *a,
const int lda) {
dger_(&m, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void syr(const char uplo, const int n, const double alpha,
const double *x, const int incx, double *a, const int lda) {
dsyr_(&uplo, &n, &alpha, x, &incx, a, &lda);
}
static void spr(const char uplo, const int n, const double alpha,
const double *x, const int incx, double *ap) {
dspr_(&uplo, &n, &alpha, x, &incx, ap);
}
static void syr2(const char uplo, const int n, const double alpha,
const double *x, const int incx, const double *y,
const int incy, double *a, const int lda) {
dsyr2_(&uplo, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void spr2(const char uplo, const int n, const double alpha,
const double *x, const int incx, const double *y,
const int incy, double *ap) {
dspr2_(&uplo, &n, &alpha, x, &incx, y, &incy, ap);
}
// Level 3
static void gemm(const char transa, const char transb, const int m,
const int n, const int k, const double alpha,
const double *a, const int lda, const double *b,
const int ldb, const double beta, double *c, const int ldc) {
dgemm_(&transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c,
&ldc);
}
static void symm(const char side, const char uplo, const int m, const int n,
const double alpha, const double *a, const int lda,
const double *b, const int ldb, const double beta, double *c,
const int ldc) {
dsymm_(&side, &uplo, &m, &n, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void syrk(const char uplo, const char trans, const int n, const int k,
const double alpha, const double *a, const int lda,
const double beta, double *c, const int ldc) {
dsyrk_(&uplo, &trans, &n, &k, &alpha, a, &lda, &beta, c, &ldc);
}
static void syr2k(const char uplo, const char trans, const int n, const int k,
const double alpha, const double *a, const int lda,
const double *b, const int ldb, const double beta,
double *c, const int ldc) {
dsyr2k_(&uplo, &trans, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void trmm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n,
const double alpha, const double *a, const int lda,
double *b, const int ldb) {
dtrmm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
static void trsm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n,
const double alpha, const double *a, const int lda,
double *b, const int ldb) {
dtrsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
};
} // namespace matrix
} // namespace utility
} // namespace polo
#endif
| 51.321357 | 80 | 0.57269 | aytekinar |
51bc4e001b165451ed5d356f30f6b1d24c029ba8 | 563 | cpp | C++ | programmers/hash1.cpp | rune2002/coding-study | 94ae7f4d4f5ea21f68538462cff56cc12f0e0718 | [
"MIT"
] | null | null | null | programmers/hash1.cpp | rune2002/coding-study | 94ae7f4d4f5ea21f68538462cff56cc12f0e0718 | [
"MIT"
] | null | null | null | programmers/hash1.cpp | rune2002/coding-study | 94ae7f4d4f5ea21f68538462cff56cc12f0e0718 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
sort(participant.begin(), participant.end());
sort(completion.begin(), completion.end());
string answer;
for (int i = 0; i < completion.size(); i++)
{
if (participant[i].compare(completion[i]) != 0)
{
answer = participant[i];
break;
}
if (i == completion.size() - 1)
answer = participant[i+1];
}
return answer;
}
| 24.478261 | 72 | 0.577265 | rune2002 |
51bd7a66f51e0b4efff85820169c5feffb791ae4 | 262 | cpp | C++ | src/batteries/suppress_test.cpp | tonyastolfi/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-04T20:28:17.000Z | 2022-01-04T20:28:17.000Z | src/batteries/suppress_test.cpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 2 | 2020-06-04T14:02:24.000Z | 2020-06-04T14:03:18.000Z | src/batteries/suppress_test.cpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-03T20:24:31.000Z | 2022-01-03T20:24:31.000Z | // Copyright 2021 Anthony Paul Astolfi
//
#include <batteries/suppress.hpp>
//
#include <batteries/suppress.hpp>
namespace {
BATT_SUPPRESS("-Wreturn-type")
BATT_SUPPRESS("-Wunused-function")
int foo()
{
}
BATT_UNSUPPRESS()
BATT_UNSUPPRESS()
} // namespace
| 13.1 | 38 | 0.729008 | tonyastolfi |
51c0068121fe645432d8c07de6d95e472cb9df6f | 700 | cpp | C++ | editor/model/serialize/ControlSurfaceSerializer.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 642 | 2017-12-10T14:22:04.000Z | 2022-03-03T15:23:23.000Z | editor/model/serialize/ControlSurfaceSerializer.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 151 | 2017-12-21T02:08:45.000Z | 2020-07-03T14:18:51.000Z | editor/model/serialize/ControlSurfaceSerializer.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 30 | 2018-09-11T14:06:31.000Z | 2021-11-09T04:19:00.000Z | #include "ControlSurfaceSerializer.h"
#include "../objects/ControlSurface.h"
using namespace AxiomModel;
void ControlSurfaceSerializer::serialize(AxiomModel::ControlSurface *surface, QDataStream &stream) {}
std::unique_ptr<ControlSurface> ControlSurfaceSerializer::deserialize(QDataStream &stream, uint32_t version,
const QUuid &uuid, const QUuid &parentUuid,
AxiomModel::ReferenceMapper *ref,
AxiomModel::ModelRoot *root) {
return ControlSurface::create(uuid, parentUuid, root);
}
| 46.666667 | 113 | 0.561429 | remaininlight |
51c4a6bb6749515743378b5a027d76c56509cd44 | 7,431 | cpp | C++ | src/shapefunction/spline.cpp | ellery85/sparselizard | 7d09e97e9443a436d74cbd241b8466527edb9e2f | [
"MIT"
] | null | null | null | src/shapefunction/spline.cpp | ellery85/sparselizard | 7d09e97e9443a436d74cbd241b8466527edb9e2f | [
"MIT"
] | null | null | null | src/shapefunction/spline.cpp | ellery85/sparselizard | 7d09e97e9443a436d74cbd241b8466527edb9e2f | [
"MIT"
] | null | null | null | #include "spline.h"
#include "mathop.h"
#include "mat.h"
#include "vec.h"
#include "myalgorithm.h"
spline::spline(std::string filename, char delimiter)
{
std::vector<double> data = mathop::loadvector(filename, delimiter, false);
if (data.size()%2 != 0)
{
std::cout << "Error in 'spline' object: expected a vector length multiple of 2 in '" << filename << "' (format {x1,y1,x2,y2,...})" << std::endl;
abort();
}
std::vector<double> xin(data.size()/2);
std::vector<double> yin(data.size()/2);
for (int i = 0; i < data.size()/2; i++)
{
xin[i] = data[2*i+0];
yin[i] = data[2*i+1];
}
set(xin,yin);
}
spline::spline(std::vector<double> xin, std::vector<double> yin)
{
set(xin,yin);
}
void spline::set(std::vector<double>& xin, std::vector<double>& yin)
{
if (xin.size() != yin.size())
{
std::cout << "Error in 'spline' object: x and y dataset sizes do not match" << std::endl;
abort();
}
int len = xin.size();
if (len < 2)
{
std::cout << "Error in 'spline' object: expected at least two data points" << std::endl;
abort();
}
myx = densematrix(len,1);
myy = densematrix(len,1);
double* xvals = myx.getvalues();
double* yvals = myy.getvalues();
// First sort ascendingly according to x:
std::vector<int> reorderingvector;
myalgorithm::stablesort(0, xin, reorderingvector);
for (int i = 0; i < len; i++)
{
xvals[i] = xin[reorderingvector[i]];
yvals[i] = yin[reorderingvector[i]];
}
xmin = xvals[0]; xmax = xvals[len-1];
double absnoise = noisethreshold*std::abs(xmax-xmin);
for (int i = 1; i < len; i++)
{
if (xvals[i]-xvals[i-1] < absnoise)
{
std::cout << "Error in 'spline' object: distance between two samples is " << (xvals[i]-xvals[i-1]) << " (below noise level " << absnoise << ")" << std::endl;
abort();
}
}
// Create the A matrix and b rhs:
intdensematrix Arows(3*len-2,1), Acols(3*len-2,1);
int* Arowvals = Arows.getvalues();
int* Acolvals = Acols.getvalues();
densematrix Av(3*len-2,1);
double* Avals = Av.getvalues();
densematrix bv(len,1);
double* bvals = bv.getvalues();
// First row has no left neighbour:
Arowvals[0] = 0; Arowvals[1] = 0; Acolvals[0] = 0; Acolvals[1] = 1;
Avals[0] = 2.0/(xvals[1]-xvals[0]); Avals[1] = 1.0/(xvals[1]-xvals[0]);
bvals[0] = 3.0*(yvals[1]-yvals[0])*Avals[1]*Avals[1];
// Rows with two neighbours:
double b1 = bvals[0]; int ind = 2;
for (int i = 1; i < len-1; i++)
{
Arowvals[ind+0] = i; Arowvals[ind+1] = i; Arowvals[ind+2] = i;
Acolvals[ind+0] = i-1; Acolvals[ind+1] = i; Acolvals[ind+2] = i+1;
Avals[ind+0] = Avals[ind-1]; Avals[ind+2] = 1.0/(xvals[i+1]-xvals[i]); Avals[ind+1] = 2.0*(Avals[ind+0]+Avals[ind+2]);
double b2 = 3.0*(yvals[i+1]-yvals[i])*Avals[ind+2]*Avals[ind+2];
bvals[i] = b1+b2;
b1 = b2;
ind += 3;
}
// Last row has no right neighbour:
Arowvals[ind+0] = len-1; Arowvals[ind+1] = len-1; Acolvals[ind+0] = len-2; Acolvals[ind+1] = len-1;
Avals[ind+0] = 1.0/(xvals[len-1]-xvals[len-2]); Avals[ind+1] = 2.0/(xvals[len-1]-xvals[len-2]);
bvals[len-1] = 3.0*(yvals[len-1]-yvals[len-2])*Avals[ind+0]*Avals[ind+0];
// Solve problem Ak = b:
mat A(len, Arows, Acols, Av);
vec b(len, intdensematrix(len,1,0,1), bv);
vec k = mathop::solve(A,b);
densematrix kv = k.getvalues(intdensematrix(len,1,0,1));
double* kvals = kv.getvalues();
// Compute the spline parameters a and b:
mya = densematrix(len,1);
myb = densematrix(len,1);
double* aparamvals = mya.getvalues();
double* bparamvals = myb.getvalues();
for (int i = 1; i < len; i++)
{
aparamvals[i] = kvals[i-1]*(xvals[i]-xvals[i-1])-(yvals[i]-yvals[i-1]);
bparamvals[i] = -kvals[i]*(xvals[i]-xvals[i-1])+(yvals[i]-yvals[i-1]);
}
}
double spline::evalat(double input)
{
std::vector<double> invec = {input};
return evalat(invec)[0];
}
std::vector<double> spline::evalat(std::vector<double> input)
{
densematrix indm(input.size(),1, input);
densematrix outdm = evalat(indm);
std::vector<double> output;
outdm.getvalues(output);
return output;
}
densematrix spline::evalat(densematrix input)
{
int numin = input.count();
double* inputvals = input.getvalues();
std::vector<double> invals;
input.getvalues(invals);
// Sort the input data ascendingly:
std::vector<int> reorderingvector;
myalgorithm::stablesort(0, invals, reorderingvector);
for (int i = 0; i < numin; i++)
inputvals[i] = invals[reorderingvector[i]];
double inmin = inputvals[0]; double inmax = inputvals[numin-1];
// Error if request is out of range:
double absnoise = noisethreshold*std::abs(xmax-xmin);
if (inmin < xmin-absnoise || inmax > xmax+absnoise)
{
std::cout << "Error in 'spline' object: data requested in interval (" << inmin << "," << inmax << ") is out of the provided data range (" << xmin << "," << xmax << ")" << std::endl;
abort();
}
std::vector<double> outvec(numin);
// Get the corresponding data via spline interpolation.
double* xvals = myx.getvalues(); double* yvals = myy.getvalues();
double* avals = mya.getvalues(); double* bvals = myb.getvalues();
// First find the corresponding spline:
int curspline = 1;
for (int i = 0; i < numin; i++)
{
double cur = inputvals[i];
// Find the spline:
while (xvals[curspline] < cur-absnoise)
curspline++;
// Interpolate on the spline:
double tx = (cur-xvals[curspline-1])/(xvals[curspline]-xvals[curspline-1]);
outvec[i] = (1.0-tx)*yvals[curspline-1] + tx*yvals[curspline] + tx*(1.0-tx)*((1.0-tx)*avals[curspline]+tx*bvals[curspline]);
}
// Unsort the data:
densematrix output(input.countrows(),input.countcolumns());
double* outputvals = output.getvalues();
for (int i = 0; i < numin; i++)
outputvals[reorderingvector[i]] = outvec[i];
return output;
}
void spline::write(std::string filename, int numsplits, char delimiter)
{
if (numsplits < 0)
{
std::cout << "Error in 'spline' object: cannot write with " << numsplits << " splits" << std::endl;
abort();
}
// Get the x positions:
double* xvalues = myx.getvalues();
densematrix xsplit(1+(myx.count()-1)*(numsplits+1),1);
double* xsplitvals = xsplit.getvalues();
double step = 1.0/(numsplits+1.0);
xsplitvals[0] = xvalues[0];
int index = 1;
for (int i = 0; i < myx.count()-1; i++)
{
for (int j = 0; j < numsplits+1; j++)
{
xsplitvals[index] = xvalues[i]+(j+1.0)*step*(xvalues[i+1]-xvalues[i]);
index++;
}
}
densematrix evaled = evalat(xsplit);
double* evaledvals = evaled.getvalues();
// Write to file:
std::vector<double> data(2*xsplit.count());
for (int i = 0; i < xsplit.count(); i++)
{
data[2*i+0] = xsplitvals[i];
data[2*i+1] = evaledvals[i];
}
mathop::writevector(filename, data, delimiter, false);
}
| 30.9625 | 189 | 0.56668 | ellery85 |
51c96f6d013ecc6f84edbadd1476d86a9c1cee6e | 54,305 | cpp | C++ | src/lms7002m/LMS7002M_RxTxCalibrations.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | src/lms7002m/LMS7002M_RxTxCalibrations.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | src/lms7002m/LMS7002M_RxTxCalibrations.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | #include "LMS7002M.h"
#include "CalibrationCache.h"
#include "ErrorReporting.h"
#include <assert.h>
#include "MCU_BD.h"
#include "IConnection.h"
#include "mcu_programs.h"
#include "LMS64CProtocol.h"
#include <vector>
#include <ciso646>
#define LMS_VERBOSE_OUTPUT
///define for parameter enumeration if prefix might be needed
#define LMS7param(id) id
using namespace lime;
float_type calibUserBwDivider = 5;
const static uint16_t MCU_PARAMETER_ADDRESS = 0x002D; //register used to pass parameter values to MCU
#define MCU_ID_DC_IQ_CALIBRATIONS 0x01
#define MCU_FUNCTION_CALIBRATE_TX 1
#define MCU_FUNCTION_CALIBRATE_RX 2
#define MCU_FUNCTION_READ_RSSI 3
#define MCU_FUNCTION_UPDATE_REF_CLK 4
#ifdef ENABLE_CALIBRATION_USING_FFT
#include "kiss_fft.h"
int fftBin = 0; //which bin to use when calibration using FFT
bool rssiFromFFT = false;
#endif // ENABLE_CALIBRATION_USING_FFT
const float calibrationSXOffset_Hz = 4e6;
const int16_t firCoefs[] =
{
8,
4,
0,
-6,
-11,
-16,
-20,
-22,
-22,
-20,
-14,
-5,
6,
20,
34,
46,
56,
61,
58,
48,
29,
3,
-29,
-63,
-96,
-123,
-140,
-142,
-128,
-94,
-44,
20,
93,
167,
232,
280,
302,
291,
244,
159,
41,
-102,
-258,
-409,
-539,
-628,
-658,
-614,
-486,
-269,
34,
413,
852,
1328,
1814,
2280,
2697,
3038,
3277,
3401,
3401,
3277,
3038,
2697,
2280,
1814,
1328,
852,
413,
34,
-269,
-486,
-614,
-658,
-628,
-539,
-409,
-258,
-102,
41,
159,
244,
291,
302,
280,
232,
167,
93,
20,
-44,
-94,
-128,
-142,
-140,
-123,
-96,
-63,
-29,
3,
29,
48,
58,
61,
56,
46,
34,
20,
6,
-5,
-14,
-20,
-22,
-22,
-20,
-16,
-11,
-6,
0,
4,
8
};
const uint16_t backupAddrs[] = {
0x0020, 0x0082, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088,
0x0089, 0x008A, 0x008B, 0x008C, 0x0100, 0x0101, 0x0102, 0x0103,
0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010C,
0x010D, 0x010E, 0x010F, 0x0110, 0x0111, 0x0112, 0x0113, 0x0114,
0x0115, 0x0116, 0x0117, 0x0118, 0x0119, 0x011A, 0x0200, 0x0201,
0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207, 0x0208, 0x0240,
0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247, 0x0248,
0x0249, 0x024A, 0x024B, 0x024C, 0x024D, 0x024E, 0x024F, 0x0250,
0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257, 0x0258,
0x0259, 0x025A, 0x025B, 0x025C, 0x025D, 0x025E, 0x025F, 0x0260,
0x0261, 0x0400, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406,
0x0407, 0x0408, 0x0409, 0x040A, 0x040C, 0x040D, 0x0440, 0x0441,
0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449,
0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, 0x0450, 0x0451,
0x0452, 0x0453, 0x0454, 0x0455, 0x0456, 0x0457, 0x0458, 0x0459,
0x045A, 0x045B, 0x045C, 0x045D, 0x045E, 0x045F, 0x0460, 0x0461
};
uint16_t backupRegs[sizeof(backupAddrs) / sizeof(int16_t)];
const uint16_t backupSXAddr[] = { 0x011C, 0x011D, 0x011E, 0x011F, 0x0120, 0x0121, 0x0122, 0x0123, 0x0124 };
uint16_t backupRegsSXR[sizeof(backupSXAddr) / sizeof(int16_t)];
uint16_t backupRegsSXT[sizeof(backupSXAddr) / sizeof(int16_t)];
int16_t rxGFIR3_backup[sizeof(firCoefs) / sizeof(int16_t)];
uint16_t backup0x010D;
uint16_t backup0x0100;
inline uint16_t pow2(const uint8_t power)
{
assert(power >= 0 && power < 16);
return 1 << power;
}
bool sign(const int number)
{
return number < 0;
}
/** @brief Parameters setup instructions for Tx calibration
@return 0-success, other-failure
*/
int LMS7002M::CalibrateTxSetup(float_type bandwidth_Hz, const bool useExtLoopback)
{
//Stage 2
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
//rfe
//reset RFE to defaults
SetDefaults(RFE);
if(useExtLoopback)
{
int LNAselection = 1;
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), LNAselection); //SEL_PATH_RFE 3
Modify_SPI_Reg_bits(LMS7param(G_LNA_RFE), 1);
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(LMS7param(CCOMP_TIA_RFE), 4);
Modify_SPI_Reg_bits(LMS7param(CFB_TIA_RFE), 50);
Modify_SPI_Reg_bits(LMS7param(ICT_LODC_RFE), 31); //ICT_LODC_RFE 31
if(LNAselection == 2)
{
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_L_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_W_RFE), 1);
}
else if(LNAselection == 3)
{
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_L_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_W_RFE), 0);
}
else
{
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_L_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_W_RFE), 1);
}
Modify_SPI_Reg_bits(LMS7param(PD_LNA_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(G_TIA_RFE), 1);
}
else
{
if(sel_band1_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 3); //SEL_PATH_RFE 3
else if(sel_band2_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 2);
else
return ReportError(EINVAL, "Tx Calibration: band not selected");
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 7);
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(LMS7param(CCOMP_TIA_RFE), 4);
Modify_SPI_Reg_bits(LMS7param(CFB_TIA_RFE), 50);
Modify_SPI_Reg_bits(LMS7param(ICT_LODC_RFE), 31); //ICT_LODC_RFE 31
if(sel_band1_trf)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 1);
}
else
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0);
}
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
}
//RBB
//reset RBB to defaults
SetDefaults(RBB);
Modify_SPI_Reg_bits(LMS7param(PD_LPFL_RBB), 1);
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), 0);
Modify_SPI_Reg_bits(LMS7param(INPUT_CTL_PGA_RBB), 2);
Modify_SPI_Reg_bits(LMS7param(ICT_PGA_OUT_RBB), 12);
Modify_SPI_Reg_bits(LMS7param(ICT_PGA_IN_RBB), 12);
//TRF
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 0); //L_LOOPB_TXPAD_TRF 0
if(useExtLoopback)
{
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 0); //EN_LOOPB_TXPAD_TRF 1
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
}
else
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 1); //EN_LOOPB_TXPAD_TRF 1
//AFE
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE1), 0); //PD_RX_AFE1 0
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2 0
//BIAS
uint16_t backup = Get_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS));
SetDefaults(BIAS);
Modify_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS), backup); //RP_CALIB_BIAS
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
const float_type cgenFreq = GetFrequencyCGEN();
int cgenMultiplier = int((cgenFreq / 46.08e6) + 0.5);
if(cgenMultiplier < 2)
cgenMultiplier = 2;
if(cgenMultiplier > 9 && cgenMultiplier < 12)
cgenMultiplier = 12;
if(cgenMultiplier > 13)
cgenMultiplier = 13;
//power up VCO
Modify_SPI_Reg_bits(0x0086, 2, 2, 0);
int status = SetFrequencyCGEN(46.08e6 * cgenMultiplier);
if(status != 0)
return status;
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SetDefaults(SX);
Modify_SPI_Reg_bits(LMS7param(PD_VCO), 0);
Modify_SPI_Reg_bits(LMS7param(ICT_VCO), 200);
{
float_type SXTfreq = GetFrequencySX(Tx);
float_type SXRfreq = SXTfreq - bandwidth_Hz / calibUserBwDivider - calibrationSXOffset_Hz;
status = SetFrequencySX(Rx, SXRfreq);
if(status != 0)
return status;
status = TuneVCO(VCO_SXR);
if(status != 0)
return status;
}
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
Modify_SPI_Reg_bits(PD_LOCH_T2RBUF, 1);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
Modify_SPI_Reg_bits(LMS7param(TSGMODE_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(INSEL_TXTSP), 1);
if(useExtLoopback)
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_TXTSP), 1);
else
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_TXTSP), 0);
Modify_SPI_Reg_bits(DC_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(GC_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(PH_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047);
Modify_SPI_Reg_bits(CMIX_SC_TXTSP, 0);
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
SetNCOFrequency(Tx, 0, bandwidth_Hz / calibUserBwDivider);
//RXTSP
SetDefaults(RxTSP);
SetDefaults(RxNCO);
Modify_SPI_Reg_bits(LMS7param(GFIR2_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(GFIR1_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 4); //Decimation HBD ratio
if(useExtLoopback)
{
Modify_SPI_Reg_bits(LMS7param(GFIR3_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(AGC_BYP_RXTSP), 1);
}
else
{
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 0x1);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
if(Get_SPI_Reg_bits(EN_ADCCLKH_CLKGN) == 1)
{
int clkh_ov = Get_SPI_Reg_bits(CLKH_OV_CLKL_CGEN);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 4 * cgenMultiplier/pow2(clkh_ov) - 1);
}
else
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 4 * cgenMultiplier - 1);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
}
if(ch == 2)
{
Modify_SPI_Reg_bits(MAC, 1);
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
Modify_SPI_Reg_bits(LMS7param(EN_NEXTRX_RFE), 1); // EN_NEXTTX_RFE 1
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); //EN_NEXTTX_TRF 1
Modify_SPI_Reg_bits(MAC, ch);
}
return 0;
}
/** @brief Flips the CAPTURE bit and returns digital RSSI value
*/
uint32_t LMS7002M::GetRSSI()
{
#ifdef ENABLE_CALIBRATION_USING_FFT
if(!rssiFromFFT)
{
const int fftSize = 16384;
StreamConfig config;
config.isTx = false;
config.channels.push_back(0);
config.channels.push_back(1);
config.format = StreamConfig::STREAM_12_BIT_IN_16;
config.bufferLength = fftSize;
size_t streamID(~0);
controlPort->SetHardwareTimestamp(0);
const auto errorMsg = controlPort->SetupStream(streamID, config);
float avgRSSI = 0;
const int channelsCount = 1;
kiss_fft_cfg m_fftCalcPlan = kiss_fft_alloc(fftSize, 0, 0, 0);
kiss_fft_cpx* m_fftCalcIn = new kiss_fft_cpx[fftSize];
kiss_fft_cpx* m_fftCalcOut = new kiss_fft_cpx[fftSize];
int16_t **buffs = new int16_t*[channelsCount];
for(int i=0; i<channelsCount; ++i)
buffs[i] = new int16_t[fftSize];
//TODO setup streaming
StreamMetadata metadata;
auto ret = controlPort->ReadStream(streamID, (void* const*)buffs, fftSize, 1000, metadata);
long samplesCollected = 0;
int16_t sample = 0;
const int stepSize = 4;
/*for (uint16_t b = 0; b < bytesReceived; b += stepSize)
{
//I sample
sample = (buffer[b] & 0xFF);
sample |= (buffer[b + 1] & 0x0F) << 8;
sample = sample << 4;
sample = sample >> 4;
m_fftCalcIn[samplesCollected].r = sample;
//Q sample
sample = (buffer[b + 2] & 0xFF);
sample |= (buffer[b + 3] & 0x0F) << 8;
sample = sample << 4;
sample = sample >> 4;
m_fftCalcIn[samplesCollected].i = sample;
++samplesCollected;
if (samplesCollected >= fftSize)
break;
}*/
kiss_fft(m_fftCalcPlan, m_fftCalcIn, m_fftCalcOut);
for (int i = 0; i < fftSize; ++i)
{
// normalize FFT results
m_fftCalcOut[i].r /= fftSize;
m_fftCalcOut[i].i /= fftSize;
}
std::vector<float> fftBins_dbFS;
fftBins_dbFS.resize(fftSize, 0);
int output_index = 0;
for (int i = 0; i < fftSize; ++i)
{
fftBins_dbFS[output_index++] = sqrt(m_fftCalcOut[i].r * m_fftCalcOut[i].r + m_fftCalcOut[i].i * m_fftCalcOut[i].i);
}
for (int s = 0; s < fftSize; ++s)
fftBins_dbFS[s] = (fftBins_dbFS[s] != 0 ? (20 * log10(fftBins_dbFS[s])) - 69.2369 : -300);
int binToGet = fftBin;
float rssiToReturn = m_fftCalcOut[binToGet].r * m_fftCalcOut[binToGet].r + m_fftCalcOut[binToGet].i * m_fftCalcOut[binToGet].i;
avgRSSI = fftBins_dbFS[binToGet];
kiss_fft_free(m_fftCalcPlan);
for(int i=0; i<channelsCount; ++i)
delete buffs[i];
delete[]buffs;
printf("FFT RSSI = %f \n", avgRSSI);
controlPort->CloseStream(streamID);
return avgRSSI;
}
#endif
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 0);
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 1);
return (Get_SPI_Reg_bits(0x040F, 15, 0, true) << 2) | Get_SPI_Reg_bits(0x040E, 1, 0, true);
}
/** @brief Calibrates Transmitter. DC correction, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
int LMS7002M::CalibrateTx(float_type bandwidth_Hz, const bool useExtLoopback)
{
if(useExtLoopback)
return ReportError(EPERM, "Calibration with external loopback not yet implemented");
int status;
if(mCalibrationByMCU)
{
uint8_t mcuID = mcuControl->ReadMCUProgramID();
if(mcuID != MCU_ID_DC_IQ_CALIBRATIONS)
{
status = mcuControl->Program_MCU(mcu_program_lms7_dc_iq_calibration_bin, MCU_BD::SRAM);
if(status != 0)
return status;
}
}
Channel ch = this->GetActiveChannel();
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
double txFreq = GetFrequencySX(Tx);
uint8_t channel = ch == 1 ? 0 : 1;
bool foundInCache = false;
int band = sel_band1_trf ? 0 : 1;
uint16_t gainAddr;
uint16_t gcorri;
uint16_t gcorrq;
uint16_t dccorri;
uint16_t dccorrq;
int16_t phaseOffset;
int16_t gain = 1983;
const uint16_t gainMSB = 10;
const uint16_t gainLSB = 0;
if(useCache)
{
int dcI, dcQ, gainI, gainQ, phOffset;
foundInCache = (mValueCache->GetDC_IQ(boardId, txFreq*1e6, channel, true, band, &dcI, &dcQ, &gainI, &gainQ, &phOffset) == 0);
if(foundInCache)
{
printf("Tx calibration: using cached values\n");
dccorri = dcI;
dccorrq = dcQ;
gcorri = gainI;
gcorrq = gainQ;
phaseOffset = phOffset;
Modify_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), dcI);
Modify_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), dcQ);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gainI);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gainQ);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), phaseOffset);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
Modify_SPI_Reg_bits(0x0208, 1, 0, 0); //GC_BYP PH_BYP
return 0;
}
}
LMS7002M_SelfCalState state(this);
Log("Tx calibration started", LOG_INFO);
BackupAllRegisters();
Log("Setup stage", LOG_INFO);
status = CalibrateTxSetup(bandwidth_Hz, useExtLoopback);
if(status != 0)
goto TxCalibrationEnd; //go to ending stage to restore registers
if(mCalibrationByMCU)
{
//set reference clock parameter inside MCU
long refClk = GetReferenceClk_SX(false);
uint16_t refClkToMCU = (int(refClk / 1000000) << 9) | ((refClk % 1000000) / 10000);
SPI_write(MCU_PARAMETER_ADDRESS, refClkToMCU);
mcuControl->CallMCU(MCU_FUNCTION_UPDATE_REF_CLK);
auto statusMcu = mcuControl->WaitForMCU(100);
//set bandwidth for MCU to read from register, value is integer stored in MHz
SPI_write(MCU_PARAMETER_ADDRESS, (uint16_t)(bandwidth_Hz / 1e6));
mcuControl->CallMCU(MCU_FUNCTION_CALIBRATE_TX);
statusMcu = mcuControl->WaitForMCU(30000);
if(statusMcu == 0)
{
printf("MCU working too long %i\n", statusMcu);
}
}
else
{
CheckSaturationTxRx(bandwidth_Hz, useExtLoopback);
Modify_SPI_Reg_bits(EN_G_TRF, 0);
if(!useExtLoopback)
CalibrateRxDC_RSSI();
CalibrateTxDC_RSSI(bandwidth_Hz);
//TXIQ
Modify_SPI_Reg_bits(EN_G_TRF, 1);
Modify_SPI_Reg_bits(CMIX_BYP_TXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6);
//coarse gain
uint32_t rssiIgain;
uint32_t rssiQgain;
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047 - 64);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047);
rssiIgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047 - 64);
rssiQgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047);
if(rssiIgain < rssiQgain)
gainAddr = GCORRI_TXTSP.address;
else
gainAddr = GCORRQ_TXTSP.address;
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Tx GAIN_%s: %i\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q", gain);
#endif
//coarse phase offset
uint32_t rssiUp;
uint32_t rssiDown;
Modify_SPI_Reg_bits(IQCORR_TXTSP, 15);
rssiUp = GetRSSI();
Modify_SPI_Reg_bits(IQCORR_TXTSP, -15);
rssiDown = GetRSSI();
if(rssiUp > rssiDown)
phaseOffset = -64;
else if(rssiUp < rssiDown)
phaseOffset = 192;
else
phaseOffset = 64;
Modify_SPI_Reg_bits(IQCORR_TXTSP, phaseOffset);
CoarseSearch(IQCORR_TXTSP.address, IQCORR_TXTSP.msb, IQCORR_TXTSP.lsb, phaseOffset, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Tx IQCORR: %i\n", phaseOffset);
#endif
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 4);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Tx GAIN_%s: %i\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q", gain);
printf("Fine search Tx GAIN_%s/IQCORR...\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q");
#endif
FineSearch(gainAddr, gainMSB, gainLSB, gain, IQCORR_TXTSP.address, IQCORR_TXTSP.msb, IQCORR_TXTSP.lsb, phaseOffset, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Tx GAIN_%s: %i, IQCORR: %i\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q", gain, phaseOffset);
#endif
Modify_SPI_Reg_bits(gainAddr, gainMSB, gainLSB, gain);
Modify_SPI_Reg_bits(IQCORR_TXTSP.address, IQCORR_TXTSP.msb, IQCORR_TXTSP.lsb, phaseOffset);
}
dccorri = Get_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), true);
dccorrq = Get_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), true);
gcorri = Get_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), true);
gcorrq = Get_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), true);
phaseOffset = Get_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), true);
TxCalibrationEnd:
Log("Restoring registers state", LOG_INFO);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
RestoreAllRegisters();
if(status != 0)
{
Log("Tx calibration failed", LOG_WARNING);
return status;
}
if(useCache)
mValueCache->InsertDC_IQ(boardId, txFreq*1e6, channel, true, band, dccorri, dccorrq, gcorri, gcorrq, phaseOffset);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), dccorri);
Modify_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), dccorrq);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), phaseOffset);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
Modify_SPI_Reg_bits(0x0208, 1, 0, 0); //GC_BYP PH_BYP
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
Log("Tx calibration finished", LOG_INFO);
return 0;
}
/** @brief Performs Rx DC offsets calibration
*/
void LMS7002M::CalibrateRxDC_RSSI()
{
#ifdef ENABLE_CALIBRATION_USING_FFT
fftBin = 0;
#endif
int16_t offsetI = 32;
int16_t offsetQ = 32;
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 1);
Modify_SPI_Reg_bits(CAPSEL, 0);
SetRxDCOFF(offsetI, offsetQ);
//find I
CoarseSearch(DCOFFI_RFE.address, DCOFFI_RFE.msb, DCOFFI_RFE.lsb, offsetI, 6);
//find Q
CoarseSearch(DCOFFQ_RFE.address, DCOFFQ_RFE.msb, DCOFFQ_RFE.lsb, offsetQ, 6);
CoarseSearch(DCOFFI_RFE.address, DCOFFI_RFE.msb, DCOFFI_RFE.lsb, offsetI, 3);
CoarseSearch(DCOFFQ_RFE.address, DCOFFQ_RFE.msb, DCOFFQ_RFE.lsb, offsetQ, 3);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx DCOFFI/DCOFFQ\n");
#endif
FineSearch(DCOFFI_RFE.address, DCOFFI_RFE.msb, DCOFFI_RFE.lsb, offsetI, DCOFFQ_RFE.address, DCOFFQ_RFE.msb, DCOFFQ_RFE.lsb, offsetQ, 5);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx DCOFFI: %i, DCOFFQ: %i\n", offsetI, offsetQ);
#endif
SetRxDCOFF(offsetI, offsetQ);
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 0); // DC_BYP 0
#ifdef ENABLE_CALIBRATION_USING_FFT
fftBin = 569; //fft bin 100 kHz
#endif
}
/** @brief Parameters setup instructions for Rx calibration
@param bandwidth_Hz filter bandwidth in Hz
@return 0-success, other-failure
*/
int LMS7002M::CalibrateRxSetup(float_type bandwidth_Hz, const bool useExtLoopback)
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//rfe
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
if(not useExtLoopback)
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 3);
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(0x010C, 1, 1, 0); //PD_TIA 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
//RBB
Modify_SPI_Reg_bits(0x0115, 15, 14, 0); //Loopback switches disable
Modify_SPI_Reg_bits(0x0119, 15, 15, 0); //OSW_PGA 0
//TRF
//reset TRF to defaults
SetDefaults(TRF);
if(not useExtLoopback)
{
Modify_SPI_Reg_bits(L_LOOPB_TXPAD_TRF, 0);
Modify_SPI_Reg_bits(EN_LOOPB_TXPAD_TRF, 1);
}
else
Modify_SPI_Reg_bits(LOSS_MAIN_TXPAD_TRF, 10);
Modify_SPI_Reg_bits(EN_G_TRF, 0);
{
uint8_t selPath;
if(useExtLoopback) //use PA1
selPath = 3;
else
selPath = Get_SPI_Reg_bits(SEL_PATH_RFE);
if (selPath == 2)
{
Modify_SPI_Reg_bits(SEL_BAND2_TRF, 1);
Modify_SPI_Reg_bits(SEL_BAND1_TRF, 0);
}
else if (selPath == 3)
{
Modify_SPI_Reg_bits(SEL_BAND2_TRF, 0);
Modify_SPI_Reg_bits(SEL_BAND1_TRF, 1);
}
else
return ReportError("CalibrateRxSetup() - SEL_PATH_RFE must be LNAL or LNAW"); //todo restore settings
}
//TBB
//reset TBB to defaults
SetDefaults(TBB);
Modify_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), 1);
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_FRP_TBB), 1); //ICT_IAMP_FRP_TBB 1
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_GG_FRP_TBB), 6); //ICT_IAMP_GG_FRP_TBB 6
//AFE
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2
//BIAS
{
uint16_t rp_calib_bias = Get_SPI_Reg_bits(0x0084, 10, 6);
SetDefaults(BIAS);
Modify_SPI_Reg_bits(0x0084, 10, 6, rp_calib_bias); //RP_CALIB_BIAS
}
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
const float_type cgenFreq = GetFrequencyCGEN();
SetDefaults(CGEN);
int cgenMultiplier = int(cgenFreq / 46.08e6 + 0.5);
if(cgenMultiplier < 2)
cgenMultiplier = 2;
if(cgenMultiplier > 9 && cgenMultiplier < 12)
cgenMultiplier = 12;
if(cgenMultiplier > 13)
cgenMultiplier = 13;
//power up VCO
Modify_SPI_Reg_bits(0x0086, 2, 2, 0);
int status = SetFrequencyCGEN(46.08e6 * cgenMultiplier);
if(status != 0)
return status;
Modify_SPI_Reg_bits(MAC, 2);
bool isTDD = Get_SPI_Reg_bits(PD_LOCH_T2RBUF, true) == 0;
if(isTDD)
{
//in TDD do nothing
Modify_SPI_Reg_bits(MAC, 1);
SetDefaults(SX);
SetFrequencySX(false, GetFrequencySX(true) - bandwidth_Hz / calibUserBwDivider - 9e6);
Modify_SPI_Reg_bits(PD_VCO, 1);
}
else
{
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
float_type SXRfreqHz = GetFrequencySX(Rx);
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
SetDefaults(SX);
Modify_SPI_Reg_bits(LMS7param(PD_VCO), 0);
status = SetFrequencySX(Tx, SXRfreqHz + bandwidth_Hz / calibUserBwDivider + 9e6);
if(status != 0) return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
SetDefaults(TxTSP);
SetDefaults(TxNCO);
Modify_SPI_Reg_bits(LMS7param(TSGFCW_TXTSP), 1);
Modify_SPI_Reg_bits(TSGMODE_TXTSP, 0x1); //TSGMODE 1
Modify_SPI_Reg_bits(INSEL_TXTSP, 1);
Modify_SPI_Reg_bits(0x0208, 6, 4, 0x7); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(CMIX_GAIN_TXTSP, 0);
Modify_SPI_Reg_bits(CMIX_SC_TXTSP, 1);
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
SetNCOFrequency(Tx, 0, 9e6);
//RXTSP
SetDefaults(RxTSP);
SetDefaults(RxNCO);
Modify_SPI_Reg_bits(0x040C, 4, 4, 1); //
Modify_SPI_Reg_bits(0x040C, 3, 3, 1); //
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 4);
if(not useExtLoopback)
{
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1); //AGC_MODE 1
Modify_SPI_Reg_bits(0x040C, 7, 7, 0x1); //CMIX_BYP 1
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 1); //agc_avg iq corr
Modify_SPI_Reg_bits(LMS7param(CMIX_GAIN_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 4*cgenMultiplier - 1);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
}
else
{
Modify_SPI_Reg_bits(0x040C, 5, 5, 1); // GFIR3_BYP
Modify_SPI_Reg_bits(AGC_BYP_RXTSP, 1);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 1);
}
SetNCOFrequency(Rx, 0, bandwidth_Hz/calibUserBwDivider - 0.1e6);
if(useExtLoopback)
{
//limelight
Modify_SPI_Reg_bits(LML1_FIDM, 1);
Modify_SPI_Reg_bits(LML2_FIDM, 1);
Modify_SPI_Reg_bits(LML1_MODE, 0);
Modify_SPI_Reg_bits(LML2_MODE, 0);
}
//modifications when calibrating channel B
if(ch == 2)
{
Modify_SPI_Reg_bits(MAC, 1);
Modify_SPI_Reg_bits(LMS7param(EN_NEXTRX_RFE), 1);
Modify_SPI_Reg_bits(EN_NEXTTX_TRF, 1);
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
Modify_SPI_Reg_bits(MAC, ch);
}
return 0;
}
/** @brief Calibrates Receiver. DC offset, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
int LMS7002M::CalibrateRx(float_type bandwidth_Hz, const bool useExtLoopback)
{
if(useExtLoopback)
return ReportError(EPERM, "Calibration with external loopback not yet implemented");
int status;
if(mCalibrationByMCU)
{
uint8_t mcuID = mcuControl->ReadMCUProgramID();
if(mcuID != MCU_ID_DC_IQ_CALIBRATIONS)
{
status = mcuControl->Program_MCU(mcu_program_lms7_dc_iq_calibration_bin, MCU_BD::SRAM);
if( status != 0)
return status;
}
}
Channel ch = this->GetActiveChannel();
uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
uint8_t channel = ch == 1 ? 0 : 1;
uint8_t sel_path_rfe = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE));
int lna = sel_path_rfe;
int16_t iqcorr_rx = 0;
int16_t dcoffi;
int16_t dcoffq;
int16_t gain;
uint16_t gainAddr = 0;
const uint8_t gainMSB = 10;
const uint8_t gainLSB = 0;
uint16_t mingcorri;
uint16_t mingcorrq;
int16_t phaseOffset;
double rxFreq = GetFrequencySX(Rx);
bool foundInCache = false;
if(useCache)
{
int dcI, dcQ, gainI, gainQ, phOffset;
foundInCache = (mValueCache->GetDC_IQ(boardId, rxFreq, channel, false, lna, &dcI, &dcQ, &gainI, &gainQ, &phOffset) == 0);
dcoffi = dcI;
dcoffq = dcQ;
mingcorri = gainI;
mingcorrq = gainQ;
phaseOffset = phOffset;
if(foundInCache)
{
printf("Rx calibration: using cached values\n");
SetRxDCOFF(dcoffi, dcoffq);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), gainI);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), gainQ);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), phaseOffset);
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
return 0;
}
}
LMS7002M_SelfCalState state(this);
Log("Rx calibration started", LOG_INFO);
Log("Saving registers state", LOG_INFO);
BackupAllRegisters();
if(sel_path_rfe == 1 || sel_path_rfe == 0)
return ReportError(EINVAL, "Rx Calibration: bad SEL_PATH");
Log("Setup stage", LOG_INFO);
status = CalibrateRxSetup(bandwidth_Hz, useExtLoopback);
if(status != 0)
goto RxCalibrationEndStage;
if(mCalibrationByMCU)
{
//set reference clock parameter inside MCU
long refClk = GetReferenceClk_SX(false);
uint16_t refClkToMCU = (int(refClk / 1000000) << 9) | ((refClk % 1000000) / 10000);
SPI_write(MCU_PARAMETER_ADDRESS, refClkToMCU);
mcuControl->CallMCU(MCU_FUNCTION_UPDATE_REF_CLK);
auto statusMcu = mcuControl->WaitForMCU(100);
//set bandwidth for MCU to read from register, value is integer stored in MHz
SPI_write(MCU_PARAMETER_ADDRESS, (uint16_t)(bandwidth_Hz / 1e6));
mcuControl->CallMCU(MCU_FUNCTION_CALIBRATE_RX);
statusMcu = mcuControl->WaitForMCU(30000);
if(statusMcu == 0)
{
printf("MCU working too long %i\n", statusMcu);
}
}
else
{
Log("Rx DC calibration", LOG_INFO);
CalibrateRxDC_RSSI();
// RXIQ calibration
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
if(not useExtLoopback)
{
if (sel_path_rfe == 2)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0);
}
if (sel_path_rfe == 3)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0);
}
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 0); //DC_BYP 0
}
Modify_SPI_Reg_bits(MAC, 2);
if (Get_SPI_Reg_bits(PD_LOCH_T2RBUF) == false)
{
Modify_SPI_Reg_bits(PD_LOCH_T2RBUF, 1);
//TDD MODE
Modify_SPI_Reg_bits(MAC, 1);
Modify_SPI_Reg_bits(PD_VCO, 0);
}
Modify_SPI_Reg_bits(MAC, ch);
CheckSaturationRx(bandwidth_Hz, useExtLoopback);
Modify_SPI_Reg_bits(CMIX_SC_RXTSP, 1);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, bandwidth_Hz/calibUserBwDivider + 0.1e6);
Modify_SPI_Reg_bits(IQCORR_RXTSP, 0);
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
//coarse gain
{
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047 - 64);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
uint32_t rssiIgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047 - 64);
uint32_t rssiQgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
gain = 1983;
if(rssiIgain < rssiQgain)
{
gainAddr = 0x0402;
Modify_SPI_Reg_bits(GCORRI_RXTSP, gain);
}
else
{
gainAddr = 0x0401;
Modify_SPI_Reg_bits(GCORRQ_RXTSP, gain);
}
}
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx GAIN_%s: %i\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q", gain);
#endif
//find phase offset
uint32_t rssiUp;
uint32_t rssiDown;
Modify_SPI_Reg_bits(IQCORR_RXTSP, 15);
rssiUp = GetRSSI();
Modify_SPI_Reg_bits(IQCORR_RXTSP, -15);
rssiDown = GetRSSI();
if(rssiUp > rssiDown)
phaseOffset = -64;
else if(rssiUp < rssiDown)
phaseOffset = 192;
else
phaseOffset = 64;
Modify_SPI_Reg_bits(IQCORR_RXTSP, phaseOffset);
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx IQCORR: %i\n", phaseOffset);
#endif
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 4);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx GAIN_%s: %i\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q", gain);
#endif
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 4);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx IQCORR: %i\n", phaseOffset);
#endif
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx GAIN_%s/IQCORR\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q");
#endif
FineSearch(gainAddr, gainMSB, gainLSB, gain, IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
Modify_SPI_Reg_bits(gainAddr, gainMSB, gainLSB, gain);
Modify_SPI_Reg_bits(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx GAIN_%s: %i, IQCORR: %i\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q", gain, phaseOffset);
#endif
}
mingcorri = Get_SPI_Reg_bits(GCORRI_RXTSP, true);
mingcorrq = Get_SPI_Reg_bits(GCORRQ_RXTSP, true);
dcoffi = Get_SPI_Reg_bits(DCOFFI_RFE, true);
dcoffq = Get_SPI_Reg_bits(DCOFFQ_RFE, true);
phaseOffset = Get_SPI_Reg_bits(IQCORR_RXTSP, true);
RxCalibrationEndStage:
Log("Restoring registers state", LOG_INFO);
RestoreAllRegisters();
if (status != 0)
{
Log("Rx calibration failed", LOG_WARNING);
return status;
}
if(useCache)
mValueCache->InsertDC_IQ(boardId, rxFreq*1e6, channel, false, lna, dcoffi, dcoffq, mingcorri, mingcorrq, phaseOffset);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
SetRxDCOFF((int8_t)dcoffi, (int8_t)dcoffq);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), mingcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), phaseOffset);
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
Log("Rx calibration finished", LOG_INFO);
return 0;
}
/** @brief Stores chip current registers state into memory for later restoration
*/
void LMS7002M::BackupAllRegisters()
{
Channel ch = this->GetActiveChannel();
SPI_read_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
this->SetActiveChannel(ChA); // channel A
SPI_read_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
//backup GFIR3 coefficients
GetGFIRCoefficients(LMS7002M::Rx, 2, rxGFIR3_backup, sizeof(rxGFIR3_backup)/sizeof(int16_t));
//EN_NEXTRX_RFE could be modified in channel A
backup0x010D = SPI_read(0x010D);
//EN_NEXTTX_TRF could be modified in channel A
backup0x0100 = SPI_read(0x0100);
this->SetActiveChannel(ChB); // channel B
SPI_read_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
this->SetActiveChannel(ch);
}
/** @brief Sets chip registers to state that was stored in memory using BackupAllRegisters()
*/
void LMS7002M::RestoreAllRegisters()
{
Channel ch = this->GetActiveChannel();
SPI_write_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
//restore GFIR3
SetGFIRCoefficients(LMS7002M::Rx, 2, rxGFIR3_backup, sizeof(rxGFIR3_backup)/sizeof(int16_t));
this->SetActiveChannel(ChA); // channel A
SPI_write(0x010D, backup0x010D); //restore EN_NEXTRX_RFE
SPI_write(0x0100, backup0x0100); //restore EN_NEXTTX_TRF
SPI_write_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
this->SetActiveChannel(ChB); // channel B
SPI_write_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
this->SetActiveChannel(ch);
//reset Tx logic registers, fixes interpolator
uint16_t x0020val = SPI_read(0x0020);
SPI_write(0x0020, x0020val & ~0xA000);
SPI_write(0x0020, x0020val);
}
int LMS7002M::CheckSaturationRx(const float_type bandwidth_Hz, const bool useExtLoopback)
{
Modify_SPI_Reg_bits(CMIX_SC_RXTSP, 0);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, bandwidth_Hz / calibUserBwDivider - 0.1e6);
uint32_t rssi = GetRSSI();
#ifdef ENABLE_CALIBRATION_USING_FFT
//use FFT bin 100 kHz for RSSI
fftBin = 569;
//0x0B000 = -3 dBFS
if(useExtLoopback)
{
const float_type target_dBFS = -14;
int loss_main_txpad = Get_SPI_Reg_bits(LOSS_MAIN_TXPAD_TRF);
while (rssi < target_dBFS && loss_main_txpad > 0)
{
rssi = GetRSSI();
if (rssi < target_dBFS)
loss_main_txpad -= 1;
if (rssi > target_dBFS)
break;
Modify_SPI_Reg_bits(G_RXLOOPB_RFE, loss_main_txpad);
}
int cg_iamp = Get_SPI_Reg_bits(CG_IAMP_TBB);
while (rssi < target_dBFS && cg_iamp < 39)
{
rssi = GetRSSI();
if (rssi < target_dBFS)
cg_iamp += 2;
if (rssi > target_dBFS)
break;
Modify_SPI_Reg_bits(CG_IAMP_TBB, cg_iamp);
}
return 0;
}
#endif
int g_rxloopb_rfe = Get_SPI_Reg_bits(G_RXLOOPB_RFE);
while (rssi < 0x0B000 && g_rxloopb_rfe < 15)
{
rssi = GetRSSI();
if (rssi < 0x0B000)
g_rxloopb_rfe += 2;
if (rssi > 0x0B000)
break;
Modify_SPI_Reg_bits(G_RXLOOPB_RFE, g_rxloopb_rfe);
}
int cg_iamp = Get_SPI_Reg_bits(CG_IAMP_TBB);
while (rssi < 0x01000 && cg_iamp < 63-6)
{
rssi = GetRSSI();
if (rssi < 0x01000)
cg_iamp += 4;
if (rssi > 0x01000)
break;
Modify_SPI_Reg_bits(CG_IAMP_TBB, cg_iamp);
}
while (rssi < 0x0B000 && cg_iamp < 62)
{
rssi = GetRSSI();
if (rssi < 0x0B000)
cg_iamp += 2;
Modify_SPI_Reg_bits(CG_IAMP_TBB, cg_iamp);
}
return 0;
}
static uint16_t toDCOffset(int16_t offset)
{
uint16_t valToSend = 0;
if (offset < 0)
valToSend |= 0x40;
valToSend |= labs(offset);
return valToSend;
}
void LMS7002M::CoarseSearch(const uint16_t addr, const uint8_t msb, const uint8_t lsb, int16_t &value, const uint8_t maxIterations)
{
const uint16_t DCOFFaddr = 0x010E;
uint8_t rssi_counter = 0;
uint32_t rssiUp;
uint32_t rssiDown;
int16_t upval;
int16_t downval;
upval = value;
for(rssi_counter = 0; rssi_counter < maxIterations - 1; ++rssi_counter)
{
rssiUp = GetRSSI();
value -= pow2(maxIterations - rssi_counter);
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
downval = value;
rssiDown = GetRSSI();
if(rssiUp >= rssiDown)
value += pow2(maxIterations - 2 - rssi_counter);
else
value = value + pow2(maxIterations - rssi_counter) + pow2(maxIterations - 1 - rssi_counter) - pow2(maxIterations - 2 - rssi_counter);
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
upval = value;
}
value -= pow2(maxIterations - rssi_counter);
rssiUp = GetRSSI();
if(addr != DCOFFaddr)
Modify_SPI_Reg_bits(addr, msb, lsb, value - pow2(maxIterations - rssi_counter));
else
Modify_SPI_Reg_bits(addr, msb, lsb, toDCOffset(value - pow2(maxIterations - rssi_counter)));
rssiDown = GetRSSI();
if(rssiUp < rssiDown)
value += 1;
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
rssiDown = GetRSSI();
if(rssiUp < rssiDown)
{
value += 1;
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
}
}
int LMS7002M::CheckSaturationTxRx(const float_type bandwidth_Hz, const bool useExtLoopback)
{
if(useExtLoopback)
{
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6 + bandwidth_Hz / calibUserBwDivider);
const float target_dBFS = -10;
int g_tia = Get_SPI_Reg_bits(G_TIA_RFE);
int g_lna = Get_SPI_Reg_bits(G_LNA_RFE);
int g_pga = Get_SPI_Reg_bits(G_PGA_RBB);
while(GetRSSI() < target_dBFS && g_lna <= 15)
{
g_lna += 1;
Modify_SPI_Reg_bits(LMS7param(G_LNA_RFE), g_lna);
}
if(g_lna > 15)
g_lna = 15;
Modify_SPI_Reg_bits(LMS7param(G_LNA_RFE), g_lna);
if(GetRSSI() >= target_dBFS)
goto rxGainFound;
while(GetRSSI() < target_dBFS && g_tia <= 3)
{
g_tia += 1;
Modify_SPI_Reg_bits(LMS7param(G_TIA_RFE), g_tia);
}
if(g_tia > 3)
g_tia = 3;
Modify_SPI_Reg_bits(LMS7param(G_TIA_RFE), g_tia);
if(GetRSSI() >= target_dBFS)
goto rxGainFound;
while(GetRSSI() < target_dBFS && g_pga < 18)
{
g_pga += 2;
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), g_pga);
}
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), g_pga);
rxGainFound:
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 0);
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 1);
CalibrateRxDC_RSSI();
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz + 0.1e6 + bandwidth_Hz / calibUserBwDivider);
Modify_SPI_Reg_bits(LMS7param(CMIX_SC_RXTSP), 1);
//---------IQ calibration-----------------
int16_t iqcorr_rx = 0;
int16_t gain;
uint16_t gainAddr = 0;
const uint8_t gainMSB = 10;
const uint8_t gainLSB = 0;
int16_t phaseOffset;
Modify_SPI_Reg_bits(IQCORR_RXTSP, 0);
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
//coarse gain
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047 - 64);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
uint32_t rssiIgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047 - 64);
uint32_t rssiQgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
gain = 1983;
if(rssiIgain < rssiQgain)
{
gainAddr = 0x0402;
Modify_SPI_Reg_bits(GCORRI_RXTSP, gain);
}
else
{
gainAddr = 0x0401;
Modify_SPI_Reg_bits(GCORRQ_RXTSP, gain);
}
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 7);
//find phase offset
{
uint32_t rssiUp;
uint32_t rssiDown;
Modify_SPI_Reg_bits(IQCORR_RXTSP, 15);
rssiUp = GetRSSI();
Modify_SPI_Reg_bits(IQCORR_RXTSP, -15);
rssiDown = GetRSSI();
if(rssiUp > rssiDown)
phaseOffset = -64;
else if(rssiUp < rssiDown)
phaseOffset = 192;
else
phaseOffset = 64;
Modify_SPI_Reg_bits(IQCORR_RXTSP, phaseOffset);
}
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 4);
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 4);
FineSearch(gainAddr, gainMSB, gainLSB, gain, IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
Modify_SPI_Reg_bits(gainAddr, gainMSB, gainLSB, gain);
Modify_SPI_Reg_bits(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset);
Modify_SPI_Reg_bits(LMS7param(CMIX_SC_RXTSP), 0);
return 0;
}
//----------------------------------------
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 0);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6 + (bandwidth_Hz / calibUserBwDivider) * 2);
uint32_t rssi = GetRSSI();
int g_pga = Get_SPI_Reg_bits(G_PGA_RBB);
int g_rxlooop = Get_SPI_Reg_bits(G_RXLOOPB_RFE);
const int saturationLevel = 0x0B000;
while(rssi < saturationLevel && g_rxlooop < 15)
{
rssi = GetRSSI();
if(rssi < saturationLevel)
{
g_rxlooop += 1;
Modify_SPI_Reg_bits(G_RXLOOPB_RFE, g_rxlooop);
}
else
break;
}
rssi = GetRSSI();
while(g_pga < 18 && g_rxlooop == 15 && rssi < saturationLevel)
{
g_pga += 1;
Modify_SPI_Reg_bits(G_PGA_RBB, g_pga);
rssi = GetRSSI();
}
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 1);
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 1);
return 0;
}
void LMS7002M::CalibrateTxDC_RSSI(const float_type bandwidth)
{
Modify_SPI_Reg_bits(EN_G_TRF, 1);
Modify_SPI_Reg_bits(CMIX_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6 + (bandwidth / calibUserBwDivider));
int16_t corrI = 64;
int16_t corrQ = 64;
Modify_SPI_Reg_bits(DCCORRI_TXTSP, 64);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, 0);
CoarseSearch(DCCORRI_TXTSP.address, DCCORRI_TXTSP.msb, DCCORRI_TXTSP.lsb, corrI, 7);
Modify_SPI_Reg_bits(DCCORRI_TXTSP, corrI);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, 64);
CoarseSearch(DCCORRQ_TXTSP.address, DCCORRQ_TXTSP.msb, DCCORRQ_TXTSP.lsb, corrQ, 7);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, corrQ);
CoarseSearch(DCCORRI_TXTSP.address, DCCORRI_TXTSP.msb, DCCORRI_TXTSP.lsb, corrI, 4);
Modify_SPI_Reg_bits(DCCORRI_TXTSP, corrI);
CoarseSearch(DCCORRQ_TXTSP.address, DCCORRQ_TXTSP.msb, DCCORRQ_TXTSP.lsb, corrQ, 4);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, corrQ);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Tx DCCORRI/DCCORRQ\n");
#endif
FineSearch(DCCORRI_TXTSP.address, DCCORRI_TXTSP.msb, DCCORRI_TXTSP.lsb, corrI, DCCORRQ_TXTSP.address, DCCORRQ_TXTSP.msb, DCCORRQ_TXTSP.lsb, corrQ, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Tx DCCORRI: %i, DCCORRQ: %i\n", corrI, corrQ);
#endif
Modify_SPI_Reg_bits(DCCORRI_TXTSP, corrI);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, corrQ);
}
void LMS7002M::FineSearch(const uint16_t addrI, const uint8_t msbI, const uint8_t lsbI, int16_t &valueI, const uint16_t addrQ, const uint8_t msbQ, const uint8_t lsbQ, int16_t &valueQ, const uint8_t fieldSize)
{
const uint16_t DCOFFaddr = 0x010E;
uint32_t **rssiField = new uint32_t*[fieldSize];
for (int i = 0; i < fieldSize; ++i)
{
rssiField[i] = new uint32_t[fieldSize];
for (int q = 0; q < fieldSize; ++q)
rssiField[i][q] = ~0;
}
uint32_t minRSSI = ~0;
int16_t minI = 0;
int16_t minQ = 0;
for (int i = 0; i < fieldSize; ++i)
{
for (int q = 0; q < fieldSize; ++q)
{
int16_t ival = valueI + (i - fieldSize / 2);
int16_t qval = valueQ + (q - fieldSize / 2);
Modify_SPI_Reg_bits(addrI, msbI, lsbI, addrI != DCOFFaddr ? ival : toDCOffset(ival), true);
Modify_SPI_Reg_bits(addrQ, msbQ, lsbQ, addrQ != DCOFFaddr ? qval : toDCOffset(qval), true);
rssiField[i][q] = GetRSSI();
if (rssiField[i][q] < minRSSI)
{
minI = ival;
minQ = qval;
minRSSI = rssiField[i][q];
}
}
}
#ifdef LMS_VERBOSE_OUTPUT
printf(" |");
for (int i = 0; i < fieldSize; ++i)
printf("%6i|", valueQ - fieldSize / 2 + i);
printf("\n");
for (int i = 0; i < fieldSize + 1; ++i)
printf("------+");
printf("\n");
for (int i = 0; i < fieldSize; ++i)
{
printf("%5i |", valueI + (i - fieldSize / 2));
for (int q = 0; q < fieldSize; ++q)
printf("%6i.2|", rssiField[i][q]);
printf("\n");
}
#endif
valueI = minI;
valueQ = minQ;
for (int i = 0; i < fieldSize; ++i)
delete rssiField[i];
delete rssiField;
}
/** @brief Loads given DC_REG values into registers
@param tx TxTSP or RxTSP selection
@param I DC_REG I value
@param Q DC_REG Q value
*/
int LMS7002M::LoadDC_REG_IQ(bool tx, int16_t I, int16_t Q)
{
if(tx)
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
}
else
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_RXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
}
return 0;
}
int LMS7002M::StoreDigitalCorrections(const bool isTx)
{
const int idx = this->GetActiveChannelIndex();
const uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
const double freq = this->GetFrequencySX(isTx);
int band = 0; //TODO
int dccorri, dccorrq, gcorri, gcorrq, phaseOffset;
if (isTx)
{
dccorri = int8_t(Get_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP))); //signed 8-bit
dccorrq = int8_t(Get_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP))); //signed 8-bit
gcorri = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRI_TXTSP))); //unsigned 11-bit
gcorrq = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP))); //unsigned 11-bit
phaseOffset = int16_t(Get_SPI_Reg_bits(LMS7param(IQCORR_TXTSP)) << 4) >> 4; //sign extend 12-bit
}
else
{
dccorri = 0;
dccorrq = 0;
gcorri = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRI_RXTSP)) << 4) >> 4;
gcorrq = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP)) << 4) >> 4;
phaseOffset = int16_t(Get_SPI_Reg_bits(LMS7param(IQCORR_RXTSP)) << 4) >> 4;
}
return mValueCache->InsertDC_IQ(boardId, freq, idx, isTx, band, dccorri, dccorrq, gcorri, gcorrq, phaseOffset);
}
int LMS7002M::ApplyDigitalCorrections(const bool isTx)
{
const int idx = this->GetActiveChannelIndex();
const uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
const double freq = this->GetFrequencySX(isTx);
int band = 0; //TODO
int dccorri, dccorrq, gcorri, gcorrq, phaseOffset;
int rc = mValueCache->GetDC_IQ_Interp(boardId, freq, idx, isTx, band, &dccorri, &dccorrq, &gcorri, &gcorrq, &phaseOffset);
if (rc != 0) return rc;
if (isTx)
{
Modify_SPI_Reg_bits(DCCORRI_TXTSP, dccorri);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, dccorrq);
Modify_SPI_Reg_bits(GCORRI_TXTSP, gcorri);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, gcorrq);
Modify_SPI_Reg_bits(IQCORR_TXTSP, phaseOffset);
Modify_SPI_Reg_bits(DC_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(PH_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(GC_BYP_TXTSP, 0);
}
else
{
Modify_SPI_Reg_bits(GCORRI_RXTSP, gcorri);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, gcorrq);
Modify_SPI_Reg_bits(IQCORR_RXTSP, phaseOffset);
Modify_SPI_Reg_bits(PH_BYP_RXTSP, 0);
Modify_SPI_Reg_bits(GC_BYP_RXTSP, 0);
}
return 0;
}
| 33.604579 | 208 | 0.646405 | bastille-attic |
51c9c21d1b4092479f18df349118a72c0f23ce99 | 520 | cc | C++ | src/fe-readatarist.cc | hpingel/fluxengine | d4db131d3c8541fa0d35bac8591e6dea192e8fd6 | [
"MIT"
] | null | null | null | src/fe-readatarist.cc | hpingel/fluxengine | d4db131d3c8541fa0d35bac8591e6dea192e8fd6 | [
"MIT"
] | null | null | null | src/fe-readatarist.cc | hpingel/fluxengine | d4db131d3c8541fa0d35bac8591e6dea192e8fd6 | [
"MIT"
] | null | null | null | #include "globals.h"
#include "flags.h"
#include "reader.h"
#include "fluxmap.h"
#include "decoders/decoders.h"
#include "sector.h"
#include "sectorset.h"
#include "record.h"
#include "dataspec.h"
#include "ibm/ibm.h"
#include "fmt/format.h"
static FlagGroup flags { &readerFlags };
int mainReadAtariST(int argc, const char* argv[])
{
setReaderDefaultSource(":t=0-79:s=0-1");
setReaderDefaultOutput("atarist.st");
flags.parseFlags(argc, argv);
IbmDecoder decoder(1);
readDiskCommand(decoder);
return 0;
}
| 20.8 | 49 | 0.715385 | hpingel |
51d0df018658860ac68fe792ad64e4345f056757 | 753 | hpp | C++ | simulator/include/marlin/simulator/core/Event.hpp | marlinprotocol/OpenWeaver | 7a8c668cccc933d652fabe8a141e702b8a0fd066 | [
"MIT"
] | 60 | 2020-07-01T17:37:34.000Z | 2022-02-16T03:56:55.000Z | simulator/include/marlin/simulator/core/Event.hpp | marlinpro/openweaver | 0aca30fbda3121a8e507f48a52b718b5664a5bbc | [
"MIT"
] | 5 | 2020-10-12T05:17:49.000Z | 2021-05-25T15:47:01.000Z | simulator/include/marlin/simulator/core/Event.hpp | marlinpro/openweaver | 0aca30fbda3121a8e507f48a52b718b5664a5bbc | [
"MIT"
] | 18 | 2020-07-01T17:43:18.000Z | 2022-01-09T14:29:08.000Z | #ifndef MARLIN_SIMULATOR_CORE_EVENT_HPP
#define MARLIN_SIMULATOR_CORE_EVENT_HPP
#include <cstdint>
namespace marlin {
namespace simulator {
template<typename EventManager>
class Event {
private:
static uint64_t id_seq;
protected:
uint64_t id;
uint64_t tick;
public:
Event(uint64_t tick);
inline uint64_t get_tick() {
return tick;
}
inline uint64_t get_id() {
return id;
}
virtual void run(EventManager&) = 0;
virtual ~Event() = default;
};
// Impl
template<typename EventManager>
uint64_t Event<EventManager>::id_seq = 0;
template<typename EventManager>
Event<EventManager>::Event(uint64_t tick) {
id = id_seq++;
this->tick = tick;
}
} // namespace simulator
} // namespace marlin
#endif // MARLIN_SIMULATOR_CORE_EVENT_HPP
| 15.367347 | 43 | 0.74502 | marlinprotocol |
51d79b198e4fbaa925d325a02ccf495b91093d73 | 1,036 | hpp | C++ | src/color/yiq/akin/lab.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | null | null | null | src/color/yiq/akin/lab.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | null | null | null | src/color/yiq/akin/lab.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 1 | 2022-03-03T07:55:24.000Z | 2022-03-03T07:55:24.000Z | #ifndef color_yiq_akin_lab
#define color_yiq_akin_lab
#include "../../generic/akin/yiq.hpp"
#include "../category.hpp"
#include "../../lab/category.hpp"
namespace color
{
namespace akin
{
template< >struct yiq< ::color::category::lab_uint8 >{ typedef ::color::category::yiq_uint8 akin_type; };
template< >struct yiq< ::color::category::lab_uint16 >{ typedef ::color::category::yiq_uint16 akin_type; };
template< >struct yiq< ::color::category::lab_uint32 >{ typedef ::color::category::yiq_uint32 akin_type; };
template< >struct yiq< ::color::category::lab_uint64 >{ typedef ::color::category::yiq_uint64 akin_type; };
template< >struct yiq< ::color::category::lab_float >{ typedef ::color::category::yiq_float akin_type; };
template< >struct yiq< ::color::category::lab_double >{ typedef ::color::category::yiq_double akin_type; };
template< >struct yiq< ::color::category::lab_ldouble >{ typedef ::color::category::yiq_ldouble akin_type; };
}
}
#endif
| 41.44 | 114 | 0.669884 | 3l0w |
51d81593a82dfd12f724018e95fd99ffeccd43d9 | 7,172 | cpp | C++ | CH19/FEM/channel.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | CH19/FEM/channel.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | CH19/FEM/channel.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | /*
channel.cpp
solve for flow rates in a rectangular channel
Nx/Ny = number of nodes along a side
g++ -I/usr/local/include/eigen3 ...
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include <vector>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
class TwoVect {
public:
double x;
double y;
TwoVect () {
x=0.0; y=0.0;
};
TwoVect (double x0, double y0) {
x=x0; y=y0;
};
void setV(double x0, double y0) {
x=x0; y=y0;
}
double mag() {
return sqrt(x*x + y*y);
}
double operator*(const TwoVect & other);
TwoVect operator+(const TwoVect & other);
TwoVect operator-(const TwoVect & other);
friend std::ostream &operator<<(std::ostream &out, TwoVect v0) {
out << v0.x << " " << v0.y;
return out;
}
}; // end of class TwoVect
TwoVect TwoVect::operator-(const TwoVect & other) {
return TwoVect(x-other.x,y-other.y);
}
TwoVect TwoVect::operator+(const TwoVect & other) {
return TwoVect(x+other.x,y+other.y);
}
double TwoVect::operator*(const TwoVect & other) {
// dot product
return x*other.x + y*other.y;
}
TwoVect operator*(const double & lhs, const TwoVect & rhs) {
TwoVect v0 = TwoVect(lhs*rhs.x,lhs*rhs.y);
return v0;
}
TwoVect operator*(const TwoVect & lhs, const double & rhs) {
TwoVect v0 = TwoVect(rhs*lhs.x,rhs*lhs.y);
return v0;
}
TwoVect operator/(const TwoVect & lhs, const double & rhs) {
TwoVect v0 = TwoVect(lhs.x/rhs,lhs.y/rhs);
return v0;
}
// --------------------------------------------------------------------
typedef int node;
typedef int element;
TwoVect *rNode = NULL; // vector of node coordinates
typedef Matrix<int,Dynamic,3> eMat; // custom Eigen matrix type
eMat nL; // track nodes associated with element 0,1,2 = CCW nodes
double area(element e) {
double a3 = rNode[nL(e,1)].x - rNode[nL(e,0)].x;
double a2 = rNode[nL(e,0)].x - rNode[nL(e,2)].x;
double b3 = rNode[nL(e,0)].y - rNode[nL(e,1)].y;
double b2 = rNode[nL(e,2)].y - rNode[nL(e,0)].y;
return 0.5*(a3*b2 - a2*b3);
}
TwoVect cm(element e) {
// center of mass of element e
return (rNode[nL(e,0)] + rNode[nL(e,1)] + rNode[nL(e,2)])/3.0;
}
int main(void) {
int verbose=0;
int Nx,Ny;
double hw,Pz,Vz;
ofstream ofs,ofs2,ofs3,ofs4;
ofs.open("channel.dat");
ofs2.open("c2.dat");
ofs3.open("c3.dat");
ofs4.open("c4.dat");
cout << " input Nx, Ny, H/W [0.5], Pz/mu [-6], Vz [0] " << endl;
cin >> Nx >> Ny >> hw >> Pz >> Vz;
cout << " enter 1 for verbose mode " << endl;
cin >> verbose;
int Nnodes = Nx*Ny;
int Nelements = (Nx-1)*(Ny-1)*2;
cout << " number of nodes: " << Nnodes << endl;
cout << " number of elements: " << Nelements << endl;
VectorXd f(Nnodes),w(Nnodes);
MatrixXd K(Nnodes,Nnodes);
nL = eMat(Nelements,3);
// define rectangle nodes
rNode = new TwoVect[Nnodes];
node nodeNumber = 0;
for (int iy=0;iy<Ny;iy++) {
for (int ix=0;ix<Nx;ix++) {
double x = (double) ix/(Nx-1);
double y = (double) iy/(Ny-1);
y *= hw; // scale to desired proportions
rNode[nodeNumber].setV(x,y);
nodeNumber++;
}}
//label elements and specify their nodes
if (verbose) cout << endl << " element and associated nodes: " << endl << endl;
for (int iy=0;iy<Ny-1;iy++) {
for (int ix=0;ix<Nx-1;ix++) {
node i = iy*(Nx-1)+ix;
element eNumber = 2*i;
node j = ix + Nx*iy;
nL(eNumber,0) = j;
nL(eNumber,1) = j+Nx+1;
nL(eNumber,2) = j+Nx;
if (verbose) cout << eNumber << " " << nL(eNumber,0) << " " << nL(eNumber,1) << " " <<
nL(eNumber,2) << endl;
eNumber++;
nL(eNumber,0) = j;
nL(eNumber,1) = j+1;
nL(eNumber,2) = j+1+Nx;
if (verbose) cout << eNumber << " " << nL(eNumber,0) << " " << nL(eNumber,1) << " " <<
nL(eNumber,2) << endl;
}}
if (verbose) {
cout << " ----------- " << endl;
// print mesh
for (element e=0;e<Nelements;e++) {
ofs << rNode[nL(e,0)] << " " << rNode[nL(e,1)] << endl;
ofs << rNode[nL(e,1)] << " " << rNode[nL(e,2)] << endl;
ofs << rNode[nL(e,2)] << " " << rNode[nL(e,0)] << endl;
ofs2 << e << " " << cm(e) << " " << area(e) << endl;
}
}
// assemble FEM stiffness matrix, K
for (element e=0;e<Nelements;e++) {
double beta[3],gamma[3];
for (int i=0;i<3;i++) {
int j = (i+1)%3;
int k = (i+2)%3;
beta[i] = rNode[nL(e,j)].y - rNode[nL(e,k)].y;
gamma[i] = rNode[nL(e,k)].x - rNode[nL(e,j)].x;
if (verbose) cout << e << " " << i << " " << beta[i] << " " << gamma[i] << endl;
}
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
node I = nL(e,i);
node J = nL(e,j);
K(I,J) += (beta[i]*beta[j] + gamma[i]*gamma[j])/(4.0*area(e));
}}
}
if (verbose) {
cout << " ----------- " << endl;
cout << "K " << endl;
cout << "det(K) = " << K.determinant() << endl;
for (node i=0;i<Nnodes;i++) {
for (node j=0;j<Nnodes;j++) {
cout << i << " " << j << " " << K(i,j) << endl;
}}
cout << " ----------- " << endl;
}
// assemble force vector [pressure gradient/viscosity = dp/dz / mu == Pz]
for (element e=0;e<Nelements;e++) {
double ff = -Pz*area(e)/3.0;
f(nL(e,0)) += ff; // sum force contribution to nodes
f(nL(e,1)) += ff;
f(nL(e,2)) += ff;
}
if (verbose) {
cout << " f " << endl;
for (node i=0;i<Nnodes;i++) cout << i << " " << f(i) << endl;
cout << " ----------- " << endl;
}
// boundary conditions [trick to force w(...) = f(...) = 0]
// we need to identify the nodes on the boundary !
for (node n=0;n<Nx;n++) {
if (verbose) cout << " boundary nodes: " << n << " " << n + Nx*(Ny-1) << endl;
K(n,n) *= 1e12;
K(n+Nx*(Ny-1),n+Nx*(Ny-1)) *= 1e12;
f(n) = 0.0*K(n,n); // bottom
f(n+Nx*(Ny-1)) = Vz*K(n+Nx*(Ny-1),n+Nx*(Ny-1)); // top
}
for (node n=1;n<Ny-1;n++) {
if (verbose) cout << " boundary nodes: " << n*Nx << " " << n*Nx + Nx - 1 << endl;
K(n*Nx,n*Nx) *= 1e12;
K(n*Nx+Nx-1,n*Nx+Nx-1) *= 1e12;
f(n*Nx) = 0.0*K(n*Nx,n*Nx); // left
f(n*Nx+Nx-1) = 0.0; // right
}
int num=0;
for (node n=0;n<Nnodes;n++) {
for (node m=0;m<Nnodes;m++) {
if (K(n,m) != 0.0) num++;
}}
cout << --num << " nonzero elements in K " << endl;
// obtain solution
w = K.inverse()*f;
// store solution
int nx = 1;
for (node n=0;n<Nnodes;n++) {
ofs4 << rNode[n] << " " << w(n) << endl;
nx++;
if (nx > Nx) {
ofs4 << " " << endl;
nx=1;
}
}
// integrate to obtain flow rate [= int dx dy w(x,y)]
double in = 0.0;
for (element e=0;e<Nelements;e++) {
in +=area(e)*(w(nL(e,0)) + w(nL(e,1)) + w(nL(e,2)));
}
in /= 3.0;
cout << " flow rate = " << in << endl;
delete [] rNode;
ofs.close();
ofs2.close();
ofs3.close();
ofs4.close();
cout << " mesh coords in channel.dat " << endl;
cout << " e cm(e) area(e) in c2.dat " << endl;
cout << " r_node w(r_node) in c4.dat" << endl;
return 0;
}
| 26.08 | 93 | 0.506274 | acastellanos95 |
51daf32dcb3c3ca753d62d048d76611712f3cb6e | 641 | hpp | C++ | SDK/ARKSurvivalEvolved_E_StegoBackplateMode_structs.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_E_StegoBackplateMode_structs.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_E_StegoBackplateMode_structs.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Basic.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Enums
//---------------------------------------------------------------------------
// UserDefinedEnum E_StegoBackplateMode.E_StegoBackplateMode
enum class E_StegoBackplateMode : uint8_t
{
E_StegoBackplateMode__NewEnumerator0 = 0,
E_StegoBackplateMode__NewEnumerator1 = 1,
E_StegoBackplateMode__NewEnumerator2 = 2,
E_StegoBackplateMode__E_MAX = 3
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 19.424242 | 77 | 0.595944 | 2bite |
51dce849eac84709b62a567aaa4f24712f72a234 | 2,156 | hpp | C++ | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/buffer/buflimit.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 10 | 2021-03-29T13:52:06.000Z | 2022-03-10T02:24:25.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/buffer/buflimit.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 1 | 2018-07-13T06:45:25.000Z | 2018-07-13T06:45:25.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/buffer/buflimit.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 7 | 2018-07-11T10:37:02.000Z | 2019-08-03T10:34:08.000Z | // OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN 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 in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_BUFFER_BUFLIMIT_H
#define OPENVPN_BUFFER_BUFLIMIT_H
#include <openvpn/buffer/buffer.hpp>
namespace openvpn {
template <typename T>
class BufferLimit
{
public:
BufferLimit()
{
set_max(0, 0);
reset();
}
BufferLimit(const T max_lines_arg,
const T max_bytes_arg)
{
set_max(max_lines_arg, max_bytes_arg);
reset();
}
void set_max(const T max_lines_arg,
const T max_bytes_arg)
{
max_lines = max_lines_arg;
max_bytes = max_bytes_arg;
}
void reset()
{
n_bytes = n_lines = 0;
}
void add(const Buffer& buf)
{
T size = (T)buf.size();
n_bytes += size;
if (max_bytes && n_bytes > max_bytes)
bytes_exceeded();
if (max_lines)
{
const unsigned char *p = buf.c_data();
while (size--)
{
const unsigned char c = *p++;
if (c == '\n')
{
++n_lines;
if (n_lines > max_lines)
lines_exceeded();
}
}
}
}
virtual void bytes_exceeded() = 0;
virtual void lines_exceeded() = 0;
protected:
T max_lines;
T max_bytes;
T n_bytes;
T n_lines;
};
}
#endif
| 23.182796 | 78 | 0.62616 | TiagoPedroByterev |
51df0512a39f1f1081ef22b241df43d76ca83074 | 8,908 | cpp | C++ | src/qt/blocknettoolbar.cpp | CircuitBreaker88/blocknet | da08717b612c582367d2a00a79c90a8db2330773 | [
"MIT"
] | 1 | 2020-09-26T15:45:32.000Z | 2020-09-26T15:45:32.000Z | src/qt/blocknettoolbar.cpp | CircuitBreaker88/blocknet | da08717b612c582367d2a00a79c90a8db2330773 | [
"MIT"
] | null | null | null | src/qt/blocknettoolbar.cpp | CircuitBreaker88/blocknet | da08717b612c582367d2a00a79c90a8db2330773 | [
"MIT"
] | null | null | null | // Copyright (c) 2018-2019 The Blocknet developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/blocknettoolbar.h>
#include <qt/blocknetguiutil.h>
#include <QApplication>
#include <QProgressBar>
#include <QTimer>
BlocknetToolBar::BlocknetToolBar(QWidget *popup, QFrame *parent) : QFrame(parent), popupWidget(popup),
layout(new QHBoxLayout) {
layout->setAlignment(Qt::AlignRight);
layout->setSpacing(BGU::spi(18));
this->setLayout(layout);
peersIndicator = new BlocknetPeersIndicator;
peersIndicator->setPeers(BGU::spi(10));
stakingIndicator = new BlocknetStakingIndicator;
stakingIndicator->setObjectName("staking");
progressIndicator = new QFrame;
progressIndicator->setObjectName("progress");
progressIndicator->setFixedSize(BGU::spi(220), BGU::spi(28));
progressIndicator->setLayout(new QHBoxLayout);
progressIndicator->layout()->setContentsMargins(QMargins());
progressBar = new QProgressBar;
#if defined(Q_OS_WIN)
progressBar->setProperty("os", "win"); // work-around bug in Qt windows QProgressBar background
#endif
progressBar->setAlignment(Qt::AlignVCenter);
progressIndicator->layout()->addWidget(progressBar);
lockIndicator = new BlocknetLockIndicator;
lockIndicator->setObjectName("lock");
layout->addStretch(1);
layout->addWidget(peersIndicator);
layout->addWidget(stakingIndicator);
layout->addWidget(progressIndicator);
layout->addWidget(lockIndicator);
lockMenu = new BlocknetLockMenu;
lockMenu->setDisplayWidget(popupWidget);
lockMenu->hOnLockWallet = [&]() { Q_EMIT lock(true); };
lockMenu->hOnChangePw = [&]() { Q_EMIT passphrase(); };
lockMenu->hOnUnlockWallet = [&]() { Q_EMIT lock(false); };
lockMenu->hOnUnlockForStaking = [&]() { Q_EMIT lock(false, true); };
lockMenu->hOnTimedUnlock = [&]() { /*lockIndicator->setTime();*/ }; // TODO Blocknet Qt setTime
lockMenu->hide();
connect(lockIndicator, &BlocknetLockIndicator::lockRequest, this, &BlocknetToolBar::onLockClicked);
}
QLabel* BlocknetToolBar::getIcon(QString path, QString description, QSize size) {
QPixmap pm(path);
pm.setDevicePixelRatio(BGU::dpr());
auto *icon = new QLabel(description);
icon->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
icon->setFixedSize(size);
icon->setPixmap(pm.scaled(icon->width()*pm.devicePixelRatio(), icon->height()*pm.devicePixelRatio(),
Qt::KeepAspectRatio, Qt::SmoothTransformation));
return icon;
}
void BlocknetToolBar::setPeers(const int peers) {
peersIndicator->setPeers(peers);
}
void BlocknetToolBar::setStaking(const bool on, const QString &msg) {
stakingIndicator->setOn(on);
stakingIndicator->setToolTip(msg);
}
void BlocknetToolBar::setLock(const bool lock, const bool stakingOnly) {
lockIndicator->setLock(lock, stakingOnly);
}
void BlocknetToolBar::setProgress(const int progress, const QString &msg, const int maximum) {
progressBar->setMaximum(maximum);
progressBar->setValue(progress);
progressBar->setStatusTip(msg);
progressBar->setToolTip(msg);
progressBar->setFormat(QString(" %1").arg(msg));
}
void BlocknetToolBar::onLockClicked(bool lock) {
if (lockMenu->isHidden()) {
QPoint li = lockIndicator->mapToGlobal(QPoint());
QPoint npos = popupWidget->mapFromGlobal(QPoint(li.x() - lockMenu->width() + 10, li.y() + lockIndicator->height() + 12));
lockMenu->move(npos);
lockMenu->show();
}
}
BlocknetPeersIndicator::BlocknetPeersIndicator(QFrame *parent) : QFrame(parent), layout(new QHBoxLayout) {
layout->setContentsMargins(QMargins());
layout->setSpacing(BGU::spi(4));
this->setLayout(layout);
auto *peersIcon = BlocknetToolBar::getIcon(QString(":/redesign/UtilityBar/Peers.png"), QString("Peers"), QSize(BGU::spi(21), BGU::spi(20)));
peersLbl = new QLabel;
peersLbl->setObjectName("peersLbl");
layout->addWidget(peersIcon);
layout->addWidget(peersLbl);
}
void BlocknetPeersIndicator::setPeers(const int peers) {
peersLbl->setText(QString::number(peers));
this->setToolTip(QString("%1: %2").arg(tr("Connected peers"), QString::number(peers)));
}
BlocknetStakingIndicator::BlocknetStakingIndicator(QFrame *parent) : QFrame(parent), layout(new QHBoxLayout) {
layout->setContentsMargins(QMargins());
layout->setSpacing(0);
this->setLayout(layout);
this->setOn(false);
}
void BlocknetStakingIndicator::setOn(const bool on) {
if (stakingIcon != nullptr) {
layout->removeWidget(stakingIcon);
stakingIcon->deleteLater();
}
QString icon = on ? ":/redesign/UtilityBar/StakingNodeIconActive.png" :
":/redesign/UtilityBar/StakingNodeIconInactive.png";
stakingIcon = BlocknetToolBar::getIcon(icon, tr("Staking"), QSize(BGU::spi(20), BGU::spi(20)));
layout->addWidget(stakingIcon);
}
/**
* Manages the lock indicator. If the datetime is set, this icon will set a QTimer to check the time once per second.
* @param parent
*/
BlocknetLockIndicator::BlocknetLockIndicator(QPushButton *parent) : QPushButton(parent), layout(new QHBoxLayout) {
layout->setContentsMargins(QMargins());
layout->setSpacing(0);
layout->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
this->setLayout(layout);
this->setFixedSize(BGU::spi(26), BGU::spi(24));
this->setCursor(Qt::PointingHandCursor);
this->setCheckable(true);
this->setLock(false);
connect(this, &BlocknetLockIndicator::clicked, this, &BlocknetLockIndicator::onClick);
}
/**
* Sets the time. A timer is fired every 1 second. If the time is set to 0 epoch the timer is cleared.
* @param time
*/
void BlocknetLockIndicator::setTime(const QDateTime time) {
this->lockTime = time;
// lock if time is in the future
// TODO Blocknet Qt needs work for older qt 5 versions
// if (time.toSecsSinceEpoch() > QDateTime::currentSecsSinceEpoch())
// this->setLock(true);
//
// if (time.toSecsSinceEpoch() == 0) {
// timer->stop();
// } else {
// this->lockTime = time;
// if (timer == nullptr) {
// timer = new QTimer;
// timer->setInterval(1000);
// timer->setTimerType(Qt::CoarseTimer);
// connect(timer, &QTimer::timeout, this, &BlocknettToolBar::tick);
// }
// timer->start();
// }
}
void BlocknetLockIndicator::setLock(const bool locked, const bool stakingOnly) {
this->locked = locked;
this->stakingOnly = stakingOnly;
removeLockIcon();
QString icon = locked ? ":/redesign/UtilityBar/LockedIcon.png" :
":/redesign/UtilityBar/UnlockedIcon.png";
lockIcon = BlocknetToolBar::getIcon(icon, tr("Wallet lock state"), QSize(BGU::spi(20), BGU::spi(16)));
layout->addWidget(lockIcon);
if (this->locked)
this->setToolTip(tr("Wallet is locked"));
else
this->setToolTip(this->stakingOnly ? tr("Wallet is unlocked for staking only") : tr("Wallet is unlocked"));
}
void BlocknetLockIndicator::tick() {
// TODO Blocknet Qt support older qt versions
// QDateTime current = QDateTime::currentDateTime();
// qint64 diff = lockTime.toSecsSinceEpoch() - current.toSecsSinceEpoch();
// if (diff < 3600 && diff >= 0) { // 1 hr
// if (lockIcon != nullptr)
// lockIcon->hide();
// if (elapsedLbl == nullptr) {
// elapsedLbl = new QLabel;
// elapsedLbl->setObjectName("timeLbl");
// layout->addWidget(elapsedLbl);
// }
// qint64 t = lockTime.toSecsSinceEpoch() - current.toSecsSinceEpoch();
// if (diff < 60) { // seconds
// elapsedLbl->setText(QString::number(t) + "s");
// } else { // minutes
// elapsedLbl->setText(QString::number(ceil((double)t/60)) + "m");
// }
// } else if (elapsedLbl != nullptr) {
// clearTimer();
// }
}
void BlocknetLockIndicator::onClick(bool) {
if (timer && timer->isActive()) {
clearTimer();
}
// If locked send lock request
Q_EMIT lockRequest(!this->locked);
}
void BlocknetLockIndicator::removeLockIcon() {
if (lockIcon == nullptr)
return;
layout->removeWidget(lockIcon);
lockIcon->deleteLater();
lockIcon = nullptr;
}
void BlocknetLockIndicator::clearTimer() {
// TODO Blocknet Qt support older qt versions
// this->lockTime = QDateTime::fromSecsSinceEpoch(0);
// if (elapsedLbl != nullptr) {
// if (lockIcon != nullptr)
// lockIcon->show();
// layout->removeWidget(elapsedLbl);
// elapsedLbl->deleteLater();
// elapsedLbl = nullptr;
// // now clear the timer
// timer->stop();
// }
}
| 36.211382 | 144 | 0.661989 | CircuitBreaker88 |
51e09353a31188075a4acc8e30d6e98201c5345d | 27,424 | cpp | C++ | WMap.cpp | HSHL/OSM | 89772fc5c89dbad08b8426de1772e49e5022005a | [
"MIT"
] | 5 | 2019-04-08T12:24:31.000Z | 2022-01-13T02:04:16.000Z | WMap.cpp | CBause/OSM | ef458a3b2787905f223180e01b79e7899e398fb6 | [
"MIT"
] | null | null | null | WMap.cpp | CBause/OSM | ef458a3b2787905f223180e01b79e7899e398fb6 | [
"MIT"
] | 2 | 2016-10-09T14:33:48.000Z | 2019-08-30T03:42:13.000Z | #include "WMap.hpp"
//-------------------------------------------------------------------------------------------------------------------------------------------------
WMap::WMap(MainController* pC, Data* pR) {
c = pC;
r = pR;
timer = new QTimer;
QObject::connect(timer,SIGNAL(timeout()),this,SLOT(zoom()));
QObject::connect(this,SIGNAL(zoomFinished()),this,SLOT(stopTimer()));
tunnel = new bool;
*tunnel = false;
scaleControl = new double;
*scaleControl = 1.0;
stepCounter = new int;
*stepCounter = 0;
moveMouse = new bool;
*moveMouse = false;
mousePos = new QPointF();
mousePos->setX(0);
mousePos->setY(0);
pen = new QPen;
pen->setCapStyle(Qt::RoundCap);
brush = new QBrush;
brush->setStyle(Qt::SolidPattern);
brush->setColor(QColor::fromRgb(128,255,128,255));
scene = new QGraphicsScene;
setBoundingRect();
scene->setSceneRect(*boundingRect);
setScene(scene);
setBackgroundBrush(*brush);
transformation = new QTransform();
transformation->rotate(180,Qt::XAxis);
this->setTransform(*transformation);
drawOuterRect();
drawRelations();
drawAreas();
drawWays();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::setBoundingRect() {
double x,y,w,h;
borderWidth = new int;
*borderWidth = 1;
x= (r->getMinLon() / 1E2) - *borderWidth;
y = (r->getMinLat() / 1E2) - *borderWidth;
w = (r->getMaxLon() / 1E2) - (r->getMinLon() / 1E2) + 2* (*borderWidth);
h = (r->getMaxLat() / 1E2) - (r->getMinLat() / 1E2) + 2* (*borderWidth);
boundingRect = new QRectF(x,y,w,h);
}
//DRAW MAP---------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawOuterRect() {
pen->setWidth(*borderWidth);
pen->setColor(Qt::black);
pen->setWidth(10);
brush->setColor(QColor::fromRgb(128,255,128,255));
QRectF borderRect = *boundingRect;
borderRect.setX(borderRect.x()-5);
borderRect.setY(borderRect.y()-5);
borderRect.setWidth(borderRect.width()+10);
borderRect.setHeight(borderRect.height()+10);
scene->addRect(borderRect,*pen,*brush);
bool b = true;
QRect rect;
QPolygonF visibleScene;
QPolygonF::iterator polyIt;
while (b) {
polyIt = visibleScene.begin();
rect = this->viewport()->rect();
visibleScene = this->mapToScene(rect);
for (int i = 0; i < visibleScene.count(); i++) {
b = false;
if (outOfBounds(*polyIt)) {
b = true;
break;
}
polyIt++;
}
if (b)
scale(1.01,1.01);
}
while (!b) {
polyIt = visibleScene.begin();
rect = this->viewport()->rect();
visibleScene = this->mapToScene(rect);
for (int i = 0; i < visibleScene.count(); i++) {
b = false;
if (outOfBounds(*polyIt)) {
b = true;
break;
}
polyIt++;
}
if (!b)
scale(0.99,0.99);
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawAreas() {
QHash<QString,Way*>::iterator wayIt = r->getWays()->begin();
for (int i = 0; i < r->getWays()->count(); i++) {
Way *w = *wayIt;
QList<Node*>::iterator nodeListIt = w->getNodeList()->begin();
QHash<QString,QString>::iterator tagIt = w->getTags()->begin();
bool area = false;
for (int j = 0; j < w->getTags()->count(); j++) {
if(tagIt.key() == "area")
area = true;
tagIt++;
}
if((area == true) && (w->getTags()->count()>1)) {
QPolygonF poly;
for (int k = 0; k < w->getNodeList()->count()-1; k++) {
double x,y;
Node *n = *nodeListIt;
x = n->getLon() / 1E2;
y = n->getLat() / 1E2;
QPointF point;
point.setX(x);
point.setY(y);
poly << point;
nodeListIt++;
}
if (changeBrush(w->getTags())) {
scene->addPolygon(poly,*pen,*brush);
}
}
wayIt++;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawWays() {
QHash<QString,Way*>::iterator wayIt = r->getWays()->begin();
for (int i = 0; i < r->getWays()->count(); i++) {
*tunnel = false;
Way *w = *wayIt;
QList<Node*>::iterator nodeListIt = w->getNodeList()->begin();
QHash<QString,QString>::iterator tagIt = w->getTags()->begin();
bool area = false;
for (int j = 0; j < w->getTags()->count(); j++) {
if(tagIt.key() == "area")
area = true;
if(tagIt.key() == "tunnel")
*tunnel = true;
tagIt++;
}
if (!area) {
for (int k = 0; k < w->getNodeList()->count()-1; k++) {
double x1, x2, y1, y2;
Node *n = *nodeListIt;
y1 = n->getLat() / 1E2;
x1 = n->getLon() / 1E2;
nodeListIt++;
n = *nodeListIt;
y2 = n->getLat() / 1E2;
x2 = n->getLon() / 1E2;
if (changePen(w->getTags()))
scene->addLine(x1,y1,x2,y2,*pen);
}
}
wayIt++;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::drawRelations() {
QHash<QString,Relation*>::Iterator relationIt = r->getRelations()->begin();
for(int i = 0; i < r->getRelations()->count(); i++) {
Relation *re = *relationIt;
QHash<QString,QString>::iterator tagIt = re->getTags()->begin();
QList<Member*>::iterator memberIt = re->getMemberList()->begin();
QList<Node*>::iterator nodeIt;
QHash<QString,Way*>::iterator wayIt;
for(int j = 0; j < re->getTags()->count(); j++) {
if (tagIt.value() == "multipolygon") {
currentPoly = new QPolygonF;
bool openPoly = false;
QList<QPolygonF> polyList;
QList<QString> roleList;
for (int l=0;l<re->getMemberList()->count();l++) {
Member *member = *memberIt;
if (member->getType() == "way" && member->getRole() != "") {
if (r->getWays()->contains(member->getRef()) ) {
wayIt = r->getWays()->find(member->getRef());
Way *w = *wayIt;
QHash<QString,QString>::iterator wayTagIt = w->getTags()->begin();
bool area = false;
for (int v = 0; v < w->getTags()->count(); v++) {
if(wayTagIt.key() == "area")
area = true;
wayTagIt++;
}
nodeIt = w->getNodeList()->begin();
if(!openPoly)
currentFirstNode = *nodeIt;
for(int k=0;k<w->getNodeList()->count();k++) {
currentLastNode = *nodeIt;
Node *n = *nodeIt;
QPointF point;
point.setX(n->getLon() / 1E2);
point.setY(n->getLat() / 1E2);
*currentPoly << point;
nodeIt++;
}
if( (area == true )) {
polyList.append(*currentPoly);
roleList.append(member->getRole());
currentPoly = new QPolygonF;
openPoly = false;
} else {
if (!openPoly) {
} else {
if (currentLastNode == currentFirstNode) {
polyList.append(*currentPoly);
roleList.append(member->getRole());
currentPoly = new QPolygonF;
openPoly = false;
}
}
}
} else {
delete currentPoly;
break;
}
}
}
memberIt++;
if (!polyList.isEmpty()) {
QList<QPolygonF>::iterator polyIt = polyList.begin();
QList<QString>::iterator roleIt = roleList.begin();
for (int u = 0; u < polyList.count(); u++) {
re->addTag("role",*roleIt);
if (changeBrush(re->getTags()))
scene->addPolygon(*polyIt,*pen,*brush);
re->getTags()->erase(re->getTags()->find("role"));
polyIt++;
roleIt++;
}
}
} // END MULTIPOLYGON
if (tagIt.value() == "associatedStreet") {
for (int k = 0; k<re->getMemberList()->count(); k++) {
Member *member = *memberIt;
if (r->getWays()->contains( member->getRef() )) {
Way *w = *r->getWays()->find(member->getRef());
if(member->getRole() == "house") {
QPolygonF poly;
nodeIt = w->getNodeList()->begin();
for(int f = 0; f < w->getNodeList()->count(); f++) {
Node *n = *nodeIt;
QPointF point;
point.setX(n->getLon() / 1E2);
point.setY(n->getLat() / 1E2);
poly << point;
nodeIt++;
}
if (changeBrush(w->getTags()))
scene->addPolygon(poly,*pen,*brush);
} else {
nodeIt = w->getNodeList()->begin();
for (int f = 0; f< w->getNodeList()->count() - 1; f++) {
Node *n = *nodeIt;
nodeIt++;
Node *m = *nodeIt;
QPointF a,b;
a.setX(n->getLon() / 1E2);
a.setY(n->getLat() / 1E2);
b.setX(m->getLon() / 1E2);
b.setY(m->getLat() / 1E2);
if (changePen(w->getTags()))
scene->addLine(a.x(),a.y(),b.x(),b.y(),*pen);
}
}
}
memberIt++;
}
} //END ASSOCIATEDSTREET
tagIt++;
}
relationIt++;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool WMap::changePen(QHash<QString,QString>* pTags) {
QHash<QString,QString>::iterator tagIt = pTags->begin();
bool set = false;
for(int i = 0; i < pTags->count(); i++) {
pen->setStyle(Qt::SolidLine);
if(*tunnel == true)
pen->setStyle(Qt::DashDotLine);
if(tagIt.key() == "highway") {
if(tagIt.value() == "primary" || tagIt.value() == "primary_link" || tagIt.value() == "trunk" || tagIt.value() == "trunk_link") {
pen->setColor(QColor::fromRgb(255,160,128,255)); pen->setWidth(10); set=true; break;}
if(tagIt.value() == "secondary" || tagIt.value() == "secondary_link") {
pen->setColor(QColor::fromRgb(255,224,128,255)); pen->setWidth(8); set=true; break;}
if (tagIt.value() == "tertiary" || tagIt.value() == "tertiary_link") {
pen->setColor(QColor::fromRgb(128,128,208,255)); pen->setWidth(8); set=true; break;}
if(tagIt.value() == "residential" || tagIt.value() == "living_street") {
pen->setColor(QColor::fromRgb(64,64,64,255)); pen->setWidth(5); set=true; break;}
if(tagIt.value() == "service") {
pen->setColor(QColor::fromRgb(208,208,208,255)); pen->setWidth(4); set=true; break;}
if(tagIt.value() == "track") {
pen->setColor(QColor::fromRgb(96,32,0,255)); pen->setWidth(1); pen->setStyle(Qt::DashLine); set=true; break;}
if(tagIt.value() == "path") {
pen->setColor(QColor::fromRgb(128,64,0,255)); pen->setWidth(1); pen->setStyle(Qt::DashLine); set=true; break;}
if(tagIt.value() == "footway") {
pen->setColor(QColor::fromRgb(192,192,192,255)); pen->setWidth(2); pen->setStyle(Qt::DashLine); set=true; break;}
if(tagIt.value() == "road") {
pen->setColor(QColor::fromRgb(32,32,32,255)); pen->setWidth(5); set=true; break;}
if((tagIt.value() == "motorway") || (tagIt.value() == "motorway_link")) {
pen->setColor(QColor::fromRgb(160,80,112,255)); pen->setWidth(10); set=true; break;}
}
if(tagIt.key() == "waterway") {
if(tagIt.value() == "river") {
pen->setColor(Qt::blue); pen->setWidth(20); set=true; break;}
if(tagIt.value() == "stream") {
pen->setColor(Qt::blue); pen->setWidth(5); set=true; break;}
}
if(tagIt.value() == "water") {
pen->setColor(Qt::blue); set=true; break;
}
if(tagIt.key() == "railway") {
pen->setWidth(2);
pen->setColor(Qt::black);
pen->setStyle(Qt::DotLine);
set = true;
break;
}
tagIt++;
}
return(set);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool WMap::changeBrush(QHash<QString,QString>* pTags) {
QHash<QString,QString>::iterator tagIt = pTags->begin();
bool set = false;
brush->setStyle(Qt::SolidPattern);
pen->setStyle(Qt::NoPen);
for(int i = 0; i < pTags->count(); i++) {
if((tagIt.value() == "reservoir") || (tagIt.value() == "basin") || (tagIt.value() == "water")) {
brush->setColor(Qt::blue); pen->setColor(Qt::blue); set=true; break;
}
if(tagIt.key() == "building" || tagIt.value() == "building") {
brush->setColor(QColor::fromRgb(128,128,128,255)); pen->setStyle(Qt::SolidLine); pen->setColor(QColor::fromRgb(16,16,16,255)); pen->setWidth(1); set=true; break;
}
if (tagIt.key() == "landuse") {
if (tagIt.value() == "forest") {
brush->setColor(QColor::fromRgb(0,160,0,125)); set=true; break;}
if(tagIt.value() == "industrial" || tagIt.value() == "retail" || tagIt.value() == "commercial") {
brush->setColor(QColor::fromRgb(160,160,255,125)); set=true; break;}
if(tagIt.value() == "railway") {
brush->setColor(QColor::fromRgb(208,208,255,125)); set=true; break;}
if(tagIt.value() == "residential") {
brush->setColor(QColor::fromRgb(220,220,220,125)); set=true; break;}
if(tagIt.value() == "cemetery") {
brush->setStyle(Qt::DiagCrossPattern); brush->setColor(QColor::fromRgb(128,255,128,125)); set=true; break;}
if(tagIt.value() == "recreation_ground" || tagIt.value() == "village_green" || tagIt.value() == "meadow" || tagIt.value() == "grass" || tagIt.value() == "greenfield") {
brush->setColor(QColor::fromRgb(80,255,80,125)); set=true; break;}
}
tagIt++;
}
return(set);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool WMap::outOfBounds(QPointF pPoint) {
if ((pPoint.x() < boundingRect->left()) || (pPoint.x() > boundingRect->right()) ||
(pPoint.y() < boundingRect->top()) || (pPoint.y() > boundingRect->bottom()) )
return(true);
return(false);
}
//KEYEVENTS-------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::keyPressEvent(QKeyEvent* event) {
if(event->key() == 16777275)
takeScreenshot();
}
//MOUSEEVENTS--------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::mousePressEvent(QMouseEvent *event) {
if(event->button() == Qt::LeftButton) {
setCursor(Qt::ClosedHandCursor);
mousePos->setX(event->x());
mousePos->setY(event->y());
*moveMouse = true;
event->accept();
}
event->ignore();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::mouseReleaseEvent(QMouseEvent *event) {
if(event->button() == Qt::LeftButton) {
setCursor(Qt::ArrowCursor);
*moveMouse = false;
event->accept();
}
event->ignore();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::mouseMoveEvent(QMouseEvent* event) {
if (*moveMouse == true) {
this->horizontalScrollBar()->setValue(this->horizontalScrollBar()->value() - (event->x() - mousePos->x()));
this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() - (event->y() - mousePos->y()));
mousePos->setX(event->x());
mousePos->setY(event->y());
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::wheelEvent(QWheelEvent* event) {
int degrees = event->delta() / 15;
int steps = degrees / 8;
if(*stepCounter * steps < 0)
*stepCounter = steps;
else
*stepCounter += steps;
if (!timer->isActive()) {;
timer->start(20);
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::stopTimer() {
timer->stop();
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::zoom() {
if (*stepCounter != 0) {
qreal viewScale = 1.0;
qreal factor = 0.2;
qreal max = 3;
if(*stepCounter < 0) {
if ( (this->horizontalScrollBar()->value() != 0) && (this->verticalScrollBar()->value() != 0) ) {
viewScale -= factor;
*scaleControl -= factor;
}
*stepCounter += 1;
} else {
if((*scaleControl+factor)<max) {
viewScale += factor;
*scaleControl += factor;
}
*stepCounter -= 1;
}
scale(viewScale,viewScale);
bool b = true;
QRect rect;
QPolygonF poly;
QPolygonF::iterator polyIt;
while(b) {
rect = this->viewport()->visibleRegion().boundingRect();
poly = this->mapToScene(rect);
polyIt = poly.begin();
for (int i=0;i < poly.count(); i++) {
if (!this->outOfBounds(*polyIt)) {
b = false;
} else {
b = true;
break;
}
polyIt++;
}
*scaleControl -= factor;
*stepCounter = 0;
scale(1.01,1.01);
}
} else {
emit zoomFinished();
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
void WMap::takeScreenshot() {
QString fileName = QFileDialog::getSaveFileName(this,"Screenshot speichern", "", "(*.png)");
QPixmap pic = QPixmap::grabWidget(this,this->viewport()->rect());
pic.save(fileName,"" ,100);
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
| 46.481356 | 190 | 0.310968 | HSHL |
51e4be76c4bf77fc17279e8e7b8acfb626ce6280 | 38,962 | cpp | C++ | sceneloader.cpp | nlguillemot/fictional-doodle | d340f4e6983f77ea38b94f8ba30f7f1f5ebb532f | [
"MIT"
] | 14 | 2016-11-20T02:36:24.000Z | 2022-02-18T07:08:25.000Z | sceneloader.cpp | nlguillemot/fictional-doodle | d340f4e6983f77ea38b94f8ba30f7f1f5ebb532f | [
"MIT"
] | 1 | 2020-07-16T14:33:19.000Z | 2020-07-26T01:49:18.000Z | sceneloader.cpp | nlguillemot/fictional-doodle | d340f4e6983f77ea38b94f8ba30f7f1f5ebb532f | [
"MIT"
] | 1 | 2016-11-21T09:50:45.000Z | 2016-11-21T09:50:45.000Z | #include "sceneloader.h"
#include "scene.h"
// assimp includes
#include <cimport.h>
// assimp also has a scene.h. weird.
#include <scene.h>
#include <postprocess.h>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <vector>
#include <string>
#include <functional>
#include <array>
static void LoadMD5Materials(
Scene* scene,
const char* assetFolder, const char* modelFolder,
aiMaterial** materials, int numMaterials,
int* materialIDMapping)
{
// Only the texture types we care about
std::array<aiTextureType,3> textureTypes = {
aiTextureType_DIFFUSE,
aiTextureType_SPECULAR,
aiTextureType_NORMALS
};
static const int numTextureTypes = (int)textureTypes.size();
// find all textures that need to be loaded
std::vector<std::vector<std::string>> texturesToLoad(numTextureTypes);
for (int materialIdx = 0; materialIdx < numMaterials; materialIdx++)
{
aiMaterial* material = materials[materialIdx];
for (int textureTypeIdx = 0; textureTypeIdx < (int)textureTypes.size(); textureTypeIdx++)
{
int textureCount = (int)aiGetMaterialTextureCount(material, textureTypes[textureTypeIdx]);
for (int textureIdxInStack = 0; textureIdxInStack < (int)textureCount; textureIdxInStack++)
{
aiString path;
aiReturn result = aiGetMaterialTexture(material, textureTypes[textureTypeIdx], textureIdxInStack, &path, NULL, NULL, NULL, NULL, NULL, NULL);
if (result != AI_SUCCESS)
{
fprintf(stderr, "aiGetMaterialTexture failed: %s\n", aiGetErrorString());
exit(1);
}
texturesToLoad[textureTypeIdx].push_back(std::string(modelFolder) + path.C_Str());
}
}
}
std::vector<std::unordered_map<std::string, int>*> textureNameToIDs
{
&scene->DiffuseTextureNameToID,
&scene->SpecularTextureNameToID,
&scene->NormalTextureNameToID,
};
assert(textureNameToIDs.size() == numTextureTypes);
// keep only the unique textures
for (int textureTypeIdx = 0; textureTypeIdx < numTextureTypes; textureTypeIdx++)
{
// remove textures that appear more than once in this list
std::sort(begin(texturesToLoad[textureTypeIdx]), end(texturesToLoad[textureTypeIdx]));
texturesToLoad[textureTypeIdx].erase(
std::unique(begin(texturesToLoad[textureTypeIdx]), end(texturesToLoad[textureTypeIdx])),
end(texturesToLoad[textureTypeIdx]));
// remove textures that were loaded by previous meshes
texturesToLoad[textureTypeIdx].erase(
std::remove_if(begin(texturesToLoad[textureTypeIdx]), end(texturesToLoad[textureTypeIdx]),
[&textureNameToIDs, textureTypeIdx](const std::string& s) {
return textureNameToIDs[textureTypeIdx]->find(s) != textureNameToIDs[textureTypeIdx]->end();
}), end(texturesToLoad[textureTypeIdx]));
}
// load all the unique textures
for (int textureTypeIdx = 0; textureTypeIdx < numTextureTypes; textureTypeIdx++)
{
for (int textureToLoadIdx = 0; textureToLoadIdx < (int)texturesToLoad[textureTypeIdx].size(); textureToLoadIdx++)
{
const std::string& fullpath = assetFolder + texturesToLoad[textureTypeIdx][textureToLoadIdx];
int width, height, comp;
int req_comp = 4;
stbi_set_flip_vertically_on_load(1); // because GL
stbi_uc* img = stbi_load(fullpath.c_str(), &width, &height, &comp, req_comp);
if (!img)
{
fprintf(stderr, "stbi_load (%s): %s\n", fullpath.c_str(), stbi_failure_reason());
}
else
{
bool hasTransparency = false;
for (int i = 0; i < width * height; i++)
{
if (img[i * 4 + 3] != 255)
{
hasTransparency = true;
break;
}
}
bool isSRGB = false;
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
isSRGB = true;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
isSRGB = false;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
isSRGB = false;
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", fullpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
// premultiply teh alphas
if (hasTransparency)
{
for (int i = 0; i < width * height; i++)
{
float alpha = glm::clamp(img[i * 4 + 3] / 255.0f, 0.0f, 1.0f);
if (isSRGB)
{
alpha = glm::clamp(std::pow(alpha, 1.0f / 2.2f), 0.0f, 1.0f);
}
img[i * 4 + 0] = stbi_uc(img[i * 4 + 0] * alpha);
img[i * 4 + 1] = stbi_uc(img[i * 4 + 1] * alpha);
img[i * 4 + 2] = stbi_uc(img[i * 4 + 2] * alpha);
}
}
if (req_comp != 0)
{
comp = req_comp;
}
GLenum srcDataFormat[4] = {
GL_RED, GL_RG, GL_RGB, GL_RGBA
};
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
float anisotropy;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &anisotropy);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, anisotropy);
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, srcDataFormat[comp - 1], GL_UNSIGNED_BYTE, img);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, srcDataFormat[comp - 1], GL_UNSIGNED_BYTE, img);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8_SNORM, width, height, 0, srcDataFormat[comp - 1], GL_UNSIGNED_BYTE, img);
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", fullpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
int id = -1;
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
DiffuseTexture d;
d.HasTransparency = hasTransparency;
d.TO = texture;
scene->DiffuseTextures.push_back(std::move(d));
id = (int)scene->DiffuseTextures.size() - 1;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
SpecularTexture s;
s.TO = texture;
scene->SpecularTextures.push_back(std::move(s));
id = (int)scene->SpecularTextures.size() - 1;
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
NormalTexture n;
n.TO = texture;
scene->NormalTextures.push_back(std::move(n));
id = (int)scene->NormalTextures.size() - 1;
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", fullpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
textureNameToIDs[textureTypeIdx]->emplace(texturesToLoad[textureTypeIdx][textureToLoadIdx], id);
stbi_image_free(img);
}
stbi_set_flip_vertically_on_load(0);
}
}
// hook up list of materials
for (int materialIdx = 0; materialIdx < numMaterials; materialIdx++)
{
aiMaterial* material = materials[materialIdx];
// Potential improvement:
// Look for an existing material with the same properties,
// instead of creating a new one.
Material newMat;
for (int textureTypeIdx = 0; textureTypeIdx < (int)textureTypes.size(); textureTypeIdx++)
{
int textureCount = (int)aiGetMaterialTextureCount(material, textureTypes[textureTypeIdx]);
for (int textureIdxInStack = 0; textureIdxInStack < (int)textureCount; textureIdxInStack++)
{
aiString path;
aiReturn result = aiGetMaterialTexture(material, textureTypes[textureTypeIdx], textureIdxInStack, &path, NULL, NULL, NULL, NULL, NULL, NULL);
if (result != AI_SUCCESS)
{
fprintf(stderr, "aiGetMaterialTexture failed: %s\n", aiGetErrorString());
exit(1);
}
std::string modelpath = std::string(modelFolder) + path.C_Str();
auto foundNameToID = textureNameToIDs[textureTypeIdx]->find(modelpath);
if (foundNameToID != textureNameToIDs[textureTypeIdx]->end())
{
int textureID = foundNameToID->second;
if (textureTypes[textureTypeIdx] == aiTextureType_DIFFUSE)
{
newMat.DiffuseTextureIDs.push_back(textureID);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_SPECULAR)
{
newMat.SpecularTextureIDs.push_back(textureID);
}
else if (textureTypes[textureTypeIdx] == aiTextureType_NORMALS)
{
newMat.NormalTextureIDs.push_back(textureID);
}
else
{
fprintf(stderr, "%s: Unhandled texture type %d\n", modelpath.c_str(), textureTypes[textureTypeIdx]);
exit(1);
}
}
}
}
if (materialIDMapping)
{
materialIDMapping[materialIdx] = (int)scene->Materials.size();
}
scene->Materials.push_back(std::move(newMat));
}
}
static int LoadMD5SkeletonNode(
Scene* scene,
const aiNode* ainode,
const std::unordered_map<std::string, glm::mat4>& invBindPoseTransforms)
{
if (strcmp(ainode->mName.C_Str(), "<MD5_Hierarchy>") != 0)
{
fprintf(stderr, "Expected <MD5_Hierarchy>, got %s\n", ainode->mName.C_Str());
exit(1);
}
// traverse skeleton and flatten it
std::vector<aiNode*> boneNodes;
std::vector<int> boneParentIDs;
std::vector<std::pair<aiNode*, int>> skeletonDFSStack;
// Initialize stack with parentless bones
for (int childIdx = (int)ainode->mNumChildren - 1; childIdx >= 0; childIdx--)
{
skeletonDFSStack.emplace_back(ainode->mChildren[childIdx], -1);
}
while (!skeletonDFSStack.empty())
{
aiNode* node = skeletonDFSStack.back().first;
int parentID = skeletonDFSStack.back().second;
skeletonDFSStack.pop_back();
int myBoneID = (int)boneNodes.size();
boneNodes.push_back(node);
boneParentIDs.push_back(parentID);
for (int childIdx = (int)node->mNumChildren - 1; childIdx >= 0; childIdx--)
{
skeletonDFSStack.emplace_back(node->mChildren[childIdx], myBoneID);
}
}
int boneCount = (int)boneNodes.size();
// Generate bone indices for rendering
std::vector<glm::uvec2> boneIndices(boneCount - 1);
for (int boneIdx = 1, indexIdx = 0; boneIdx < boneCount; boneIdx++, indexIdx++)
{
boneIndices[indexIdx] = glm::uvec2(boneParentIDs[boneIdx], boneIdx);
}
Skeleton skeleton;
skeleton.BoneNames.resize(boneCount);
skeleton.BoneInverseBindPoseTransforms.resize(boneCount);
skeleton.BoneLengths.resize(boneCount);
skeleton.BoneParents = std::move(boneParentIDs);
skeleton.NumBones = boneCount;
skeleton.NumBoneIndices = 2 * (int)boneIndices.size();
for (int boneID = 0; boneID < boneCount; boneID++)
{
skeleton.BoneNames[boneID] = boneNodes[boneID]->mName.C_Str();
skeleton.BoneNameToID.emplace(skeleton.BoneNames[boneID], boneID);
int parentBoneID = skeleton.BoneParents[boneID];
// Unused bones won't have an inverse bind pose transform to use
auto it = invBindPoseTransforms.find(skeleton.BoneNames[boneID]);
if (it != invBindPoseTransforms.end())
{
skeleton.BoneInverseBindPoseTransforms[boneID] = it->second;
}
else
{
// Missing inverse bind pose implies no local transformation
printf("Bone %s has no inverse bind pose transform, assigning from ", skeleton.BoneNames[boneID].c_str());
if (parentBoneID >= 0)
{
// Same absolute transform as parent
printf("%s\n", skeleton.BoneNames[parentBoneID].c_str());
skeleton.BoneInverseBindPoseTransforms[boneID] = skeleton.BoneInverseBindPoseTransforms[parentBoneID];
}
else
{
// No absolute transform
printf("identity\n");
skeleton.BoneInverseBindPoseTransforms[boneID] = glm::mat4(1.0);
}
}
if (parentBoneID != -1)
{
glm::mat4 childInvBindPose = skeleton.BoneInverseBindPoseTransforms[boneID];
glm::mat4 childBindPose = inverse(childInvBindPose);
glm::vec3 childPosition = glm::vec3(childBindPose[3]);
glm::mat4 parentInvBindPose = skeleton.BoneInverseBindPoseTransforms[parentBoneID];
glm::mat4 parentBindPose = inverse(parentInvBindPose);
glm::vec3 parentPosition = glm::vec3(parentBindPose[3]);
skeleton.BoneLengths[boneID] = length(childPosition - parentPosition);
}
}
// Upload bone indices
glGenBuffers(1, &skeleton.BoneEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skeleton.BoneEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, boneIndices.size() * sizeof(boneIndices[0]), boneIndices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
scene->Skeletons.push_back(std::move(skeleton));
return (int)scene->Skeletons.size() - 1;
}
static int LoadMD5Skeleton(
Scene* scene,
const aiScene* aiscene)
{
aiNode* root = aiscene->mRootNode;
if (strcmp(root->mName.C_Str(), "<MD5_Root>") != 0)
{
fprintf(stderr, "Expected <MD5_Root>, got %s\n", root->mName.C_Str());
exit(1);
}
// Global skeleton transformation
glm::mat4 skeletonTransform = glm::transpose(glm::make_mat4(&root->mTransformation.a1));
// Retrieve inverse bind pose transformation for each mesh's bones
std::unordered_map<std::string, glm::mat4> invBindPoseTransforms;
for (int meshIdx = 0; meshIdx < (int)aiscene->mNumMeshes; meshIdx++)
{
for (int boneIdx = 0; boneIdx < (int)aiscene->mMeshes[meshIdx]->mNumBones; boneIdx++)
{
const aiBone* bone = aiscene->mMeshes[meshIdx]->mBones[boneIdx];
std::string boneName = bone->mName.C_Str();
invBindPoseTransforms[boneName] = glm::transpose(glm::make_mat4(&bone->mOffsetMatrix.a1));
}
}
// traverse all children
for (int childIdx = 0; childIdx < (int)root->mNumChildren; childIdx++)
{
aiNode* child = root->mChildren[childIdx];
if (strcmp(child->mName.C_Str(), "<MD5_Hierarchy>") == 0)
{
// Found skeleton
int skeletonID = LoadMD5SkeletonNode(scene, child, invBindPoseTransforms);
scene->Skeletons[skeletonID].Transform = skeletonTransform;
return skeletonID;
}
}
fprintf(stderr, "Failed to find skeleton in scene\n");
exit(1);
return -1;
}
static void LoadMD5Meshes(
Scene* scene,
int skeletonID,
const char* modelFolder, const char* meshFile,
aiMesh** meshes, int numMeshes,
const int* materialIDMapping, // 1-1 mapping with assimp scene materials
int* bindPoseMeshIDMapping)
{
for (int meshIdx = 0; meshIdx < numMeshes; meshIdx++)
{
aiMesh* mesh = meshes[meshIdx];
if (mesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
{
fprintf(stderr, "Mesh %s was not made out of triangles\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTextureCoords[0])
{
fprintf(stderr, "Mesh %s didn't have TexCoord\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mNormals)
{
fprintf(stderr, "Mesh %s didn't have normals\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTangents)
{
fprintf(stderr, "Mesh %s didn't have tangents\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mBitangents)
{
fprintf(stderr, "Mesh %s didn't have bitangents\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mBones)
{
fprintf(stderr, "Mesh %s didn't have bones\n", mesh->mName.C_Str());
exit(1);
}
int vertexCount = (int)mesh->mNumVertices;
std::vector<PositionVertex> positions(vertexCount);
std::vector<TexCoordVertex> texCoords(vertexCount);
std::vector<DifferentialVertex> differentials(vertexCount);
for (int vertexIdx = 0; vertexIdx < vertexCount; vertexIdx++)
{
positions[vertexIdx].Position = glm::make_vec3(&mesh->mVertices[vertexIdx][0]);
texCoords[vertexIdx].TexCoord = glm::make_vec2(&mesh->mTextureCoords[0][vertexIdx][0]);
differentials[vertexIdx].Normal = glm::make_vec3(&mesh->mNormals[vertexIdx][0]);
differentials[vertexIdx].Tangent = glm::make_vec3(&mesh->mTangents[vertexIdx][0]);
differentials[vertexIdx].Bitangent = glm::make_vec3(&mesh->mBitangents[vertexIdx][0]);
}
const Skeleton& skeleton = scene->Skeletons[skeletonID];
int boneCount = (int)mesh->mNumBones;
std::vector<BoneWeightVertex> boneWeights(vertexCount);
std::vector<int> vertexNumBones(vertexCount);
for (int boneIdx = 0; boneIdx < boneCount; boneIdx++)
{
aiBone* bone = mesh->mBones[boneIdx];
int boneWeightCount = (int)bone->mNumWeights;
auto foundBone = skeleton.BoneNameToID.find(bone->mName.C_Str());
if (foundBone == end(skeleton.BoneNameToID))
{
fprintf(stderr, "Couldn't find bone %s in skeleton\n", bone->mName.C_Str());
exit(1);
}
int boneID = foundBone->second;
for (int weightIdx = 0; weightIdx < boneWeightCount; weightIdx++)
{
aiVertexWeight vertexWeight = bone->mWeights[weightIdx];
int vertexID = vertexWeight.mVertexId;
float weight = vertexWeight.mWeight;
if (vertexNumBones[vertexID] < 4)
{
boneWeights[vertexID].BoneIDs[vertexNumBones[vertexID]] = boneID;
boneWeights[vertexID].Weights[vertexNumBones[vertexID]] = weight;
vertexNumBones[vertexID]++;
}
else if (boneWeights[vertexID].Weights[3] < weight)
{
// Keep the top 4 influencing weights in sorted order. bubble down.
boneWeights[vertexID].Weights[3] = weight;
for (int nextWeight = 2; nextWeight >= 0; nextWeight--)
{
if (boneWeights[vertexID].Weights[nextWeight] >= boneWeights[vertexID].Weights[nextWeight + 1])
{
break;
}
std::swap(boneWeights[vertexID].Weights[nextWeight], boneWeights[vertexID].Weights[nextWeight + 1]);
}
}
}
}
int faceCount = (int)mesh->mNumFaces;
std::vector<glm::uvec3> indices(faceCount);
for (int faceIdx = 0; faceIdx < faceCount; faceIdx++)
{
indices[faceIdx] = glm::make_vec3(&mesh->mFaces[faceIdx].mIndices[0]);
}
BindPoseMesh bindPoseMesh;
bindPoseMesh.NumVertices = vertexCount;
bindPoseMesh.NumIndices = faceCount * 3;
bindPoseMesh.SkeletonID = skeletonID;
bindPoseMesh.MaterialID = materialIDMapping[mesh->mMaterialIndex];
glGenBuffers(1, &bindPoseMesh.PositionVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.PositionVBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]), positions.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(texCoords[0]), texCoords.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.DifferentialVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.DifferentialVBO);
glBufferData(GL_ARRAY_BUFFER, differentials.size() * sizeof(differentials[0]), differentials.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.BoneVBO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.BoneVBO);
glBufferData(GL_ARRAY_BUFFER, boneWeights.size() * sizeof(boneWeights[0]), boneWeights.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &bindPoseMesh.EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bindPoseMesh.EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]), indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glGenVertexArrays(1, &bindPoseMesh.SkinningVAO);
glBindVertexArray(bindPoseMesh.SkinningVAO);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.PositionVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(PositionVertex), (GLvoid*)offsetof(PositionVertex, Position));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.TexCoordVBO);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(TexCoordVertex), (GLvoid*)offsetof(TexCoordVertex, TexCoord));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.DifferentialVBO);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Normal));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Tangent));
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Bitangent));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glBindBuffer(GL_ARRAY_BUFFER, bindPoseMesh.BoneVBO);
glVertexAttribIPointer(5, 4, GL_UNSIGNED_BYTE, sizeof(BoneWeightVertex), (GLvoid*)offsetof(BoneWeightVertex, BoneIDs));
glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(BoneWeightVertex), (GLvoid*)offsetof(BoneWeightVertex, Weights));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(5);
glEnableVertexAttribArray(6);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bindPoseMesh.EBO);
glBindVertexArray(0);
if (bindPoseMeshIDMapping)
{
bindPoseMeshIDMapping[meshIdx] = (int)scene->BindPoseMeshes.size();
}
scene->BindPoseMeshes.push_back(std::move(bindPoseMesh));
}
}
void LoadMD5Mesh(
Scene* scene,
const char* assetFolder, const char* modelFolder,
const char* meshFile,
std::vector<int>* loadedMaterialIDs,
int* loadedSkeletonID,
std::vector<int>* loadedBindPoseMeshIDs)
{
std::string meshpath = std::string(assetFolder) + modelFolder + meshFile;
const aiScene* aiscene = aiImportFile(meshpath.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
if (!aiscene)
{
fprintf(stderr, "aiImportFile: %s\n", aiGetErrorString());
exit(1);
}
std::vector<int> materialIDMapping(aiscene->mNumMaterials);
LoadMD5Materials(
scene,
assetFolder, modelFolder,
aiscene->mMaterials, (int)aiscene->mNumMaterials,
materialIDMapping.data());
int skeletonID = LoadMD5Skeleton(scene, aiscene);
if (loadedSkeletonID) *loadedSkeletonID = skeletonID;
if (loadedBindPoseMeshIDs)
{
loadedBindPoseMeshIDs->resize(aiscene->mNumMeshes);
}
LoadMD5Meshes(
scene,
skeletonID,
modelFolder, meshFile,
&aiscene->mMeshes[0], (int)aiscene->mNumMeshes,
materialIDMapping.data(),
loadedBindPoseMeshIDs ? loadedBindPoseMeshIDs->data() : NULL);
if (loadedMaterialIDs)
{
*loadedMaterialIDs = std::move(materialIDMapping);
}
aiReleaseImport(aiscene);
}
void LoadMD5Anim(
Scene* scene,
int skeletonID,
const char* assetFolder, const char* modelFolder,
const char* animFile,
int* loadedAnimSequenceID)
{
std::string fullpath = std::string(assetFolder) + modelFolder + animFile;
const aiScene* animScene = aiImportFile(fullpath.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
// Check if file exists and was successfully parsed
if (!animScene)
{
fprintf(stderr, "aiImportFile: %s\n", aiGetErrorString());
return;
}
// Check if file contains an animation
if (animScene->mNumAnimations != 1)
{
fprintf(stderr, "Expected 1 animation in %s, got %d\n", fullpath.c_str(), (int)animScene->mNumAnimations);
return;
}
// TODO: Check if animation is valid for the skeleton
// One animation per file
const aiAnimation* animation = animScene->mAnimations[0];
AnimSequence animSequence;
animSequence.Name = std::string(modelFolder) + animFile;
animSequence.SkeletonID = skeletonID;
animSequence.FramesPerSecond = (int)animation->mTicksPerSecond;
animSequence.NumFrames = (int)animation->mDuration;
// Allocate storage for each bone
animSequence.BoneBaseFrame.resize(animation->mNumChannels);
animSequence.BoneChannelBits.resize(animation->mNumChannels);
animSequence.BoneFrameDataOffsets.resize(animation->mNumChannels);
int numFrameComponents = 0;
// For each bone
for (int bone = 0; bone < (int)animation->mNumChannels; bone++)
{
aiNodeAnim* boneAnim = animation->mChannels[bone];
// Base frame bone position
aiVector3D baseT = boneAnim->mPositionKeys[0].mValue;
animSequence.BoneBaseFrame[bone].T = glm::vec3(baseT.x, baseT.y, baseT.z);
// Base frame bone orientation
aiQuaternion baseQ = boneAnim->mRotationKeys[0].mValue;
animSequence.BoneBaseFrame[bone].Q = glm::quat(baseQ.w, baseQ.x, baseQ.y, baseQ.z);
// Find which position components of this bone are animated
glm::bvec3 isAnimatedT(false);
for (int i = 1; i < (int)boneAnim->mNumPositionKeys; i++)
{
aiVector3D v0 = boneAnim->mPositionKeys[i - 1].mValue;
aiVector3D v1 = boneAnim->mPositionKeys[i].mValue;
if (v0.x != v1.x) { isAnimatedT.x = true; }
if (v0.y != v1.y) { isAnimatedT.y = true; }
if (v0.z != v1.z) { isAnimatedT.z = true; }
if (all(isAnimatedT))
{
break;
}
}
// Find which orientation components of this bone are animated
glm::bvec3 isAnimatedQ(false);
for (int i = 1; i < (int)boneAnim->mNumRotationKeys; i++)
{
aiQuaternion q0 = boneAnim->mRotationKeys[i - 1].mValue;
aiQuaternion q1 = boneAnim->mRotationKeys[i].mValue;
if (q0.x != q1.x) { isAnimatedQ.x = true; }
if (q0.y != q1.y) { isAnimatedQ.y = true; }
if (q0.z != q1.z) { isAnimatedQ.z = true; }
if (all(isAnimatedQ))
{
break;
}
}
// Encode which position and orientation components are animated
animSequence.BoneChannelBits[bone] |= isAnimatedT.x ? ANIMCHANNEL_TX_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedT.y ? ANIMCHANNEL_TY_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedT.z ? ANIMCHANNEL_TZ_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedQ.x ? ANIMCHANNEL_QX_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedQ.y ? ANIMCHANNEL_QY_BIT : 0;
animSequence.BoneChannelBits[bone] |= isAnimatedQ.z ? ANIMCHANNEL_QZ_BIT : 0;
animSequence.BoneFrameDataOffsets[bone] = numFrameComponents;
// Update offset for the next bone
for (uint8_t bits = animSequence.BoneChannelBits[bone]; bits != 0; bits &= (bits - 1))
{
numFrameComponents++;
}
}
// Create storage for frame data
animSequence.BoneFrameData.resize(animSequence.NumFrames * numFrameComponents);
animSequence.NumFrameComponents = numFrameComponents;
// Generate encoded frame data
for (int bone = 0; bone < (int)animation->mNumChannels; bone++)
{
for (int frame = 0; frame < animSequence.NumFrames; frame++)
{
int off = animSequence.BoneFrameDataOffsets[bone];
uint8_t bits = animSequence.BoneChannelBits[bone];
if (bits & ANIMCHANNEL_TX_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mPositionKeys[frame].mValue.x;
}
if (bits & ANIMCHANNEL_TY_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mPositionKeys[frame].mValue.y;
}
if (bits & ANIMCHANNEL_TZ_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mPositionKeys[frame].mValue.z;
}
if (bits & ANIMCHANNEL_QX_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mRotationKeys[frame].mValue.x;
}
if (bits & ANIMCHANNEL_QY_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mRotationKeys[frame].mValue.y;
}
if (bits & ANIMCHANNEL_QZ_BIT)
{
int index = frame * numFrameComponents + off++;
animSequence.BoneFrameData[index] = animation->mChannels[bone]->mRotationKeys[frame].mValue.z;
}
}
}
scene->AnimSequences.push_back(std::move(animSequence));
int animSequenceID = (int)scene->AnimSequences.size() - 1;
if (loadedAnimSequenceID)
{
*loadedAnimSequenceID = animSequenceID;
}
aiReleaseImport(animScene);
}
static void LoadOBJMeshes(
Scene* scene,
const char* modelFolder, const char* meshFile,
aiMesh** meshes, int numMeshes,
const int* materialIDMapping, // 1-1 mapping with assimp scene materials
int* staticMeshIDMapping)
{
for (int meshIdx = 0; meshIdx < numMeshes; meshIdx++)
{
aiMesh* mesh = meshes[meshIdx];
if (mesh->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
{
fprintf(stderr, "Mesh %s was not made out of triangles\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTextureCoords[0])
{
fprintf(stderr, "Mesh %s didn't have TexCoord\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mNormals)
{
fprintf(stderr, "Mesh %s didn't have normals\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mTangents)
{
fprintf(stderr, "Mesh %s didn't have tangents\n", mesh->mName.C_Str());
exit(1);
}
if (!mesh->mBitangents)
{
fprintf(stderr, "Mesh %s didn't have bitangents\n", mesh->mName.C_Str());
exit(1);
}
int vertexCount = (int)mesh->mNumVertices;
std::vector<PositionVertex> positions(vertexCount);
std::vector<TexCoordVertex> texCoords(vertexCount);
std::vector<DifferentialVertex> differentials(vertexCount);
for (int vertexIdx = 0; vertexIdx < vertexCount; vertexIdx++)
{
positions[vertexIdx].Position = glm::make_vec3(&mesh->mVertices[vertexIdx][0]);
texCoords[vertexIdx].TexCoord = glm::make_vec2(&mesh->mTextureCoords[0][vertexIdx][0]);
differentials[vertexIdx].Normal = glm::make_vec3(&mesh->mNormals[vertexIdx][0]);
differentials[vertexIdx].Tangent = glm::make_vec3(&mesh->mTangents[vertexIdx][0]);
differentials[vertexIdx].Bitangent = glm::make_vec3(&mesh->mBitangents[vertexIdx][0]);
}
int faceCount = (int)mesh->mNumFaces;
std::vector<glm::uvec3> indices(faceCount);
for (int faceIdx = 0; faceIdx < faceCount; faceIdx++)
{
indices[faceIdx] = glm::make_vec3(&mesh->mFaces[faceIdx].mIndices[0]);
}
StaticMesh staticMesh;
staticMesh.NumVertices = vertexCount;
staticMesh.NumIndices = faceCount * 3;
staticMesh.MaterialID = materialIDMapping[mesh->mMaterialIndex];
glGenBuffers(1, &staticMesh.PositionVBO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.PositionVBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]), positions.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &staticMesh.TexCoordVBO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.TexCoordVBO);
glBufferData(GL_ARRAY_BUFFER, texCoords.size() * sizeof(texCoords[0]), texCoords.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &staticMesh.DifferentialVBO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.DifferentialVBO);
glBufferData(GL_ARRAY_BUFFER, differentials.size() * sizeof(differentials[0]), differentials.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &staticMesh.MeshEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, staticMesh.MeshEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]), indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glGenVertexArrays(1, &staticMesh.MeshVAO);
glBindVertexArray(staticMesh.MeshVAO);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.PositionVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(PositionVertex), (GLvoid*)offsetof(PositionVertex, Position));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.TexCoordVBO);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(TexCoordVertex), (GLvoid*)offsetof(TexCoordVertex, TexCoord));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, staticMesh.DifferentialVBO);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Normal));
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Tangent));
glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(DifferentialVertex), (GLvoid*)offsetof(DifferentialVertex, Bitangent));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glEnableVertexAttribArray(4);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, staticMesh.MeshEBO);
glBindVertexArray(0);
if (staticMeshIDMapping)
{
staticMeshIDMapping[meshIdx] = (int)scene->StaticMeshes.size();
}
scene->StaticMeshes.push_back(std::move(staticMesh));
}
}
void LoadOBJMesh(
Scene* scene,
const char* assetFolder, const char* modelFolder,
const char* objFile,
std::vector<int>* loadedMaterialIDs,
std::vector<int>* loadedStaticMeshIDs)
{
std::string meshpath = std::string(assetFolder) + modelFolder + objFile;
const aiScene* aiscene = aiImportFile(meshpath.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
if (!aiscene)
{
fprintf(stderr, "aiImportFile: %s\n", aiGetErrorString());
exit(1);
}
std::vector<int> materialIDMapping(aiscene->mNumMaterials);
LoadMD5Materials(
scene,
assetFolder, modelFolder,
aiscene->mMaterials, (int)aiscene->mNumMaterials,
materialIDMapping.data());
std::vector<int> staticMeshIDMapping(aiscene->mNumMeshes);
LoadOBJMeshes(
scene,
modelFolder, objFile,
aiscene->mMeshes, (int)aiscene->mNumMeshes,
materialIDMapping.data(),
staticMeshIDMapping.data());
if (loadedMaterialIDs)
{
*loadedMaterialIDs = std::move(materialIDMapping);
}
if (loadedStaticMeshIDs)
{
*loadedStaticMeshIDs = std::move(staticMeshIDMapping);
}
aiReleaseImport(aiscene);
}
| 38.729622 | 157 | 0.603768 | nlguillemot |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.