hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ddb11134f9802c15fbfe734240305f83341b65cb | 17,661 | hpp | C++ | include/util.hpp | yge58/collaborative_a_star_pathfinding | da19e859d37d44c18cd2a2104bdb0c46f56dc09d | [
"MIT"
] | 41 | 2017-08-02T11:33:32.000Z | 2022-03-18T19:33:46.000Z | include/util.hpp | yge58/collaborative_a_star_pathfinding | da19e859d37d44c18cd2a2104bdb0c46f56dc09d | [
"MIT"
] | null | null | null | include/util.hpp | yge58/collaborative_a_star_pathfinding | da19e859d37d44c18cd2a2104bdb0c46f56dc09d | [
"MIT"
] | 7 | 2018-10-25T16:37:21.000Z | 2021-10-20T15:09:14.000Z | #ifndef UTIL_HPP
#define UTIL_HPP
#include "common.hpp"
#include "Agent.hpp"
#include "Map.hpp"
/*********************************************************************/
using hash_map = unordered_map<Node, vector<Agent*>>;
/********************************************************************/
// manhattan distance heuristic.
inline uint manhattan_heuristic(const Node& a, const Node& b)
{// the cost moving form one spot to an adjacent spot vertically or horizontally is 10
return 10 * ( std::abs(static_cast<int>(a.x - b.x)) + std::abs(static_cast<int>(a.y - b.y)) );
}
/********************************************************************/
// Basic A-Star pathfinding for single agent.
bool aStar(Agent &agent, Map &map)
{
// empty agent's closedSet
if (!agent.closedSet.empty())
agent.closedSet.clear();
if (!agent.openSet.empty())
cout << "openSet is not empty, error\n";
Node start = agent.getStart();
Node goal = agent.getGoal();
// Initially, only the start node is known.
agent.openSet.push(start);
// The cost of going from start to start is zero.
agent.gScore.insert( {start, 0} ) ;
// For the first node, that value is completely heuristic.
agent.fScore.insert( {start, manhattan_heuristic(start, goal)} );
while (!agent.openSet.empty())
{
Node current = agent.openSet.top();
agent.openSet.pop();
if (current == goal)
return true;
agent.closedSet.insert({current, agent.fScore[current]}); // change closedSet to vector.
vector<Node> Neighbors;
map.getNeighbors(current, Neighbors);
for (Node& neighbor : Neighbors) {
// insert new nodes
if(agent.cameFrom.find(neighbor) == agent.cameFrom.end()) {
agent.cameFrom.insert(make_pair(neighbor, current));
agent.gScore.insert(make_pair(neighbor, MAX));
agent.fScore.insert(make_pair(neighbor, MAX));
}
if (agent.closedSet.find(neighbor) != agent.closedSet.end())
continue; // Ignore the neighbor which is already evaluated
if (map.isObstacle(neighbor)) { // if neighbor is obstacles, add to closedSet.
agent.closedSet.insert( {neighbor, MAX} ); // fscore is set to be max.
continue;
}
// The distance from start to a neighbor, diagonal 14, vertical or horizontal 10.
uint dist_neighbor = abs((int)(neighbor.x-current.x)) + \
abs((int)(neighbor.y-current.y)) == 2 ? 14:10;
uint tentative_gScore = agent.gScore[current] + dist_neighbor;
if (tentative_gScore >= agent.gScore[neighbor])
continue;
agent.cameFrom[neighbor] = current;
agent.gScore[neighbor] = tentative_gScore;
agent.fScore[neighbor] = tentative_gScore + manhattan_heuristic(neighbor, goal);
neighbor.fScore = tentative_gScore + manhattan_heuristic(neighbor, goal);
/*
cout << "[" << neighbor.x << ", " << neighbor.y <<"]" <<" is cameFrom " \
<< "[" << current.x << ", " << current.y << "] ";
cout << "gScore: " << agent.gScore[neighbor] << " fScore: " << agent.fScore[neighbor] << endl << endl;
*/
agent.openSet.push(neighbor);
}
}
return false;
}
/********************************************************************************
reverse resumable A* (Backwards Search ignoring other agents)
the g value (measured distance to goal) is the true distance heuristic value.
if g value of requested node is not known, set goal at requestedNode.
*********************************************************************************/
bool get_true_distance_heuristic(Agent& agent, Map& map, const Node& requestNode)
{
bool goal_found = false;
//check requested Node
if (map.isObstacle(requestNode))
{
cout << "<get_true_distance_heuristic>: Requested node is an obstacle.\n";
agent.closedSet.insert({requestNode, MAX});
return false;
}
// start position is the goal position.
Node start = agent.getGoal(); // reversed, goal is start.
Node goal = requestNode;
// Initially, only the start node is known.
agent.openSet.push(start);
// The cost of going from start to start is zero.
agent.gScore.insert( {start, 0} ) ;
// For the first node, that value is completely heuristic.
agent.fScore.insert( {start, manhattan_heuristic(start, goal)} );
while (!agent.openSet.empty())
{
Node current = agent.openSet.top();
agent.openSet.pop();
if (current == goal)
{
goal_found = true;
}
agent.closedSet.insert({current, agent.fScore[current]}); // change closedSet to vector.
vector<Node> Neighbors;
map.getNeighbors(current, Neighbors);
for (Node& neighbor : Neighbors) {
// if neighbors not exist, creat new nodes
if(agent.cameFrom.find(neighbor) == agent.cameFrom.end()) {
agent.cameFrom.insert(make_pair(neighbor, current));
agent.gScore.insert(make_pair(neighbor, MAX));
agent.fScore.insert(make_pair(neighbor, MAX));
}
// Ignore the neighbor which is already evaluated
if (agent.closedSet.find(neighbor) != agent.closedSet.end())
continue;
// if neighbor node is obstacle, pust to closedSet and continue.
if (map.isObstacle(neighbor)) { // if neighbor is obstacles, add to closedSet.
agent.closedSet.insert( {neighbor, MAX} ); // fscore is set to be max.
continue;
}
// if count diagonal neighbor, uncomment this code.
// uint dist_neighbor = abs((int)(neighbor.x-current.x)) + abs((int)(neighbor.y-current.y)) == 2 ? 14:10;
uint dist_neighbor = 10;
uint tentative_gScore = agent.gScore[current] + dist_neighbor;
if (tentative_gScore >= agent.gScore[neighbor])
continue;
agent.cameFrom[neighbor] = current;
agent.gScore[neighbor] = tentative_gScore;
// if goal is already found, manhattan_heuristic is inaccurate to measure fScore.
// because manhanttan heuristic ignore obstacles.
// if goal is found, we simply add 20, why? for example, if we know node A's fScore
// and node B is A's neighbor, and if A is the only parent of B, then the cost of
// going from A to B is 10, so B_fSCore = A_fSCore + 10;
// in order for B to reach goal, it must go back to A,
// so add 10 to B_fScore again, total is 20;
if (!goal_found)
{
agent.fScore[neighbor] = tentative_gScore + manhattan_heuristic(neighbor, goal);
neighbor.fScore = tentative_gScore + manhattan_heuristic(neighbor, goal);
}
else
{
uint newfScore = agent.fScore[current] + 20;
agent.fScore[neighbor] = newfScore;
neighbor.fScore = newfScore;
}
/*
cout << "[" << neighbor.x << ", " << neighbor.y <<"]" <<" is cameFrom " \
<< "[" << current.x << ", " << current.y << "] ";
cout << "gScore: " << agent.gScore[neighbor] << " fScore: " << agent.fScore[neighbor] << endl << endl;
*/
agent.openSet.push(neighbor);
}
}
return true;
}
/*********************************************************************************/
void print_fScore(const Agent& agent, Map& map)
{
uint width = map.getWidth();
uint height = map.getHeight();
for (uint w = 0; w < width; ++w)
cout << "X\t";
cout << endl;
for (uint h = 1; h < height-1; ++h){
cout << "X\t";
for (uint w = 1; w < width-1; ++w){
Node n{w,h};
if (map.isObstacle(n)){
cout << "X\t";
continue;
}
auto search = agent.closedSet.find(n);
if (search != agent.closedSet.end()){
if (search->second == MAX)
cout << "INF\t";
else
cout << search->second << "\t";
}
else
cout << "0\t";
}
cout << "X\n";
}
for (uint w = 0; w < width; ++w)
cout << "X\t";
cout << endl;
}
/*********************************************************************************/
void print_gScore(const Agent& agent, Map& map)
{
uint width = map.getWidth();
uint height = map.getHeight();
for (uint w = 0; w < width; ++w)
cout << "X\t";
cout << endl;
for (uint h = 1; h < height-1; ++h){
cout << "X\t";
for (uint w = 1; w < width-1; ++w){
Node n{w,h};
if (map.isObstacle(n)){
cout << "X\t";
continue;
}
auto search = agent.gScore.find(n);
if (search != agent.gScore.end()){
if (search->second == MAX)
cout << "X\t";
else
cout << search->second << "\t";
}
else
cout << "0\t";
}
cout << "X\n";
}
for (uint w = 0; w < width; ++w)
cout << "X\t";
cout << endl;
}
/********************************************************************************/
void print_hash_map(const hash_map& h)
{
for (const auto& i : h)
{
cout << "Node: " << i.first << " Agent: ";
for (const auto& j : i.second)
cout << j->getName() << " ";
cout << endl;
}
cout << endl;
}
/*********************************************************************************/
void print_path(const list<Node> path)
{
for (const auto& i : path)
if (i == path.back())
cout << i << endl;
else
cout << i << "->";
}
/*********************************************************************************/
void print_neighbor_nodes(const vector<Node> v)
{
for(const auto& i : v)
cout << i << " ";
cout << endl;
}
/********************************************************************************/
void print_agents_path(const vector<list<Node>>& v)
{
int n = 0;
for(const auto& i : v)
{
cout << "Agent " << n++ << ": ";
print_path(i);
}
}
/*********************************************************************/
uint get_longest_agent_path(const vector<list<Node>>& v)
{
uint max = 0;
for (const auto& i : v)
{
if (max < i.size())
max = i.size();
}
return max;
}
/*********************************************************************/
void print_conflict_agents(const vector<vector<Agent*>>& conflict_agents_pairs)
{
cout << "Agents who have conflicts:\n";
for (const auto& v : conflict_agents_pairs)
{
cout << "< ";
for (const auto& i : v)
{
cout << i->getName() << " ";
}
cout << ">\n";
}
}
/*********************************************************************/
void print_space_map(const vector< unordered_map<Node, Agent*>> &space_map, Map &map)
{
for (auto i = 0; i < WINDOW_SIZE; i++)
{
cout << "\n>>>>>>>>>>>>> space_map at time [" << i << "] <<<<<<<<<<<<<<<\n";
map.print_map_with_agents(space_map[i]);
cout << endl;
}
}
/*********************************************************************/
void print_agents_current_position(vector<Agent*> agents)
{
cout << "agents current position:\n";
for (const auto& i : agents)
{
cout << i->getName() << ": " << i->get_current_node() << endl;
}
cout << endl;
}
/*********************************************************************/
// check face to face collisions, each colliion involves two agents, where agent1 walking from A to B, agent2 walking from B to A
bool check_collision_type2( const hash_map& t0, hash_map& t1, vector<vector<Node>>& collision_nodes_pairs)
{
bool conflict_exist = false;
for (const auto& h0 : t0)
{
char agent1_name = h0.second[0]->getName(); // agent 1 is walking from n0 to n0_next;
Node agent1_n0 = h0.first;
Node agent1_n1;
if(!h0.second[0]->getNextNode(agent1_n0, agent1_n1))
{
cout << "<detect_collision>:" << agent1_name << \
": there is no node after " << agent1_n0 << endl;
continue;
}
cout << agent1_name << " is walking from " << agent1_n0 <<" -> " << agent1_n1 << endl;
for (const auto& h1 : t1) {
char agent2_name = h1.second[0]->getName();
if(agent2_name == agent1_name) // if itself, skip.
continue;
Node agent2_n1 = h1.first;
// cout << "Agent " << agent2_name << " at t1: " << agent2_n1 << " ?= " << agent1_n0 << endl;
if (agent2_n1 == agent1_n0)
{
Node agent2_n0 = h1.second[0]->get_current_node();
// cout << agent2_n0 << "? === " << agent1_n1 << endl;
if (agent2_n0 == agent1_n1)
{// voila, c'est tout!
cout << "we need to stop " << agent2_name << " walking from " << agent2_n0 << " -> " << agent2_n1 << endl;
vector<Node> nodes_pair { agent1_n0, agent1_n1 };
collision_nodes_pairs.push_back( nodes_pair );
conflict_exist = true;
t1.erase(agent2_n0);
t1.erase(agent2_n1);
if (t1.empty())
break;
}
}
}
}
return conflict_exist;
}
/*********************************************************************/
//agents will not stay still, both move
void fix_pair ( hash_map& t0, hash_map& t1, Node a1_current_node, Node& a2_current_node, Map& m)
{
bool collision_fixed = false;
Agent* a1 = t0[a1_current_node][0];
Agent* a2 = t0[a2_current_node][0];
// gScore is the true distance to goal
uint a1_current_node_gScore = a1->gScore[a1_current_node];
uint a2_current_node_gScore = a2->gScore[a2_current_node];
Node a1_prev_node = a1->getPrevNode();
Node a2_prev_node = a2->getPrevNode();
// compare two gScore, if a1 lower, means a1 is closer to goal, a2 try to make way for a1
cout << a1->getName() << ": " << a1_current_node << " gScore: " << a1_current_node_gScore << " prev node: " << a1_prev_node <<endl;
cout << a2->getName() << ": " << a2_current_node << " gScore: " << a2_current_node_gScore << " prev node: " << a2_prev_node <<endl;
vector<Node> a1_possible_moves, a2_possible_moves;
m.get_clean_neighbors(a1_current_node, a1_possible_moves);
m.get_clean_neighbors(a2_current_node, a2_possible_moves);
// lowest gScore on top.
p_queue a1_gScore_queue;
p_queue a2_gScore_queue;
// depend on the cooperative level, neighbors can include more neighborhood, not just adjacent ones.
cout << "Agent " << a1->getName() << " ----possible next node gScore:\n";
for (auto& a1_next_possible_node : a1_possible_moves) {
if (a1_next_possible_node == a2_current_node)
continue; // exclude its original node.
a1_next_possible_node.gScore = a1->gScore[a1_next_possible_node];
cout << a1_next_possible_node << " = " << a1->gScore[a1_next_possible_node] << endl;
a1_gScore_queue.push(a1_next_possible_node);
}
cout << "Agent " << a2->getName() << " ----possible next node gScore:\n";
for ( auto& a2_next_possible_node : a2_possible_moves) {
if (a2_next_possible_node == a1_current_node)
continue;// exclude its original next node.
a2_next_possible_node.gScore = a2->gScore[a2_next_possible_node];
cout << a2_next_possible_node << " = " << a2->gScore[a2_next_possible_node] << endl;
a2_gScore_queue.push(a2_next_possible_node);
}
// case 1: one agent keep its path, the other changes. this is the best case!
if (a1_current_node_gScore <= a2_current_node_gScore) // check a2 queue i.e. agent A
{
cout << "Agent " << a2->getName() << " gscore checking ... " << endl;
p_queue q2 = a2_gScore_queue;
while (!q2.empty()) {
Node a2_next_node = q2.top();
if (a2_next_node == a2_prev_node)
{ // for now, we dont consider going back.
q2.pop();
continue;
}
cout << a2_next_node << " gscore = " << a2->gScore[a2_next_node] << endl;;
// we hope this is the next node for a2.
// but we first check if this node is gona taken by others.
if ( t1.find(a2_next_node) != t1.end() )
continue;
cout << "find fix! inserting node .... " << a2_next_node << endl;
list<Node> l2 = {a2_next_node, a2_current_node};
cout << "inserting path to front....";
print_path(l2);
a2->insert_path_after_front( l2 ); // a2 will walk back to its original path
collision_fixed = true;
break;
}
}
if (!collision_fixed)
{
// a1 changes routes, a2 stays on course., check a1 queue. i.e. agent B
cout << "Agent " << a1->getName() << " gscore checking ... " << endl;
p_queue q1 = a1_gScore_queue;
while(!q1.empty()) {
Node a1_next_node = q1.top();
if (a1_next_node == a1_prev_node) {
q1.pop();
continue;
}
cout << a1_next_node << " gscore = " << a1->gScore[a1_next_node] << endl;
// we hope this is the next node for a2.
// check if this node is taken by other agents...
if(t1.find(a1_next_node) != t1.end()) // meaning this node will be occupied by other agents
continue;
cout << "find fix! inserting node .... " << a1_next_node << endl;
// now we got a free node, no other agents are gona take it, so a1 will go to that node temporarily.
list<Node> l1 = {a1_next_node, a1_current_node}; // we assume a1 will walk back. if there is a collision, we deal with it later...
cout << "inserting path to front....";
print_path( l1 );
a1->insert_path_after_front( l1 );
cout << "new path is\n";
a1->print_path();
collision_fixed = true;
break;
}
}
if (collision_fixed)
return;
else
cout << "type 2 collision not fixed!\n";
}
/*********************************************************************/
void fix_agents ( hash_map& hmap_t0, hash_map& hmap_t1, vector<vector<Node>>& collision_nodes_pairs, Map& m )
{
cout << "fix_agents now\n";
uint n_pairs = collision_nodes_pairs.size();
cout << "n_pairs = " << n_pairs << endl;
cout << "\n\n";
for (auto i = 0; i < n_pairs; i++)
{
Node n1, n2;
n1 = collision_nodes_pairs[i][0];
n2 = collision_nodes_pairs[i][1];
cout << "n1: " << n1 << ", n2: " << n2 << endl;
fix_pair( hmap_t0, hmap_t1, n1, n2, m );
}
}
/*********************************************************************/
void update_space_map(vector<unordered_map<Node, Agent*>> &space_map, Agent* agent)
{
list<Node> l;
agent->get_portion_path( l );
for (auto i = 0; i < WINDOW_SIZE; ++i)
{
space_map[i][l.front()] = agent;
l.pop_front();
}
}
#endif
| 32.888268 | 136 | 0.572504 | [
"vector"
] |
ddc70f6f13fbafdc8347bb7fb427fbae2a76f34b | 5,078 | cpp | C++ | src/util/gui/flowlayout.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/util/gui/flowlayout.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/util/gui/flowlayout.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "flowlayout.h"
#include <QWidget>
namespace LeechCraft
{
namespace Util
{
FlowLayout::FlowLayout (QWidget *parent,
int margin, int hspace, int vspace)
: QLayout { parent }
, HSpace_ { hspace }
, VSpace_ { vspace }
{
setContentsMargins (margin, margin, margin, margin);
}
FlowLayout::FlowLayout (int margin, int hspace, int vspace)
: FlowLayout { nullptr, margin, hspace, vspace }
{
}
FlowLayout::~FlowLayout ()
{
while (const auto item = takeAt (0))
delete item;
}
void FlowLayout::addItem (QLayoutItem *item)
{
ItemList_ << item;
}
int FlowLayout::horizontalSpacing () const
{
return HSpace_ >= 0 ?
HSpace_ :
SmartSpacing (QStyle::PM_LayoutHorizontalSpacing);
}
int FlowLayout::verticalSpacing () const
{
return VSpace_ >= 0 ?
VSpace_ :
SmartSpacing (QStyle::PM_LayoutVerticalSpacing);
}
Qt::Orientations FlowLayout::expandingDirections () const
{
return 0;
}
bool FlowLayout::hasHeightForWidth () const
{
return true;
}
int FlowLayout::heightForWidth (int width) const
{
return DoLayout ({ 0, 0, width, 0 }, true);
}
int FlowLayout::count () const
{
return ItemList_.size ();
}
QLayoutItem* FlowLayout::itemAt (int idx) const
{
return ItemList_.value (idx);
}
QLayoutItem* FlowLayout::takeAt (int idx)
{
if (idx >= 0 && idx < ItemList_.size ())
return ItemList_.takeAt (idx);
else
return nullptr;
}
QSize FlowLayout::minimumSize () const
{
QSize size;
for (const auto item : ItemList_)
size = size.expandedTo (item->minimumSize ());
size += QSize { margin () * 2, margin () * 2 };
return size;
}
void FlowLayout::setGeometry (const QRect& rect)
{
QLayout::setGeometry (rect);
DoLayout (rect, false);
}
QSize FlowLayout::sizeHint () const
{
return minimumSize ();
}
int FlowLayout::DoLayout (const QRect& rect, bool testOnly) const
{
int left = 0, top = 0, right = 0, bottom = 0;
getContentsMargins (&left, &top, &right, &bottom);
const auto& effectiveRect = rect.adjusted (left, top, -right, -bottom);
int x = effectiveRect.x ();
int y = effectiveRect.y ();
int lineHeight = 0;
for (const auto item : ItemList_)
{
const auto widget = item->widget ();
int spaceX = horizontalSpacing ();
if (spaceX == -1)
spaceX = widget->style ()->layoutSpacing (QSizePolicy::PushButton,
QSizePolicy::PushButton, Qt::Horizontal);
int spaceY = verticalSpacing ();
if (spaceY == -1)
spaceY = widget->style ()->layoutSpacing (QSizePolicy::PushButton,
QSizePolicy::PushButton, Qt::Vertical);
const auto& sizeHint = item->sizeHint ();
const int hintWidth = sizeHint.width ();
int nextX = x + hintWidth + spaceX;
if (nextX - spaceX > effectiveRect.right () &&
lineHeight > 0)
{
x = effectiveRect.x ();
y += lineHeight + spaceY;
nextX = x + hintWidth + spaceX;
lineHeight = 0;
}
if (!testOnly)
item->setGeometry ({ { x, y }, sizeHint });
x = nextX;
lineHeight = std::max (lineHeight, sizeHint.height ());
}
return y + lineHeight - rect.y () + bottom;
}
int FlowLayout::SmartSpacing (QStyle::PixelMetric pm) const
{
const auto obj = parent ();
if (!obj)
return -1;
else if (obj->isWidgetType ())
{
const auto pw = static_cast<QWidget*> (obj);
return pw->style ()->pixelMetric (pm, 0, pw);
}
else
return static_cast<QLayout*> (obj)->spacing ();
}
}
}
| 26.726316 | 78 | 0.663056 | [
"object"
] |
ddd4159a6527593c8acedb5546d40b65d9e89f16 | 1,256 | cpp | C++ | src/metafilelib.cpp | Light-Keeper/metafile | e8cd66c33675514d95e5eaeb24da95781f943bd8 | [
"BSD-2-Clause"
] | 1 | 2021-07-22T02:43:12.000Z | 2021-07-22T02:43:12.000Z | src/metafilelib.cpp | Light-Keeper/metafile | e8cd66c33675514d95e5eaeb24da95781f943bd8 | [
"BSD-2-Clause"
] | null | null | null | src/metafilelib.cpp | Light-Keeper/metafile | e8cd66c33675514d95e5eaeb24da95781f943bd8 | [
"BSD-2-Clause"
] | null | null | null | /* Copyright (C) 2015, Vadym Ianushkevych ( vadik.ya@gmail.com )
* All Rights Reserved.
* You may use, distribute and modify this code under the terms
* of the Simplified BSD License. You should have received a copy
* of the Simplified BSD License with this file. If not, see
* http://opensource.org/licenses/BSD-2-Clause
*/
#include "metafilelib.h"
#include "metafile.h"
#include <assert.h>
namespace metafile
{
MetafileLib::MetafileLib(const std::shared_ptr<FileAccessInterfaceAbstractFactory> &factory)
: m_AccessFactory(factory)
{
assert(m_AccessFactory);
}
MetafileLib::~MetafileLib()
{
}
std::shared_ptr<Metafile> MetafileLib::OpenInternal(const std::string &path)
{
auto fileAccess = m_AccessFactory->CreateFile();
fileAccess->UseFile(path);
auto file = std::make_shared<Metafile>();
file->SetFileAccessInterface(fileAccess);
return file;
}
std::shared_ptr<Metafile> MetafileLib::CreateNewFile(const std::string &path, const std::vector<std::string> &threadNames)
{
auto file = OpenInternal(path);
file->InitEmpty(threadNames);
return file;
}
std::shared_ptr<Metafile> MetafileLib::OpenFile(const std::string &path)
{
auto file = OpenInternal(path);
file->Init();
return file;
}
} // namespace
| 24.627451 | 123 | 0.730096 | [
"vector"
] |
dddb058b26067492e6fd64246bd4874148265266 | 3,160 | cpp | C++ | src/fsc/object/base/line.cpp | nnoell/fsc | 19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb | [
"BSD-3-Clause"
] | 1 | 2018-11-26T19:06:52.000Z | 2018-11-26T19:06:52.000Z | src/fsc/object/base/line.cpp | nnoell/fsc | 19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb | [
"BSD-3-Clause"
] | null | null | null | src/fsc/object/base/line.cpp | nnoell/fsc | 19c6e471fa0712c6fe4817b08d3bf8c6ae2b16fb | [
"BSD-3-Clause"
] | null | null | null | //----------------------------------------------------------------------------------------------------------------------
// Copyright : (c) Julian Bouzas 2018
// License : BSD3-style (see LICENSE)
// Maintainer : Julian Bouzas - nnoell3[at]gmail.com
//----------------------------------------------------------------------------------------------------------------------
// FSC
#include "line.hpp"
#include "../../pipeline.hpp"
namespace fsc {
namespace object {
namespace base {
Line::Line(std::vector<glm::vec3> points, glm::vec4 color,
transformer::Translate translate, transformer::Scale scale, transformer::Rotate rotate, transformer::Model model) :
Simple(std::move(color), std::move(translate), std::move(scale), std::move(rotate), std::move(model)),
points_(std::move(points)),
num_vertices_(0),
vertices_(nullptr),
vao_(0),
vbo_(0) {
Update();
}
Line::~Line() {
// Release VAO and VBO
if (vbo_)
glDeleteBuffers(1, &vbo_);
if (vao_)
glDeleteVertexArrays(1, &vao_);
}
void Line::SetPoints(std::vector<glm::vec3> points) {
points_ = std::move(points);
Update();
}
void Line::Draw() const {
// Return if there are no points
if (points_.size() == 0)
return;
// Set the pipeline
Pipeline::GetInstance().SetBool("is_text_", false);
Pipeline::GetInstance().SetMat4("model_", GetModel());
Pipeline::GetInstance().SetVec4("object_color_", GetColor());
Pipeline::GetInstance().SetVec4("light_color_", glm::vec4{ 1.0f, 1.0f, 1.0f, 1.0f});
// Draw
glBindVertexArray(vao_);
glDrawArrays(GL_LINES, 0, num_vertices_);
glBindVertexArray(0);
}
void Line::Update() {
// Return if there are no points
if (points_.size() == 0)
return;
// Update the number of vertices
num_vertices_ = points_.size() * 6;
// Allocate the vertices array
vertices_ = std::shared_ptr<float []> {new float[num_vertices_], std::default_delete<float[]>()};
// Set the vertices array
unsigned int i = 0;
for (auto&& p : points_) {
vertices_[i++] = p.x;
vertices_[i++] = p.y;
vertices_[i++] = p.z;
vertices_[i++] = 1.0f;
vertices_[i++] = 0.0f;
vertices_[i++] = 0.0f;
}
// Release VAO and VBO
if (vbo_)
glDeleteBuffers(1, &vbo_);
if (vao_)
glDeleteVertexArrays(1, &vao_);
// Generate VAO and VBO
glGenVertexArrays(1, &vao_);
glGenBuffers(1, &vbo_);
// Bind VAO
glBindVertexArray(vao_);
// Bind and set VBO
glBindBuffer(GL_ARRAY_BUFFER, vbo_);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * num_vertices_, vertices_.get(), GL_STATIC_DRAW);
// Configure Vertex
constexpr unsigned int stride = 6;
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(float) * stride, (void*)0);
glEnableVertexAttribArray(0);
// Configure Extra
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * stride, (void*)(4 * sizeof(float)));
glEnableVertexAttribArray(1);
// Unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
} // namespace base
} // namespace object
} // namespace fsc | 28.727273 | 121 | 0.587025 | [
"object",
"vector",
"model"
] |
50b7d922ff034dd092f9aea9cdbb092f5910194a | 8,002 | cpp | C++ | Development/HeadMovement/ImageProcessing/src/Contour.cpp | sheldonrobinson/face-gesture-api | 3c92f6033d667445067643399a73478f9449ebe2 | [
"BSD-3-Clause"
] | null | null | null | Development/HeadMovement/ImageProcessing/src/Contour.cpp | sheldonrobinson/face-gesture-api | 3c92f6033d667445067643399a73478f9449ebe2 | [
"BSD-3-Clause"
] | null | null | null | Development/HeadMovement/ImageProcessing/src/Contour.cpp | sheldonrobinson/face-gesture-api | 3c92f6033d667445067643399a73478f9449ebe2 | [
"BSD-3-Clause"
] | null | null | null | #include "dolslr/doldef.h"
#include "dolslr/Contour.h"
#include "opencv2/legacy/legacy.hpp"
using namespace std;
using namespace cv;
Contour::Contour(void)
{
}
Contour::~Contour(void)
{
}
void Contour::InitProcess(Mat& frame)
{
if(frame.channels() == 3)
cvtColor(frame, grayFrame_, CV_BGR2GRAY);
else
grayFrame_ = frame.clone();
//resize(grayFrame_, grayFrame_, size_);
}
void Contour::FindLargestContour(Mat& frame, vector<Point>& handContour)
{
double maxSize = -1;
int maxInd = -1;
InitProcess(frame);
// Find all of the contours.
findContours(grayFrame_, contours_, hierarchy_, CV_RETR_LIST, CHAIN_APPROX_SIMPLE);
// Find the biggest contour over the current frame.
for( size_t i = 0; i < contours_.size(); i++ )
{
double actSize = contourArea(contours_[i]);
if(actSize > maxSize)
{
maxSize = actSize;
handContour = contours_[i];
maxInd = i;
}
}
}
void Contour::ChainCode(vector<Point>& contour, vector<int>& chainCode)
{
int length = contour.size();
for(int i = 0; i < length; i++)
{
int j = ( i + 1 ) % length;
if( contour[i].x == contour[j].x && contour[i].y > contour[j].y )
chainCode.push_back(2);
else if( contour[i].x < contour[j].x && contour[i].y > contour[j].y )
chainCode.push_back(1);
else if( contour[i].x < contour[j].x && contour[i].y == contour[j].y )
chainCode.push_back(0);
else if( contour[i].x < contour[j].x && contour[i].y < contour[j].y )
chainCode.push_back(7);
else if( contour[i].x == contour[j].x && contour[i].y < contour[j].y )
chainCode.push_back(6);
else if( contour[i].x > contour[j].x && contour[i].y < contour[j].y )
chainCode.push_back(5);
else if( contour[i].x > contour[j].x && contour[i].y == contour[j].y )
chainCode.push_back(4);
else
chainCode.push_back(3);
}
}
void Contour::SmoothChainCode(vector<int>& chainCode, vector<double>& chainCodeSmoothed)
{
int length = chainCode.size();
// v_new(n) = (1/16)*(v(n-2) + 4* v(n-1) + 6* v(n) + 4*(v(n+1) + v(n+2))
for(int i = 0; i < length; i++)
{
int ip1 = ( i + 1 ) % length;
int ip2 = ( i + 2 ) % length;
int im1 = i == 0 ? length - 1 : i - 1;
int im2 = i == 0 ? length - 2 : ( i == 1 ? length - 1 : i - 2 );
chainCodeSmoothed.push_back( 1.0/16.0 * (chainCode[im2] + 4.0*chainCode[im1] + 6.0*chainCode[i] + 4.0*chainCode[ip1] + chainCode[ip2]) );
}
}
void Contour::DeriveChainCode(vector<double>& chainCode, vector<double>& chainCodeFirstDiff, vector<double>& chainCodeSecondDiff)
{
int length = chainCode.size();
for (int i = 0; i < length; i++)
{
int ip1 = ( i + 1 ) % length;
int im1 = i == 0 ? length - 1 : i - 1;
chainCodeFirstDiff.push_back(chainCode[ip1] - chainCode[im1]);
chainCodeSecondDiff.push_back(chainCode[ip1] - 2 * chainCode[i] + chainCode[im1]);
}
}
void Contour::DrawContour(Mat& image, vector<Point>& contour, Scalar& color, int thickness )
{
//int length = contour.size();
////int r = 0, g = 0, b = 0;
//for(int i = 0; i < length; i++)
//{
// //Scalar color = Scalar(r % 255, b % 255, g % 255);
// int j = ( i + 1 ) % length;
// line(image, contour[i], contour[j], color, thickness);
// //r += 2, g += 2, b += 2;
//}
vector<vector<Point> > contoursArray;
contoursArray.push_back(contour);
drawContours(image, contoursArray, 0, color, thickness);
}
void Contour::DrawContour2f(Mat& image, vector<Point2f>& contour, Scalar& color, int thickness )
{
vector<vector<Point2f> > contoursArray;
contoursArray.push_back(contour);
drawContours(image, contoursArray, 0, color, thickness);
}
void Contour::ILocateConvexityDefects(vector<Point>& contour, vector<int>& hull, vector<Point>& startPoint, vector<Point>& endPoint, vector<Point>& depthPoint, vector<float>& depth)
{
if(hull.size() > 0 && contour.size() > 0)
{
CvSeq* contourPoints;
CvSeq* defects;
CvMemStorage* storage;
CvMemStorage* strDefects;
CvMemStorage* contourStr;
CvConvexityDefect *defectArray = 0;
startPoint.clear();
endPoint.clear();
depthPoint.clear();
depth.clear();
strDefects = cvCreateMemStorage();
defects = cvCreateSeq( CV_SEQ_KIND_GENERIC|CV_32SC2, sizeof(CvSeq),sizeof(CvPoint), strDefects );
// Transform our vector<Point> into a CvSeq* object of CvPoint.
contourStr = cvCreateMemStorage();
contourPoints = cvCreateSeq(CV_SEQ_KIND_GENERIC|CV_32SC2, sizeof(CvSeq), sizeof(CvPoint), contourStr);
for(int i = 0; i < (int)contour.size(); i++)
{
CvPoint cp = {contour[i].x, contour[i].y};
cvSeqPush(contourPoints, &cp);
}
// Now, we do the same thing with the hull index
int count = (int)hull.size();
// int hullK[count];
int* hullK = (int*)malloc(count * sizeof(int));
for(int i = 0; i < count; i++)
hullK[i] = hull.at(i);
CvMat hullMat = cvMat(1, count, CV_32SC1, hullK);
// Calculate convexity defects
storage = cvCreateMemStorage(0);
defects = cvConvexityDefects(contourPoints, &hullMat, storage);
defectArray = (CvConvexityDefect*)malloc(defects->total * sizeof(CvConvexityDefect));
cvCvtSeqToArray(defects, defectArray, CV_WHOLE_SEQ);
//printf("DefectArray %i %i\n",defectArray->end->x, defectArray->end->y);
// Store defects points in the convexDefects parameter.
for(int i = 0; i < defects->total; i++)
{
CvPoint ptf;
ptf.x = defectArray[i].start->x;
ptf.y = defectArray[i].start->y;
startPoint.push_back(ptf);
ptf.x = defectArray[i].end->x;
ptf.y = defectArray[i].end->y;
endPoint.push_back(ptf);
ptf.x = defectArray[i].depth_point->x;
ptf.y = defectArray[i].depth_point->y;
depthPoint.push_back(ptf);
depth.push_back(defectArray[i].depth);
}
// Release memory
cvReleaseMemStorage(&contourStr);
cvReleaseMemStorage(&strDefects);
cvReleaseMemStorage(&storage);
free(hullK);
free(defectArray);
}
}
void Contour::ISnakeImage(Mat& contourMask, vector<Point>& activeContour)
{
IplImage *iplContourMask = new IplImage(contourMask);
CvMemStorage* storage = cvCreateMemStorage(0);
CvSeq* contours = 0;
cvThreshold(iplContourMask, iplContourMask, 141, 255, CV_THRESH_BINARY);
cvFindContours(iplContourMask, storage, &contours, sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
if(!contours)
{
delete iplContourMask;
cvReleaseMemStorage(&storage);
return;
}
int length = contours->total;
if(length < 10)
{
delete iplContourMask;
cvReleaseMemStorage(&storage);
return;
}
CvPoint* points = new CvPoint[length];
CvSeqReader reader;
CvPoint pt = cvPoint(0, 0);
CvSeq* contour2 = contours;
cvStartReadSeq(contour2, &reader);
for(int i = 0; i < length; i++)
{
CV_READ_SEQ_ELEM(pt, reader);
points[i] = pt;
}
cvReleaseMemStorage(&storage);
float alpha = snakeParam_.ialpha / 100.0f;
float beta = snakeParam_.ibeta / 100.0f;
float gamma = snakeParam_.igamma / 100.0f;
cvSnakeImage(iplContourMask, points, length, &alpha, &beta, &gamma, snakeParam_.coeff_usage, snakeParam_.size, snakeParam_.criteria, snakeParam_.calc_gradient);
for(int i = 0; i < length; i++)
activeContour.push_back(Point(points[i].x, points[i].y));
delete iplContourMask;
delete[] points;
}
void Contour::SetSnakeParameters(int alpha, int beta, int gamma, double perimeter, Size size, int maxIter, double eps)
{
snakeParam_.ialpha = alpha;
snakeParam_.ibeta = beta;
snakeParam_.igamma = gamma;
snakeParam_.perimeter = perimeter;
// Different uses of the previous three parameters:
// - CV_VALUE - indicates that each of alpha, beta, gamma is a pointer to a single value to be used for all points;
// - CV_ARRAY - indicates that each of alpha, beta, gamma is a pointer to an array of coefficients different for all the points of the snake. All the arrays must have the size equal to the contour size.
snakeParam_.coeff_usage = CV_VALUE;
snakeParam_.size.width = size.width;
snakeParam_.size.height = size.height;
snakeParam_.criteria.type = CV_TERMCRIT_ITER;
snakeParam_.criteria.max_iter = maxIter;
snakeParam_.criteria.epsilon = eps;
snakeParam_.calc_gradient = 0;
}
| 27.881533 | 203 | 0.680955 | [
"object",
"vector",
"transform"
] |
50b89dfc44e88398b9dfe2a094927fb42589dd05 | 6,474 | cpp | C++ | ccore/tst/utest-ttsas.cpp | JosephChataignon/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 1,013 | 2015-01-26T19:50:14.000Z | 2022-03-31T07:38:48.000Z | ccore/tst/utest-ttsas.cpp | peterlau0626/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 542 | 2015-01-20T16:44:32.000Z | 2022-01-29T14:57:20.000Z | ccore/tst/utest-ttsas.cpp | peterlau0626/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 262 | 2015-03-19T07:28:12.000Z | 2022-03-30T07:28:24.000Z | /*!
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
*/
#include <gtest/gtest.h>
#include <pyclustering/cluster/ttsas.hpp>
#include <pyclustering/utils/metric.hpp>
#include "samples.hpp"
#include "utenv_check.hpp"
using namespace pyclustering;
using namespace pyclustering::clst;
static void
template_ttsas_length_process_data(const dataset_ptr p_data,
const double & p_threshold1,
const double & p_threshold2,
const std::vector<size_t> & p_expected_cluster_length,
const distance_metric<point> & p_metric = distance_metric_factory<point>::euclidean()) {
ttsas_data output_result;
ttsas solver(p_threshold1, p_threshold2, p_metric);
solver.process(*p_data, output_result);
const dataset & data = *p_data;
const cluster_sequence & actual_clusters = output_result.clusters();
const representative_sequence & actual_repr = output_result.representatives();
for (auto & repr : actual_repr)
ASSERT_EQ(data[0].size(), repr.size());
ASSERT_EQ(actual_repr.size(), actual_clusters.size());
ASSERT_CLUSTER_SIZES(data, actual_clusters, p_expected_cluster_length);
}
TEST(utest_ttsas, allocation_sample_simple_01) {
const std::vector<size_t> expected_clusters_length = { 5, 5 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1.0, 2.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_sample_simple_01_euclidean) {
const std::vector<size_t> expected_clusters_length = { 5, 5 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1.0, 2.0, expected_clusters_length, distance_metric_factory<point>::euclidean());
}
TEST(utest_ttsas, allocation_sample_simple_01_euclidean_square) {
const std::vector<size_t> expected_clusters_length = { 5, 5 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1.0, 2.0, expected_clusters_length, distance_metric_factory<point>::euclidean_square());
}
TEST(utest_ttsas, allocation_sample_simple_01_manhattan) {
const std::vector<size_t> expected_clusters_length = { 5, 5 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1.0, 2.0, expected_clusters_length, distance_metric_factory<point>::manhattan());
}
TEST(utest_ttsas, allocation_sample_simple_01_chebyshev) {
const std::vector<size_t> expected_clusters_length = { 5, 5 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1.0, 2.0, expected_clusters_length, distance_metric_factory<point>::chebyshev());
}
TEST(utest_ttsas, allocation_sample_simple_01_minkowski) {
const std::vector<size_t> expected_clusters_length = { 5, 5 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1.0, 2.0, expected_clusters_length, distance_metric_factory<point>::minkowski(2.0));
}
TEST(utest_ttsas, allocation_sample_simple_01_user_defined) {
const std::vector<size_t> expected_clusters_length = { 5, 5 };
auto user_metric = [](const point & p1, const point & p2) { return euclidean_distance(p1, p2); };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 1.0, 2.0, expected_clusters_length, distance_metric_factory<point>::user_defined(user_metric));
}
TEST(utest_ttsas, allocation_one_allocation_sample_simple_01) {
const std::vector<size_t> expected_clusters_length = { 10 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_01), 10.0, 20.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_sample_simple_02) {
const std::vector<size_t> expected_clusters_length = { 5, 8, 10 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_02), 1.0, 2.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_one_allocation_sample_simple_02) {
const std::vector<size_t> expected_clusters_length = { 23 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_02), 10.0, 20.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_sample_simple_03) {
const std::vector<size_t> expected_clusters_length = { 10, 10, 10, 30 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_03), 1.0, 2.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_one_dimension_points_1) {
const std::vector<size_t> expected_clusters_length = { 10, 10 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_07), 1.0, 2.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_one_allocation_one_dimension_points_1) {
const std::vector<size_t> expected_clusters_length = { 20 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_07), 10.0, 20.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_one_dimension_points_2) {
const std::vector<size_t> expected_clusters_length = { 10, 20 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 1.0, 2.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_one_allocation_one_dimension_points_2) {
const std::vector<size_t> expected_clusters_length = { 30 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_09), 10.0, 20.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_three_dimension_points_2) {
const std::vector<size_t> expected_clusters_length = { 10, 10 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 1.0, 2.0, expected_clusters_length);
}
TEST(utest_ttsas, allocation_three_allocation_one_dimension_points_2) {
const std::vector<size_t> expected_clusters_length = { 20 };
template_ttsas_length_process_data(simple_sample_factory::create_sample(SAMPLE_SIMPLE::SAMPLE_SIMPLE_11), 10.0, 20.0, expected_clusters_length);
} | 43.449664 | 206 | 0.7751 | [
"vector"
] |
50bfac924dde7913bfcab236a656fbe371a7950a | 2,789 | hpp | C++ | source/blind_jump/entity/entity.hpp | Manolomon/blind-jump-portable | 6149d8b639bc9c50533b7eb5fc26884addf563fd | [
"MIT"
] | 140 | 2019-08-31T02:52:17.000Z | 2022-03-25T12:38:23.000Z | source/blind_jump/entity/entity.hpp | Manolomon/blind-jump-portable | 6149d8b639bc9c50533b7eb5fc26884addf563fd | [
"MIT"
] | 8 | 2020-11-30T11:29:56.000Z | 2021-08-08T16:39:17.000Z | source/blind_jump/entity/entity.hpp | Manolomon/blind-jump-portable | 6149d8b639bc9c50533b7eb5fc26884addf563fd | [
"MIT"
] | 5 | 2020-07-08T23:44:32.000Z | 2021-11-04T21:17:52.000Z | #pragma once
#include <algorithm>
#include "graphics/sprite.hpp"
class Platform;
class Game;
class Entity {
public:
using Health = s32;
using Id = u32;
Entity();
Entity(Health health);
// Entity(Entity&) = delete;
void update(Platform&, Game&, Microseconds);
Health get_health() const;
bool alive() const;
const Sprite& get_sprite() const;
Sprite& get_sprite();
void add_health(Health amount);
const Vec2<Float>& get_position() const;
static constexpr bool multiface_sprite = false;
static constexpr bool has_shadow = false;
static constexpr bool multiface_shadow = false;
void set_health(Health health)
{
health_ = health;
}
bool visible() const
{
return visible_;
}
// IMPORTANT! The automatically assigned Entity ids are guaranteed to be
// synchronized between multiplayer games at the start of each level. But
// after the level has started, there is no guarantee that newly spawned
// entities will have the same ID. If you need to synchronize entities
// created after level generation, you should exercise caution. See, for
// example, how the game allows players to trade items. One player drops an
// item chest, and sends an event over the network, with the item, and the
// entity id of the item chest. Then, the receiver must check that no
// existing entities within the same group have a matching id. In the event
// of an id collision, the receiver should not spawn the new entity, and
// send its own event back to the sender, if appropriate.
static void reset_ids();
static Id max_id();
// Be careful with this function! Before calling, you should make sure that
// no similar extant entities share the same id.
void override_id(Id id);
Id id() const
{
return id_;
}
// This is VERY BAD CODE. Basically, the rendering loop already determines
// which objects are visible within the window when drawing sprites. To save
// CPU cycles, we are marking an object visible during a rendering pass, so
// that the game logic doesn't need to repeat the visibility calculation.
void mark_visible(bool visible)
{
visible_ = visible;
}
void on_death(Platform&, Game&)
{
}
void set_position(const Vec2<Float>& position);
protected:
void debit_health(Health amount = 1)
{
health_ = std::max(Health(0), health_ - amount);
}
void kill()
{
health_ = 0;
}
Sprite sprite_;
Vec2<Float> position_;
private:
Health health_;
Id id_;
bool visible_ = false;
};
#include <memory>
template <typename T> using EntityRef = std::unique_ptr<T, void (*)(T*)>;
| 21.96063 | 80 | 0.661169 | [
"object"
] |
50c9298693b54de16b213e73cade86ac7ee35bbd | 7,282 | hpp | C++ | src/json/parser.hpp | Lythenas/json-query | 3614deade41d66dd0e99442e53ac5a76dd5ef5fc | [
"MIT"
] | 1 | 2020-08-02T19:15:45.000Z | 2020-08-02T19:15:45.000Z | src/json/parser.hpp | Lythenas/json-query | 3614deade41d66dd0e99442e53ac5a76dd5ef5fc | [
"MIT"
] | null | null | null | src/json/parser.hpp | Lythenas/json-query | 3614deade41d66dd0e99442e53ac5a76dd5ef5fc | [
"MIT"
] | null | null | null | #ifndef JSON_QUERY_JSON_PARSER_HPP
#define JSON_QUERY_JSON_PARSER_HPP
#ifdef TRACE
#define BOOST_SPIRIT_DEBUG
#endif
#include <boost/phoenix.hpp>
#include <boost/spirit/home/qi/directive/lexeme.hpp>
#include <boost/spirit/home/qi/nonterminal/debug_handler.hpp>
#include <boost/spirit/home/support/iterators/line_pos_iterator.hpp>
#include <boost/spirit/home/support/iterators/multi_pass.hpp>
#include <boost/spirit/include/qi.hpp>
#include <iterator>
#include <memory>
#include <stdexcept>
#include "../errors.hpp"
#include "types.hpp"
namespace json {
namespace spirit = boost::spirit;
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
class FailedToParseJsonException : public std::exception {
const char* reason;
public:
FailedToParseJsonException(const char* reason) : reason(reason) {}
virtual const char* what() const noexcept override { return reason; }
};
class InnerSyntaxError : public std::exception {
typedef boost::spirit::line_pos_iterator<std::string::const_iterator>
Iterator;
public:
Iterator first;
Iterator last;
Iterator error_pos;
boost::spirit::info info;
InnerSyntaxError(Iterator first, Iterator last, Iterator error_pos,
const boost::spirit::info& info)
: first(first), last(last), error_pos(error_pos), info(info) {}
virtual const char* what() const noexcept override {
return "Syntax error";
}
};
class SyntaxError : public std::exception {
typedef boost::spirit::line_pos_iterator<std::string::const_iterator>
Iterator;
std::size_t line_num;
// 0 indexed column
std::size_t col_num;
std::string line;
std::string expected;
std::string what_;
public:
SyntaxError(Iterator begin, Iterator current, Iterator end,
const std::string& what): expected(what) {
line_num = spirit::get_line(current);
Iterator current_line_start = spirit::get_line_start(begin, current);
// 0 indexed column
col_num = spirit::get_column(current_line_start, current) - 1;
boost::iterator_range<Iterator> line_range =
spirit::get_current_line(current_line_start, current, end);
line = std::string(line_range.begin(), line_range.end());
what_ = "Expected " + expected + " but got \"" + line[col_num] + "\"";
}
// to make this a proper std::exception
// but not used by me (except maybe in tests)
virtual const char* what() const noexcept override { return what_.c_str(); }
template <typename Out> void pretty_print(Out& o) const {
o << "Error in json (line " << line_num << ":" << col_num << ") expected " + expected + "\n";
}
};
// Grammar created using https://tools.ietf.org/html/rfc8259 and
// https://www.json.org/
// TODO support unicode
template <typename Iterator>
struct json_grammar : qi::grammar<Iterator, JsonNode(), ascii::space_type> {
json_grammar() : json_grammar::base_type(root) {
using boost::phoenix::bind;
using boost::phoenix::construct;
using boost::phoenix::if_;
using boost::phoenix::new_;
using boost::phoenix::throw_;
using boost::phoenix::val;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::_val;
using qi::char_;
using qi::digit;
using qi::fail;
using qi::int_;
using qi::lexeme;
using qi::lit;
using qi::on_error;
using qi::rule;
using qi::uint_;
root = value[_val = construct<JsonNode>(_1)];
value = (literal | object | array | number |
string)[_val = construct<JsonNode>(_1)];
literal = lit("false")[_val = val(JsonLiteral(JSON_FALSE))] |
lit("true")[_val = val(JsonLiteral(JSON_TRUE))] |
lit("null")[_val = val(JsonLiteral(JSON_NULL))];
object = ('{' > -(member % ',') >
'}')[if_(_1)[_val = construct<JsonObject>(*_1)]
.else_[_val = construct<JsonObject>()]];
member =
(string_inner > ':' >
value)[_val = construct<std::pair<std::string, JsonNode>>(_1, _2)];
array = ('[' > -(value % ',') >
']')[if_(_1)[_val = construct<JsonArray>(*_1)]
.else_[_val = construct<JsonArray>()]];
number = qi::as_string[lexeme[-char_('-') >> +digit >> -frac >> -exp]]
[_val = construct<JsonNumber>(_1)];
frac = char_('.') >> +digit;
exp = (char_('e') | char_('E')) >> -char_('-') >> +digit;
string = string_inner[_val = construct<JsonString>(_1)];
string_inner = '"' > lexeme[+(unescaped | escaped)[_val += _1]] > '"';
unescaped = char_ - '"' - '\\' - ascii::cntrl;
escaped =
char_('\\') > (char_('\\') | char_('"') | char_('n') | char_('b') |
char_('f') | char_('r') | char_('t') |
(char_('u') >> qi::repeat(1, 4)[ascii::xdigit]));
on_error<fail>(root,
throw_(construct<InnerSyntaxError>(_1, _2, _3, _4)));
}
qi::rule<Iterator, JsonNode(), ascii::space_type> root;
qi::rule<Iterator, JsonNode(), ascii::space_type> value;
qi::rule<Iterator, JsonNode()> literal;
qi::rule<Iterator, JsonNode(), ascii::space_type> object;
qi::rule<Iterator, std::pair<std::string, JsonNode>(), ascii::space_type>
member;
qi::rule<Iterator, JsonNode(), ascii::space_type> array;
qi::rule<Iterator, JsonNode()> number;
qi::rule<Iterator, std::string()> frac;
qi::rule<Iterator, std::string()> exp;
qi::rule<Iterator, JsonNode()> string;
qi::rule<Iterator, std::string()> string_inner;
qi::rule<Iterator, std::string()> unescaped;
qi::rule<Iterator, std::string()> escaped;
};
/**
* Parses a string into a json object or throw an exception.
*
* Throws either FailedToParseJsonException or SyntaxError.
*
* NOTE: There is only a string version provided. For one this allows for
* better error messages because we can display the line where the error
* occured. This is not possible using e.g. std::ifstream. And also I couldn't
* solve the error when trying to use std::ifstream with
* boost::spirit::line_pos_iterator<boost::spirit::istream_iterator> as the
* Iterator type. It would just crash with an std::__ios_failure exception with
* the message "basic_ios::clear: iostream error".
*/
JsonNode parse_json(const std::string& s) {
typedef boost::spirit::line_pos_iterator<std::string::const_iterator>
Iterator;
Iterator begin(s.cbegin());
Iterator end(s.cend());
JsonNode json;
try {
bool ok = qi::phrase_parse(begin, end, json_grammar<Iterator>(),
ascii::space, json);
if (!ok || begin != end) {
throw FailedToParseJsonException("parser failed");
}
} catch (InnerSyntaxError& e) {
std::string expected;
std::stringstream ss;
ss << e.info;
expected = ss.str();
throw SyntaxError(Iterator(s.cbegin()), e.error_pos, end, expected);
}
return json;
}
} // namespace json
#endif
| 34.028037 | 101 | 0.610959 | [
"object"
] |
50d06aa140ab0979bee0b8ff12ed687f4c67381a | 12,130 | cc | C++ | cpp/shared/tflite_model_parameters/tflite_model_parameters/tflite_model_parameters.cc | SiliconLabs/mltk | 56b19518187e9d1c8a0d275de137fc9058984a1f | [
"Zlib"
] | null | null | null | cpp/shared/tflite_model_parameters/tflite_model_parameters/tflite_model_parameters.cc | SiliconLabs/mltk | 56b19518187e9d1c8a0d275de137fc9058984a1f | [
"Zlib"
] | 1 | 2021-11-19T20:10:09.000Z | 2021-11-19T20:10:09.000Z | cpp/shared/tflite_model_parameters/tflite_model_parameters/tflite_model_parameters.cc | sldriedler/mltk | d82a60359cf875f542a2257f1bc7d8eb4bdaa204 | [
"Zlib"
] | null | null | null | #include "tflite_model_parameters/tflite_model_parameters.hpp"
#include "mltk_tflite_micro_helper.hpp"
namespace mltk
{
using StringList = TfliteModelParameters::StringList;
using Int32List = TfliteModelParameters::Int32List;
using FloatList = TfliteModelParameters::FloatList;
const char TfliteModelParameters::METADATA_TAG[] = "SL_PARAMSv1";
/*************************************************************************************************/
bool TfliteModelParameters::load_from_tflite_flatbuffer(const void* flatbuffer, TfliteModelParameters& parameters)
{
const void* metadata = get_metadata_from_tflite_flatbuffer(flatbuffer, TfliteModelParameters::METADATA_TAG);
if(metadata == nullptr)
{
return false;
}
if(!parameters.load(metadata))
{
return false;
}
return true;
}
/*************************************************************************************************/
bool TfliteModelParameters::load(const schema::Dictionary *fb_dictionary)
{
if (fb_dictionary == nullptr || fb_dictionary->entries() == nullptr)
{
return false;
}
else
{
_fb_dictionary = fb_dictionary;
return true;
}
}
/*************************************************************************************************/
bool TfliteModelParameters::load(const void *flatbuffer)
{
const auto fb_dictionary = schema::GetDictionary(flatbuffer);
return load(fb_dictionary);
}
/*************************************************************************************************/
void TfliteModelParameters::unload()
{
_fb_dictionary = nullptr;
}
/*************************************************************************************************/
TfliteModelParameters::TfliteModelParameters(const TfliteModelParameters& other)
{
load(other._fb_dictionary);
}
/*************************************************************************************************/
TfliteModelParameters& TfliteModelParameters::operator=(const TfliteModelParameters& other)
{
load(other._fb_dictionary);
return *this;
}
/*************************************************************************************************/
const TfliteModelParameters::Value *TfliteModelParameters::get(const char *key) const
{
const TfliteModelParameters::Value *retval = nullptr;
if (_fb_dictionary != nullptr)
{
for (auto entry : *this)
{
if (strcmp(entry->key(), key) == 0)
{
retval = entry;
break;
}
}
}
return retval;
}
/*************************************************************************************************/
bool TfliteModelParameters::contains(const char *key) const
{
bool retval = false;
if (_fb_dictionary != nullptr)
{
for (auto entry : *this)
{
if (strcmp(entry->key(), key) == 0)
{
retval = true;
break;
}
}
}
return retval;
}
/*************************************************************************************************/
const TfliteModelParameters::Value *TfliteModelParameters::operator[](const char *key) const
{
return get(key);
}
/*************************************************************************************************/
TfliteModelParameters::Iterator TfliteModelParameters::begin(void) const
{
return TfliteModelParameters::Iterator(_fb_dictionary->entries()->begin());
}
/*************************************************************************************************/
TfliteModelParameters::Iterator TfliteModelParameters::end() const
{
return TfliteModelParameters::Iterator(_fb_dictionary->entries()->end());
}
/*************************************************************************************************/
bool TfliteModelParameters::get(const char *key, const char *&value) const
{
auto entry = get(key);
if (entry != nullptr && entry->type() == schema::Value::str)
{
value = entry->str();
return true;
}
else
{
return false;
}
}
/*************************************************************************************************/
bool TfliteModelParameters::get(const char *key, const uint8_t *&value) const
{
auto entry = get(key);
if (entry != nullptr && entry->type() == schema::Value::bin)
{
value = entry->bin();
return true;
}
else
{
return false;
}
}
/*************************************************************************************************/
bool TfliteModelParameters::get(const char *key, StringList &value) const
{
auto entry = get(key);
if (entry != nullptr && entry->type() == schema::Value::str_list)
{
value = entry->str_list();
return true;
}
else
{
return false;
}
}
/*************************************************************************************************/
bool TfliteModelParameters::get(const char *key, Int32List &value) const
{
auto entry = get(key);
if (entry != nullptr && entry->type() == schema::Value::int32_list)
{
value = entry->int32_list();
return true;
}
else
{
return false;
}
}
/*************************************************************************************************/
bool TfliteModelParameters::get(const char *key, FloatList &value) const
{
auto entry = get(key);
if (entry != nullptr && entry->type() == schema::Value::float_list)
{
value = entry->float_list();
return true;
}
else
{
return false;
}
}
/*************************************************************************************************/
bool TfliteModelParameters::get(const char* key, const uint8_t* &data, uint32_t &length) const
{
auto entry = get(key);
if (entry == nullptr || entry->type() != schema::Value::bin)
{
return false;
}
else
{
length = entry->bin_length();
data = entry->bin();
return true;
}
}
/*************************************************************************************************/
TfliteModelParameters::Iterator::Iterator(EntryVectorIterator it) : it(it)
{
}
/*************************************************************************************************/
bool TfliteModelParameters::Iterator::operator!=(Iterator rhs)
{
return it != rhs.it;
}
/*************************************************************************************************/
const TfliteModelParameters::Value *TfliteModelParameters::Iterator::operator*()
{
auto entry = *it;
return reinterpret_cast<const Value *>(entry);
}
/*************************************************************************************************/
void TfliteModelParameters::Iterator::operator++()
{
++it;
}
schema::Value TfliteModelParameters::Value::type(void) const
{
return value_type();
}
const char *TfliteModelParameters::Value::key(void) const
{
return schema::Entry::key()->c_str();
}
bool TfliteModelParameters::Value::boolean(void) const
{
return value_as_boolean()->value();
}
int8_t TfliteModelParameters::Value::i8(void) const
{
return value_as_i8()->value();
}
uint8_t TfliteModelParameters::Value::u8(void) const
{
return value_as_u8()->value();
}
int16_t TfliteModelParameters::Value::i16(void) const
{
return value_as_i16()->value();
}
uint16_t TfliteModelParameters::Value::u16(void) const
{
return value_as_u16()->value();
}
int32_t TfliteModelParameters::Value::i32(void) const
{
return value_as_i32()->value();
}
uint32_t TfliteModelParameters::Value::u32(void) const
{
return value_as_u32()->value();
}
int64_t TfliteModelParameters::Value::i64(void) const
{
return value_as_i64()->value();
}
uint64_t TfliteModelParameters::Value::u64(void) const
{
return value_as_u64()->value();
}
float TfliteModelParameters::Value::f32(void) const
{
return value_as_f32()->value();
}
double TfliteModelParameters::Value::f64(void) const
{
return value_as_f64()->value();
}
const char *TfliteModelParameters::Value::str(void) const
{
return value_as_str()->data()->c_str();
}
TfliteModelParameters::StringList TfliteModelParameters::Value::str_list(void) const
{
return StringList(value_as_str_list()->data());
}
TfliteModelParameters::Int32List TfliteModelParameters::Value::int32_list(void) const
{
return Int32List(value_as_int32_list()->data());
}
TfliteModelParameters::FloatList TfliteModelParameters::Value::float_list(void) const
{
return FloatList(value_as_float_list()->data());
}
const uint8_t *TfliteModelParameters::Value::bin(void) const
{
return value_as_bin()->data()->Data();
}
uint32_t TfliteModelParameters::Value::bin_length(void) const
{
return value_as_bin()->data()->size();
}
StringList::StringList(const StringVector *vector) : vector(vector)
{
}
StringList::StringList(const StringList& other)
{
this->vector = other.vector;
}
StringList& StringList::operator=(const StringList& other)
{
this->vector = other.vector;
return *this;
}
uint32_t StringList::size(void) const
{
return (vector != nullptr) ? vector->size() : 0;
}
const char *StringList::operator[](unsigned index) const
{
return (vector != nullptr) ? vector->GetAsString(index)->c_str() : nullptr;
}
StringList::Iterator StringList::begin(void) const
{
return (vector != nullptr) ? StringList::Iterator(vector->begin()) : StringList::Iterator();
}
StringList::Iterator StringList::end(void) const
{
return (vector != nullptr) ? StringList::Iterator(vector->end()) : StringList::Iterator();
}
StringList::Iterator::Iterator(StringVectorIterator it) : it(it)
{
}
bool StringList::Iterator::operator!=(Iterator rhs)
{
return it != rhs.it;
}
const char *StringList::Iterator::operator*()
{
auto v = *it;
return v->c_str();
}
void StringList::Iterator::operator++()
{
++it;
}
Int32List::Int32List(const Int32Vector *vector) : vector(vector)
{
}
Int32List::Int32List(const Int32List& other)
{
this->vector = other.vector;
}
Int32List& Int32List::operator=(const Int32List& other)
{
this->vector = other.vector;
return *this;
}
uint32_t Int32List::size(void) const
{
return (vector != nullptr) ? vector->size() : 0;
}
int32_t Int32List::operator[](unsigned index) const
{
return (vector != nullptr) ? vector->Get(index) : 0;
}
Int32List::Iterator Int32List::begin(void) const
{
return (vector != nullptr) ? Int32List::Iterator(vector->begin()) : Int32List::Iterator();
}
Int32List::Iterator Int32List::end(void) const
{
return (vector != nullptr) ? Int32List::Iterator(vector->end()) : Int32List::Iterator();
}
Int32List::Iterator::Iterator(Int32VectorIterator it) : it(it)
{
}
bool Int32List::Iterator::operator!=(Iterator rhs)
{
return it != rhs.it;
}
int32_t Int32List::Iterator::operator*()
{
return *it;
}
void Int32List::Iterator::operator++()
{
++it;
}
FloatList::FloatList(const FloatVector *vector) : vector(vector)
{
}
FloatList::FloatList(const FloatList& other)
{
this->vector = other.vector;
}
FloatList& FloatList::operator=(const FloatList& other)
{
this->vector = other.vector;
return *this;
}
uint32_t FloatList::size(void) const
{
return (vector != nullptr) ? vector->size() : 0;
}
float FloatList::operator[](unsigned index) const
{
return (vector != nullptr) ? vector->Get(index) : 0;
}
FloatList::Iterator FloatList::begin(void) const
{
return (vector != nullptr) ? FloatList::Iterator(vector->begin()) : FloatList::Iterator();
}
FloatList::Iterator FloatList::end(void) const
{
return (vector != nullptr) ? FloatList::Iterator(vector->end()) : FloatList::Iterator();
}
FloatList::Iterator::Iterator(FloatVectorIterator it) : it(it)
{
}
bool FloatList::Iterator::operator!=(Iterator rhs)
{
return it != rhs.it;
}
float FloatList::Iterator::operator*()
{
return *it;
}
void FloatList::Iterator::operator++()
{
++it;
}
} // namespace mltk
| 23.507752 | 114 | 0.549876 | [
"vector"
] |
50d12a5af4b67b3dbfc83b125f09fc7c6151fa32 | 13,607 | cpp | C++ | BSP/c5soc/source/host/mmd/acl_mmd_mm_io.cpp | hammadj/Qwik-e-Classifier | 4b1668cb1f0e21381873cfbc79424045d6e15411 | [
"MIT"
] | 6 | 2019-07-31T12:54:40.000Z | 2021-07-01T11:50:46.000Z | BSP/c5soc/source/host/mmd/acl_mmd_mm_io.cpp | hammadj/Qwik-e-Classifier | 4b1668cb1f0e21381873cfbc79424045d6e15411 | [
"MIT"
] | 22 | 2018-02-06T03:21:27.000Z | 2019-05-15T15:11:24.000Z | BSP/c5soc/source/host/mmd/acl_mmd_mm_io.cpp | hammadj/Qwik-e-Classifier | 4b1668cb1f0e21381873cfbc79424045d6e15411 | [
"MIT"
] | 2 | 2018-12-13T06:07:46.000Z | 2020-08-19T07:14:59.000Z | // (C) 1992-2017 Intel Corporation.
// Intel, the Intel logo, Intel, MegaCore, NIOS II, Quartus and TalkBack words
// and logos are trademarks of Intel Corporation or its subsidiaries in the U.S.
// and/or other countries. Other marks and brands may be claimed as the property
// of others. See Trademarks on intel.com for full list of Intel trademarks or
// the Trademarks & Brands Names Database (if Intel) or See www.Intel.com/legal (if Altera)
// Your use of Intel Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Intel MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Intel and sold by
// Intel or its authorized distributors. Please refer to the applicable
// agreement for further details.
/* ===- acl_mmd_mm_io.cpp ------------------------------------------- C++ -*-=== */
/* */
/* Intel(R) OpenCL MMD Driver */
/* */
/* ===-------------------------------------------------------------------------=== */
/* */
/* This file implements the class to handle memory mapped IO */
/* The declaration of the class lives in the acl_mmd_mm_io.h. */
/* */
/* ===-------------------------------------------------------------------------=== */
// common and its own header files
#include "acl_mmd.h"
#include "acl_mmd_mm_io.h"
// other header files inside MMD driver
#include "acl_mmd_debug.h"
// other standard header files
#include <string.h>
#if defined(LINUX)
# include <unistd.h> // template
#endif // LINUX
ACL_MMD_MM_IO_DEVICE::ACL_MMD_MM_IO_DEVICE
(
WDC_DEVICE_HANDLE device,
DWORD bar,
KPTR device_offset,
const char* name,
bool diff_endian
)
{
ACL_MMD_ASSERT(device != INVALID_DEVICE, "passed in an invalid device when creating mm_io object.\n");
ACL_MMD_ASSERT(name != NULL, "passed in an empty name pointer when creating mm_io object.\n");
strncpy(m_name, name, (MAX_NAME_LENGTH-1));
m_name[(MAX_NAME_LENGTH-1)] = '\0';
m_device = device;
m_bar = bar;
m_offset = device_offset;
m_diff_endian = diff_endian;
ACL_MMD_DEBUG_MSG(":: [%s] Init: Bar %d, Total offset 0x" SIZE_FMT_X ", diff_endian is %d \n",
m_name, m_bar, (size_t) m_offset, m_diff_endian?1:0 );
}
ACL_MMD_MM_IO_DEVICE::~ACL_MMD_MM_IO_DEVICE()
{
}
#if defined(LINUX)
// Helper functions to implement all other read/write functions
template<typename T>
DWORD linux_read ( WDC_DEVICE_HANDLE device, DWORD bar, KPTR address, T *data )
{
struct acl_cmd driver_cmd;
driver_cmd.bar_id = bar;
driver_cmd.command = ACLSOC_CMD_DEFAULT;
driver_cmd.device_addr = reinterpret_cast<void *>(address);
driver_cmd.user_addr = data;
driver_cmd.size = sizeof(*data);
// function invoke linux_read will not write to global memory.
// So is_diff_endian is always false
driver_cmd.is_diff_endian = 0;
return read (device, &driver_cmd, sizeof(driver_cmd));
}
template<typename T>
DWORD linux_write ( WDC_DEVICE_HANDLE device, DWORD bar, KPTR address, T data )
{
struct acl_cmd driver_cmd;
driver_cmd.bar_id = bar;
driver_cmd.command = ACLSOC_CMD_DEFAULT;
driver_cmd.device_addr = reinterpret_cast<void *>(address);
driver_cmd.user_addr = &data;
driver_cmd.size = sizeof(data);
// function invoke linux_write will not write to global memory.
// So is_diff_endian is always false
driver_cmd.is_diff_endian = 0;
return write (device, &driver_cmd, sizeof(driver_cmd));
}
#endif // LINUX
int ACL_MMD_MM_IO_DEVICE::read8 ( size_t addr, UINT8 *data )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
status = linux_read ( m_device, m_bar, bar_addr, data );
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Read 8 bits from 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, addr, (size_t)bar_addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Read 8 bits (0x%x) from 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, *data, addr, (size_t)bar_addr);
return 0; // success
}
int ACL_MMD_MM_IO_DEVICE::write8 ( size_t addr, UINT8 data )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
status = linux_write ( m_device, m_bar, bar_addr, data );
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Writing 8 bits to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, addr, (size_t)bar_addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Wrote 8 bits (0x%x) to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, data, addr, (size_t)bar_addr);
return 0; // success
}
int ACL_MMD_MM_IO_DEVICE::read32 ( size_t addr, UINT32 *data )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
status = linux_read ( m_device, m_bar, bar_addr, data );
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Read 32 bits from 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, addr, (size_t)bar_addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Read 32 bits (0x%x) from 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, *data, addr, (size_t)bar_addr);
return 0; // success
}
int ACL_MMD_MM_IO_DEVICE::write32 ( size_t addr, UINT32 data )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
status = linux_write ( m_device, m_bar, bar_addr, data );
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Writing 32 bits to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, addr, (size_t)bar_addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Wrote 32 bits (0x%x) to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, data, addr, (size_t) bar_addr);
return 0; // success
}
int ACL_MMD_MM_IO_DEVICE::read64 ( size_t addr, UINT64 *data )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
status = linux_read ( m_device, m_bar, bar_addr, data );
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Read 64 bits from 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, addr, (size_t)bar_addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Read 64 bits (0x%llx) from 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, *data, addr, (size_t)bar_addr);
return 0; // success
}
int ACL_MMD_MM_IO_DEVICE::write64 ( size_t addr, UINT64 data )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
status = linux_write ( m_device, m_bar, bar_addr, data );
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Writing 64 bits to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, bar_addr, (size_t)bar_addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Wrote 64 bits (0x%llx) to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, data, addr, (size_t)bar_addr);
return 0; // success
}
int ACL_MMD_MM_IO_DEVICE::write_block ( size_t addr, size_t size, void *src )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Writing block (" SIZE_FMT_U " bytes) to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, size, addr, (size_t)bar_addr);
// Can't use templated linux_write here because *src doesn't give you the size to read.
struct acl_cmd driver_cmd;
driver_cmd.bar_id = m_bar;
driver_cmd.device_addr = reinterpret_cast<void *>(bar_addr);
driver_cmd.user_addr = src;
driver_cmd.size = size;
// Notify the driver if the host and device's memory have different endianess.
driver_cmd.is_diff_endian = m_diff_endian?1:0;
status = write (m_device, &driver_cmd, sizeof(driver_cmd));
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Writing block (" SIZE_FMT_U " bytes) to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, size, addr, (size_t)bar_addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Writing block (" SIZE_FMT_U " bytes) to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset) SUCCEEDED\n",
m_name, size, addr, (size_t)bar_addr);
return 0; // success
}
int ACL_MMD_MM_IO_DEVICE::read_block ( size_t addr, size_t size, void *dst )
{
DWORD status;
KPTR bar_addr = convert_to_bar_addr(addr);
ACL_MMD_DEBUG_MSG_VERBOSE(VERBOSITY_MMD,
":::::: [%s] Reading block (" SIZE_FMT_U " bytes) from 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, size, addr, (size_t)bar_addr);
// Can't use templated linux_write here because *src doesn't give you the size to read.
struct acl_cmd driver_cmd;
driver_cmd.bar_id = m_bar;
driver_cmd.device_addr = reinterpret_cast<void *>(bar_addr);
driver_cmd.user_addr = dst;
driver_cmd.size = size;
// Notify the driver if the host and device's memory have different endianess.
driver_cmd.is_diff_endian = m_diff_endian?1:0;
status = read (m_device, &driver_cmd, sizeof(driver_cmd));
ACL_MMD_ERROR_IF(status != WD_STATUS_SUCCESS, return -1,
"[%s] Reading block (" SIZE_FMT_U " bytes) to 0x" SIZE_FMT_X " (0x" SIZE_FMT_X " with offset)\n",
m_name, size, addr, (size_t)bar_addr);
return 0; // success
}
ACL_MMD_MM_IO_MGR::ACL_MMD_MM_IO_MGR( WDC_DEVICE_HANDLE device ) :
mem (NULL),
mmd_cra (NULL),
dma (NULL),
dma_descriptor (NULL),
window (NULL),
version (NULL),
uniphy_status (NULL),
kernel_if (NULL),
pll (NULL),
temp_sensor (NULL)
{
ACL_MMD_ASSERT(device != INVALID_DEVICE, "passed in an invalid device when creating mm_io_mgr.\n");
// This is the MMD interface for directly accessing memory.
// This view of memory is segmented so that the size of this
// address space can be smaller than the amount of physical device.
// The window interface controls which region of physical memory
// this interface currently maps to. The last flag indicate if
// the device on both side of transferring have different endianess.
#ifdef ACL_BIG_ENDIAN
mem = new ACL_MMD_MM_IO_DEVICE( device, ACL_MMD_GLOBAL_MEM_BAR, (KPTR)ACL_MMD_MEMWINDOW_BASE, "GLOBAL-MEM" , true );
#else
mem = new ACL_MMD_MM_IO_DEVICE( device, ACL_MMD_GLOBAL_MEM_BAR, (KPTR)ACL_MMD_MEMWINDOW_BASE, "GLOBAL-MEM" , false);
#endif
// This is the CRA port of our HPS2FPGA controller. Used for configuring
// interrupts and things like that.
mmd_cra = new ACL_MMD_MM_IO_DEVICE( device, ACL_MMD_CRA_BAR, ACL_MMD_CRA_OFFSET, "HPS2FPGA-CRA" );
// This interface sets the high order address bits for the FPGA's direct
// memory accesses via "mem" (above).
window = new ACL_MMD_MM_IO_DEVICE( device, ACL_MMD_MEMWINDOW_BAR, ACL_MMD_MEMWINDOW_CRA, "MEMWINDOW" );
// DMA interfaces
dma = new ACL_MMD_MM_IO_DEVICE( device, ACL_MMD_DMA_BAR, ACL_MMD_DMA_OFFSET, "DMA-CSR" );
dma_descriptor = new ACL_MMD_MM_IO_DEVICE( device, ACL_MMD_DMA_DESCRIPTOR_BAR, ACL_MMD_DMA_DESCRIPTOR_OFFSET, "DMA-DESCRIPTOR" );
// Version ID check
version = new ACL_MMD_MM_IO_DEVICE( device, ACL_VERSIONID_BAR, ACL_VERSIONID_OFFSET, "VERSION" );
// Uniphy Status
uniphy_status = new ACL_MMD_MM_IO_DEVICE( device, ACL_UNIPHYSTATUS_BAR, ACL_UNIPHYSTATUS_OFFSET, "UNIPHYSTATUS" );
// Kernel interface
kernel_if = new ACL_MMD_MM_IO_DEVICE( device, ACL_KERNEL_CSR_BAR, ACL_KERNEL_CSR_OFFSET, "KERNEL" );
// PLL interface
pll = new ACL_MMD_MM_IO_DEVICE( device, ACL_KERNELPLL_RECONFIG_BAR, ACL_KERNELPLL_RECONFIG_OFFSET, "PLL" );
// temperature sensor
if( ACL_MMD_HAS_TEMP_SENSOR ) {
temp_sensor = new ACL_MMD_MM_IO_DEVICE( device, ACL_VERSIONID_BAR, ACL_TEMP_SENSOR_ADDRESS, "TEMP-SENSOR");
}
}
ACL_MMD_MM_IO_MGR::~ACL_MMD_MM_IO_MGR()
{
if(mem) { delete mem; mem = NULL; }
if(mmd_cra) { delete mmd_cra; mmd_cra = NULL; }
if(dma) { delete dma; dma = NULL; }
if(dma_descriptor) { delete dma_descriptor; dma_descriptor = NULL; }
if(window) { delete window; window = NULL; }
if(version) { delete version; version = NULL; }
if(uniphy_status) { delete uniphy_status; uniphy_status = NULL; }
if(kernel_if) { delete kernel_if; kernel_if = NULL; }
if(pll) { delete pll; pll = NULL; }
if(temp_sensor) { delete temp_sensor; temp_sensor = NULL; }
}
| 40.861862 | 132 | 0.64849 | [
"object"
] |
50d20d31231089ebc44f6d411d14761703a04ca2 | 1,315 | hpp | C++ | src/image.hpp | stephanlachnit/vkBasalt | dd6a067b7eada67f4f34e56054ef24264f6856d7 | [
"Zlib"
] | 748 | 2019-10-20T14:21:20.000Z | 2022-03-22T05:53:42.000Z | src/image.hpp | stephanlachnit/vkBasalt | dd6a067b7eada67f4f34e56054ef24264f6856d7 | [
"Zlib"
] | 160 | 2019-10-20T16:35:47.000Z | 2022-03-30T19:21:56.000Z | src/image.hpp | stephanlachnit/vkBasalt | dd6a067b7eada67f4f34e56054ef24264f6856d7 | [
"Zlib"
] | 58 | 2019-10-20T19:15:01.000Z | 2022-01-02T01:16:08.000Z | #ifndef IMAGE_HPP_INCLUDED
#define IMAGE_HPP_INCLUDED
#include <vector>
#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <cstring>
#include <memory>
#include "vulkan_include.hpp"
#include "logical_device.hpp"
namespace vkBasalt
{
std::vector<VkImage> createImages(LogicalDevice* pLogicalDevice,
uint32_t count,
VkExtent3D extent,
VkFormat format,
VkImageUsageFlags usage,
VkMemoryPropertyFlags properties,
VkDeviceMemory& imageMemory,
uint32_t mipLevels = 1);
void uploadToImage(
LogicalDevice* pLogicalDevice, VkImage image, VkExtent3D extent, uint32_t size, const unsigned char* writeData, uint32_t mipLevels = 1);
void changeImageLayout(LogicalDevice* pLogicalDevice, std::vector<VkImage> images, uint32_t mipLevels = 1);
void generateMipMaps(LogicalDevice* pLogicalDevice, VkCommandBuffer commandBuffer, VkImage image, VkExtent3D extent, uint32_t mipLevels);
} // namespace vkBasalt
#endif // IMAGE_HPP_INCLUDED
| 37.571429 | 144 | 0.590875 | [
"vector"
] |
50ebe0b6093a4f6f01f9995e45a43fdfcabf8972 | 74,951 | cpp | C++ | src/rcv/rt17.cpp | akstuki/rtklibcpp | 241753fba4d92fb09f3337e6c82b1ed9283675be | [
"BSD-2-Clause"
] | 1 | 2020-06-05T15:16:36.000Z | 2020-06-05T15:16:36.000Z | src/rcv/rt17.cpp | akstuki/rtklibcpp | 241753fba4d92fb09f3337e6c82b1ed9283675be | [
"BSD-2-Clause"
] | 1 | 2020-06-14T07:04:29.000Z | 2020-06-14T07:04:29.000Z | src/rcv/rt17.cpp | akstuki/rtklibcpp | 241753fba4d92fb09f3337e6c82b1ed9283675be | [
"BSD-2-Clause"
] | 2 | 2021-09-26T09:00:02.000Z | 2021-09-26T10:07:52.000Z | /*------------------------------------------------------------------------------
* rt17.c : Trimble RT-17 dependent functions
*
* Copyright (C) 2016 Daniel A. Cook, All rights reserved.
*
* references:
* [1] https://github.com/astrodanco/RTKLIB/tree/cmr/src/rcv/rt17.c
* [2] Trimble, Trimble OEM BD9xx GNSS Receiver Family IDC, version 4.82
* Revision A, December, 2013
*
* version : $Revision:$ $Date:$
* history : 2014/08/26 1.0 imported from GitHub (ref [1])
* modified to get initial week number
* modified obs types for raw obs data
* function added to output message type
* 2014/09/06 1.1 Remove prehistorical revision history
* Remove dead code
* Fix len vs. plen typo
* Check week/time valid flag in GSOF 16 message
* Set time when reading GSOF messages, where possible.
* 2016/06/16 1.2 Refactored
* 2016/07/16 1.3 modified by T.T
* raw->strfmt -> raw->format
* int free_rt17() -> void free_rt17()
* 2016/07/29 1.4 suppress warning
* 2017/04/11 1.5 (char *) -> (signed char *)
*-----------------------------------------------------------------------------*/
/*
| Trimble real-time binary data stream and file handler functions.
|
| Written in July 2014 by Daniel A. Cook, for inclusion into the RTKLIB library.
| Copyright (C) 2014, 2016 by Daniel A. Cook. All Rights Reserved.
|
| Here we implement four public functions, one for reading Trimble real-time
| binary data streams and another for reading log files containng data in the
| same format, a third to initialize RT17 related memory storage and a fourth
| to free up RT17 related memory storage. This real-time streaming data format,
| sometimes called RT-17, was designed by Trimble for use by Trimble receivers.
| Trimble receivers with the "Real-Time Survey Data" or "Binary Outputs" options
| can output this data. The RT-17 moniker refers to the GPS observables data
| record (record type 0) itself. There is also a GNSS observables data record
| (record type 6), which is referred to as RT-27. We also wish to handle RT-27
| data records, but lack sufficient documentation to do so.
|
| Notes:
|
| To specify receiver dependent options, set raw->opt to the following case
| sensitive option strings separated by spaces.
|
| Receiver dependent options:
|
| -EPHALL : Input all ephemerides
| -WEEK=n : Explicitly set starting GPS week number
|
| Neither the Trimble RT-17 observables packets nor the ION / UTC data packets
| contain the GPS week number. By default the current computer "now" time is
| used to determine the GPS week number. This works well in real time, but
| can be problematic when later converting and/or post processing recorded
| data. When recording data, also enable either GSOF Position & Time (1) or
| GSOF Current Time (16) messages on the same serial port along with the
| RT-17 Real-Time Survey Data output. For best results enable the GSOF
| message(s) and get them streaming prior to enabling the RT-17 messages.
|
| If desired the -WEEK=n option can be specified when converting or post
| processing recorded data to explicitly set the starting GPS week number.
| This option overrides anything and everything, including the current
| computer "now" time and any GSOF or other messages read from the raw
| data stream or recorded file. Note that the GPS week number explicitly
| specified with the -WEEK=n option GPS is automatically incremented when
| and if a subsequent GPS week number rollover occurs in the raw data.
|
| In addition to enabling RT-17 Real-Time Survey Data output, it is very
| helpful to also enable GSOF Position & Time (1) or GSOF Current Time (16)
| messages on the same serial port. This allows the GPS week number to be
| determined without using the current computer "now" time or the -WEEK=n
| option. Although not as important for real-time streaming data use where
| the current computer "now" time can be used to determine the current GPS
| week number, it becomes more important when recording files for later
| conversion and/or post processing. For best results enable the GSOF
| message(s) and get them streaming prior to enabling the RT-17 messages.
|
| Support is provided for the following Trimble RT-17 packet Types:
|
| Raw Observation Satellite ION/UTC
| Format Data Ephemerides Parameters GSOF
| ------- --------------- ---------------- ---------------- ------------
| Trimble 0x57 (RAWDATA) 0x55 (RETSVDATA) 0x55 (RETSVDATA) 1, 16,
| RT-17 Recordtype 0 & 7 Subtype 1 Subtype 3 26, 41
|
| When the -WEEK=n option is NOT used, the GPS week number is set from any
| RAWDATA record type 7 or GENOUT (GSOF) 1, 16, 26, 41 records encountered
| in the raw data stream. These messages are only used to obtain the GPS
| WEEK number and are not used for any other purpose.
|
| Support is not provided for the GPS L2C or L5 signals. Those would likely
| require Trimble RT-27 protocol support. Support for that and much more
| could easily be added by anyone with the required RAWDATA record type
| 6 documentation.
|
| For Trimble GPS receivers which are capable of RT-17 binary output, the
| receiver and/or receiver configuration software generally provide several
| RT-17 binary output options:
|
| 1. Compact format aka Concise format
| (RECOMMENDED)
|
| This option causes the raw satellite data to be streamed in a more compact
| format. The compact format does not include L2 DOPPLER observables.
|
| 2. Expanded format
|
| This is usually the default format if compact format is not enabled. The
| only advantage of this format over compact format is that L2 DOPPLER
| observables are output when used in combination with the Real Time
| Enhancements option. Otherwise this format just consumes more bandwidth
| and/or file space than compact format while offering no other advantages.
|
| 3. Real Time Enhancements, aka Real-time Enhanced format, aka R-T FLAGS
|
| This option adds extra data to the raw satellite data output by the
| receiver. When used in combination with expanded format, L2 DOPPLER
| observables are output. L2 DOPPLER can be used by RTKLIB.
|
| 3. Measurements
| (REQUIRED)
|
| If your configuration has a measurements option, enable it. Measurements
| are the raw satellite data. If you don't see this option then it is
| implied and enabled by default.
|
| 4. Ephermeris AKA Stream Ephemeris
| (HIGHLY RECOMMENDED)
|
| This option causes satellite ephemerides and UTC / ION data to be streamed
| along with the raw satellite data. Streamed ephemerides and UTC / ION data
| consume very little extra bandwidth in the stream and/or space in a file.
| In most situations with most applications you will need them as well.
|
| 5. Positions AKA Stream Positions
| (NOT RECOMMENDED)
|
| Streamed postions are of no use to RTKLIB. They will be ignored. RTKLIB
| computes positions from the raw satellite data. It has no use for the
| receiver's position solutions. Streamed positions also consume
| considerable bandwidth in the stream and/or space in a file.
|
| 6. Positions Only
| (HIGHLY NOT RECOMMENDED)
|
| Enabling the positions only option causes only positions and nothing else
| to be output, including no raw satellite data and no ephemerides and no
| ION / UTC data.
|
| Design notes:
|
| This source code handles GPS L1/L2 only. RT-17 is GPS. RT27 is GNSS.
| If you have RT27 (RAWDATA 57h record type 6) documentation, please
| forward it to the author.
|
| An RT-17 real-time survey data message is a series of RAWDATA (57h,
| Real-time survey data report) and RETSVDATA (55h, Satellite information
| report) packets.
|
| Each assembled RAWDATA message in an RT-17 packet stream may contain
| any of the following: Compact Format raw satellite measurements, Expanded
| Format raw satellite measurements, a receiver computed position or an
| event mark. Receiver computed positions and event marks are of no
| interest to RTKLIB, therefore we ignore them.
|
| Each RETSVDATA message in an RT-17 packet stream may contain any one
| of the following: SV flags indicating tracking, a GPS Ephemeris, a GPS
| Almanac, ION / UTC Data or an Extended GPS Almanac. Of these only
| the GPS Ephemeris and the ION / UTC Data are of interest to RTKLIB.
| In practice only GPS Ephemeris and ION / UTC Data are transmitted.
| Some receivers can be set to transmit them at regular intervals
| rather than only when they change.
|
| Certain simplifying assumptions are made concerning the way in which
| RAWDATA and GENOUT packets are transmitted in the stream or stored
| into the file.
|
| Therefore it is assumed that:
|
| 1. RAWDATA and GENOUT packets are never interleaved or interspersed
| with packets of other types.
|
| 2. The sequence of page frames in a RAWDATA message are transmitted in the
| stream or stored into a file as packets in order from first to last.
| RAWDATA page numbers are one based. That is, 1 of n, 2 of n, 3 of n,
| ..., to 15 of 15 for a total of 15 possible pages. We check for this
| ordering. RAWDATA messages can therefore reach almost 4K in total
| length. We check for potential buffer overflows in the input_rt17()
| function.
|
| 3. The Record Interpretation Flags (RIF) field is repeated within the
| page frame of every page making up a single RAWDATA message. It is
| assumed that this is redundant and that the actual value of the record
| interpretation flags does not change from one page to the next within
| a single RAWDATA message. We check for this too.
|
| 4. The sequence of pages in a GENOUT message are transmitted in the
| stream or stored into a file as packets in order from first to last.
| GENOUT page numbers are zero based. That is, 0 of n, 1 of n, 2 of n,
| ..., to 255 of 255 for a total of 256 possible pages. We check for
| this ordering. GENOUT messages can therefore reach almost 64K in
| total length. Such a large GENOUT message could exceed our maximum
| buffer size. We check for potential buffer overflows in the
| input_rt17() function.
|
| This code was tested using RT-17 data output from the following receivers:
|
| 1. Trimble 4000SSI, firmware version 7.32
| 2. Trimble 5700, firmware version 2.32
| 3. Spectra Precision Epoch 25 Base, firmware version 2.32
|
| By convention functions within this source file appear in alphabetical
| order. Public functions appear as a set first (there are only two of
| them), followed by private functions as a set. Because of this, forward
| definitions are required for the private functions. Please keep that
| in mind when making changes to this source file.
|
| References:
|
| 1. Trimble Serial Reference Specification, Version 4.82, Revision A,
| December 2013. Though not being in any way specific to the BD9xx
| family of receivers, a handy downloadable copy of this document
| is contained in the "Trimble OEM BD9xx GNSS Receiver Family ICD"
| document located at <http://www.trimble.com/OEM_ReceiverHelp/
| v4.85/en/BinaryInterfaceControlDoc.pdf>
|
| 2. Trimble General Serial Output Format (GSOF)
| <http://www.trimble.com/OEM_ReceiverHelp/v4.85/en/GSOFmessages_GSOF.html>
|
| 3. ICD-GPS-200C, Interface Control Document, Revision C, 10 October 1993
| <http://www.gps.gov/technical/icwg/ICD-GPS-200C.pdf>
|
| 4. IS-GPS-200H, Interface Specification, 24 September 2013
| <http://www.gps.gov/technical/icwg/IS-GPS-200H.pdf>
|
| 5. RTKLIB Version 2.4.2 Manual, April 29 2013
| <http://www.rtklib.com/prog/manual_2.4.2.pdf>
*/
/* Included files: */
#include "rtklib.h"
/* General purpose flag bits masks: */
#define M_BIT0 (1 << 0)
#define M_BIT1 (1 << 1)
#define M_BIT2 (1 << 2)
#define M_BIT3 (1 << 3)
#define M_BIT4 (1 << 4)
#define M_BIT5 (1 << 5)
#define M_BIT6 (1 << 6)
#define M_BIT7 (1 << 7)
#define M_BIT8 (1 << 8)
#define M_BIT9 (1 << 9)
#define M_BIT10 (1 << 10)
#define M_BIT11 (1 << 11)
#define M_BIT12 (1 << 12)
#define M_BIT13 (1 << 13)
#define M_BIT14 (1 << 14)
#define M_BIT15 (1 << 15)
/* Constant definitions: */
#define STX 2 /* Start of packet character */
#define ETX 3 /* End of packet character */
#define GENOUT 0x40 /* General Serial Output Format (GSOF) */
#define RETSVDATA 0x55 /* Satellite information reports */
#define RAWDATA 0x57 /* Position or real-time survey data report */
#define MBUFF_LENGTH 8192 /* Message buffer length */
#define PBUFF_LENGTH (4+255+2) /* Packet buffer length */
/* Record Interpretation Flags bit masks: */
#define M_CONCISE M_BIT0 /* Concise format */
#define M_ENHANCED M_BIT1 /* Enhanced record with real-time flags and IODE information */
/* rt17.flag bit definitions: */
#define M_WEEK_OPTION M_BIT0 /* GPS week number set by WEEK=n option */
#define M_WEEK_EPH M_BIT1 /* GPS week number set by ephemeris week */
#define M_WEEK_TIME M_BIT2 /* GPS week set by computer time */
#define M_WEEK_SCAN M_BIT3 /* WEEK=n option already looked for, no need to do it again */
/* Data conversion macros: */
#define I1(p) (*((signed char*)(p))) /* One byte signed integer */
#define U1(p) (*((unsigned char*)(p))) /* One byte unsigned integer */
#define I2(p) ReadI2(p) /* Two byte signed integer */
#define U2(p) ReadU2(p) /* Two byte unsigned integer */
#define I4(p) ReadI4(p) /* Four byte signed integer */
#define U4(p) ReadU4(p) /* Four byte unsigned integer */
#define R4(p) ReadR4(p) /* IEEE S_FLOAT floating point number */
#define R8(p) ReadR8(p) /* IEEE T_FLOAT floating point number */
/* Internal structure definitions. */
typedef union {unsigned short u2; unsigned char c[2];} ENDIAN_TEST;
/* GENOUT 0x40 message types: */
static const char *GSOFTable[] = {
/* 00 */ NULL,
/* 01 */ "Position Time",
/* 02 */ "Latitude Longitude Height",
/* 03 */ "ECEF Position",
/* 04 */ "Local Datum LLH Position",
/* 05 */ "Local Zone ENU Position",
/* 06 */ "ECEF Delta",
/* 07 */ "Tangent Plane Delta",
/* 08 */ "Velocity Data",
/* 09 */ "DOP Information",
/* 10 */ "Clock Information",
/* 11 */ "Position VCV Information",
/* 12 */ "Position Sigma Information",
/* 13 */ "SV Brief Information",
/* 14 */ "SV Detailed Information",
/* 15 */ "Receiver Serial Number",
/* 16 */ "Current Time UTC",
/* 17 */ NULL,
/* 18 */ NULL,
/* 19 */ NULL,
/* 20 */ NULL,
/* 21 */ NULL,
/* 22 */ NULL,
/* 23 */ NULL,
/* 24 */ NULL,
/* 25 */ NULL,
/* 26 */ "Position Time UTC",
/* 27 */ "Attitude Information",
/* 28 */ NULL,
/* 29 */ NULL,
/* 30 */ NULL,
/* 31 */ NULL,
/* 32 */ NULL,
/* 33 */ "All SV Brief Information",
/* 34 */ "All SV Detailed Information",
/* 35 */ "Received Base Information",
/* 36 */ NULL,
/* 37 */ "Battery and Memory Information",
/* 38 */ NULL,
/* 39 */ NULL,
/* 40 */ "L-Band Status Information",
/* 41 */ "Base Position and Quality Indicator"
};
/* RAWDATA 0x57 message types: */
static const char *RawdataTable[] = {
/* 00 */ "Real-time GPS Survey Data, type 17",
/* 01 */ "Position Record, type 11",
/* 02 */ "Event Mark",
/* 03 */ NULL,
/* 04 */ NULL,
/* 05 */ NULL,
/* 06 */ "Real-time GNSS Survey Data, type 27",
/* 07 */ "Enhanced Position Record, type 29"
};
/* RETSVDATA 0x55 message types: */
static const char *RetsvdataTable[] = {
/* 00 */ "SV Flags",
/* 01 */ "GPS Ephemeris",
/* 02 */ "GPS Almanac",
/* 03 */ "ION / UTC Data",
/* 04 */ "Disable Satellite, depreciated",
/* 05 */ "Enable Satellite, depreciated",
/* 06 */ NULL,
/* 07 */ "Extended GPS Almanac",
/* 08 */ "GLONASS Almanac",
/* 09 */ "GLONASS Ephemeris",
/* 10 */ NULL,
/* 11 */ "Galileo Ephemeris",
/* 12 */ "Galileo Almanac",
/* 13 */ NULL,
/* 14 */ "QZSS Ephemeris",
/* 15 */ NULL,
/* 16 */ "QZSS Almanac",
/* 17 */ NULL,
/* 18 */ NULL,
/* 19 */ NULL,
/* 20 */ "SV Flags",
/* 21 */ "BeiDou Ephemeris",
/* 22 */ "BeiDou Almanac"
};
/*
| Typedefs.
*/
typedef struct { /* RT17 information struct type */
unsigned char *MessageBuffer; /* Message buffer */
unsigned char *PacketBuffer; /* Packet buffer */
double Tow; /* Receive time of week */
unsigned int Flags; /* Miscellaneous internal flag bits */
unsigned int MessageBytes; /* Number of bytes in message buffer */
unsigned int MessageLength; /* Message length (bytes) */
unsigned int PacketBytes; /* How many packet bytes have been read so far */
unsigned int PacketLength; /* Total size of packet to be read */
unsigned int Page; /* Last page number */
unsigned int Reply; /* Current reply number */
int Week; /* GPS week number */
} rt17_t;
/*
| Internal private function forward declarations (in alphabetical order):
*/
static int CheckPacketChecksum(unsigned char *PacketBuffer);
static void ClearMessageBuffer(rt17_t *rt17);
static void ClearPacketBuffer(rt17_t *rt17);
static int DecodeBeidouEphemeris(raw_t *Raw);
static int DecodeGalileoEphemeris(raw_t *Raw);
static int DecodeGLONASSEphemeris(raw_t *Raw);
static int DecodeGPSEphemeris(raw_t *Raw);
static int DecodeGSOF(raw_t *Raw);
static int DecodeGSOF1(raw_t *Raw, unsigned char *p);
static int DecodeGSOF3(raw_t *Raw, unsigned char *p);
static int DecodeGSOF15(raw_t *Raw, unsigned char *p);
static int DecodeGSOF16(raw_t *Raw, unsigned char *p);
static int DecodeGSOF26(raw_t *Raw, unsigned char *p);
static int DecodeGSOF41(raw_t *Raw, unsigned char *p);
static int DecodeIONAndUTCData(raw_t *Raw);
static int DecodeQZSSEphemeris(raw_t *Raw);
static int DecodeRawdata(raw_t *Raw);
static int DecodeRetsvdata(raw_t *Raw);
static int DecodeType17(raw_t *Raw, unsigned int rif);
static int DecodeType29(raw_t *Raw);
static int GetWeek(raw_t *Raw, double tow);
static short ReadI2(unsigned char *p);
static int ReadI4(unsigned char *p);
static float ReadR4(unsigned char *p);
static double ReadR8(unsigned char *p);
static unsigned short ReadU2(unsigned char *p);
static unsigned int ReadU4(unsigned char *p);
static void SetWeek(raw_t *Raw, int Week, double tow);
static int SyncPacket(rt17_t *rt17, unsigned char Data);
static void UnwrapRawdata(rt17_t *rt17, unsigned int *rif);
static void UnwrapGenout(rt17_t *rt17);
/* Public functions (in alphabetical order): */
/* free_rt17 - Free up RT17 dependent private storage */
EXPORT void free_rt17(raw_t *Raw)
{
rt17_t *rt17 = NULL;
if (Raw->format != STRFMT_RT17)
return;
if ((rt17 = (rt17_t*) Raw->rcv_data))
{
if (rt17->MessageBuffer)
{
memset(rt17->MessageBuffer, 0, MBUFF_LENGTH);
free(rt17->MessageBuffer);
rt17->MessageBuffer = NULL;
}
if (rt17->PacketBuffer)
{
memset(rt17->PacketBuffer, 0, PBUFF_LENGTH);
free(rt17->PacketBuffer);
rt17->PacketBuffer = NULL;
}
memset(rt17, 0, sizeof(rt17_t));
free(rt17);
Raw->rcv_data = NULL;
}
}
/* init_rt17 = Initialize RT17 dependent private storage */
EXPORT int init_rt17(raw_t *Raw)
{
rt17_t *rt17 = NULL;
unsigned char *MessageBuffer = NULL, *PacketBuffer = NULL;
if (Raw->format != STRFMT_RT17)
return 0;
if (!(rt17 = (rt17_t*) calloc(1, sizeof(rt17_t))))
{
tracet(0, "RT17: unable to allocate RT17 dependent private data structure.\n");
return 0;
}
Raw->rcv_data = (void*) rt17;
if (!(MessageBuffer = (unsigned char*) calloc(MBUFF_LENGTH, sizeof(unsigned char))))
{
tracet(0, "RT17: unable to allocate RT17 message buffer.\n");
free_rt17(Raw);
return 0;
}
rt17->MessageBuffer = MessageBuffer;
if (!(PacketBuffer = (unsigned char*) calloc(PBUFF_LENGTH, sizeof(unsigned char))))
{
tracet(0, "RT17: unable to allocate RT17 packet buffer.\n");
free_rt17(Raw);
return 0;
}
rt17->PacketBuffer = PacketBuffer;
return 1;
}
/*
| input_rt17 - Read an RT-17 mesasge from a raw data stream
|
| Returns:
|
| -1: error message
| 0: no message (tells caller to please read more data from the stream)
| 1: input observation data
| 2: input ephemeris
| 9: input ion/utc parameter
|
| Each message begins with a 4-byte header, followed by the bytes of data in the packet,
| and the packet ends with a 2-byte trailer. Byte 3 is set to 0 (00h) when the packet
| contains no data.
*/
EXPORT int input_rt17(raw_t *Raw, unsigned char Data)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *MessageBuffer = rt17->MessageBuffer;
unsigned char *PacketBuffer = rt17->PacketBuffer;
unsigned int Page, Pages, Reply;
int Ret = 0;
/* If no current packet */
if (rt17->PacketBytes == 0)
{
/* Find something that looks like a packet. */
if (SyncPacket(rt17, Data))
{
/* Found one. */
rt17->PacketLength = 4 + PacketBuffer[3] + 2; /* 4 (header) + length + 2 (trailer) */
rt17->PacketBytes = 4; /* We now have four bytes in the packet buffer */
}
/* Continue reading the rest of the packet from the stream */
return 0;
}
/* Store the next byte of the packet */
PacketBuffer[rt17->PacketBytes++] = Data;
/*
| Keep storing bytes into the current packet
| until we have what we think are all of them.
*/
if (rt17->PacketBytes < rt17->PacketLength)
return 0;
/*
| At this point we think have an entire packet.
| The prospective packet must end with an ETX.
*/
if (rt17->PacketBuffer[rt17->PacketLength-1] != ETX)
{
tracet(2, "RT17: Prospective packet did not end with an ETX character. Some data lost.\n");
ClearPacketBuffer(rt17);
return 0;
}
/*
| We do indeed have an entire packet.
| Check the packet checksum.
*/
if (!CheckPacketChecksum(PacketBuffer))
{
tracet(2, "RT17: Packet checksum failure. Packet discarded.\n");
ClearPacketBuffer(rt17);
return 0;
}
if (Raw->outtype)
sprintf(Raw->msgtype, "RT17 0x%02X (%4d)", PacketBuffer[2], rt17->PacketLength);
/* If this is a SVDATA packet, then process it immediately */
if (PacketBuffer[2] == RETSVDATA)
{
Ret = DecodeRetsvdata(Raw);
ClearPacketBuffer(rt17);
return Ret;
}
/* Accumulate a sequence of RAWDATA packets (pages) */
if (PacketBuffer[2] == RAWDATA)
{
Page = PacketBuffer[5] >> 4;
Pages = PacketBuffer[5] & 15;
Reply = PacketBuffer[6];
/*
| If this is the first RAWDATA packet in a sequence of RAWDATA packets,
| then make sure it's page one and not a packet somewhere in the middle.
| If not page one, then skip it and continue reading from the stream
| until we find one that starts at page one. Otherwise make sure it is
| a part of the same requence of packets as the last one, that it's
| page number is in sequence.
*/
if (rt17->MessageBytes == 0)
{
if (Page != 1)
{
tracet(2, "RT17: First RAWDATA packet is not page #1. Packet discarded.\n");
ClearPacketBuffer(rt17);
return 0;
}
rt17->Reply = PacketBuffer[6];
}
else if ((Reply != rt17->Reply) || (Page != (rt17->Page + 1)))
{
tracet(2, "RT17: RAWDATA packet sequence number mismatch or page out of order. %u RAWDATA packets discarded.\n", Page);
ClearMessageBuffer(rt17);
ClearPacketBuffer(rt17);
return 0;
}
/* Check for message buffer overflow */
if ((rt17->MessageBytes + rt17->PacketBytes) > MBUFF_LENGTH)
{
tracet(2, "RT17: Buffer would overflow. %u RAWDATA packets discarded.\n", Page);
ClearMessageBuffer(rt17);
ClearPacketBuffer(rt17);
return 0;
}
memcpy(MessageBuffer + rt17->MessageBytes, PacketBuffer, rt17->PacketBytes);
rt17->MessageBytes += rt17->PacketBytes;
rt17->MessageLength += rt17->PacketLength;
ClearPacketBuffer(rt17);
if (Page == Pages)
{
Ret = DecodeRawdata(Raw);
ClearMessageBuffer(rt17);
return Ret;
}
rt17->Page = Page;
return 0;
}
/* Accumulate a sequence of GENOUT (GSOF) packets (pages) */
if (PacketBuffer[2] == GENOUT)
{
Reply = PacketBuffer[4];
Page = PacketBuffer[5];
Pages = PacketBuffer[6];
/*
| If this is the first GENOUT packet in a sequence of GENOUT packets,
| then make sure it's page zero and not a packet somewhere in the middle.
| If not page zero, then skip it and continue reading from the stream
| until we find one that starts at page zero. Otherwise make sure it is
| a part of the same requence of packets as the last one, that it's
| page number is in sequence.
*/
if (rt17->MessageBytes == 0)
{
if (Page != 0)
{
tracet(3, "RT17: First GENOUT packet is not page #0. Packet discarded.\n");
ClearPacketBuffer(rt17);
return 0;
}
rt17->Reply = PacketBuffer[4];
}
else if ((Reply != rt17->Reply) || (Page != (rt17->Page + 1)))
{
tracet(2, "RT17: GENOUT packet sequence number mismatch or page out of order. %u GENOUT packets discarded.\n", Page);
ClearMessageBuffer(rt17);
ClearPacketBuffer(rt17);
return 0;
}
/* Check for message buffer overflow. */
if ((rt17->MessageBytes + rt17->PacketBytes) > MBUFF_LENGTH)
{
tracet(2, "RT17: Buffer would overflow. %u GENOUT packets discarded.\n", Page);
ClearMessageBuffer(rt17);
ClearPacketBuffer(rt17);
return 0;
}
memcpy(MessageBuffer + rt17->MessageBytes, PacketBuffer, rt17->PacketBytes);
rt17->MessageBytes += rt17->PacketBytes;
rt17->MessageLength += rt17->PacketLength;
ClearPacketBuffer(rt17);
if (Page == Pages)
{
Ret = DecodeGSOF(Raw);
ClearMessageBuffer(rt17);
return Ret;
}
rt17->Page = Page;
return 0;
}
/*
| If we fall through to here, then the packet is not one that we support
| (and hence we can't really even get here). Dump the packet on the floor
| and continue reading from the stream.
*/
tracet(2, "RT17: Packet is not GENOUT, RAWDATA or RETSVDATA. Packet discarded.\n");
ClearPacketBuffer(rt17);
return 0;
}
/*
| input_rt17f - Read an RT-17 mesasge from a file
|
| Returns:
|
| -2: End of file (EOF)
| -1: error message
| 0: no message
| 1: input observation data
| 2: input ephemeris
| 9: input ion/utc parameter
*/
EXPORT int input_rt17f(raw_t *Raw, FILE *fp)
{
int i, Data, Ret;
for (i = 0; i < 4096; i++)
{
if ((Data = fgetc(fp)) == EOF) return -2;
if ((Ret = input_rt17(Raw, (unsigned char) Data))) return Ret;
}
return 0; /* return at every 4k bytes */
}
/*
| Private functions (in alphabetical order):
*/
/*
| CheckPacketChecksum - Check the packet checksum
|
| The checksum is computed as the modulo 256 (unsigned 8-bit integer) sum
| of the packet contents starting with the status byte, including the
| packet type byte, length byte, data bytes and ending with the last byte
| of the data bytes. It does not include the STX leader, the ETX trailer
| nor the checksum byte.
*/
static int CheckPacketChecksum(unsigned char *PacketBuffer)
{
unsigned char Checksum = 0;
unsigned char *p = &PacketBuffer[1]; /* Starting with status */
unsigned int Length = PacketBuffer[3] + 3; /* status, type, length, data */
/* Compute the packet checksum */
while (Length > 0)
{
Checksum += *p++;
Length--;
}
/*
| Make sure our computed checksum matches the one at the end of the packet.
| (Note that the above loop by design very conveniently left *p pointing
| to the checksum byte at the end of the packet.)
*/
return (Checksum == *p);
}
/* ClearMessageBuffer - Clear the raw data stream buffer */
static void ClearMessageBuffer(rt17_t *rt17)
{
unsigned char *MessageBuffer = rt17->MessageBuffer;
int i;
for (i = 0; i < 4; i++)
MessageBuffer[i] = 0;
rt17->MessageLength = rt17->MessageBytes = 0;
rt17->Reply = 0;
}
/* ClearPacketBuffer - Clear the packet buffer */
static void ClearPacketBuffer(rt17_t *rt17)
{
unsigned char *PacketBuffer = rt17->PacketBuffer;
int i;
for (i = 0; i < 4; i++)
PacketBuffer[i] = 0;
rt17->PacketLength = rt17->PacketBytes = 0;
}
/*
| DecodeBeidouEphemeris - Decode a Beidou Ephemeris record
|
| Returns:
|
| -1: error message
| 2: input ephemeris
|
| See reference #1 above for documentation of the RETSVDATA Beidou Ephemeris.
*/
static int DecodeBeidouEphemeris(raw_t *Raw)
{
tracet(3, "DecodeBeidouEphemeris(); not yet implemented.\n");
return 0;
#if 0
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *p = rt17->PacketBuffer;
int prn, sat, toc, tow;
unsigned int Flags, toe;
double sqrtA;
eph_t eph={0};
tracet(3, "RT17: DecodeBeidouEphemeris(); Length=%d\n", rt17->PacketLength);
if (rt17->PacketLength < 182)
{
tracet(2, "RT17: RETSVDATA packet length %d < 182 bytes. GPS ephemeris packet discarded.\n", rt17->PacketLength);
return -1;
}
prn = U1(p+5);
if (!(sat=satno(SYS_CMP, prn)))
{
tracet(2, "RT17: Beidou ephemeris satellite number error, PRN=%d.\n", prn);
return -1;
}
eph.week = U2(p+6); /* 006-007: Ephemeris Week number (weeks) */
eph.iodc = U2(p+8); /* 008-009: IODC */
/* Reserved byte */ /* 010-010: RESERVED */
eph.iode = U1(p+11); /* 011-011: IODE */
tow = I4(p+12); /* 012-015: TOW */
toc = I4(p+16); /* 016-019: TOC (seconds) */
toe = U4(p+20); /* 020-023: TOE (seconds) */
eph.tgd[0]= R8(p+24); /* 024-031: TGD (seconds) */
eph.f2 = R8(p+32); /* 032-029: AF2 (seconds/seconds^2) */
eph.f1 = R8(p+40); /* 040-047: AF1 (seconds/seconds) */
eph.f0 = R8(p+48); /* 048-055: AF0 (seconds) */
eph.crs = R8(p+56); /* 056-063: CRS (meters) */
eph.deln = R8(p+64); /* 064-071: DELTA N (semi-circles/second) */
eph.M0 = R8(p+72); /* 072-079: M SUB 0 (semi-circles) */
eph.cuc = R8(p+80); /* 080-087: CUC (semi-circles) */
eph.e = R8(p+88); /* 088-095: ECCENTRICITY (dimensionless) */
eph.cus = R8(p+96); /* 096-103: CUS (semi-circles) */
sqrtA = R8(p+104); /* 104-111: SQRT A (meters ^ 0.5) */
eph.cic = R8(p+112); /* 112-119: CIC (semi-circles) */
eph.OMG0 = R8(p+120); /* 120-127: OMEGA SUB 0 (semi-circles) */
eph.cis = R8(p+128); /* 128-135: CIS (semi-circlces) */
eph.i0 = R8(p+136); /* 136-143: I SUB 0 (semi-circles) */
eph.crc = R8(p+144); /* 144-151: CRC (meters) */
eph.omg = R8(p+152); /* 152-159: OMEGA (semi-circles?) */
eph.OMGd = R8(p+160); /* 160-167: OMEGA DOT (semi-circles/second) */
eph.idot = R8(p+168); /* 168-175: I DOT (semi-circles/second) */
Flags = U4(p+176); /* 176-179: FLAGS */
/*
| Multiply these by PI to make semi-circle units into radian units for RTKLIB.
*/
eph.deln *= SC2RAD;
eph.i0 *= SC2RAD;
eph.idot *= SC2RAD;
eph.M0 *= SC2RAD;
eph.omg *= SC2RAD;
eph.OMG0 *= SC2RAD;
eph.OMGd *= SC2RAD;
/*
| As specifically directed to do so by Reference #1, multiply these by PI.
| to make semi-circle units into radian units, which is what RTKLIB needs.
*/
eph.cic *= SC2RAD;
eph.cis *= SC2RAD;
eph.cuc *= SC2RAD;
eph.cus *= SC2RAD;
/*
| Select the correct curve fit interval as per ICD-GPS-200 sections
| 20.3.3.4.3.1 and 20.3.4.4 using IODC, fit flag and Table 20-XII.
*/
if (Flags & M_BIT10) /* Subframe 2, word 10, bit 17 (fit flag) */
{
if ((eph.iodc >= 240) && (eph.iodc <= 247))
eph.fit = 8;
else if (((eph.iodc >= 248) && (eph.iodc <= 255)) || (eph.iodc == 496))
eph.fit = 14;
else if ((eph.iodc >= 497) && (eph.iodc <= 503))
eph.fit = 26;
else if ((eph.iodc >= 504) && (eph.iodc <= 510))
eph.fit = 50;
else if ((eph.iodc == 511) || ((eph.iodc >= 752) && (eph.iodc <= 756)))
eph.fit = 74;
else if ((eph.iodc >= 757) && (eph.iodc <= 763))
eph.fit = 98;
else if (((eph.iodc >= 764) && (eph.iodc <= 767)) || ((eph.iodc >= 1008) && (eph.iodc <= 1010)))
eph.fit = 122;
else if ((eph.iodc >= 1011) && (eph.iodc <= 1020))
eph.fit = 146;
else
eph.fit = 6;
}
else
eph.fit = 4;
eph.flag = (Flags & M_BIT0); /* Subframe 1, word 4, bit 1, Data flag for L2 P-code */
eph.code = (Flags >> 1) & 3; /* Subframe 1, word 3, bits 11-12, Codes on L2 channel */
eph.svh = (Flags >> 4) & 127; /* Subframe 1, word 3, bits 17-22, SV health from ephemeris */
eph.sva = (Flags >> 11) & 15; /* Subframe 1, word 3, bits 13-16, User Range Accuracy index */
eph.A = sqrtA * sqrtA;
eph.toes = toe;
eph.toc = bdt2gpst(bdt2time(eph.week, toc));
eph.toe = bdt2gpst(bdt2time(eph.week, toe));
eph.ttr = bdt2gpst(bdt2time(eph.week, tow));
tracet(3, "RT17: DecodeBeidouEphemeris(); SAT=%d, IODC=%d, IODE=%d, WEEK=%d.\n", sat, eph.iodc, eph.iode, eph.week);
if (!strstr(Raw->opt,"-EPHALL"))
{
if (eph.iode == Raw->nav.eph[sat-1].iode)
return 0; /* unchanged */
}
eph.sat = sat;
Raw->nav.eph[sat-1] = eph;
Raw->ephsat = sat;
return 2;
#endif
}
/*
| DecodeGalileoEphemeris - Decode a Galileo Ephemeris record
|
| Returns:
|
| -1: error message
| 2: input ephemeris
|
| See reference #1 above for documentation of the RETSVDATA Galileo Ephemeris.
*/
static int DecodeGalileoEphemeris(raw_t *Raw)
{
tracet(3, "DecodeGalileoEphemeris(); not yet implemented.\n");
return 0;
#if 0
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *p = rt17->PacketBuffer;
int prn, sat, toc, tow;
unsigned int toe;
double sqrtA;
eph_t eph={0};
unsigned char SISA, MODEL1, MODEL2;
unsigned short IODnav, HSDVS;
double BDG1, BDG2;
tracet(3, "RT17: DecodeGalileoEphemeris(); Length=%d\n", rt17->PacketLength);
if (rt17->PacketLength < 190)
{
tracet(2, "RT17: RETSVDATA packet length %d < 190 bytes. Galileo ephemeris packet discarded.\n", rt17->PacketLength);
return -1;
}
prn = U1(p+5);
if (!(sat=satno(SYS_GAL, prn)))
{
tracet(2, "RT17: Galileo ephemeris satellite number error, PRN=%d.\n", prn);
return -1;
}
eph.code = U1(p+6); /* 006-006: Data source 0:E1B 1:E5B 2:E5A */
eph.week = U2(p+7); /* 007-008: Ephemeris Week number (weeks) */
tow = I4(p+9); /* 008-012: TOW */
IODnav = U2(p+13); /* 013-014: Ephemeris and clock correction issue of data */
toe = U4(p+15); /* 015-018: TOE (seconds) */
eph.crs = R8(p+19); /* 019-026: CRS (meters) */
eph.deln = R8(p+27); /* 027-034: DELTA N (semi-circles/second) */
eph.M0 = R8(p+35); /* 035-042: M SUB 0 (semi-circles) */
eph.cuc = R8(p+43); /* 043-050: CUC (semi-circles) */
eph.e = R8(p+51); /* 051-058: ECCENTRICITY (dimensionless) */
eph.cus = R8(p+59); /* 059-066: CUS (semi-circles) */
sqrtA = R8(p+67); /* 067-074: SQRT A (meters ^ 0.5) */
eph.cic = R8(p+75); /* 075-082: CIC (semi-circles) */
eph.OMG0 = R8(p+83); /* 083-090: OMEGA SUB 0 (semi-circles) */
eph.cis = R8(p+91); /* 091-098: CIS (semi-circlces) */
eph.i0 = R8(p+99); /* 099-106: I SUB 0 (semi-circles) */
eph.crc = R8(p+107); /* 107-114: CRC (meters) */
eph.omg = R8(p+115); /* 115-122: OMEGA (semi-circles?) */
eph.OMGd = R8(p+123); /* 123-130: OMEGA DOT (semi-circles/second) */
eph.idot = R8(p+131); /* 131-138: I DOT (semi-circles/second) */
SISA = U1(p+149); /* 149-149: ? */
HSDVS = U2(p+150); /* 150-151: Signal Health Flag */
toc = I4(p+142); /* 142-145: TOC (seconds) */
eph.f0 = R8(p+146); /* 146-153: AF0 (seconds) */
eph.f1 = R8(p+154); /* 154-161: AF1 (seconds/seconds) */
eph.f2 = R8(p+162); /* 162-169: AF2 (seconds/seconds^2) */
BDG1 = R8(p+170); /* 170-177: Seconds */
MODEL1 = U1(p+178); /* 178-178: Clock model for TOC/AF0?2/BGD1 */
BDG2 = R8(p+179); /* 179-186: Seconds */
MODEL2 = U1(p+187); /* 187-187: Clock model for BGD2 */
/*
| Multiply these by PI to make semi-circle units into radian units for RTKLIB.
*/
eph.deln *= SC2RAD;
eph.i0 *= SC2RAD;
eph.idot *= SC2RAD;
eph.M0 *= SC2RAD;
eph.omg *= SC2RAD;
eph.OMG0 *= SC2RAD;
eph.OMGd *= SC2RAD;
/*
| As specifically directed to do so by Reference #1, multiply these by PI.
| to make semi-circle units into radian units, which is what RTKLIB needs.
*/
eph.cic *= SC2RAD;
eph.cis *= SC2RAD;
eph.cuc *= SC2RAD;
eph.cus *= SC2RAD;
eph.A = sqrtA * sqrtA;
eph.toes = toe;
eph.toc = gst2time(eph.week, toc);
eph.toe = gst2time(eph.week, toe);
eph.ttr = gst2time(eph.week, tow);
tracet(3, "RT17: DecodeGalileoEphemeris(); SAT=%d, IODC=%d, IODE=%d, WEEK=%d.\n", sat, eph.iodc, eph.iode, eph.week);
if (!strstr(Raw->opt,"-EPHALL"))
{
if (eph.iode == Raw->nav.eph[sat-1].iode)
return 0; /* unchanged */
}
eph.sat = sat;
Raw->nav.eph[sat-1] = eph;
Raw->ephsat = sat;
return 2;
#endif
}
/*
| DecodeGLONASSEphemeris - Decode a GLONASS Ephemeris record
|
| Returns:
|
| -1: error message
| 2: input ephemeris
|
| See reference #1 above for documentation of the RETSVDATA GLONASS Ephemeris.
*/
static int DecodeGLONASSEphemeris(raw_t *Raw)
{
tracet(3, "DecodeGLONASSEphemeris(); not yet implemented.\n");
return 0;
}
/*
| DecodeGPSEphemeris - Decode a GPS Ephemeris record
|
| Returns:
|
| -1: error message
| 2: input ephemeris
|
| See ICD-GPS-200C.PDF for documentation of the GPS satellite ephemeris.
| See reference #1 above for documentation of the RETSVDATA GPS Ephemeris.
*/
static int DecodeGPSEphemeris(raw_t *Raw)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *p = rt17->PacketBuffer;
int prn, sat, toc, tow;
unsigned int Flags, toe;
double sqrtA;
eph_t eph={0};
tracet(3, "RT17: DecodeGPSEphemeris(); Length=%d\n", rt17->PacketLength);
if (rt17->PacketLength < 182)
{
tracet(2, "RT17: RETSVDATA packet length %d < 182 bytes. GPS ephemeris packet discarded.\n", rt17->PacketLength);
return -1;
}
prn = U1(p+5);
if (!(sat=satno(SYS_GPS, prn)))
{
tracet(2, "RT17: GPS ephemeris satellite number error, PRN=%d.\n", prn);
return -1;
}
eph.week = U2(p+6); /* 006-007: Ephemeris Week number (weeks) */
eph.iodc = U2(p+8); /* 008-009: IODC */
/* Reserved byte */ /* 010-010: RESERVED */
eph.iode = U1(p+11); /* 011-011: IODE */
tow = I4(p+12); /* 012-015: TOW */
toc = I4(p+16); /* 016-019: TOC (seconds) */
toe = U4(p+20); /* 020-023: TOE (seconds) */
eph.tgd[0]= R8(p+24); /* 024-031: TGD (seconds) */
eph.f2 = R8(p+32); /* 032-029: AF2 (seconds/seconds^2) */
eph.f1 = R8(p+40); /* 040-047: AF1 (seconds/seconds) */
eph.f0 = R8(p+48); /* 048-055: AF0 (seconds) */
eph.crs = R8(p+56); /* 056-063: CRS (meters) */
eph.deln = R8(p+64); /* 064-071: DELTA N (semi-circles/second) */
eph.M0 = R8(p+72); /* 072-079: M SUB 0 (semi-circles) */
eph.cuc = R8(p+80); /* 080-087: CUC (semi-circles) */
eph.e = R8(p+88); /* 088-095: ECCENTRICITY (dimensionless) */
eph.cus = R8(p+96); /* 096-103: CUS (semi-circles) */
sqrtA = R8(p+104); /* 104-111: SQRT A (meters ^ 0.5) */
eph.cic = R8(p+112); /* 112-119: CIC (semi-circles) */
eph.OMG0 = R8(p+120); /* 120-127: OMEGA SUB 0 (semi-circles) */
eph.cis = R8(p+128); /* 128-135: CIS (semi-circlces) */
eph.i0 = R8(p+136); /* 136-143: I SUB 0 (semi-circles) */
eph.crc = R8(p+144); /* 144-151: CRC (meters) */
eph.omg = R8(p+152); /* 152-159: OMEGA (semi-circles?) */
eph.OMGd = R8(p+160); /* 160-167: OMEGA DOT (semi-circles/second) */
eph.idot = R8(p+168); /* 168-175: I DOT (semi-circles/second) */
Flags = U4(p+176); /* 176-179: FLAGS */
/*
| Multiply these by PI to make ICD specified semi-circle units into radian
| units for RTKLIB.
*/
eph.deln *= SC2RAD;
eph.i0 *= SC2RAD;
eph.idot *= SC2RAD;
eph.M0 *= SC2RAD;
eph.omg *= SC2RAD;
eph.OMG0 *= SC2RAD;
eph.OMGd *= SC2RAD;
/*
| As specifically directed to do so by Reference #1, multiply these by PI.
| to make semi-circle units into radian units, which is what ICD-GPS-200C
| calls for and also what RTKLIB needs.
*/
eph.cic *= SC2RAD;
eph.cis *= SC2RAD;
eph.cuc *= SC2RAD;
eph.cus *= SC2RAD;
/*
| Select the correct curve fit interval as per ICD-GPS-200 sections
| 20.3.3.4.3.1 and 20.3.4.4 using IODC, fit flag and Table 20-XII.
*/
if (Flags & M_BIT10) /* Subframe 2, word 10, bit 17 (fit flag) */
{
if ((eph.iodc >= 240) && (eph.iodc <= 247))
eph.fit = 8;
else if (((eph.iodc >= 248) && (eph.iodc <= 255)) || (eph.iodc == 496))
eph.fit = 14;
else if ((eph.iodc >= 497) && (eph.iodc <= 503))
eph.fit = 26;
else if ((eph.iodc >= 504) && (eph.iodc <= 510))
eph.fit = 50;
else if ((eph.iodc == 511) || ((eph.iodc >= 752) && (eph.iodc <= 756)))
eph.fit = 74;
else if ((eph.iodc >= 757) && (eph.iodc <= 763))
eph.fit = 98;
else if (((eph.iodc >= 764) && (eph.iodc <= 767)) || ((eph.iodc >= 1008) && (eph.iodc <= 1010)))
eph.fit = 122;
else if ((eph.iodc >= 1011) && (eph.iodc <= 1020))
eph.fit = 146;
else
eph.fit = 6;
}
else
eph.fit = 4;
eph.flag = (Flags & M_BIT0); /* Subframe 1, word 4, bit 1, Data flag for L2 P-code */
eph.code = (Flags >> 1) & 3; /* Subframe 1, word 3, bits 11-12, Codes on L2 channel */
eph.svh = (Flags >> 4) & 127; /* Subframe 1, word 3, bits 17-22, SV health from ephemeris */
eph.sva = (Flags >> 11) & 15; /* Subframe 1, word 3, bits 13-16, User Range Accuracy index */
eph.A = sqrtA * sqrtA;
eph.toes = toe;
eph.toc = gpst2time(eph.week, toc);
eph.toe = gpst2time(eph.week, toe);
eph.ttr = gpst2time(eph.week, tow);
tracet(3, "RT17: DecodeGPSEphemeris(); SAT=%d, IODC=%d, IODE=%d, WEEK=%d.\n", sat, eph.iodc, eph.iode, eph.week);
if (rt17->Week && (rt17->Week != eph.week))
{
tracet(2, "RT17: Currently set or assumed GPS week does not match received ephemeris week.\n");
tracet(2, "RT17: Set or assumed GPS week: %d Received ephemeris week: %d\n", rt17->Week, eph.week);
}
if (!(rt17->Flags & M_WEEK_OPTION))
{
if (!rt17->Week || (rt17->Flags & M_WEEK_TIME) || (eph.week > rt17->Week))
{
if (!rt17->Week)
tracet(2, "RT17: Initial GPS WEEK number unknown; WEEK number %d assumed for now.\n", eph.week);
else
tracet(2, "RT17: Changing assumed week number from %d to %d.\n", rt17->Week, eph.week);
rt17->Flags &= ~M_WEEK_TIME;
rt17->Flags |= M_WEEK_EPH;
rt17->Week = eph.week;
}
}
if (!strstr(Raw->opt,"-EPHALL"))
{
if (eph.iode == Raw->nav.eph[sat-1].iode)
return 0; /* unchanged */
}
eph.sat = sat;
Raw->nav.eph[sat-1] = eph;
Raw->ephsat = sat;
return 2;
}
/* DecodeGSOF - Decode a General Serial Output Format (GSOF) message */
static int DecodeGSOF(raw_t *Raw)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
int InputLength, Ret = 0;
unsigned char RecordLength, RecordType, *p;
char *RecordType_s = NULL;
/*
| Reassemble origional message by removing packet headers,
| trailers and page framing.
*/
UnwrapGenout(rt17);
p = rt17->MessageBuffer;
InputLength = rt17->MessageLength;
while (InputLength)
{
RecordType = p[0];
RecordLength = p[1];
if (RecordType < (sizeof(GSOFTable) / sizeof(char*)))
RecordType_s = (char*) GSOFTable[RecordType];
if (!RecordType_s)
RecordType_s = "Unknown";
tracet(3, "RT17: Trimble packet type=0x40 (GENOUT), GSOF record type=%d (%s), Length=%d.\n", RecordType, RecordType_s, RecordLength);
/* Process (or possibly ignore) the message */
switch (RecordType)
{
case 1:
Ret = DecodeGSOF1(Raw, p);
break;
case 3:
Ret = DecodeGSOF3(Raw, p);
break;
case 15:
Ret = DecodeGSOF15(Raw, p);
break;
case 16:
Ret = DecodeGSOF16(Raw, p);
break;
case 26:
Ret = DecodeGSOF26(Raw, p);
break;
case 41:
Ret = DecodeGSOF41(Raw, p);
break;
default:
tracet(3, "RT17: GSOF message not processed.\n");
}
RecordLength += 2;
p += RecordLength;
InputLength -= RecordLength;
}
return Ret;
}
/* DecodeGSOF1 - Decode a Position Time GSOF message */
static int DecodeGSOF1(raw_t *Raw, unsigned char *p)
{
if (p[1] < 6)
tracet(2, "RT17: GSOF Position Time message record length %d < 6 bytes. Record discarded.\n", p[1]);
else
SetWeek(Raw, I2(p+6), ((double) I4(p+2)) * 0.001);
return 0;
}
/* DecodeGSOF3 - Decode an ECEF Position GSOF message */
static int DecodeGSOF3(raw_t *Raw, unsigned char *p)
{
sta_t *sta = &Raw->sta;
if (p[1] < 24)
tracet( 2, "RT17: GSOF ECEF Position record length %d < 24 bytes. Record discarded.\n", p[1] );
else
{
sta->pos[0] = R8(p+2);
sta->pos[1] = R8(p+10);
sta->pos[2] = R8(p+18);
sta->del[0] = 0.0;
sta->del[1] = 0.0;
sta->del[2] = 0.0;
sta->hgt = 0.0;
sta->deltype = 0; /* e/n/u */
}
return 5;
}
/* DecodeGSOF15 - Decode a Receiver Serial Number GSOF message */
static int DecodeGSOF15(raw_t *Raw, unsigned char *p)
{
if (p[1] < 15)
tracet(2, "RT17: GSOF Receiver Serial Number record length %d < 15 bytes. Record discarded.\n", p[1]);
else
sprintf(Raw->sta.recsno, "%u", U4(p+2));
return 0;
}
/* DecodeGSOF16 - Decode a Current Time GSOF message */
static int DecodeGSOF16(raw_t *Raw, unsigned char *p)
{
if (p[1] < 9)
tracet( 2, "RT17: GSOF Current Time message record length %d < 9 bytes. Record discarded.\n", p[1] );
else if (U1(p+10) & M_BIT0) /* If week and milliseconds of week are valid */
SetWeek(Raw, I2(p+6), ((double) I4(p+2)) * 0.001);
return 0;
}
/* DecodeGSOF26 - Decode a Position Time UTC GSOF message */
static int DecodeGSOF26(raw_t *Raw, unsigned char *p)
{
if (p[1] < 6)
tracet(2, "RT17: GSOF Position Time UTC message record length %d < 6 bytes. Record discarded.\n", p[1]);
else
SetWeek(Raw, I2(p+6), ((double) I4(p+2)) * 0.001);
return 0;
}
/* DecodeGSOF41 - Decode a Base Position and Quality Indicator GSOF message */
static int DecodeGSOF41(raw_t *raw, unsigned char *p)
{
if (p[1] < 6)
tracet(2, "RT17: GSOF Base Position and Quality Indicator message record length %d < 6 bytes. Record discarded.\n", p[1]);
else
SetWeek(raw, I2(p+6), ((double) I4(p+2)) * 0.001);
return 0;
}
/*
| DecodeIONAndUTCData - Decode an ION / UTC data record
|
| Returns:
|
| -1: error message
| 9: input ion/utc parameter|
|
| See ICD-GPS-200C.PDF for documetation of GPS ION / UTC data.
| See reference #1 above for documentation of RETSVDATA and ION / UTC data.
*/
static int DecodeIONAndUTCData(raw_t *Raw)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
int week;
unsigned char *p = rt17->PacketBuffer;
nav_t *nav = &Raw->nav;
double *ion_gps = nav->ion_gps;
double *utc_gps = nav->utc_gps;
tracet(3, "RT17: DecodeIONAndUTCData, Length=%d.\n", rt17->PacketLength);
if (rt17->PacketLength < 129)
{
tracet(2, "RT17: RETSVDATA packet length %d < 129 bytes. GPS ION / UTC data packet discarded.\n", rt17->PacketLength);
return -1;
}
/* ION / UTC data does not have the current GPS week number. Punt! */
week = GetWeek(Raw, 0.0);
ion_gps[0] = R8(p+6); /* 006-013: ALPHA 0 (seconds) */
ion_gps[1] = R8(p+14); /* 014-021: ALPHA 1 (seconds/semi-circle) */
ion_gps[2] = R8(p+22); /* 022-029: ALPHA 2 (seconds/semi-circle)^2 */
ion_gps[3] = R8(p+30); /* 030-037: ALPHA 3 (seconds/semi-circle)^3 */
ion_gps[4] = R8(p+38); /* 038-045: BETA 0 (seconds) */
ion_gps[5] = R8(p+46); /* 046-053: BETA 1 (seconds/semi-circle) */
ion_gps[6] = R8(p+54); /* 054-061: BETA 2 (seconds/semi-circle)^2 */
ion_gps[7] = R8(p+62); /* 062-069: BETA 3 (seconds/semi-circle)^3 */
utc_gps[0] = R8(p+70); /* 070-077: ASUB0 (seconds)*/
utc_gps[1] = R8(p+78); /* 078-085: ASUB1 (seconds/seconds) */
utc_gps[2] = R8(p+86); /* 086-093: TSUB0T */
utc_gps[3] = week;
nav->leaps =(int) R8(p+94); /* 094-101: DELTATLS (seconds) */
/* Unused by RTKLIB R8 */ /* 102-109: DELTATLSF */
/* Unused by RTKLIB R8 */ /* 110-117: IONTIME */
/* Unused by RTKLIB U1 */ /* 118-118: WNSUBT */
/* Unused by RTKLIB U1 */ /* 119-119: WNSUBLSF */
/* Unused by RTKLIB U1 */ /* 120-120: DN */
/* Reserved six bytes */ /* 121-126: RESERVED */
return 9;
}
/*
| DecodeQZSSEphemeris - Decode a QZSS Ephemeris record
|
| Returns:
|
| -1: error message
| 2: input ephemeris
|
| See reference #1 above for documentation of the RETSVDATA QZSS Ephemeris.
*/
static int DecodeQZSSEphemeris(raw_t *Raw)
{
tracet(3, "DecodeQZSSEphemeris(); not yet implemented.\n");
return 0;
#if 0
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *p = rt17->PacketBuffer;
int prn, sat, toc, tow;
unsigned int Flags, toe;
double sqrtA;
eph_t eph={0};
tracet(3, "RT17: DecodeQZSSEphemeris(); Length=%d\n", rt17->PacketLength);
if (rt17->PacketLength < 184)
{
tracet(2, "RT17: RETSVDATA packet length %d < 184 bytes. QZSS ephemeris packet discarded.\n", rt17->PacketLength);
return -1;
}
prn = U1(p+5);
if (!(sat=satno(SYS_GPS, prn)))
{
tracet(2, "RT17: QZSS ephemeris satellite number error, PRN=%d.\n", prn);
return -1;
}
/* Not used by RTKLIB 006-006: Source: 0:L1CA 1:L1C 2:L2C 3:L5 */
eph.week = U2(p+8); /* 008-009: Ephemeris Week number (weeks) */
eph.iodc = U2(p+10); /* 010-011: IODC */
/* Reserved byte 012-012: RESERVED */
eph.iode = U1(p+13); /* 013-013: IODE */
tow = I4(p+14); /* 014-017: TOW */
toc = I4(p+18); /* 018-021: TOC (seconds) */
toe = U4(p+22); /* 022-025: TOE (seconds) */
eph.tgd[0]= R8(p+26); /* 026-033: TGD (seconds) */
eph.f2 = R8(p+34); /* 034-041: AF2 (seconds/seconds^2) */
eph.f1 = R8(p+42); /* 042-049: AF1 (seconds/seconds) */
eph.f0 = R8(p+50); /* 050-057: AF0 (seconds) */
eph.crs = R8(p+58); /* 058-065: CRS (meters) */
eph.deln = R8(p+66); /* 066-073: DELTA N (semi-circles/second) */
eph.M0 = R8(p+74); /* 074-081: M SUB 0 (semi-circles) */
eph.cuc = R8(p+82); /* 082-089: CUC (semi-circles) */
eph.e = R8(p+90); /* 090-097: ECCENTRICITY (dimensionless) */
eph.cus = R8(p+98); /* 098-105: CUS (semi-circles) */
sqrtA = R8(p+106); /* 106-113: SQRT A (meters ^ 0.5) */
eph.cic = R8(p+114); /* 114-121: CIC (semi-circles) */
eph.OMG0 = R8(p+122); /* 122-129: OMEGA SUB 0 (semi-circles) */
eph.cis = R8(p+130); /* 130-137: CIS (semi-circlces) */
eph.i0 = R8(p+138); /* 138-145: I SUB 0 (semi-circles) */
eph.crc = R8(p+146); /* 146-153: CRC (meters) */
eph.omg = R8(p+154); /* 154-161: OMEGA (semi-circles?) */
eph.OMGd = R8(p+162); /* 162-169: OMEGA DOT (semi-circles/second) */
eph.idot = R8(p+170); /* 170-177: I DOT (semi-circles/second) */
Flags = U4(p+178); /* 178-181: FLAGS */
/*
| Multiply these by PI to make ICD specified semi-circle units into radian
| units for RTKLIB.
*/
eph.deln *= SC2RAD;
eph.i0 *= SC2RAD;
eph.idot *= SC2RAD;
eph.M0 *= SC2RAD;
eph.omg *= SC2RAD;
eph.OMG0 *= SC2RAD;
eph.OMGd *= SC2RAD;
/*
| As specifically directed to do so by Reference #1, multiply these by PI.
| to make semi-circle units into radian units, which is what ICD-GPS-200C
| calls for and also what RTKLIB needs.
*/
eph.cic *= SC2RAD;
eph.cis *= SC2RAD;
eph.cuc *= SC2RAD;
eph.cus *= SC2RAD;
/*
| Select the correct curve fit interval as per ICD-GPS-200 sections
| 20.3.3.4.3.1 and 20.3.4.4 using IODC, fit flag and Table 20-XII.
*/
if (Flags & M_BIT10) /* Subframe 2, word 10, bit 17 (fit flag) */
{
if ((eph.iodc >= 240) && (eph.iodc <= 247))
eph.fit = 8;
else if (((eph.iodc >= 248) && (eph.iodc <= 255)) || (eph.iodc == 496))
eph.fit = 14;
else if ((eph.iodc >= 497) && (eph.iodc <= 503))
eph.fit = 26;
else if ((eph.iodc >= 504) && (eph.iodc <= 510))
eph.fit = 50;
else if ((eph.iodc == 511) || ((eph.iodc >= 752) && (eph.iodc <= 756)))
eph.fit = 74;
else if ((eph.iodc >= 757) && (eph.iodc <= 763))
eph.fit = 98;
else if (((eph.iodc >= 764) && (eph.iodc <= 767)) || ((eph.iodc >= 1008) && (eph.iodc <= 1010)))
eph.fit = 122;
else if ((eph.iodc >= 1011) && (eph.iodc <= 1020))
eph.fit = 146;
else
eph.fit = 6;
}
else
eph.fit = 4;
eph.flag = (Flags & M_BIT0); /* Subframe 1, word 4, bit 1, Data flag for L2 P-code */
eph.code = (Flags >> 1) & 3; /* Subframe 1, word 3, bits 11-12, Codes on L2 channel */
eph.svh = (Flags >> 4) & 127; /* Subframe 1, word 3, bits 17-22, SV health from ephemeris */
eph.sva = (Flags >> 11) & 15; /* Subframe 1, word 3, bits 13-16, User Range Accuracy index */
eph.A = sqrtA * sqrtA;
eph.toes = toe;
eph.toc = gpst2time(eph.week, toc);
eph.toe = gpst2time(eph.week, toe);
eph.ttr = gpst2time(eph.week, tow);
tracet(3, "RT17: DecodeQZSSEphemeris(); SAT=%d, IODC=%d, IODE=%d, WEEK=%d.\n", sat, eph.iodc, eph.iode, eph.week);
if (!strstr(Raw->opt,"-EPHALL"))
{
if (eph.iode == Raw->nav.eph[sat-1].iode)
return 0; /* unchanged */
}
eph.sat = sat;
Raw->nav.eph[sat-1] = eph;
Raw->ephsat = sat;
return 2;
#endif
}
/*
| DecodeRawdata - Decode an RAWDATA packet sequence
|
| Returns:
|
| -1: error message
| 0: no message (tells caller to please read more data from the stream)
| 1: input observation data
*/
static int DecodeRawdata(raw_t *Raw)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *MessageBuffer = rt17->MessageBuffer;
int Ret = 0;
unsigned int rif;
char *RecordType_s = NULL;
unsigned char RecordType = MessageBuffer[4];
if (RecordType < (sizeof(RawdataTable) / sizeof(char*)))
RecordType_s = (char*) RawdataTable[RecordType];
if (!RecordType_s)
RecordType_s = "Unknown";
tracet(3, "RT17: Trimble packet type=0x57 (RAWDATA), Recordtype=%d (%s), Length=%d.\n", RecordType, RecordType_s, rt17->MessageLength);
/*
| Reassemble origional message by removing packet headers,
| trailers and page framing.
*/
UnwrapRawdata(rt17, &rif);
/* Process (or possibly ignore) the message */
switch (RecordType)
{
case 0:
Ret = DecodeType17(Raw, rif);
break;
case 7:
Ret = DecodeType29(Raw);
break;
default:
tracet(3, "RT17: Packet not processed.\n");
}
return Ret;
}
/*
| DecodeRetsvdata - Decode an SVDATA packet
|
| Returns:
|
| -1: error message
| 0: no message (tells caller to please read more data from the stream)
| 2: input ephemeris
| 9: input ion/utc parameter
*/
static int DecodeRetsvdata(raw_t *Raw)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *PacketBuffer = rt17->PacketBuffer;
int Ret = 0;
char *Subtype_s = NULL;
unsigned char Subtype = PacketBuffer[4];
if (Subtype < (sizeof(RetsvdataTable) / sizeof(char*)))
Subtype_s = (char*) RetsvdataTable[Subtype];
if (!Subtype_s)
Subtype_s = "Unknown";
tracet(3, "RT17: Trimble packet type=0x55 (RETSVDATA), Subtype=%d (%s), Length=%d.\n", Subtype, Subtype_s, rt17->PacketLength);
/* Process (or possibly ignore) the message */
switch (Subtype)
{
case 1:
Ret = DecodeGPSEphemeris(Raw);
break;
case 3:
Ret = DecodeIONAndUTCData(Raw);
break;
case 9:
Ret = DecodeGLONASSEphemeris(Raw);
break;
case 11:
Ret = DecodeGalileoEphemeris(Raw);
break;
case 14:
Ret = DecodeQZSSEphemeris(Raw);
break;
case 21:
Ret = DecodeBeidouEphemeris(Raw);
break;
default:
tracet(3, "RT17: Packet not processed.\n");
}
return Ret;
}
/*
| DecodeType17 - Decode Real-Time survey data (record type 17)
|
| Returns:
|
| -1: error message
| 0: no message (tells caller to please read more data from the stream)
| 1: input observation data
|
| Handles expanded and concise formats with and without enhanced record data.
*/
static int DecodeType17(raw_t *Raw, unsigned int rif)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *p = rt17->MessageBuffer;
double ClockOffset, tow;
int Flags1, Flags2, FlagStatus, i, n, nsat, prn, Week;
gtime_t Time;
obsd_t *obs;
tow = R8(p) * 0.001; p += 8; /* Receive time within the current GPS week. */
ClockOffset = R8(p) * 0.001; p += 8; /* Clock offset value. 0.0 = not known */
#if 0
tow += ClockOffset;
#endif
/* The observation data does not have the current GPS week number. Punt! */
Week = GetWeek(Raw, tow);
Time = gpst2time(Week, tow);
nsat = U1(p); p++; /* Number of SV data blocks in the record */
for (i = n = 0; (i < nsat) && (i < MAXOBS); i++)
{
obs = &Raw->obs.data[n];
memset(obs, 0, sizeof(obsd_t));
obs->time = Time;
if (rif & M_CONCISE)
{
/* Satellite number (1-32). */
prn = U1(p);
p++;
/* These indicate what data is loaded, is valid, etc */
Flags1 = U1(p);
p++;
Flags2 = U1(p);
p++;
/* These are not needed by RTKLIB */
p++; /* I1 Satellite Elevation Angle (degrees) */
p += 2; /* I2 Satellite Azimuth (degrees) */
if (Flags1 & M_BIT6) /* L1 data valid */
{
/* Measure of L1 signal strength (dB * 4) */
obs->SNR[0] = U1(p);
p++;
/* Full L1 C/A code or P-code pseudorange (meters) */
obs->P[0] = R8(p);
p += 8;
/* L1 Continuous Phase (cycles) */
if (Flags1 & M_BIT4) /* L1 phase valid */
obs->L[0] = -R8(p);
p += 8;
/* L1 Doppler (Hz) */
obs->D[0] = R4(p);
p += 4;
}
if (Flags1 & M_BIT0) /* L2 data loaded */
{
/* Measure of L2 signal strength (dB * 4) */
obs->SNR[1] = U1(p);
p++;
/* L2 Continuous Phase (cycles) */
if (Flags1 & M_BIT5)
obs->L[1] = -R8(p);
p += 8;
/* L2 P-Code or L2 Encrypted Code */
if (Flags1 & M_BIT5) /* L2 range valid */
obs->P[1] = obs->P[0] + R4(p);
p += 4;
}
/*
| We can't use the IODE flags in this context.
| We already have slip flags and don't need slip counters.
*/
if (rif & M_ENHANCED)
{
p++; /* U1 IODE, Issue of Data Ephemeris */
p++; /* U1 L1 cycle slip roll-over counter */
p++; /* U1 L2 cycle slip roll-over counter */
}
}
else /* Expanded Format */
{
/* Satellite number (1-32) */
prn = U1(p);
p++;
/* These indicate what data is loaded, is valid, etc */
Flags1 = U1(p);
p++;
Flags2 = U1(p);
p++;
/* Indicates whether FLAGS1 bit 6 and FLAGS2 are valid */
FlagStatus = U1(p);
p++;
/* These are not needed by RTKLIB */
p += 2; /* I2 Satellite Elevation Angle (degrees) */
p += 2; /* I2 Satellite Azimuth (degrees) */
/*
| FLAG STATUS bit 0 set = Bit 6 of FLAGS1 and bit 0-7 of FLAGS2 are valid.
| FLAG STATUS bit 0 clear = Bit 6 of FLAGS1 and bit 0-7 of FLAGS2 are UNDEFINED.
|
| According to reference #1 above, this bit should ALWAYS be set
| for RAWDATA. If this bit is not set, then we're lost and cannot
| process this message any further.
*/
if (!(FlagStatus & M_BIT0)) /* Flags invalid */
return 0;
if (Flags1 & M_BIT6) /* L1 data valid */
{
/* Measure of satellite signal strength (dB) */
obs->SNR[0] = R8(p) * 4.0;
p += 8;
/* Full L1 C/A code or P-code pseudorange (meters) */
obs->P[0] = R8(p);
p += 8;
/* L1 Continuous Phase (cycles) */
if (Flags1 & M_BIT4) /* L1 phase valid */
obs->L[0] = -R8(p);
p += 8;
/* L1 Doppler (Hz) */
obs->D[0] = R8(p);
p += 8;
/* Reserved 8 bytes */
p += 8;
}
if (Flags1 & M_BIT0) /* L2 data loaded */
{
/* Measure of L2 signal strength (dB) */
obs->SNR[1] = R8(p) * 4.0;
p += 8;
/* L2 Continuous Phase (cycles) */
if (Flags1 & M_BIT5) /* L2 phase valid */
obs->L[1] = -R8(p);
p += 8;
/* L2 P-Code or L2 Encrypted Code */
if (Flags1 & M_BIT5) /* L2 pseudorange valid */
obs->P[1] = obs->P[0] + R8(p);
p += 8;
}
if (rif & M_ENHANCED)
{
/*
| We can't use the IODE flags in this context.
| We already have slip flags and don't need slip counters.
*/
p++; /* U1 IODE, Issue of Data Ephemeris */
p++; /* U1 L1 cycle slip roll-over counter */
p++; /* U1 L2 cycle slip roll-over counter */
p++; /* U1 Reserved byte */
/* L2 Doppler (Hz) */
obs->D[1] = R8(p);
p += 8;
}
}
obs->code[0] = (obs->P[0] == 0.0) ? CODE_NONE : (Flags2 & M_BIT0) ? CODE_L1P : CODE_L1C;
obs->code[1] = (obs->P[1] == 0.0) ? CODE_NONE : (Flags2 & M_BIT2) ? CODE_L2W : (Flags2 & M_BIT1) ? CODE_L2P : CODE_L2C;
if (Flags1 & M_BIT1)
obs->LLI[0] |= 1; /* L1 cycle slip */
if (Flags1 & M_BIT2)
obs->LLI[1] |= 1; /* L2 cycle slip */
if ((Flags2 & M_BIT2) && (obs->P[1] != 0.0))
obs->LLI[1] |= 4; /* Tracking encrypted code */
if (!(obs->sat = satno(SYS_GPS, prn)))
{
tracet(2, "RT17: Satellite number error, PRN=%d.\n", prn);
continue;
}
#if 0
/* Apply clock offset to observables */
if (ClockOffset != 0.0)
{
obs->P[0] += ClockOffset * (CLIGHT/FREQ1);
obs->P[1] += ClockOffset * (CLIGHT/FREQ2);
obs->L[0] += ClockOffset * FREQ1;
obs->L[1] += ClockOffset * FREQ2;
}
#endif
n++;
}
Raw->time = Time;
Raw->obs.n = n;
if (n > 0)
{
tracet(2, "RT17: Observations output:\n");
traceobs(2, Raw->obs.data, Raw->obs.n);
}
return (n > 0);
}
/* DecodeType29 - Decode Enhanced position (record type 29) */
static int DecodeType29(raw_t *Raw)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
unsigned char *p = rt17->MessageBuffer;
if (*p < 7)
tracet(2, "RT17: Enhanced Position record block #1 length %d < 7 bytes. Record discarded.\n", *p);
else
SetWeek(Raw, I2(p+1), ((double) I4(p+3)) * 0.001);
return 0;
}
/*
| GetWeek - Get GPS week number
|
| Returns: GPS week number
|
| The -WEEK=n initial week option overrides everything else.
| Week rollover and increment from the initial week and
| subsequent weeks is handled.
*/
static int GetWeek(raw_t *Raw, double Tow)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
int Week = 0;
if (rt17->Flags & M_WEEK_OPTION)
{
if ((Tow && rt17->Tow) && (Tow < rt17->Tow))
{
tracet(2, "RT17: GPS WEEK rolled over from %d to %d.\n", rt17->Week, rt17->Week + 1);
rt17->Week++;
}
if (Tow != 0.0)
rt17->Tow = Tow;
}
else if (!(rt17->Flags & M_WEEK_SCAN))
{
char *opt = strstr(Raw->opt, "-WEEK=");
rt17->Flags |= M_WEEK_SCAN;
if (opt)
{
if (!sscanf(opt+6, "%d", &Week) || (Week <= 0))
tracet(0, "RT17: Invalid -WEEK=n receiver option value.\n");
else
{
rt17->Week = Week;
rt17->Flags |= M_WEEK_OPTION;
tracet(2, "RT17: Initial GPS WEEK explicitly set to %d by user.\n", Week, Week);
}
}
}
Week = rt17->Week;
if (!Week && !(rt17->Flags & (M_WEEK_OPTION|M_WEEK_EPH)))
{
if ((Raw->time.time == 0) && (Raw->time.sec == 0.0))
Raw->time = timeget();
time2gpst(Raw->time, &Week);
if (Tow != 0.0)
Raw->time = gpst2time(Week, Tow);
rt17->Week = Week;
rt17->Flags |= M_WEEK_TIME;
tracet(2, "RT17: Initial GPS WEEK number unknown; WEEK number %d assumed for now.\n", Week);
}
return Week;
}
/* ReadI2 - Fetch & convert a signed two byte integer (short) */
static short ReadI2(unsigned char *p)
{
union I2 {short i2; unsigned char c[2];} u;
ENDIAN_TEST et;
memcpy(&u.i2, p, sizeof(u.i2));
et.u2 = 0; et.c[0] = 1;
if (et.u2 == 1)
{
unsigned char t;
t = u.c[0]; u.c[0] = u.c[1]; u.c[1] = t;
}
return u.i2;
}
/* ReadI4 - Fetch & convert a four byte signed integer (int) */
static int ReadI4(unsigned char *p)
{
union i4 {int i4; unsigned char c[4];} u;
ENDIAN_TEST et;
memcpy(&u.i4, p, sizeof(u.i4));
et.u2 = 0; et.c[0] = 1;
if (et.u2 == 1)
{
unsigned char t;
t = u.c[0]; u.c[0] = u.c[3]; u.c[3] = t;
t = u.c[1]; u.c[1] = u.c[2]; u.c[2] = t;
}
return u.i4;
}
/* ReadR4 - Fetch & convert an IEEE S_FLOAT (float) */
static float ReadR4(unsigned char *p)
{
union R4 {float f; unsigned int u4;} u;
u.u4 = U4(p);
return u.f;
}
/* ReadR8 - Fetch & convert an IEEE T_FLOAT (double) */
static double ReadR8(unsigned char *p)
{
ENDIAN_TEST et;
union R8 {double d; unsigned char c[8];} u;
memcpy(&u.d, p, sizeof(u.d));
et.u2 = 0; et.c[0] = 1;
if (et.u2 == 1)
{
unsigned char t;
t = u.c[0]; u.c[0] = u.c[7]; u.c[7] = t;
t = u.c[1]; u.c[1] = u.c[6]; u.c[6] = t;
t = u.c[2]; u.c[2] = u.c[5]; u.c[5] = t;
t = u.c[3]; u.c[3] = u.c[4]; u.c[4] = t;
}
return u.d;
}
/* ReadU2 - Fetch & convert an unsigned twe byte integer (unsigned short) */
static unsigned short ReadU2(unsigned char *p)
{
ENDIAN_TEST et;
union U2 {unsigned short u2; unsigned char c[2];} u;
memcpy(&u.u2, p, sizeof(u.u2));
et.u2 = 0; et.c[0] = 1;
if (et.u2 == 1)
{
unsigned char t;
t = u.c[0]; u.c[0] = u.c[1]; u.c[1] = t;
}
return u.u2;
}
/* ReadU4 - Fetch & convert a four byte unsigned integer (unsigned int) */
static unsigned int ReadU4(unsigned char *p)
{
ENDIAN_TEST et;
union U4 {unsigned int u4; unsigned char c[4];} u;
memcpy(&u.u4, p, sizeof(u.u4));
et.u2 = 0; et.c[0] = 1;
if (et.u2 == 1)
{
unsigned char t;
t = u.c[0]; u.c[0] = u.c[3]; u.c[3] = t;
t = u.c[1]; u.c[1] = u.c[2]; u.c[2] = t;
}
return u.u4;
}
/*
| SetWeek - Set GPS week number
|
| The -WEEK=n initial week option overrides us.
*/
static void SetWeek(raw_t *Raw, int Week, double Tow)
{
rt17_t *rt17 = (rt17_t*) Raw->rcv_data;
if (!(rt17->Flags & M_WEEK_OPTION))
{
if (rt17->Week)
{
if (Week != rt17->Week)
{
if (Week == (rt17->Week + 1))
tracet(2, "RT17: GPS WEEK rolled over from %d to %d.\n", rt17->Week, Week);
else
tracet(2, "RT17: GPS WEEK changed from %d to %d.\n", rt17->Week, Week);
}
}
else
tracet(2, "RT17: GPS WEEK initially set to %d.\n", Week);
rt17->Week = Week;
}
/* Also update the time if we can */
if (Week && (Tow != 0.0))
Raw->time = gpst2time(Week, Tow);
}
/* SyncPacket - Synchronize the raw data stream to the start of a series of RT-17 packets */
static int SyncPacket(rt17_t *rt17, unsigned char Data)
{
unsigned char Type, *PacketBuffer = rt17->PacketBuffer;
PacketBuffer[0] = PacketBuffer[1];
PacketBuffer[1] = PacketBuffer[2];
PacketBuffer[2] = PacketBuffer[3];
PacketBuffer[3] = Data;
Type = PacketBuffer[2];
/*
| Byte 0 must be an STX character.
| Byte 1 = status byte which we always ignore (for now).
| Byte 2 = packet type which must be GENOUT (0x40) RAWDATA (0x57) or RETSVDATA (0x55) (for now).
| Byte 3 = data length which must be non-zero for any packet we're interested in.
*/
return ((PacketBuffer[0] == STX) && (Data != 0) && ((Type == GENOUT) || (Type == RAWDATA) || (Type == RETSVDATA)));
}
/*
| UnwrapGenout - Reassemble GENOUT message by removing packet headers, trailers and page framing
|
| The GENOUT message is broken up on _arbitrary byte boundries_ into
| pages of no more than 246 bytes each, then wrapped with page frames,
| packet headers and packet trailers. We reassemble the original message
| so that it is uninterrupted by removing the extraneous packet headers,
| trailers and page framing.
*/
static void UnwrapGenout(rt17_t *rt17)
{
unsigned char *p_in = rt17->MessageBuffer;
unsigned char *p_out = p_in;
unsigned int InputLength, InputLengthTotal = rt17->MessageLength;
unsigned int OutputLength, OutputLengthTotal = 0;
while (InputLengthTotal > 0)
{
InputLength = p_in[3] + 6;
OutputLength = p_in[3] - 3;
memmove(p_out, p_in + 7, OutputLength);
p_in += InputLength;
p_out += OutputLength;
OutputLengthTotal += OutputLength;
InputLengthTotal -= InputLength;
}
rt17->MessageBytes = rt17->MessageLength = OutputLengthTotal;
}
/*
| UnwrapRawdata - Reassemble message by removing packet headers, trailers and page framing
|
| The RAWDATA message is broken up on _arbitrary byte boundries_ into
| pages of no more than 244 bytes each, then wrapped with page frames,
| packet headers and packet trailers. We reassemble the original message
| so that it is uninterrupted by removing the extraneous packet headers,
| trailers and page framing.
|
| While we're at it we also check to make sure the Record Interpretation
| Flags are consistent. They should be the same in every page frame.
*/
static void UnwrapRawdata(rt17_t *rt17, unsigned int *rif)
{
unsigned char *p_in = rt17->MessageBuffer;
unsigned char *p_out = p_in;
unsigned int InputLength, InputLengthTotal = rt17->MessageLength;
unsigned int OutputLength, OutputLengthTotal = 0;
*rif = p_in[7];
while (InputLengthTotal > 0)
{
if ((unsigned int)p_in[7] != *rif)
tracet(2, "RT17: Inconsistent Record Interpretation Flags within a single RAWDATA message.\n");
InputLength = p_in[3] + 6;
OutputLength = p_in[3] - 4;
memmove(p_out, p_in + 8, OutputLength);
p_in += InputLength;
p_out += OutputLength;
OutputLengthTotal += OutputLength;
InputLengthTotal -= InputLength;
}
rt17->MessageBytes = rt17->MessageLength = OutputLengthTotal;
}
| 34.523722 | 141 | 0.577311 | [
"model"
] |
50ec7a6ace10862205a56e3b1c524846461ebb03 | 19,821 | cpp | C++ | src/context.cpp | AIS-Bonn/stillleben | f3673d1ef48c50debe52cf9c634ae000556259c8 | [
"MIT"
] | 46 | 2020-05-16T08:21:05.000Z | 2022-02-14T03:02:42.000Z | src/context.cpp | AIS-Bonn/stillleben | f3673d1ef48c50debe52cf9c634ae000556259c8 | [
"MIT"
] | 4 | 2020-06-26T07:40:30.000Z | 2020-10-23T08:43:13.000Z | src/context.cpp | AIS-Bonn/stillleben | f3673d1ef48c50debe52cf9c634ae000556259c8 | [
"MIT"
] | 2 | 2021-02-19T03:10:34.000Z | 2022-02-17T10:42:53.000Z | // stillleben context
// Author: Max Schwarz <max.schwarz@ais.uni-bonn.de>
#include <stillleben/context.h>
#include <stillleben/physx.h>
#include <algorithm>
#include <Corrade/PluginManager/PluginManager.h>
#include <Corrade/Utility/FormatStl.h>
#include <Magnum/GL/Context.h>
#include <Magnum/GL/RectangleTexture.h>
#include <Magnum/GL/Texture.h>
#include <Magnum/GL/TextureFormat.h>
#include <Magnum/ImageView.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Platform/GLContext.h>
#include <Magnum/PixelFormat.h>
#include <Magnum/Trade/AbstractImporter.h>
#include <Magnum/Trade/AbstractImageConverter.h>
#include <Magnum/Trade/ImageData.h>
#include <Magnum/DebugTools/ResourceManager.h>
#include <cstring>
#include <sstream>
#include <mutex>
#include <iostream>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#if HAVE_CUDA
#include <cuda_gl_interop.h>
#endif
template<class T>
T getExtension(const char* name)
{
return reinterpret_cast<T>(eglGetProcAddress(name));
}
#include "physx_impl.h"
using namespace Magnum;
namespace sl
{
namespace
{
bool envFlag(const char* name)
{
const char* env = getenv(name);
if(!env)
return false;
return strcmp(env, "1") == 0;
}
std::string eglErrorString(EGLint error)
{
switch(error)
{
case EGL_SUCCESS: return "No error";
case EGL_NOT_INITIALIZED: return "EGL not initialized or failed to initialize";
case EGL_BAD_ACCESS: return "Resource inaccessible";
case EGL_BAD_ALLOC: return "Cannot allocate resources";
case EGL_BAD_ATTRIBUTE: return "Unrecognized attribute or attribute value";
case EGL_BAD_CONTEXT: return "Invalid EGL context";
case EGL_BAD_CONFIG: return "Invalid EGL frame buffer configuration";
case EGL_BAD_CURRENT_SURFACE: return "Current surface is no longer valid";
case EGL_BAD_DISPLAY: return "Invalid EGL display";
case EGL_BAD_SURFACE: return "Invalid surface";
case EGL_BAD_MATCH: return "Inconsistent arguments";
case EGL_BAD_PARAMETER: return "Invalid argument";
case EGL_BAD_NATIVE_PIXMAP: return "Invalid native pixmap";
case EGL_BAD_NATIVE_WINDOW: return "Invalid native window";
case EGL_CONTEXT_LOST: return "Context lost";
}
return Corrade::Utility::formatString("Unknown error 0x%04X", error);
}
struct DisplayConfig
{
DisplayConfig(DisplayConfig&) = delete;
DisplayConfig& operator=(const DisplayConfig&) = delete;
EGLDisplay display{};
Display* x11 = nullptr;
};
DisplayConfig getEglDisplay()
{
EGLDisplay display = nullptr;
const char* extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if(!extensions)
{
Error() << "Could not query EGL extensions";
return {};
}
auto eglGetPlatformDisplayEXT = getExtension<PFNEGLGETPLATFORMDISPLAYEXTPROC>("eglGetPlatformDisplayEXT");
if(!eglGetPlatformDisplayEXT)
{
Error() << "Could not find required eglGetPlatformDisplayEXT";
return {};
}
// Try X11 first, if available. The user will likely want to use
// the same device as X11 is running on...
if(getenv("DISPLAY") && strstr(extensions, "EGL_EXT_platform_x11"))
{
auto x11Display = XOpenDisplay(nullptr);
display = eglGetPlatformDisplayEXT(EGL_PLATFORM_X11_EXT, x11Display, nullptr);
if(display)
return {display, x11Display};
else
Debug() << "X11 failed";
}
// Load required extensions for enumeration
auto eglQueryDevicesEXT = getExtension<PFNEGLQUERYDEVICESEXTPROC>("eglQueryDevicesEXT");
if(!eglQueryDevicesEXT)
{
Error() << "Could not find required eglQueryDevicesEXT";
return {};
}
auto eglQueryDeviceStringEXT = getExtension<PFNEGLQUERYDEVICESTRINGEXTPROC>("eglQueryDeviceStringEXT");
// Enumerate devices
std::vector<EGLDeviceEXT> devices(64);
EGLint num_devices;
if(!eglQueryDevicesEXT(devices.size(), devices.data(), &num_devices))
{
Error() << "Could not enumerate EGL devices";
return {};
}
if(num_devices > 0)
{
Debug{} << "Found EGL device(s) (count:" << num_devices << "), trying to create display...";
if(eglQueryDeviceStringEXT)
{
for(EGLint i = 0; i < num_devices; ++i)
{
const char* extension = eglQueryDeviceStringEXT(devices[i], EGL_EXTENSIONS);
if(strcmp(extension, "EGL_EXT_device_drm") == 0)
{
const char* device = eglQueryDeviceStringEXT(devices[i], EGL_DRM_DEVICE_FILE_EXT);
Debug{} << " - device" << i << ":" << device;
}
else
Debug{} << " - device" << i << ":" << extension;
}
}
display = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, devices.front(), nullptr);
}
if(!display)
{
Debug() << "Could not enumerate EGL devices, trying MESA targets with EGL_DEFAULT_DISPLAY...";
if(strstr(extensions, "EGL_MESA_platform_surfaceless"))
{
display = eglGetPlatformDisplayEXT(EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, nullptr);
if(!display)
Debug() << "surfaceless failed";
}
if(!display && strstr(extensions, "EGL_MESA_platform_gbm"))
{
display = eglGetPlatformDisplayEXT(EGL_PLATFORM_GBM_MESA, EGL_DEFAULT_DISPLAY, nullptr);
if(!display)
Debug() << "gpm failed";
}
}
return {display, nullptr};
}
}
using ImporterManager = PluginManager::Manager<Trade::AbstractImporter>;
using ImageConverterManager = PluginManager::Manager<Trade::AbstractImageConverter>;
class Context::Private
{
public:
Private(const std::string& installPrefix = {})
{
cudaDebug = envFlag("STILLLEBEN_CUDA_DEBUG");
int argc = 3;
std::vector<const char*> argv{
"dummy",
"--magnum-log", "quiet"
};
gl_context.reset(new Platform::GLContext{NoCreate, argc, argv.data()});
if(!installPrefix.empty())
{
#ifndef NDEBUG
importerPath = installPrefix + "/lib/magnum-d/importers";
imageConverterPath = installPrefix + "/lib/magnum-d/imageconverters";
#else
importerPath = installPrefix + "/lib/magnum/importers";
imageConverterPath = installPrefix + "/lib/magnum/imageconverters";
#endif
}
// Setup PhysX stuff
pxFoundation.reset(
PxCreateFoundation(PX_PHYSICS_VERSION, pxAllocator, pxErrorCallback)
);
pxPvd.reset(
PxCreatePvd(*pxFoundation)
);
pxPvdTransport.reset(
// physx::PxDefaultPvdFileTransportCreate("/tmp/test.pvd")
physx::PxDefaultPvdSocketTransportCreate("127.0.0.1", 5425, 10)
);
pxPvd->connect(
*pxPvdTransport,
physx::PxPvdInstrumentationFlag::eALL
);
physx::PxTolerancesScale scale;
pxPhysics.reset(PxCreatePhysics(
PX_PHYSICS_VERSION, *pxFoundation, scale, true, pxPvd.get()
));
pxCooking.reset(PxCreateCooking(
PX_PHYSICS_VERSION, *pxFoundation, physx::PxCookingParams(scale)
));
}
bool initWithDisplay(const DisplayConfig& displayConfig)
{
egl_display = displayConfig.display;
EGLint major, minor;
if(!eglInitialize(egl_display, &major, &minor))
{
Error() << "Could not initialize EGL display";
return false;
}
if constexpr(false)
{
Debug{} << "Display initialized for EGL " << major << "." << minor;
const char* vendor = eglQueryString(egl_display, EGL_VENDOR);
if(vendor)
Debug{} << "EGL vendor:" << vendor;
}
if(!eglBindAPI(EGL_OPENGL_API))
{
Error() << "Could not bind OpenGL API";
return false;
}
EGLint surfaceType = EGL_PBUFFER_BIT;
if(displayConfig.x11)
surfaceType |= EGL_WINDOW_BIT;
EGLint numberConfigs;
EGLConfig eglConfig;
EGLint configAttribs[] = {
EGL_SURFACE_TYPE, surfaceType,
EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
EGL_NONE
};
if(!eglChooseConfig(egl_display, configAttribs, &eglConfig, 1, &numberConfigs))
{
Error() << "Could not call eglChooseConfig";
return false;
}
if(!numberConfigs)
{
Error() << "Could not find any matching EGL config :-(";
return false;
}
EGLint contextAttribs[]{
// EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
EGL_CONTEXT_MAJOR_VERSION, 4,
EGL_CONTEXT_MINOR_VERSION, 5,
EGL_NONE
};
egl_context = eglCreateContext(egl_display, eglConfig, EGL_NO_CONTEXT, contextAttribs);
if(!egl_context)
{
Error() << "Could not create EGL context:" << eglErrorString(eglGetError());
return false;
}
egl_config = eglConfig;
if(!makeCurrent())
{
Error() << "Cannot make context current";
return false;
}
if(!gl_context->tryCreate())
{
Error() << "Could not create Platform::GLContext";
return false;
}
x11_display = displayConfig.x11;
return true;
}
bool makeCurrent()
{
if(!eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, egl_context))
{
Error() << "Cannot make context current";
return false;
}
return true;
}
~Private()
{
eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroyContext(egl_display, egl_context);
eglTerminate(egl_display);
}
void* egl_display = nullptr;
void* egl_context = nullptr;
EGLConfig egl_config{};
Display* x11_display = nullptr;
std::unique_ptr<Platform::GLContext> gl_context;
DebugTools::ResourceManager resourceManager;
physx::PxDefaultAllocator pxAllocator;
physx::PxDefaultErrorCallback pxErrorCallback;
PhysXHolder<physx::PxFoundation> pxFoundation;
PhysXHolder<physx::PxPvdTransport> pxPvdTransport;
PhysXHolder<physx::PxPvd> pxPvd;
PhysXHolder<physx::PxPhysics> pxPhysics;
PhysXHolder<physx::PxCooking> pxCooking;
bool cudaDebug = false;
std::string importerPath;
std::string imageConverterPath;
};
Context::Context(const std::string& installPrefix)
: m_d{std::make_unique<Private>(installPrefix)}
{
}
Context::Ptr Context::Create(const std::string& installPrefix)
{
Context::Ptr context{new Context(installPrefix)};
auto displayConfig = getEglDisplay();
EGLDisplay display = displayConfig.display;
if(!display)
{
Error() << "Could not create EGL display";
return {};
}
if(!context->m_d->initWithDisplay(displayConfig))
return {};
return context;
}
Context::Ptr Context::CreateCUDA(unsigned int device, const std::string& installPrefix)
{
auto eglGetPlatformDisplayEXT = getExtension<PFNEGLGETPLATFORMDISPLAYEXTPROC>("eglGetPlatformDisplayEXT");
if(!eglGetPlatformDisplayEXT)
{
Error() << "Could not find required eglGetPlatformDisplayEXT";
return {};
}
const char* extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS);
if(!extensions)
{
Error() << "Could not query EGL extensions";
return {};
}
#if HAVE_CUDA
// First attempt: Just use the standard X11 context. But we have to make
// sure that this context is connected to the right GPU...
auto initWithX11 = [&]() -> Context::Ptr {
if(!getenv("DISPLAY"))
return {};
if(!strstr(extensions, "EGL_EXT_platform_x11"))
return {};
auto x11Display = XOpenDisplay(nullptr);
if(!x11Display)
return {};
auto display = eglGetPlatformDisplayEXT(EGL_PLATFORM_X11_EXT, x11Display, nullptr);
if(!display)
return {};
Context::Ptr context(new Context(installPrefix));
DisplayConfig cfg{display, x11Display};
if(!context->m_d->initWithDisplay(cfg))
{
XCloseDisplay(x11Display);
return {};
}
// NOW we can finally check if this context is usable with the CUDA
// device...
unsigned int count = 0;
std::array<int, 10> devices;
if(cudaGLGetDevices(&count, devices.data(), devices.size(), cudaGLDeviceListAll) != cudaSuccess)
return {};
auto it = std::find(devices.begin(), devices.end(), device);
if(it == devices.end())
return {};
return context;
};
if(auto ctx = initWithX11())
return ctx;
#endif
// It seems either X11 is not available or the X server is running on a
// different device. In that case, we will bind to our target device
// without X11 support.
std::shared_ptr<Context> context(new Context(installPrefix));
if(context->m_d->cudaDebug)
Debug{} << "stillleben CUDA initialization";
// Load required extensions
auto eglQueryDevicesEXT = getExtension<PFNEGLQUERYDEVICESEXTPROC>("eglQueryDevicesEXT");
if(!eglQueryDevicesEXT)
{
Error() << "Could not find required eglQueryDevicesEXT";
return {};
}
auto eglQueryDeviceAttribEXT = getExtension<PFNEGLQUERYDEVICEATTRIBEXTPROC>("eglQueryDeviceAttribEXT");
if(!eglQueryDeviceAttribEXT)
{
Error() << "Could not find required eglQueryDeviceAttribEXT";
return {};
}
auto eglQueryDeviceStringEXT = getExtension<PFNEGLQUERYDEVICESTRINGEXTPROC>("eglQueryDeviceStringEXT");
// Enumerate devices
std::vector<EGLDeviceEXT> devices(64);
EGLint num_devices;
if(!eglQueryDevicesEXT(devices.size(), devices.data(), &num_devices))
{
Error() << "Could not enumerate EGL devices";
return {};
}
if(num_devices < 1)
{
Error() << "Could not find an EGL device";
return {};
}
devices.resize(num_devices);
if(context->m_d->cudaDebug)
{
Debug{} << "Found EGL devices:";
for(auto& dev : devices)
{
EGLAttrib devCudaIndex;
if(eglQueryDeviceAttribEXT(dev, EGL_CUDA_DEVICE_NV, &devCudaIndex))
Debug{} << " - CUDA device" << devCudaIndex;
else if(eglQueryDeviceStringEXT)
{
const char* extension = eglQueryDeviceStringEXT(dev, EGL_EXTENSIONS);
Debug{} << " - non-CUDA device:" << extension;
}
}
}
auto it = std::find_if(devices.begin(), devices.end(), [&](EGLDeviceEXT& dev){
EGLAttrib devCudaIndex;
if(!eglQueryDeviceAttribEXT(dev, EGL_CUDA_DEVICE_NV, &devCudaIndex))
{
return false;
}
return devCudaIndex == device;
});
if(it == devices.end())
{
Error() << "Could not find matching CUDA device with index" << device;
return {};
}
auto display = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, *it, nullptr);
if(!display)
{
Error() << "Could not get display for CUDA device";
return {};
}
DisplayConfig cfg{display, nullptr};
if(!context->m_d->initWithDisplay(cfg))
return {};
return context;
}
bool Context::makeCurrent()
{
return m_d->makeCurrent();
}
Magnum::GL::RectangleTexture Context::loadTexture(const std::string& path)
{
Corrade::PluginManager::Manager<Trade::AbstractImporter> manager(importerPluginPath());
auto importer = manager.loadAndInstantiate("AnyImageImporter");
std::ostringstream ss;
Error redirectTo{&ss};
if(!importer)
throw std::logic_error("Could not load AnyImageImporter plugin");
if(!importer->openFile(path))
throw std::runtime_error("Could not open image file: " + ss.str());
auto image = importer->image2D(0);
if(!image)
throw std::runtime_error("Could not load image: " + ss.str());
GL::TextureFormat format;
if(image->format() == PixelFormat::RGB8Unorm)
format = GL::TextureFormat::RGB8;
else if(image->format() == PixelFormat::RGBA8Unorm)
format = GL::TextureFormat::RGBA8;
else
throw std::runtime_error("Unsupported texture format");
GL::RectangleTexture texture;
texture.setStorage(format, image->size());
texture.setSubImage({}, *image);
// Needed for sticker textures - this is ugly.
texture.setWrapping(Magnum::SamplerWrapping::ClampToBorder);
texture.setBorderColor(Magnum::Color4{0.0, 0.0, 0.0, 0.0});
std::string messages = ss.str();
if(!messages.empty())
std::cerr << messages << std::flush;
return texture;
}
Magnum::GL::Texture2D Context::loadTexture2D(const std::string& path)
{
Corrade::PluginManager::Manager<Trade::AbstractImporter> manager(importerPluginPath());
auto importer = manager.loadAndInstantiate("AnyImageImporter");
std::ostringstream ss;
Error redirectTo{&ss};
if(!importer)
throw std::logic_error("Could not load AnyImageImporter plugin");
if(!importer->openFile(path))
throw std::runtime_error("Could not open image file: " + ss.str());
auto image = importer->image2D(0);
if(!image)
throw std::runtime_error("Could not load image: " + ss.str());
GL::TextureFormat format;
if(image->format() == PixelFormat::RGB8Unorm)
format = GL::TextureFormat::RGB8;
else if(image->format() == PixelFormat::RGBA8Unorm)
format = GL::TextureFormat::RGBA8;
else
throw std::runtime_error("Unsupported texture format");
GL::Texture2D texture;
texture.setMaxAnisotropy(GL::Sampler::maxMaxAnisotropy());
texture.setStorage(Math::log2(image->size().max())+1, format, image->size());
texture.setSubImage(0, {}, *image);
texture.generateMipmap();
// Needed for sticker textures - this is ugly.
texture.setWrapping(Magnum::SamplerWrapping::ClampToBorder);
texture.setBorderColor(Magnum::Color4{0.0, 0.0, 0.0, 0.0});
std::string messages = ss.str();
if(!messages.empty())
std::cerr << messages << std::flush;
return texture;
}
physx::PxPhysics& Context::physxPhysics()
{
return *m_d->pxPhysics;
}
physx::PxCooking& Context::physxCooking()
{
return *m_d->pxCooking;
}
std::string Context::importerPluginPath() const
{
return m_d->importerPath;
}
std::string Context::imageConverterPluginPath() const
{
return m_d->imageConverterPath;
}
Magnum::DebugTools::ResourceManager& Context::debugResourceManager()
{
return m_d->resourceManager;
}
int Context::visualID() const
{
EGLint id;
if(!eglGetConfigAttrib(m_d->egl_display, m_d->egl_config, EGL_NATIVE_VISUAL_ID, &id))
throw std::runtime_error{"Could not query visual ID"};
return id;
}
void* Context::eglConfig() const
{
return m_d->egl_config;
}
void *Context::x11Display() const
{
return m_d->x11_display;
}
}
| 29.148529 | 114 | 0.61783 | [
"vector"
] |
50fc877168511fe19602880563aff3458c7c1fb9 | 11,135 | cpp | C++ | src/npy.cpp | berquist/exdir-cpp | d0986356ab4de67b8541bf8ac08af7860d32072a | [
"BSD-3-Clause"
] | 2 | 2020-04-06T19:24:57.000Z | 2021-07-12T00:03:38.000Z | src/npy.cpp | berquist/exdir-cpp | d0986356ab4de67b8541bf8ac08af7860d32072a | [
"BSD-3-Clause"
] | null | null | null | src/npy.cpp | berquist/exdir-cpp | d0986356ab4de67b8541bf8ac08af7860d32072a | [
"BSD-3-Clause"
] | 2 | 2021-12-16T17:15:42.000Z | 2022-03-06T15:25:13.000Z | /*
* exdir-cpp
*
* Copyright (C) 2020, Hunter Belanger (hunter.belanger@gmail.com)
* All rights reserved.
*
* Released under the terms and conditions of the BSD 3-Clause license.
* For more information, refer to the GitHub repo for this library at:
* https://github.com/HunterBelanger/exdir-cpp
*
* */
#include "npy.hpp"
namespace exdir {
void load_npy(std::filesystem::path fpath, char*& data_ptr,
std::vector<size_t>& shape, DType& dtype, bool& c_contiguous) {
// Open file
std::ifstream file(fpath);
// Read magic string
char* magic_string = new char[6];
file.read(magic_string, 6);
// Ensure magic string has right value
if (magic_string[0] != '\x93' || magic_string[1] != 'N' ||
magic_string[2] != 'U' || magic_string[3] != 'M' ||
magic_string[4] != 'P' || magic_string[5] != 'Y') {
std::string mssg = fpath.string() + " is an invalid .npy file.";
throw std::runtime_error(mssg);
}
char major_verison = 0x00;
char minor_version = 0x00;
file.read(&major_verison, 1);
file.read(&minor_version, 1);
uint32_t length_of_header = 0;
// Do any version checks here if required
if (major_verison == 0x01) {
uint16_t length_temp = 0;
file.read((char*)&length_temp, 2);
// Value is stored as little endian. If system is big-endian, swap bytes
if (!system_is_little_endian()) {
swap_bytes((char*)&length_temp, 2, 1);
}
// Cast to main variable
length_of_header = static_cast<uint32_t>(length_temp);
} else if (major_verison >= 0x02) {
uint32_t length_temp = 0;
file.read((char*)&length_temp, 4);
// Value is stored as little endian. If system is big-endian, swap bytes
if (!system_is_little_endian()) {
swap_bytes((char*)&length_temp, 4, 1);
}
// Set to main variable
length_of_header = length_temp;
}
// Array for header, and read in
char* header_char = new char[length_of_header];
file.read(header_char, length_of_header);
std::string header(header_char);
// Parse header to get continuity
size_t loc1 = header.find("'fortran_order': ");
loc1 += 17;
std::string f_order_string = "";
size_t i = 0;
while (true) {
if (header[loc1 + i] != ' ') {
if (header[loc1 + i] == ',')
break;
else
f_order_string += header[loc1 + i];
}
i++;
}
if (f_order_string == "False")
c_contiguous = true;
else
c_contiguous = false;
// Parse header to get type description
loc1 = header.find("'descr': ");
loc1 += 9;
std::string descr_string = "";
bool data_is_little_endian = false;
if (header[loc1 + 1] == '>')
data_is_little_endian = false;
else
data_is_little_endian = true;
i = 2;
while (true) {
if (header[loc1 + i] != ' ') {
if (header[loc1 + i] != '\'') {
descr_string += header[loc1 + i];
} else
break;
}
i++;
}
dtype = descr_to_DType(descr_string);
size_t element_size = size_of_DType(dtype);
// Parse header to get shape
loc1 = header.find('(');
size_t loc2 = header.find(')');
loc1 += 1;
// Clear shape vector to ensure it's empty (even though it should already be
// empty)
shape.clear();
if (loc1 == loc2) {
shape.push_back(1);
} else {
std::string temp = "";
for (i = loc1; i < loc2; i++) {
if (header[i] != ',')
temp += header[i];
else {
if (temp.size() > 0) {
shape.push_back(std::stoi(temp));
temp = "";
}
}
}
if (temp.size() > 0) {
shape.push_back(std::stoi(temp));
}
}
// Get number of bytes to be read into system
uint64_t n_elements = shape[0];
for (size_t j = 1; j < shape.size(); j++) n_elements *= shape[j];
uint64_t n_bytes_to_read = n_elements * element_size;
char* data = new char[n_bytes_to_read];
file.read(data, n_bytes_to_read);
// If byte order of data different from byte order of system, swap data bytes
if (system_is_little_endian() != data_is_little_endian) {
swap_bytes(data, n_elements, element_size);
}
// Set pointer reference
data_ptr = data;
// Clear Memory
delete[] magic_string;
delete[] header_char;
file.close();
}
void write_npy(std::filesystem::path fpath, const char* data_ptr,
std::vector<size_t> shape, DType dtype, bool c_contiguous) {
// Calculate number of elements from the shape
uint64_t n_elements = shape[0];
for (size_t j = 1; j < shape.size(); j++) {
n_elements *= shape[j];
}
// Open file
std::ofstream file(fpath);
// First write magic string
file << '\x93' << 'N' << 'U' << 'M' << 'P' << 'Y';
// Next make the header. This is needed to know what version number to use
std::string header = "{'descr': '";
// Get system endianness
if (system_is_little_endian())
header += "<";
else
header += ">";
header += DType_to_descr(dtype) + "', ";
// Fortran ordering
header += "'fortran_order': ";
if (c_contiguous)
header += "False, ";
else
header += "True, ";
// Shape
header += "'shape': (";
for (const auto& e : shape) {
header += std::to_string(e) + ",";
}
header += "), }";
// Based on header length, get version
char major_version;
uint64_t beginning_length = 6 + 2 + 2 + header.size();
uint8_t padding_needed = 64 - (beginning_length % 64);
if (beginning_length + padding_needed > 65535) {
major_version = 0x02;
beginning_length += 2;
} else
major_version = 0x01;
// Add padding
for (uint8_t p = 0; p < padding_needed - 1; p++) header += '\x20';
header += '\n';
char minor_version = 0x00;
file << major_version << minor_version;
// Inf for len of header
if (major_version == 0x01) {
uint16_t len = static_cast<uint16_t>(header.size());
if (!system_is_little_endian()) {
swap_two_bytes((char*)&len);
}
file << ((char*)&len)[0] << ((char*)&len)[1];
} else {
uint32_t len = static_cast<uint32_t>(header.size());
if (!system_is_little_endian()) {
swap_four_bytes((char*)&len);
}
file << ((char*)&len)[0] << ((char*)&len)[1] << ((char*)&len)[2]
<< ((char*)&len)[3];
}
// Write header to file
file << header.c_str();
// Write all data to file
uint64_t n_bytes = n_elements * size_of_DType(dtype);
for (uint64_t i = 0; i < n_bytes; i++) file << data_ptr[i];
// Close file
file.close();
}
DType descr_to_DType(std::string dtype) {
if (dtype == "b1")
return DType::CHAR;
else if (dtype == "B1")
return DType::UCHAR;
else if (dtype == "i2")
return DType::INT16;
else if (dtype == "i4")
return DType::INT32;
else if (dtype == "i8")
return DType::INT64;
else if (dtype == "u2")
return DType::UINT16;
else if (dtype == "u4")
return DType::UINT32;
else if (dtype == "u8")
return DType::UINT64;
else if (dtype == "f4")
return DType::FLOAT32;
else if (dtype == "f8")
return DType::DOUBLE64;
else if (dtype == "c8")
return DType::COMPLEX64;
else if (dtype == "c16")
return DType::COMPLEX128;
else {
std::string mssg = "Data type " + dtype + " is unknown.";
throw std::runtime_error(mssg);
}
}
std::string DType_to_descr(DType dtype) {
if (dtype == DType::CHAR)
return "b1";
else if (dtype == DType::UCHAR)
return "B1";
else if (dtype == DType::INT16)
return "i2";
else if (dtype == DType::INT32)
return "i4";
else if (dtype == DType::INT64)
return "i8";
else if (dtype == DType::UINT16)
return "u2";
else if (dtype == DType::UINT32)
return "u4";
else if (dtype == DType::UINT64)
return "u8";
else if (dtype == DType::FLOAT32)
return "f4";
else if (dtype == DType::DOUBLE64)
return "f8";
else if (dtype == DType::COMPLEX64)
return "c8";
else if (dtype == DType::COMPLEX128)
return "c16";
else {
std::string mssg = "Unknown DType identifier.";
throw std::runtime_error(mssg);
}
}
size_t size_of_DType(DType dtype) {
if (dtype == DType::CHAR)
return 1;
else if (dtype == DType::UCHAR)
return 1;
else if (dtype == DType::INT16)
return 2;
else if (dtype == DType::INT32)
return 4;
else if (dtype == DType::INT64)
return 8;
else if (dtype == DType::UINT16)
return 2;
else if (dtype == DType::UINT32)
return 4;
else if (dtype == DType::UINT64)
return 8;
else if (dtype == DType::FLOAT32)
return 4;
else if (dtype == DType::DOUBLE64)
return 8;
else if (dtype == DType::COMPLEX64)
return 8;
else if (dtype == DType::COMPLEX128)
return 16;
else {
std::string mssg = "Unknown DType identifier.";
throw std::runtime_error(mssg);
}
}
bool system_is_little_endian() {
int x = 1;
if (((char*)&x)[0] == 0x01)
return true;
else
return false;
}
void swap_bytes(char* data, uint64_t n_elements, size_t element_size) {
// Calculate number of total bytes
uint64_t number_of_bytes = n_elements * element_size;
// Iterate through all elements, and swap their bytes
for (uint64_t i = 0; i < number_of_bytes; i += element_size) {
if (element_size == 1) {
// Nothing to do
} else if(element_size == 2) {
swap_two_bytes(data + i);
} else if(element_size == 4) {
swap_four_bytes(data + i);
} else if(element_size == 8) {
swap_eight_bytes(data + i);
} else if(element_size == 16) {
swap_sixteen_bytes(data+i);
} else {
std::string mssg = "Cannot swap bytes for data types of size " +
std::to_string(element_size);
throw std::runtime_error(mssg);
}
}
}
void swap_two_bytes(char* bytes) {
// Temporary array to store original bytes
char temp[2];
// Copyr original bytes into temp array
std::memcpy(&temp, bytes, 2);
// Set original bytes to new values
bytes[0] = temp[1];
bytes[1] = temp[0];
}
void swap_four_bytes(char* bytes) {
// Temporary array to store original bytes
char temp[4];
// Copyr original bytes into temp array
std::memcpy(&temp, bytes, 4);
// Set original bytes to new values
bytes[0] = temp[3];
bytes[1] = temp[2];
bytes[2] = temp[1];
bytes[3] = temp[0];
}
void swap_eight_bytes(char* bytes) {
// Temporary array to store original bytes
char temp[8];
// Copyr original bytes into temp array
std::memcpy(&temp, bytes, 8);
// Set original bytes to new values
bytes[0] = temp[7];
bytes[1] = temp[6];
bytes[2] = temp[5];
bytes[3] = temp[4];
bytes[4] = temp[3];
bytes[5] = temp[2];
bytes[6] = temp[1];
bytes[7] = temp[0];
}
void swap_sixteen_bytes(char* bytes) {
// Temporary array to store original bytes
char temp[16];
// Copyr original bytes into temp array
std::memcpy(&temp, bytes, 16);
// Set original bytes to new values
bytes[0] = temp[15];
bytes[1] = temp[14];
bytes[2] = temp[13];
bytes[3] = temp[12];
bytes[4] = temp[11];
bytes[5] = temp[10];
bytes[6] = temp[9];
bytes[7] = temp[8];
bytes[8] = temp[7];
bytes[9] = temp[6];
bytes[10] = temp[5];
bytes[11] = temp[4];
bytes[12] = temp[3];
bytes[13] = temp[2];
bytes[14] = temp[1];
bytes[15] = temp[0];
}
}; // namespace exdir
| 25.597701 | 79 | 0.606107 | [
"shape",
"vector"
] |
50fddaa70ae36ded44ec11c0732ecf1f69e50831 | 231 | cpp | C++ | Session 2019/453.cpp | JanaSabuj/Leetcode-solutions | 78d10926b15252a969df598fbf1f9b69b2760b79 | [
"MIT"
] | 13 | 2019-10-12T14:36:32.000Z | 2021-06-08T04:26:30.000Z | Session 2019/453.cpp | JanaSabuj/Leetcode-solutions | 78d10926b15252a969df598fbf1f9b69b2760b79 | [
"MIT"
] | 1 | 2020-02-29T14:02:39.000Z | 2020-02-29T14:02:39.000Z | Session 2019/453.cpp | JanaSabuj/Leetcode-solutions | 78d10926b15252a969df598fbf1f9b69b2760b79 | [
"MIT"
] | 3 | 2020-02-08T12:04:28.000Z | 2020-03-17T11:53:00.000Z | class Solution {
public:
int minMoves(vector<int>& nums) {
int y = *min_element(nums.begin(), nums.end());
int ans=0;
for(auto x:nums)
ans += abs(x - y);
return ans;
}
}; | 21 | 55 | 0.47619 | [
"vector"
] |
dd076efe16961953a785d5b44e4389c953a0bd20 | 1,500 | hpp | C++ | thread/container/vector.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 1 | 2017-08-11T19:12:24.000Z | 2017-08-11T19:12:24.000Z | thread/container/vector.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | 11 | 2018-07-07T20:09:44.000Z | 2020-02-16T22:45:09.000Z | thread/container/vector.hpp | aconstlink/snakeoil | 3c6e02655e1134f8422f01073090efdde80fc109 | [
"MIT"
] | null | null | null | //------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#ifndef _SNAKEOIL_THREAD_CONTAINER_VECTOR_HPP_
#define _SNAKEOIL_THREAD_CONTAINER_VECTOR_HPP_
#include "../typedefs.h"
#include "../mutex.h"
namespace so_thread
{
template< typename T >
class vector
{
so_this_typedefs( vector<T> ) ;
so_typedefs( T, type ) ;
so_typedefs( so_std::vector<T>, container ) ;
private:
mutable so_thread::mutex_t _mtx ;
container_t _cont ;
public:
vector( void_t )
{}
vector( this_rref_t rhv )
{
so_thread::lock_guard_t lk(_mtx) ;
_cont = std::move( rhv._cont ) ;
}
vector( this_cref_t rhv )
{
so_thread::lock_guard_t lk( _mtx ) ;
_cont = rhv._cont ;
}
~vector( void_t )
{}
public:
this_ref_t push_back( type_cref_t v )
{
so_thread::lock_guard_t lk( _mtx ) ;
_cont.push_back( v ) ;
return *this ;
}
size_t size( void_t ) const
{
so_thread::lock_guard_t lk( _mtx ) ;
return _cont.size() ;
}
container_t move_out( void_t )
{
so_thread::lock_guard_t lk(_mtx) ;
return std::move( _cont ) ;
}
};
}
#endif
| 21.126761 | 62 | 0.484667 | [
"vector"
] |
dd0efac52c29eab21fa60aa7f75ec7a45c53de1a | 1,187 | cpp | C++ | iodaemon/src/logic/logic.cpp | BeeeOn/adaapp-modules | 6b836a0e8014cc30672fb109ad183919347ad2a8 | [
"BSD-3-Clause"
] | null | null | null | iodaemon/src/logic/logic.cpp | BeeeOn/adaapp-modules | 6b836a0e8014cc30672fb109ad183919347ad2a8 | [
"BSD-3-Clause"
] | null | null | null | iodaemon/src/logic/logic.cpp | BeeeOn/adaapp-modules | 6b836a0e8014cc30672fb109ad183919347ad2a8 | [
"BSD-3-Clause"
] | null | null | null | /*
* @file logic.cpp
* @Author BeeeOn team - Richard Wolfert (wolfert.richard@gmail.com)
* @date July 2016
* @brief IO logic implementation
*/
#include "logic.h"
void Logic::addLedConfiguration(struct ledConfiguration ledConf, int priority)
{
for (std::vector<std::pair<int, struct ledConfiguration>>::iterator it = ledConfigs.begin(); it != ledConfigs.end();) {
if ((*it).first == priority) {
it = ledConfigs.erase(it);
}
else {
it++;
}
}
ledConfigs.push_back(std::pair<int, struct ledConfiguration>(priority, ledConf));
}
void Logic::removeLedConfiguration(int priority)
{
for (std::vector<std::pair<int, struct ledConfiguration>>::iterator it = ledConfigs.begin(); it != ledConfigs.end();) {
if ((*it).first == priority) {
it = ledConfigs.erase(it);
}
else {
it++;
}
}
}
struct ledConfiguration Logic::getHighestLedConf()
{
int highestPriority = 0;
struct ledConfiguration ledConf;
for (std::vector<std::pair<int, struct ledConfiguration>>::iterator it = ledConfigs.begin(); it != ledConfigs.end();) {
if ((*it).first >= highestPriority) {
ledConf = (*it).second;
highestPriority = (*it).first;
}
it++;
}
return ledConf;
}
| 24.22449 | 120 | 0.669756 | [
"vector"
] |
dd16dd56e49138dcb65bc9dfc1fda17b38516e51 | 585 | cpp | C++ | LeetCode/leetcode 1304.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | LeetCode/leetcode 1304.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | LeetCode/leetcode 1304.cpp | Xi-Plus/OJ-Code | 7ff6d691f34c9553d53dc9cddf90ad7dc7092349 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define endl '\n'
using namespace std;
class Solution {
public:
vector<int> sumZero(int n) {
vector<int> ans;
if (n & 1) {
ans.push_back(0);
}
for (int q = 1; q <= n / 2; q++) {
ans.push_back(q);
ans.push_back(-q);
}
return ans;
}
};
int main() {
// ios::sync_with_stdio(false);
// cin.tie(0);
for (auto t : Solution().sumZero(5)) {
cout << t << " ";
}
cout << endl;
for (auto t : Solution().sumZero(3)) {
cout << t << " ";
}
cout << endl;
for (auto t : Solution().sumZero(1)) {
cout << t << " ";
}
cout << endl;
}
| 16.25 | 39 | 0.524786 | [
"vector"
] |
dd1a3165b475209b65cbc6cbb76acc37d944b28b | 1,744 | cpp | C++ | android-29/android/graphics/fonts/FontVariationAxis.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/graphics/fonts/FontVariationAxis.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/graphics/fonts/FontVariationAxis.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../../JArray.hpp"
#include "../../../JObject.hpp"
#include "../../../JString.hpp"
#include "./FontVariationAxis.hpp"
namespace android::graphics::fonts
{
// Fields
// QJniObject forward
FontVariationAxis::FontVariationAxis(QJniObject obj) : JObject(obj) {}
// Constructors
FontVariationAxis::FontVariationAxis(JString arg0, jfloat arg1)
: JObject(
"android.graphics.fonts.FontVariationAxis",
"(Ljava/lang/String;F)V",
arg0.object<jstring>(),
arg1
) {}
// Methods
JArray FontVariationAxis::fromFontVariationSettings(JString arg0)
{
return callStaticObjectMethod(
"android.graphics.fonts.FontVariationAxis",
"fromFontVariationSettings",
"(Ljava/lang/String;)[Landroid/graphics/fonts/FontVariationAxis;",
arg0.object<jstring>()
);
}
JString FontVariationAxis::toFontVariationSettings(JArray arg0)
{
return callStaticObjectMethod(
"android.graphics.fonts.FontVariationAxis",
"toFontVariationSettings",
"([Landroid/graphics/fonts/FontVariationAxis;)Ljava/lang/String;",
arg0.object<jarray>()
);
}
jboolean FontVariationAxis::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jfloat FontVariationAxis::getStyleValue() const
{
return callMethod<jfloat>(
"getStyleValue",
"()F"
);
}
JString FontVariationAxis::getTag() const
{
return callObjectMethod(
"getTag",
"()Ljava/lang/String;"
);
}
jint FontVariationAxis::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
JString FontVariationAxis::toString() const
{
return callObjectMethod(
"toString",
"()Ljava/lang/String;"
);
}
} // namespace android::graphics::fonts
| 22.075949 | 71 | 0.696101 | [
"object"
] |
dd2bf5e395c075df7828335f9367dae2c484bd85 | 9,001 | tpp | C++ | src/multiDim.tpp | abhilekh/multidimsparsearray | dc2bc22be7fb49ad1d79f39e8d409727afd20629 | [
"BSD-3-Clause"
] | 2 | 2020-12-04T03:26:16.000Z | 2020-12-07T19:25:35.000Z | src/multiDim.tpp | abhilekh/multidimsparsearray | dc2bc22be7fb49ad1d79f39e8d409727afd20629 | [
"BSD-3-Clause"
] | 1 | 2020-12-07T19:35:07.000Z | 2020-12-07T19:35:07.000Z | src/multiDim.tpp | abhilekh/multidimsparsearray | dc2bc22be7fb49ad1d79f39e8d409727afd20629 | [
"BSD-3-Clause"
] | null | null | null | /**
* This file is part of the MultiDimSparseArray library
*
* @license BSD-3
* @author Abhilekh Agarwal
*/
#pragma once
#include <algorithm>
#include <array>
#include <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
#include "patch/patch.hpp"
#include "SparseDim.tpp"
#include "exception.h"
#include "MultiDimIter.tpp"
template<typename T, unsigned N = 2>
class MultiDim: public SparseDim<T, N> {
public:
MultiDim(const std::array<int, N> &dims_sz, T defval = T()) :
SparseDim<T, N>(dims_sz, defval) { // Constructor 1
}
MultiDim(const SparseDim<T, N> & matrix) :
SparseDim<T, N>(matrix) { // Constructor 2
}
MultiDim<T, N> & operator =(const MultiDim<T, N> & matrix) {
this->printallowed = 0;
if (this->printallowed)
std::cout << __func__ << __LINE__ << std::endl;
if (&matrix != this) {
this->deepCopy(matrix);
}
return *this;
}
MultiDim<T, N> & operator =(const SparseDim<T, N> & matrix) {
this->printallowed = 0;
if (this->printallowed)
std::cout << __func__ << __LINE__ << std::endl;
if (&matrix != this) {
this->deepCopy(matrix);
}
return *this;
}
// === OPERATORS ==============================================
MultiDim<T, N> operator +(const T &t) {
return _oper([&t](T& i) {i+=t;}, false);
}
MultiDim<T, N> operator +(const MultiDim<T, N> &sd) {
if (this->printallowed)
std::cout << __func__ << __LINE__ << std::endl;
if (this->_dims_sz != sd._dims_sz) {
throw InvalidDimensionsException(
"Cannot add: matrices dimensions don't match.");
}
auto defval = this->_defval + sd._defval;
MultiDim<T, N> result(*this);
result._defval = defval;
if (sd._defval == T()) {
// Now result equlas part 1, and can only change when there is
// a val in part b. Another assumption is
// b's default value is 0 which makes add/subs as 1st val
for (int _v : patch::xrange(this->_virdimsz)) {
auto& rowlst = sd.rowlst_lst[_v];
auto& collst = sd.collst_lst[_v];
auto& vallst = sd.vallst_lst[_v];
for (int row : patch::xrange(this->_dims_sz[N - 2])) {
for (int pos = rowlst[row]; pos < rowlst[row + 1]; pos++) {
auto chval = vallst.at(pos);
result._setop(_v, row, collst[pos],
[&chval](T i) {return (i + chval);});
}
}
}
} else {
// General case
int vgrp = -1;
for (auto arr : mdrange<N>(this->_dims_sz)) {
if (!arr[N - 2] && !arr[N - 1]) {
vgrp++;
}
auto oval = this->_get(arr, vgrp);
auto nval = oval + sd._get(arr, vgrp);
if (nval != oval)
result._set(nval, arr, vgrp);
}
}
return result;
}
MultiDim<T, N> operator -(const T &t) const {
return _oper([&t](T& i) {i-=t;}, false);
}
MultiDim<T, N> operator -(const MultiDim<T, N> &sd) {
if (this->printallowed)
std::cout << __func__ << __LINE__ << std::endl;
if (this->_dims_sz != sd._dims_sz) {
throw InvalidDimensionsException(
"Cannot sub: matrices dimensions don't match.");
}
auto defval = this->_defval - sd._defval;
MultiDim<T, N> result(*this);
result._defval = defval;
if (sd._defval == T()) {
// Now result equals part 1, and can only change when there is
// a val in part b. Another assumption is
// b's default value is 0 which makes add/subs as 1st val
for (int _v : patch::xrange(this->_virdimsz)) {
auto& rowlst = sd.rowlst_lst[_v];
auto& collst = sd.collst_lst[_v];
auto& vallst = sd.vallst_lst[_v];
for (int row : patch::xrange(this->_dims_sz[N - 2])) {
for (int pos = rowlst[row]; pos < rowlst[row + 1]; pos++) {
auto chval = vallst.at(pos);
result._setop(_v, row, collst[pos],
[&chval](T i) {return (i - chval);});
}
}
}
} else {
// General case
int vgrp = -1;
for (auto arr : mdrange<N>(this->_dims_sz)) {
if (!arr[N - 2] && !arr[N - 1]) {
vgrp++;
}
auto oval = this->_get(arr, vgrp);
auto nval = oval - sd._get(arr, vgrp);
if (nval != oval)
result._set(nval, arr, vgrp);
}
}
return result;
}
MultiDim<T, N> operator *(const T &t) const {
if (t == T() && (this->vallst_lst[0].size() > 0)
&& (t * this->vallst_lst[0][0] == t)) {
// This means either t is some thing like zero or
// 1st item is identity element in my domain.
// Making idempotent does not make sense.
MultiDim<T, N> result(*this);
result._defval = this->_defval * t;
for (auto& vallst : result.vallst_lst)
vallst.clear();
for (auto& collst : result.collst_lst)
collst.clear();
for (auto& rowlst : result.rowlst_lst)
std::fill(rowlst.begin(), rowlst.end(), 0);
return result;
} else {
// Simple case
return this->_oper([&t](T& i) {i*=t;}, false);
}
}
MultiDim<T, N> operator /(const T &t) const {
return this->_oper([&t](T& i) {i/=t;}, false);
}
MultiDim<T, N> operator %(const T &t) const {
return this->_oper([&t](T& i) {i%=t;}, false);
}
template<typename UniOpType>
MultiDim<T, N> oper(UniOpType op) const {
return this->_oper(op, true);
}
// === FRIEND FUNCTIONS =========================================
friend std::ostream & operator <<(std::ostream & os,
const MultiDim<T, N> & sd) {
int vgrp = -1;
for (auto arr : mdrange<N>(sd._dims_sz)) {
if (!arr[N - 1]) {
os << "\n";
}
if (!arr[N - 2] && !arr[N - 1]) {
os << "\nCase:";
for (int a : patch::xrange(N - 1)) {
os << arr[a] << ",";
}
os << arr[N - 1] << "\n";
vgrp++;
}
if (arr[N - 1]) {
os << " ";
}
os << sd._get(arr, vgrp);
}
return os;
}
protected:
void deepCopy(const MultiDim<T, N> & md) {
if (this->printallowed)
std::cout << __func__ << __LINE__ << std::endl;
this->_virdimsz = md._virdimsz;
this->_defval = md._defval;
std::copy(std::begin(md._dims_sz), std::end(md._dims_sz),
std::begin(this->_dims_sz));
this->vallst_lst = std::vector<std::vector<T> >(this->_virdimsz);
this->collst_lst = std::vector<std::vector<int> >(this->_virdimsz);
this->rowlst_lst = std::vector<std::vector<int> >(this->_virdimsz);
for (int i : patch::xrange(this->_virdimsz)) {
this->vallst_lst[i] = std::vector<T>(md.vallst_lst[i]);
this->vallst_lst[i].reserve(10);
this->collst_lst[i] = std::vector<int>(md.collst_lst[i]);
this->collst_lst[i].reserve(10);
// We make row one size larger in CSR
this->rowlst_lst[i] = std::vector<int>(md.rowlst_lst[i]);
}
}
private:
template<typename OpType>
inline void _setop(int _virtualidx, int row, int col, OpType op) {
// No bound check. It will make it slower
if (this->printallowed > 1)
std::cout << __func__ << __LINE__ << std::endl;
int currCol = -1;
auto& rowlst = this->rowlst_lst[_virtualidx];
auto& collst = this->collst_lst[_virtualidx];
int pos;
for (pos = rowlst[row]; pos < rowlst[row + 1]; pos++) {
currCol = collst[pos];
if (currCol >= col) {
break;
}
}
if (currCol != col) {
T val = op(T());
if (val != this->_defval) {
this->insert(_virtualidx, pos, row, col, val);
}
} else {
T val = op(this->vallst_lst[_virtualidx][pos]);
if (val == this->_defval) {
this->remove(_virtualidx, pos, row);
} else {
this->vallst_lst[_virtualidx][pos] = val;
}
}
}
};
| 33.838346 | 79 | 0.470725 | [
"vector"
] |
dd3abf57a30689702dc6dad6157b72cdc45b2f2e | 11,495 | hpp | C++ | include/Lz/Take.hpp | RichardPoes/cpp-lazy | 84d9c0960b0fbed8e0bb41dd40773d2351dd719a | [
"MIT"
] | null | null | null | include/Lz/Take.hpp | RichardPoes/cpp-lazy | 84d9c0960b0fbed8e0bb41dd40773d2351dd719a | [
"MIT"
] | null | null | null | include/Lz/Take.hpp | RichardPoes/cpp-lazy | 84d9c0960b0fbed8e0bb41dd40773d2351dd719a | [
"MIT"
] | null | null | null | #pragma once
#ifndef LZ_TAKE_HPP
#define LZ_TAKE_HPP
#include "detail/BasicIteratorView.hpp"
namespace lz {
template<LZ_CONCEPT_ITERATOR Iterator>
class Take final : public internal::BasicIteratorView<Iterator> {
public:
using iterator = Iterator;
using const_iterator = Iterator;
using value_type = internal::ValueType<Iterator>;
template<class Function>
LZ_CONSTEXPR_CXX_20 Take(Iterator begin, Iterator end, Function predicate) :
internal::BasicIteratorView<iterator>(begin != end ? (!predicate(*begin) ? end : begin) : end, end) {
}
LZ_CONSTEXPR_CXX_20 Take(Iterator begin, Iterator end, std::nullptr_t) :
internal::BasicIteratorView<iterator>(std::move(begin), std::move(end)) {
}
constexpr Take() = default;
};
// Start of group
/**
* @defgroup ItFns Iterator free functions.
* These are the iterator functions and can all be used to iterate over in a
* `for (auto var : lz::someiterator(...))`-like fashion. Also, all objects contain a `toVector`,
* `toVector<Allocator>`, `toArray<N>`, `to<container>. toMap, toUnorderedMap` (specifying its value type of the container is not
* necessary, so e.g. `to<std::list>()` will do), `begin()`, `end()` methods and `value_type` and `iterator`
* typedefs.
* @{
*/
/**
* @brief Takes elements from an iterator from [begin, ...) while the function returns true. If the function
* returns false, the iterator stops. Its `begin()` function returns an iterator.
* If MSVC and the type is an STL iterator, pass a pointer iterator, not an actual iterator object.
* @param begin The beginning of the iterator.
* @param end The beginning of the iterator.
* @param predicate A function that returns a bool and passes a value type in its argument. If the function returns
* false, the iterator stops.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeWhileRange(...))`.
*/
template<LZ_CONCEPT_ITERATOR Iterator, class Function>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<Iterator> takeWhileRange(Iterator begin, Iterator end, Function predicate) {
return Take<Iterator>(std::move(begin), std::move(end), std::move(predicate));
}
/**
* @brief This function does the same as `lz::takeWhileRange` except that it takes an iterable as parameter.
* Its `begin()` function returns an iterator.
* @param iterable An object that has methods `begin()` and `end()`.
* @param predicate A function that returns a bool and passes a value type in its argument. If the function returns
* false, the iterator stops.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeWhile(...))`.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class Function>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<internal::IterTypeFromIterable<Iterable>> takeWhile(Iterable&& iterable, Function predicate) {
return takeWhileRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(predicate));
}
/**
* @brief This function takes a range between two iterators from [begin, end). Its `begin()` function returns a
* an iterator. If MSVC and the type is an STL iterator, pass a pointer iterator, not an actual
* iterator object.
* @param begin The beginning of the 'view'.
* @param end The ending of the 'view'.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::takeRange(...))`.
*/
template<LZ_CONCEPT_ITERATOR Iterator>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<Iterator>
takeRange(Iterator begin, Iterator end, const internal::DiffType<Iterator> amount) {
using lz::distance;
using lz::next;
using std::distance;
using std::next;
LZ_ASSERT(amount <= distance(begin, end), "cannot access elements after end");
static_cast<void>(end);
return takeWhileRange(begin, next(begin, amount), nullptr);
}
/**
* @brief This function takes an iterable and slices `amount` from the beginning of the array. Essentially it is
* equivalent to [`iterable.begin(), iterable.begin() + amount`). Its `begin()` function returns a random
* access iterator.
* @param iterable An iterable with method `begin()`.
* @param amount The amount of elements to take from the beginning of the `iterable`.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::take(...))`.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class IterType = internal::IterTypeFromIterable<Iterable>>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<IterType> take(Iterable&& iterable, const internal::DiffType<IterType> amount) {
return takeRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)), amount);
}
/**
* Drops an amount of items, starting from begin.
* @param begin The beginning of the sequence.
* @param end The ending of the sequence.
* @param amount The amount of items to drop, which is equivalent to next(begin, amount)
* @return A Take iterator where the first `amount` items have been dropped.
*/
template<LZ_CONCEPT_ITERATOR Iterator>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<Iterator>
dropRange(Iterator begin, Iterator end, const internal::DiffType<Iterator> amount) {
using lz::distance;
using lz::next;
using std::distance;
using std::next;
return takeRange(next(begin, amount), end, distance(begin, end) - amount);
}
/**
* Drops an amount of items, starting from begin.
* @param iterable The iterable to drop from.
* @param amount The amount of items to drop, which is equivalent to next(begin, amount)
* @return A Take iterator where the first `amount` items have been dropped.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class IterType = internal::IterTypeFromIterable<Iterable>>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<IterType> drop(Iterable&& iterable, const internal::DiffType<IterType> amount) {
return dropRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)), amount);
}
/**
* @brief This function slices an iterable. It is equivalent to [`begin() + from, begin() + to`).
* Its `begin()` function returns an iterator.
* @param iterable An iterable with method `begin()`.
* @param from The offset from the beginning of the iterable.
* @param to The offset from the beginning to take. `from` must be higher than `to`.
* @return A Take object that can be converted to an arbitrary container or can be iterated over using
* `for (auto... lz::slice(...))`.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class IterType = internal::IterTypeFromIterable<Iterable>>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<internal::IterTypeFromIterable<Iterable>>
slice(Iterable&& iterable, const internal::DiffType<IterType> from, const internal::DiffType<IterType> to) {
using lz::next;
using std::next;
LZ_ASSERT(to >= from, "parameter `to` cannot be more than `from`");
auto begin = internal::begin(std::forward<Iterable>(iterable));
begin = next(std::move(begin), from);
return takeRange(begin, internal::end(std::forward<Iterable>(iterable)), to - from);
}
#ifdef LZ_HAS_EXECUTION
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param begin The beginning of the sequence.
* @param end The ending of the sequence.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @param execution The execution policy. Must be one of std::execution::*
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERATOR Iterator, class Function, class Execution = std::execution::sequenced_policy>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<Iterator>
dropWhileRange(Iterator begin, Iterator end, Function predicate, Execution execution = std::execution::seq) {
using lz::distance;
using std::distance;
using ValueType = internal::ValueType<Iterator>;
if constexpr (internal::checkForwardAndPolicies<Execution, Iterator>()) {
static_cast<void>(execution);
begin = std::find_if_not(std::move(begin), end, std::move(predicate));
}
else {
begin = std::find_if_not(execution, std::move(begin), end, std::move(predicate));
}
return takeRange(begin, end, distance(begin, end));
}
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param iterable The sequence with the values that can be iterated over.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @param execution The execution policy. Must be one of std::execution::*
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class Function, class Execution = std::execution::sequenced_policy>
LZ_NODISCARD LZ_CONSTEXPR_CXX_20 Take<internal::IterTypeFromIterable<Iterable>>
dropWhile(Iterable&& iterable, Function predicate, Execution execution = std::execution::seq) {
return dropWhileRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(predicate), execution);
}
#else // ^^^ lz has execution vvv lz ! has execution
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param begin The beginning of the sequence.
* @param end The ending of the sequence.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERATOR Iterator, class Function>
Take<Iterator> dropWhileRange(Iterator begin, Iterator end, Function predicate) {
using lz::distance;
using std::distance;
begin = std::find_if_not(std::move(begin), end, std::move(predicate));
return takeRange(begin, end, distance(begin, end));
}
/**
* @brief Creates a Take iterator view object.
* @details This iterator view object can be used to skip values while `predicate` returns true. After the `predicate` returns
* false, no more values are being skipped.
* @param iterable The sequence with the values that can be iterated over.
* @param predicate Function that must return `bool`, and take a `Iterator::value_type` as function parameter.
* @return A Take iterator view object.
*/
template<LZ_CONCEPT_ITERABLE Iterable, class Function>
Take<internal::IterTypeFromIterable<Iterable>> dropWhile(Iterable&& iterable, Function predicate) {
return dropWhileRange(internal::begin(std::forward<Iterable>(iterable)), internal::end(std::forward<Iterable>(iterable)),
std::move(predicate));
}
#endif // LZ_HAS_EXECUTION
// End of group
/**
* @}
*/
} // namespace lz
#endif | 48.914894 | 133 | 0.715963 | [
"object"
] |
dd3b4649b405f2c0f45b03eb7d3a89936b88bd2b | 1,175 | cpp | C++ | source/aufgabe_11.cpp | Mudartastisch/programmiersprachen-aufgabenblatt-3 | f552ed8e0c165389e60e1ac6835ca647d374f547 | [
"MIT"
] | null | null | null | source/aufgabe_11.cpp | Mudartastisch/programmiersprachen-aufgabenblatt-3 | f552ed8e0c165389e60e1ac6835ca647d374f547 | [
"MIT"
] | null | null | null | source/aufgabe_11.cpp | Mudartastisch/programmiersprachen-aufgabenblatt-3 | f552ed8e0c165389e60e1ac6835ca647d374f547 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <cmath>
#include <algorithm>
using namespace std;
bool is_multiple_of_3(int i)
{
return i % 3 == 0;
}
TEST_CASE("filter alle vielfache von drei", "[erase]")
{
vector<unsigned int> v_0;
srand (time(NULL)); //random seed
for (int i = 0; i < 100; i++)
{
v_0.push_back(rand() % 100); //fill set with rand 0-99
}
//https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom
//invert result of is_multiple_of_3 with std::not1
//this requires is_multiple_of_3 to be encapsulated in ptr_fun
std::copy(std::cbegin(v_0), std::cend(v_0),
std::ostream_iterator<int>(std::cout, " "));
v_0.erase(std::remove_if(v_0.begin(), v_0.end(), std::not1(std::ptr_fun(is_multiple_of_3))), v_0.end());
std::cout << "\n" << "Only mod 3 remaining" << std::endl;
std::copy(std::cbegin(v_0), std::cend(v_0),
std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
std::cout << endl;
REQUIRE(std::all_of(v_0.begin(), v_0.end(), is_multiple_of_3));
}
int main(int argc, char *argv[])
{
return Catch ::Session().run(argc, argv);
} | 30.128205 | 112 | 0.619574 | [
"vector"
] |
dd3dee1b7f2c1c6616c3808ba7c072ec64764b07 | 1,317 | hpp | C++ | console/tetris/Piece.hpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | 4 | 2019-10-17T20:26:09.000Z | 2019-11-14T12:01:57.000Z | console/tetris/Piece.hpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | null | null | null | console/tetris/Piece.hpp | piotrek-szczygiel/rpi-tetris | 1120b0ac024ef36f48a4fe67087e3e2c78cf83f8 | [
"MIT"
] | null | null | null | #pragma once
#include "Matrix.hpp"
#include "Shape.hpp"
#include <functional>
namespace Tetris {
enum class Movement {
NONE,
MOVE,
ROTATE,
};
class Piece {
public:
using CollisionFunction = std::function<bool(const Piece&)>;
Piece(ShapeType shape_type)
: m_shape { shape_from_type(shape_type) }
{
m_x = static_cast<int>(static_cast<float>(WIDTH) / 2.0F
- static_cast<float>(m_shape.grids[m_rotation].width) / 2.0F);
m_y = VANISH - m_shape.grids[m_rotation].height - m_shape.grids[m_rotation].y;
}
int x() const { return m_x; }
int y() const { return m_y; }
const ShapeGrid& grid() const { return m_shape.grids[m_rotation]; }
ShapeType type() const { return m_shape.type; };
bool move(int x, int y, const CollisionFunction& collision_fun);
bool rotate(bool right, const CollisionFunction& collision_fun);
int fall(const CollisionFunction& collision_fun);
bool touching_floor(const CollisionFunction& collision_fun);
void draw(int level, int draw_x, int draw_y, bool small, bool ghost) const;
private:
Shape m_shape;
int m_x {};
int m_y {};
int m_rotation { 0 };
Movement m_last_movement { Movement::NONE };
bool collision(int x, int y, const CollisionFunction& collision_fun);
};
}
| 25.823529 | 86 | 0.671982 | [
"shape"
] |
dd4e857f84777cb24f1bf2b38961414db4392293 | 1,213 | cpp | C++ | Codeforces/contests/Technocup 2022 - Elimination Round 1/A.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | Codeforces/contests/Technocup 2022 - Elimination Round 1/A.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | Codeforces/contests/Technocup 2022 - Elimination Round 1/A.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | /* A - Windblume Ode */
// https://codeforces.com/contest/1583/problem/A
// Date: Oct/17/2021 14:25 (00:20:24)
// Runtime: 15 ms
// Memory: 0 KB
// Verdict: AC
#include <bitset>
#include <iostream>
#include <vector>
using namespace std;
const int MAX = 20100;
bitset<MAX> is_prime;
void sieve() {
is_prime.set();
is_prime[0] = is_prime[1] = false;
for (int i = 2; i < MAX; i++) if (is_prime[i])
for (int j = i * i; j < MAX; j += i) is_prime[j] = false;
}
int main() {
sieve();
int TC;
cin >> TC;
while (TC--) {
int n;
cin >> n;
vector<int> a(n);
for (auto&& ai : a) cin >> ai;
int sum = 0;
for (auto&& ai : a) sum += ai;
if (!is_prime[sum]) {
cout << n << endl;
for (int i = 1; i <= n; i++) cout << i << " ";
} else {
int idx_exc = -1;
for (int i = 0; i < n; i++)
if (!is_prime[sum - a[i]]) {
idx_exc = i;
break;
}
cout << n - 1 << endl;
for (int i = 1; i <= n; i++) if (i != idx_exc + 1) cout << i << " ";
}
cout << endl;
}
} | 22.462963 | 80 | 0.42127 | [
"vector"
] |
dd50296f2286818a90457f2de6675c2377cd2548 | 419 | cpp | C++ | contest/yukicoder/397.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/yukicoder/397.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/yukicoder/397.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "vector.hpp"
int main() {
int n(in);
Vector<int> a(n, in);
Vector<Tuple<int, int>> res;
for (int i = 0; i < n; ++i) {
int j = min_element(a.begin() + i, a.end()) - a.begin();
if (i != j) {
res.emplace_back(i, j);
}
swap(a[i], a[j]);
}
cout << res.size() << endl;
for (auto i : res) {
cout << i.get<0>() << " " << i.get<1>() << endl;
}
(void)static_cast<int>(in);
}
| 20.95 | 60 | 0.472554 | [
"vector"
] |
dd5a42a2ca73bd6f5c48bd30ad4c80953e78eb11 | 3,422 | cpp | C++ | SegTree2.cpp | pushkarmishra/StandardAlgosAndDS | bb310cab4cca582ea31304fc8d653eaa8c4899f8 | [
"MIT"
] | 4 | 2016-12-02T11:24:01.000Z | 2017-12-27T18:21:19.000Z | SegTree2.cpp | pushkarmishra/StandardAlgosAndDS | bb310cab4cca582ea31304fc8d653eaa8c4899f8 | [
"MIT"
] | null | null | null | SegTree2.cpp | pushkarmishra/StandardAlgosAndDS | bb310cab4cca582ea31304fc8d653eaa8c4899f8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <cstdio>
#include <cstring>
#include <cassert>
using namespace std;
#define FOR(i, n) for(int i=0;i<int(n);i++)
#define FOR1(i, n) for(int i=1;i<=int(n);i++)
#define FORA(i, a, n) for(int i=a;i<int(n);i++)
#define FORR(i, n) for(int i=n-1;i>=0;i--)
#define foreach(it, c) for(typeof(c.begin()) it = c.begin(); it != c.end(); it++)
#define all(c) c.begin(), c.end()
#define clear(c,v) memset(c,v,sizeof(c))
typedef long long int lli;
typedef pair<int,int> ii;
// interval updates, interval queries (lazy propagation)
const int SN = 256; // must be a power of 2
struct SegmentTree {
// T[x] is the (properly updated) sum of indices represented by node x
// U[x] is pending increment for _each_ node in the subtree rooted at x
int T[2*SN], U[2*SN];
SegmentTree() { clear(T,0), clear(U,0); }
// increment every index in [ia,ib) by incr
// the current node is x which represents the interval [a,b)
void update(int incr, int ia, int ib, int x = 1, int a = 0, int b = SN) { // [a,b)
ia = max(ia,a), ib = min(ib,b); // intersect [ia,ib) with [a,b)
if(ia >= ib) return; // [ia,ib) is empty
if(ia == a and ib == b) { // We push the increment to 'pending increments'
U[x] += incr; // And stop recursing
return;
}
T[x] += incr * (ib - ia); // Update the current node
update(incr,ia,ib,2*x,a,(a+b)/2); // And push the increment to its children
update(incr,ia,ib,2*x+1,(a+b)/2, b);
}
int query(int ia, int ib, int x = 1, int a = 0, int b = SN) {
ia = max(ia,a), ib = min(ib,b); // intersect [ia,ib) with [a,b)
if(ia >= ib) return 0; // [ia,ib) is empty
if(ia == a and ib == b)
return U[x]*(b - a) + T[x];
T[x] += (b - a) * U[x]; // Carry out the pending increments
U[2*x] += U[x], U[2*x+1] += U[x]; // Push to the childrens' pending increments
U[x] = 0;
return query(ia,ib,2*x,a,(a+b)/2) + query(ia,ib,2*x+1,(a+b)/2,b);
}
};
int main()
{
ios::sync_with_stdio(false);
SegmentTree T;
int n = SN;
srand(time(0));
int Q = 1000000;
vector<int> v(n);
char c;
int a,b,x;
// while(cin >> c >> a >> b){
// if(c == 'u'){
// cin >> x;
// T.update(x,a,b);
// FORA(i,a,b) v[i] += x;
// }
// else {
// int sum = 0;
// FORA(i,a,b) sum += v[i];
// cout << T.query(a,b) << ' ' << sum << endl;
// }
// FOR(i,n) cout << v[i] << ' '; cout << endl;
// }
// return 0;
while(Q--){
a = (rand() % n) + 1, b = (rand() % n) + 1;
if(a > b) swap(a,b);
x = rand() % (n*n);
printf("update : [%d,%d) +%d\n", a,b,x);
T.update(x,a,b);
FORA(i,a,b) v[i] += x;
a = (rand() % n) + 1, b = (rand() % n) + 1;
if(a > b) swap(a,b);
printf("query : [%d,%d) \n",a,b);
int sum = 0;
FORA(i,a,b) sum += v[i];
FOR1(i,n) cout << v[i] << ' '; cout << endl;
cout << T.query(a,b) << ' ' << sum << endl;
assert(T.query(a,b) == sum);
}
return 0;
}
| 29 | 88 | 0.476914 | [
"vector"
] |
e57c023ca924402e21c690d034228fc44a8c3b8c | 668 | cpp | C++ | src/qt/dividendkeysdialog.cpp | dmitriy79/bestexeas | 4884b5c4fdc5efec54594a3098b98c337139023e | [
"MIT"
] | null | null | null | src/qt/dividendkeysdialog.cpp | dmitriy79/bestexeas | 4884b5c4fdc5efec54594a3098b98c337139023e | [
"MIT"
] | null | null | null | src/qt/dividendkeysdialog.cpp | dmitriy79/bestexeas | 4884b5c4fdc5efec54594a3098b98c337139023e | [
"MIT"
] | null | null | null | #include "dividendkeysdialog.h"
#include "ui_dividendkeysdialog.h"
#include "base58.h"
DividendKeysDialog::DividendKeysDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::DividendKeysDialog)
{
ui->setupUi(this);
}
DividendKeysDialog::~DividendKeysDialog()
{
delete ui;
}
void DividendKeysDialog::setKeys(const std::vector<CDividendSecret>& vSecret)
{
QString text;
for (std::vector<CDividendSecret>::const_iterator it = vSecret.begin(); it != vSecret.end(); ++it)
{
if (it != vSecret.begin())
text.append("\n");
text.append(QString::fromStdString(it->ToString()));
}
ui->keys->setPlainText(text);
}
| 23.857143 | 102 | 0.669162 | [
"vector"
] |
e57e23b90177314d8da6d0f40290eaeffc8a3b0c | 29,590 | cpp | C++ | source/spatial_solvers/solver_eqn_base.cpp | jfbucas/PION | e0a66aa301e4d94d581ba4df078f1a3b82faab99 | [
"BSD-3-Clause"
] | 4 | 2020-08-20T11:31:22.000Z | 2020-12-05T13:30:03.000Z | source/spatial_solvers/solver_eqn_base.cpp | Mapoet/PION | 51559b18f700c372974ac8658a266b6a647ec764 | [
"BSD-3-Clause"
] | null | null | null | source/spatial_solvers/solver_eqn_base.cpp | Mapoet/PION | 51559b18f700c372974ac8658a266b6a647ec764 | [
"BSD-3-Clause"
] | 4 | 2020-08-20T14:33:19.000Z | 2022-03-07T10:29:34.000Z | /// \file solver_eqn_base.cc
///
/// \brief Class definition for various solvers implemented in my FV grid-code.
/// \author Jonathan Mackey
///
/// Modifications:
/// - 2007-07-10 Part Way through writing it.
/// - 2007-07-11 Still writing it and working out class heirarchy.
/// - 2007-07-12 Got the class heirarchy working (I think...).
/// - 2007-07-13 New Class structure implemented.
/// - 2007-07-16 Reverted to less complicated class hierarchy. Runs fast.
/// - 2007-07-23 Started to add passive tracer variables
/// - 2007-07-24 Added passive tracer variable support.
/// - 2007-08-01 cylindrical coordinates support.
/// - 2007-08-08 cylindrical coordinates hd/i-mhd/glm-mhd working.
/// - 2007-11-30 Worked on Toth's Field-CD method for keeping divB=0.
/// - 2009-10-20 New structure built on equations and flux classes...
/// - 2009-10-24 Cut out all the old solver classes.
/// - 2010.09.30 JM: Worked on Lapidus AV (added set_div_v() function for cells)
/// - 2010.11.12 JM: Changed ->col to use cell interface for
/// extra_data.
/// - 2010.11.15 JM: Renamed calculate_flux() to inviscid_flux() and
/// moved AV calculation to FV_solver_base class. Added Pre- and
/// Post-flux viscosity functions for the H-correction and Lapidus
/// viscosity functions.
/// Added H-correction functions for calculating eta and getting
/// the maximum value of eta on a given H-stencil.
/// Made InterCellFlux general for all classes.
/// - 2010.11.19 JM: Debugged.
/// - 2010.12.08 JM: Got the H-correction to work for 1D grids.
/// - 2010.12.23 JM: Added new set_interface_tracer_flux(lp,rp,flux);
/// function. Removed riemann_base calls. Added pstar[] array
/// to intercell_flux() function since it is no longer inherited.
/// - 2010.12.27 JM: modified args to post_calc_viscous_terms to pass
/// in left, right, pstar (since these are no longer class vars).
/// - 2011.01.03 JM: Moved preprocess_data() and calc_Hcorrection from
/// gridMethods.cc
/// - 2011.02.25 JM: removed HCORR ifdef around new code
/// - 2011.04.06 JM: Added thermal-conduction to preprocess_data.
/// - 2012.08.05 JM: Added spacers between functions for readability.
/// Thermal Conduction module is unusable now, needs re-writing.
/// - 2015.01.14 JM: Modified for new code structure; added the grid
/// pointer everywhere.
/// - 2015.08.03 JM: Added pion_flt for double* arrays (allow floats)
/// - 2016.05.21 JM: Tidied up H-correction terms.
/// - 2016.08.25 JM: Changed H-correction loop to start with
/// FirstPt_All() instead of FirstPt(). Now serial/parallel code
/// produces identical results for the 3D blastwave test.
/// - 2018.01.24 JM: worked on making SimPM non-global
/// - 2018.04.14 JM: Moved flux solver to FV_solver
/// - 2018.08.03 JM: Added Berger & Colella (1989) flux correction
/// algorithm to PostProcess_dU()
#include "defines/functionality_flags.h"
#include "defines/testing_flags.h"
#include "tools/reporting.h"
#include "tools/mem_manage.h"
#include "solver_eqn_base.h"
using namespace std;
// ##################################################################
// ##################################################################
FV_solver_base::FV_solver_base(
const int nv, ///< number of variables in state vector.
const int nd, ///< number of space dimensions in grid.
const double cflno, ///< CFL number
const double gam, ///< gas eos gamma.
const double avcoeff, ///< Artificial Viscosity Parameter etav.
const int ntr ///< Number of tracer variables.
)
: eqns_base(nv),
FV_gndim(nd), FV_cfl(cflno),
FV_etav(avcoeff), FV_etaB(avcoeff), FV_ntr(ntr)
{
eq_gamma = gam;
eqTR = 0;
if (FV_ntr>0) {
eqTR = mem.myalloc(eqTR, FV_ntr);
for (int i=0;i<FV_ntr;i++) eqTR[i] = eq_nvar-FV_ntr+i;
}
HC_etamax=0.0;
return;
}
FV_solver_base::~FV_solver_base()
{
if (FV_ntr>0) {
eqTR = mem.myfree(eqTR);
}
return;
}
// ##################################################################
// ##################################################################
int FV_solver_base::get_LaxFriedrichs_flux(
const pion_flt *l,
const pion_flt *r,
pion_flt *f,
const double dx, ///< cell size dx
const double
)
{
//
// This has to be in this solver because we need dx,dt,ndim
//
pion_flt u1[eq_nvar], u2[eq_nvar], f1[eq_nvar], f2[eq_nvar];
PtoU(l, u1, eq_gamma); PtoU(r, u2, eq_gamma);
UtoFlux(u1, f1, eq_gamma); UtoFlux(u2, f2, eq_gamma);
// Then get inter-cell flux from this.
for (int v=0;v<eq_nvar;v++)
f[v] = 0.5*(f1[v]+f2[v] +dx/FV_dt*(u1[v]-u2[v])/FV_gndim);
//
// Calculate tracer flux based on whether flow is to left or right.
//
if (FV_ntr>0) {
if (f[eqRHO]>=0.) {
for (int t=0;t<FV_ntr;t++)
f[eqTR[t]] = l[eqTR[t]]*f[eqRHO];
}
else {
for (int t=0;t<FV_ntr;t++)
f[eqTR[t]] = r[eqTR[t]]*f[eqRHO];
}
}
return 0;
}
// ##################################################################
// ##################################################################
///
/// Calculate Flux between a left and right state.
///
int FV_solver_base::InterCellFlux(
class SimParams &par, ///< simulation parameters
class GridBaseClass *grid,
class cell *Cl, ///< Left state cell pointer
class cell *Cr, ///< Right state cell pointer
pion_flt *lp, ///< Left Primitive State Vector.
pion_flt *rp, ///< Right Primitive State Vector.
pion_flt *f, ///< Flux Vector. (written to).
const double g, ///< gas EOS gamma.
const double dx ///< Cell size dx.
)
{
//cout <<"FV_solver_base::InterCellFlux() gamma="<<eq_gamma<<" and passed in was g="<<g<<"\n";
eq_gamma=g;
pion_flt pstar[eq_nvar];
//
// Pre-calcualate anything needed for the viscosity (H-correction).
// Data is stored in each cell, so no values returned.
//
pre_calc_viscous_terms(grid,Cl,Cr,par.artviscosity);
//
// Get the flux from the flux solver:
//
int err = inviscid_flux(par,grid,dx,Cl,Cr,lp,rp,f,pstar,par.solverType,g);
#ifdef DEBUG
if (fabs(f[0]) > 1.0e-50) {
rep.printVec("flux=",f,eq_nvar);
rep.printVec("left=",lp,eq_nvar);
rep.printVec("rght=",rp,eq_nvar);
rep.printVec("pstr=",pstar,eq_nvar);
}
#endif
//
// Post-calculate anthing needed for the viscosity: calls the FKJ98
// viscosity function which acts after the flux has been calculated
//
post_calc_viscous_terms(Cl,Cr,lp,rp,pstar,f,par.artviscosity);
//
// Calculate tracer flux based on whether flow is to left or right.
//
set_interface_tracer_flux(lp,rp,f);
//rep.printVec("left=",lp,eq_nvar);
//rep.printVec("rght=",rp,eq_nvar);
//rep.printVec("flux",f,eq_nvar);
return err;
}
// ##################################################################
// ##################################################################
void FV_solver_base::pre_calc_viscous_terms(
class GridBaseClass *grid,
const cell *cl, ///< left-of-interface cell
const cell *cr, ///< right-of-interface cell
const int av_flag ///< what kind of AV?
)
{
//
// Only the H-correction acts before the actual flux calculation:
//
switch (av_flag) {
case AV_HCORRECTION: // H-correction
case AV_HCORR_FKJ98: // H-correction +FKJ98 viscosity
FV_solver_base::HC_etamax = select_Hcorr_eta(cl,cr, grid);
break;
default:
// Just silently continue if not doing the H-correction.
break;
}
return;
}
// ##################################################################
// ##################################################################
void FV_solver_base::post_calc_viscous_terms(
const cell *cl, ///< left-of-interface cell
const cell *cr, ///< right-of-interface cell
const pion_flt *Pl,
const pion_flt *Pr,
const pion_flt *Pstar,
pion_flt *flux, ///< flux vector
const int av_flag ///< what kind of AV?
)
{
// cout <<"etav="<<FV_etav<<"\t"; rep.printVec("flux",flux,eq_nvar);
// rep.printVec("flux",flux,eq_nvar);
int err=0;
switch (av_flag) {
case AV_FKJ98_1D: // FKJ98 Viscosity
case AV_HCORR_FKJ98: // FKJ98+HCORR
//cout <<"FKJ98 AV being applied!\n";
err += AVFalle(Pl,Pr,Pstar,flux,FV_etav,eq_gamma);
break;
default:
// Silently continue if av_flag==0 or 3.
break;
}
// rep.printVec("flux",flux,eq_nvar);
return;
}
// ##################################################################
// ##################################################################
void FV_solver_base::set_interface_tracer_flux(
const pion_flt *left, //prim.var.
const pion_flt *right,//prim.var.
pion_flt *flux
)
{
pion_flt corrector[eq_nvar];
for (int v=0;v<eq_nvar;v++) corrector[v]=1.0;
#ifdef FUNCTION_ID
cout <<"FV_solver_base::set_interface_tracer_flux ...starting.\n";
#endif //FUNCTION_ID
//
// Calculate tracer flux here -- if mass flux is positive then
// contact is at x>0 and we advect the left state tracer across
// the boundary. Otherwise we advect the right state to the left.
//
// N.B. Without introducing minimum density and velocity scales, it
// is impossible to avoid introducing some asymmetry here.
#ifdef TEST_SYMMETRY
if (FV_ntr>0) {
if (flux[eqRHO]>1.0e-28)
for (int t=0;t<FV_ntr;t++)
flux[eqTR[t]] = left[eqTR[t]]*flux[eqRHO];
else if (flux[eqRHO]<-1.0e-28)
for (int t=0;t<FV_ntr;t++)
flux[eqTR[t]] = right[eqTR[t]]*flux[eqRHO];
else
for (int t=0;t<FV_ntr;t++) flux[eqTR[t]] = 0.0;
}
#else
if (FV_ntr>0) {
#ifdef TEST_INF
if (!isfinite(flux[eqRHO])) {
cout <<"FV_solver_base::set_interface_tracer_flux: ";
rep.printVec("inf flux",flux,eq_nvar);
}
#endif
if (flux[eqRHO]>0.0) {
if (MP) MP->sCMA(corrector, left);
for (int t=0;t<FV_ntr;t++) {
flux[eqTR[t]] = left[eqTR[t]]*flux[eqRHO]*corrector[eqTR[t]];
}
}
else if (flux[eqRHO]<0.0) {
if (MP) MP->sCMA(corrector, right);
for (int t=0;t<FV_ntr;t++) {
flux[eqTR[t]] = right[eqTR[t]]*flux[eqRHO]*corrector[eqTR[t]];
}
}
else {
for (int t=0;t<FV_ntr;t++) flux[eqTR[t]] = 0.0;
}
}
#endif
#ifdef FUNCTION_ID
cout <<"FV_solver_base::set_interface_tracer_flux ...returning.\n";
#endif //FUNCTION_ID
return;
}
// ##################################################################
// ##################################################################
//
// Multi-dimensional calculations to be performed on every cell before
// the flux calculations.
//
int FV_solver_base::preprocess_data(
const int csp, ///< spatial order of accuracy required.
class SimParams &SimPM, ///< pointer to simulation parameters
class GridBaseClass *grid ///< pointer to grid.
)
{
// cout <<"\t\t\tpreprocess_data(): Starting: ndim = "<<SimPM.ndim<<"\n";
int err=0;
#ifdef THERMAL_CONDUCTION
//
// If we are on the first half-step (or first order integration) we don't need
// to calculate Edot, because it was already done in calc_dt(). But on the
// second half step we need to calculate it here.
//
if (csp != OA1) {
//cout <<"\tFV_solver_base::preprocess_data: setting Edot for 2nd step.\n";
err = set_thermal_conduction_Edot(SimPM);
if (err) {
rep.error("FV_solver_base::preprocess_data: set_thermal_conduction_Edot()",err);
}
}
//
// We need to multiply dU[ERG] by dt to convert from Edot to Delta-E
// TODO: Wrap this in an if statement when I get the SimPM.EP.conduction
// flag integrated into the code.
//
class cell* c = grid->FirstPt();
//cout <<"\tmultiplying conduction dU by dt.\n";
do {
c->dU[ERG] *= SimPM.dt;
} while ( (c =grid->NextPt(c)) !=0);
#endif // THERMAL CONDUCTION
//
// For the H-correction we need a maximum speed in each direction
// for every cell. Note this calculation is very time-consuming
// because all of the slopes and edge-states must be calculated.
//
if (SimPM.artviscosity==AV_HCORRECTION ||
SimPM.artviscosity==AV_HCORR_FKJ98) {
err += calc_Hcorrection(csp, SimPM, grid);
}
// HLLD has a switch based on velocity divergence, where it can
// reduce to HLL near strong shocks. So set divV here.
if (SimPM.solverType==FLUX_RS_HLLD) {
class cell* c = grid->FirstPt_All();
double gradp = 0.0;
int indices[MAX_DIM];
indices[0]=eqVX; indices[1]=eqVY; indices[2]=eqVZ;
do {
CI.set_DivV(c, Divergence(c,1,indices, grid));
gradp = 0.0;
for (int i=0; i<SimPM.ndim; i++)
gradp += GradZone(grid,c,i,1,PG);
CI.set_MagGradP(c, gradp);
} while ( (c =grid->NextPt_All(c)) !=0);
}
return err;
}
// ##################################################################
// ##################################################################
int FV_solver_base::calc_Hcorrection(
const int csp,
class SimParams &SimPM, ///< pointer to simulation parameters
class GridBaseClass *grid
)
{
#ifdef TESTING
cout <<"\t\t\tcalc_Hcorrection() ndim = "<<SimPM.ndim<<"\n";
#endif // TESTING
//
// This function is quite similar to calc_dU() and dU_column()
// because it steps through the grid in the same way.
//
//
// Allocate arrays for direction values.
//
int err=0;
enum direction posdirs[MAX_DIM], negdirs[MAX_DIM];
enum axes axis[MAX_DIM];
posdirs[0] = XP; posdirs[1] = YP; posdirs[2] = ZP;
negdirs[0] = XN; negdirs[1] = YN; negdirs[2] = ZN;
axis[0] = XX; axis[1] = YY; axis[2] = ZZ;
//
// Slope and edge state temporary arrays: This could be more
// computationally efficient if these were cell members (i.e. if
// each cell had a slope vector for each direction), but obviously
// this would increase the memory overhead hugely.
//
pion_flt *slope_cpt=0, *slope_npt=0, *edgeR=0, *edgeL=0, *temp=0;
slope_cpt = mem.myalloc(slope_cpt, SimPM.nvar);
slope_npt = mem.myalloc(slope_npt, SimPM.nvar);
edgeL = mem.myalloc(edgeL, SimPM.nvar);
edgeR = mem.myalloc(edgeR, SimPM.nvar);
//
// Loop through each direction.
//
for (int idim=0;idim<SimPM.ndim;idim++) {
#ifdef TESTING
cout <<"\t\t\tidim="<<idim<<"\n";
#endif // TESTING
SetDirection(axis[idim]);
class cell *start = grid->FirstPt_All();
class cell *marker = grid->FirstPt_All();
//
// Loop over z-planes (there must be at least one!)
//
bool zplanes_finished = false;
bool xcolumns_finished = false;
do {
//
// Loop over x-columns in the y-direction (at least one!)
//
xcolumns_finished = false;
do {
// --------------------------------------------------------
// Calculate the H-correction coefficients for this column:
// Start at the outermost boundary cell, and go to the end.
// We need all interfaces between and including the
// grid-boundary interface.
// --------------------------------------------------------
//
// Set three cell pointers (2nd order slopes have a 3-point
// stencil).
//
cell *cpt = start;
cell *npt = grid->NextPt(cpt,posdirs[idim]);
cell *n2pt = grid->NextPt(npt,posdirs[idim]);
if (npt==0 || n2pt==0)
rep.error("Couldn't find two real cells in column",0);
//
// Need to get slopes and edge states if 2nd order (csp==OA2).
//
for (int v=0;v<SimPM.nvar;v++) {
slope_cpt[v] = 0.;
edgeL[v] = 0.;
} // slope_npt[] and edgeR[] get initialised in next loop.
// --------------------------------------------------------
// Run through column, calculating slopes, edge-states, and
// eta[] values as we go.
// --------------------------------------------------------
do {
err += SetEdgeState(cpt, posdirs[idim], SimPM.nvar, slope_cpt, edgeL, csp, grid);
err += SetSlope(npt, axis[idim], SimPM.nvar, slope_npt, csp, grid);
err += SetEdgeState(npt, negdirs[idim], SimPM.nvar, slope_npt, edgeR, csp, grid);
set_Hcorrection(cpt, axis[idim], edgeL, edgeR, SimPM.gamma);
//cout <<" Hcorr["<<axis[idim]<<"] = "<<CI.get_Hcorr(cpt,axis[idim])<<"\n";
cpt = npt;
npt = n2pt;
temp = slope_cpt;
slope_cpt = slope_npt;
slope_npt = temp;
} while ( (n2pt=grid->NextPt(n2pt,posdirs[idim])) !=0);
// If 1st order, cpt is still a grid cell (2nd order we are done)
err += SetEdgeState(cpt, posdirs[idim], SimPM.nvar, slope_cpt, edgeL, csp, grid);
for (int v=0;v<SimPM.nvar;v++) slope_npt[v] = 0.; // last cell must be 1st order.
err += SetEdgeState(npt, negdirs[idim], SimPM.nvar, slope_npt, edgeR, csp, grid);
set_Hcorrection(cpt, axis[idim], edgeL, edgeR, SimPM.gamma);
//cout <<" Hcorr["<<axis[idim]<<"] = "<<CI.get_Hcorr(cpt,axis[idim])<<"\n";
// --------------------------------------------------------
// Finished H-correction calculation for the column.
// --------------------------------------------------------
//
// Get next x-column, or if it doesn't exist set a flag to
// indicate that we are finished.
//
if (SimPM.ndim==1) xcolumns_finished = true;
else {
start = grid->NextPt(start,posdirs[(idim+1)%SimPM.ndim]);
if (!start) xcolumns_finished = true;
}
} while (!xcolumns_finished);
//
// Get next z-plane, or if it doesn't exist set a flag to
// indicate that we are finished. Reset marker to the first
// cell in the new plane.
//
if (SimPM.ndim<=2) zplanes_finished = true;
else {
start = grid->NextPt(marker,posdirs[(idim+2)%SimPM.ndim]);
marker = start;
if (!start) zplanes_finished = true;
}
} while (!zplanes_finished);
} // Loop over Ndim directions.
SetDirection(axis[0]); // Reset fluxes to x-dir, (just to be safe!).
slope_cpt = mem.myfree(slope_cpt);
slope_npt = mem.myfree(slope_npt);
edgeL = mem.myfree(edgeL);
edgeR = mem.myfree(edgeR);
return err;
} // calc_Hcorrection()
// ##################################################################
// ##################################################################
void FV_solver_base::set_Hcorrection(
cell *c, ///< cell to operate on
const axes axis, ///< axis normal to interface.
const pion_flt *edgeL, ///< Left state
const pion_flt *edgeR, ///< right state
const double g ///< gamma
)
{
if (axis != GetDirection()) {
cout <<GetDirection()<<"\t";
rep.error("bad direction in FV_solver_base::set_Hcorrection()",axis);
}
//
// Sanders, Morano, Druguet, (1998, JCP, 145, 511) eq. 10
//
double eta = 0.5*(fabs(edgeR[eqVX]-edgeL[eqVX]) +
fabs(maxspeed(edgeR,g)-maxspeed(edgeL,g)) );
CI.set_Hcorr(c,axis,eta);
return;
}
// ##################################################################
// ##################################################################
double FV_solver_base::select_Hcorr_eta(
const cell *cl, ///< cell to left of interface
const cell *cr, ///< cell to right of interface
class GridBaseClass *grid
)
{
//
// Based on Sanders, Morano, Druguet, (1998, JCP, 145, 511)
// Fig. 9 and Eq. 16 (with obvious extension to 3D).
//
//
// First get the current direction.
//
double eta = 0.0;
enum axes axis = GetDirection();
//
// First the interface between left and right cells.
//
eta = CI.get_Hcorr(cl,axis);
//
// If we are in 1D this is the only interface, so we can return.
// Otherwise we have another 4 or 8 more interfaces to calculate.
//
if (FV_gndim==1) return eta;
//
// Now the two in the positive direction of the 1st perpendicular
// axis. (i,j+1/2) and (i+1,j+1/2)
//
enum axes perp = static_cast<axes>((static_cast<int>(axis) +1)%FV_gndim);
eta = max(eta, CI.get_Hcorr(cl,perp));
eta = max(eta, CI.get_Hcorr(cr,perp));
//
// Positive direction of the 2nd perp. axis, if 3D grid:
// (i,j,k+1/2) (i+1,j,k+1/2)
//
if (FV_gndim>2) {
perp = static_cast<axes>((static_cast<int>(axis) +2)%FV_gndim);
eta = max(eta, CI.get_Hcorr(cl,perp));
eta = max(eta, CI.get_Hcorr(cr,perp));
}
//
// Negative direction of the (up to) two perp. axes. We need to
// make sure the cells exist, and if they don't we just ignore the
// non-existent interface. It's up to the grid to have all the
// cells it needs, with the correct connectivity.
//
enum direction negdir = NO;
cell *cneg=0;
for (int idim=1; idim < FV_gndim; idim++) {
perp = static_cast<axes>((static_cast<int>(axis) +idim)%FV_gndim);
negdir = static_cast<direction>(static_cast<int>(axis)*2);
cneg = grid->NextPt(cl,negdir);
if (cneg)
eta = max(eta, CI.get_Hcorr(cneg,perp));
cneg = grid->NextPt(cr,negdir);
if (cneg)
eta = max(eta, CI.get_Hcorr(cneg,perp));
}
//
// Will want to comment this out later...
//
#ifdef TESTING
cout <<"cell id="<<cl->id<<" axis="<<axis<<", eta_max="<<eta<<"\n";
#endif // TESTING
return eta;
}
// ##################################################################
// ##################################################################
#ifdef THERMAL_CONDUCTION
int FV_solver_base::set_thermal_conduction_Edot(
class SimParams &SimPM ///< pointer to simulation parameters
)
{
//
// This function is quite similar to calc_dU() and dU_column()
// because it steps through the grid in the same way.
//
//cout <<"IntUniformFV::calc_conduction_dt_and_Edot()\n\tcalculating Temperature.\n";
//
// First we need to calculate the temperature in every cell. We do
// this first for grid cells, and then we will calculate it for boundary
// data later as they are encountered. Temperature is stored in dU[RHO] --
// We will reset it to zero at the end of this function.
//
if (!MP) {
rep.error("Why do conductivity without having Microphysics?",MP);
}
cell *c = grid->FirstPt();
do {
//cout <<"dU[RHO]="<<c->dU[RHO];
c->dU[RHO] = MP->Temperature(c->Ph,SimPM.gamma);
//cout <<", replaced with T="<<c->dU[RHO]<<"\n";
} while ((c=grid->NextPt(c)) !=0);
//cout <<"\tT calculated, now calculating divQ.\n";
//
// Allocate arrays
//
enum direction posdirs[MAX_DIM], negdirs[MAX_DIM];
enum axes axis[MAX_DIM];
posdirs[0] = XP; posdirs[1] = YP; posdirs[2] = ZP;
negdirs[0] = XN; negdirs[1] = YN; negdirs[2] = ZN;
axis[0] = XX; axis[1] = YY; axis[2] = ZZ;
double q_neg=0.0, q_pos=0.0, gradT=0.0, Qclassical=0.0, Qsaturated=0.0, T=0.0;
double dx=grid->DX();
//
// Loop through each direction.
//
for (int idim=0;idim<SimPM.ndim;idim++) {
//cout <<"\t\t\tidim="<<idim<<"\n";
//
// Start at first grid cells in each column, and we will move back
// to the first boundary cell to get the correct edge-cell in/out
// heat flux in each direction.
//
class cell *start = grid->FirstPt();
class cell *marker = grid->FirstPt();
//
// Loop over z-planes (there must be at least one!)
//
bool zplanes_finished = false;
bool xcolumns_finished = false;
do {
//
// Loop over x-columns in the y-direction (at least one!)
//
xcolumns_finished = false;
do {
// --------------------------------------------------------
// Calculate the Heat fluxes coefficients for this column:
// Start at the outermost boundary cell, and go to the end.
// We need all interfaces between and including the
// grid-boundary interface.
// --------------------------------------------------------
cell *cpt = start;
while (grid->NextPt(cpt,negdirs[idim])) {
cpt = grid->NextPt(cpt,negdirs[idim]);
}
cell *npt = grid->NextPt(cpt,posdirs[idim]);
if (npt==0)
rep.error("Couldn't find two cells in column",0);
q_neg = 0.0; // no flux coming in from non-existent boundary data.
q_pos = 0.0;
//
// Run through column, calculating slopes, edge-states, and
// eta[] values as we go.
//
do {
//
// Check if we have boundary data, b/c we need to set T for these cells.
//
if (!cpt->isgd) {
//cout <<"\tBoundary cpt dU[RHO]="<<cpt->dU[RHO];
cpt->dU[RHO] = MP->Temperature(cpt->Ph,SimPM.gamma);
//cout <<", replaced with T="<<cpt->dU[RHO]<<"\n";
}
if (!npt->isgd) {
//cout <<"\tBoundary npt dU[RHO]="<<npt->dU[RHO];
npt->dU[RHO] = MP->Temperature(npt->Ph,SimPM.gamma);
//cout <<", replaced with T="<<npt->dU[RHO]<<"\n";
}
//
// Now use the Slavin & Cox (1992) formula for conduction to get
// the conductive heat flux from cpt to npt in direction posdir[idim].
// We use the more opaque function idifference_cell2cell() since it gives
// the correct distance between centres-of-volume of cells on curvilinear
// grids.
//
gradT = (npt->dU[RHO]-cpt->dU[RHO])/(grid->idifference_cell2cell(cpt,npt,axis[idim])*CI.phys_per_int());
//cout <<"\tT2="<<npt->dU[RHO]<<", T1="<<cpt->dU[RHO]<<", grad(T)="<<gradT<<"\n";
//
// If flow is from npt to cpt, we use npt's values for calculating Q.
// Else we use cpt's values. (note if gradT>0, then T2>T1, flow from 2->1
// in the *negative* direction).
//
if (gradT>0.0) c=npt;
else c=cpt;
//
// First we get ln(Lambda) and then the classical and saturated fluxes.
// For ln(Lambda) the formula is only valid for T>4.2e5. The value of
// 4.2735e23 is (1.4*m_p)^{-1}.
//
T = c->dU[RHO];
if (T<4.2e5) Qclassical = 29.7;
else Qclassical = 29.7+log(T/(1.0e6*sqrt(c->Ph[RO]*4.2735e23)));
Qclassical = -1.84e-5*pow(T,2.5)*gradT/Qclassical;
//
// For saturated Q we follow S&C(1992) and use phi_s=0.3
//
Qsaturated = -1.5*pow(c->Ph[PG],1.5)/sqrt(c->Ph[RO]);
if (gradT<0.0) Qsaturated *= -1.0;
//
// now Q = Qs*(1-exp(-Qc/Qs)). (Qs>>Qc)=>(Q->Qc). (Qc>>Qs)=>(Q->Qs).
//
q_pos = Qsaturated*(1.0-exp(-Qclassical/Qsaturated));
//
// Finally cpt needs an updated -div(q) value from the current direction.
// This is a hack, because there is no VectorOps function to do this for me.
// I should write a function in VectorOps which I can call to do this... I
// should also make the base grid derive from base-VectorOps, so that the
// functions are accessible!
//
if (SimPM.coord_sys==COORD_CYL && axis[idim]==Rcyl) {
double rp = CI.get_dpos(c,Rcyl)+0.5*dx; double rn=rp-dx;
cpt->dU[ERG] += 2.0*(rn*q_neg-rp*q_pos)/(rp*rp-rn*rn);
}
else if (SimPM.coord_sys==COORD_SPH && axis[idim]==Rsph) {
double rc = CI.get_dpos(c,Rsph);
double rp = rc+0.5*dx; double rn=rp-dx;
rc = (pow(rp,3.0) -pow(rn,3.0))/3.0;
cpt->dU[ERG] += (rn*rn*q_neg-rp*rp*q_pos)/rc;
}
else {
cpt->dU[ERG] += (q_neg-q_pos)/dx;
}
//cout <<"\tQc="<<Qclassical<<", Qs="<<Qsaturated<<", Q="<<q_pos<<", Edot="<<cpt->dU[ERG]<<"\n";
//
// Set npt to cpt, set current q_pos to q_neg for next cell.
// Move to next cell.
//
q_neg = q_pos;
cpt = npt;
} while ( (npt=grid->NextPt(npt,posdirs[idim])) !=0);
// --------------------------------------------------------
// Finished Heat conduction calculation for the column.
// --------------------------------------------------------
//
// Get next x-column, or if it doesn't exist set a flag to
// indicate that we are finished.
//
if (SimPM.ndim==1) xcolumns_finished = true;
else {
start = grid->NextPt(start,posdirs[(idim+1)%SimPM.ndim]);
if (!start || !start->isgd) xcolumns_finished = true;
}
} while (!xcolumns_finished);
//
// Get next z-plane, or if it doesn't exist set a flag to
// indicate that we are finished. Reset marker to the first
// cell in the new plane.
//
if (SimPM.ndim<=2) zplanes_finished = true;
else {
start = grid->NextPt(marker,posdirs[(idim+2)%SimPM.ndim]);
marker = start;
if (!start || !start->isgd) zplanes_finished = true;
}
} while (!zplanes_finished);
} // Loop over Ndim directions.
//
// Now reset the temporary storage of Temperature in dU[RHO] to zero.
//
c = grid->FirstPt();
do {
c->dU[RHO]=0.0;
} while ((c=grid->NextPt(c)) !=0);
return 0;
}
#endif // THERMAL_CONDUCTION
// ##################################################################
// ##################################################################
| 32.768549 | 114 | 0.555931 | [
"vector",
"3d"
] |
e5a1ac8ff32078628d03c34e8948f66329f510ee | 5,908 | cpp | C++ | circe/gl/graphics/shader_manager.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | 1 | 2021-09-17T18:12:47.000Z | 2021-09-17T18:12:47.000Z | circe/gl/graphics/shader_manager.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | null | null | null | circe/gl/graphics/shader_manager.cpp | gui-works/circe | c126a8f9521dca1eb23ac47c8f2e8081f2102f17 | [
"MIT"
] | 2 | 2021-09-17T18:13:02.000Z | 2021-09-17T18:16:21.000Z | /*
* Copyright (c) 2017 FilipeCN
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include <circe/gl/graphics/shader_manager.h>
#include <hermes/common/file_system.h>
namespace circe::gl {
ShaderManager ShaderManager::instance_;
ShaderManager::ShaderManager() = default;
int ShaderManager::loadFromFiles(std::initializer_list<const char *> l) {
std::vector<GLuint> objects;
GLuint types[] = {GL_VERTEX_SHADER, GL_GEOMETRY_SHADER, GL_FRAGMENT_SHADER,
GL_COMPUTE_SHADER};
for (auto v : l) {
std::string filename(v);
if (filename.size() < 4)
continue;
std::cout << "loading shader file " << filename << std::endl;
auto source = hermes::FileSystem::readFile(filename);
if (source.empty())
continue;
GLuint shaderType = 0;
switch (filename[filename.size() - 4]) {
case 'v':shaderType = 0;
break;
case 'g':shaderType = 1;
break;
case 'f':shaderType = 2;
break;
case 'c':shaderType = 3;
break;
default:continue;
}
objects.emplace_back(compile(source.c_str(), types[shaderType]));
}
if (objects.empty())
return -1;
GLuint program = createProgram(objects);
if (!program)
return -1;
return static_cast<int>(program);
}
int ShaderManager::loadFromTexts(const char *vs, const char *gs,
const char *fs) {
std::vector<GLuint> objects(3, 0);
if (vs != nullptr)
objects[0] = compile(vs, GL_VERTEX_SHADER);
if (gs != nullptr)
objects[1] = compile(gs, GL_GEOMETRY_SHADER);
if (fs != nullptr)
objects[2] = compile(fs, GL_FRAGMENT_SHADER);
GLuint program = createProgram(objects);
if (!program)
return -1;
return static_cast<int>(program);
}
int ShaderManager::loadFromText(const char *s, GLuint shaderType) {
std::vector<GLuint> object(1, 0);
if (!s)
return -1;
object[0] = compile(s, shaderType);
GLuint program = createProgram(object);
if (!program)
return -1;
return static_cast<int>(program);
}
bool ShaderManager::useShader(GLuint program) {
CHECK_GL(glUseProgram(program));
return true;
}
GLuint ShaderManager::createProgram(const GLchar *vertexShaderSource,
const GLchar *fragmentShaderSource) {
GLuint ProgramObject; // handles to objects
GLint vertCompiled, fragCompiled; // status values
GLint linked;
// Create a vertex shader object and a fragment shader object
GLuint VertexShaderObject = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER);
// Load source code strings into shaders
glShaderSource(VertexShaderObject, 1, &vertexShaderSource, nullptr);
glShaderSource(FragmentShaderObject, 1, &fragmentShaderSource, nullptr);
// Compile the brick vertex shader, and print out
// the compiler log file.
glCompileShader(VertexShaderObject);
CHECK_GL_ERRORS;
glGetShaderiv(VertexShaderObject, GL_COMPILE_STATUS, &vertCompiled);
if (!vertCompiled)
printShaderInfoLog(VertexShaderObject);
// Compile the brick vertex shader, and print out
// the compiler log file.
glCompileShader(FragmentShaderObject);
CHECK_GL_ERRORS;
glGetShaderiv(FragmentShaderObject, GL_COMPILE_STATUS, &fragCompiled);
if (!fragCompiled)
printShaderInfoLog(FragmentShaderObject);
if (!vertCompiled || !fragCompiled) {
std::cerr << "couldn't compile shader!\n";
return 0;
}
// Create a program object and attach the two compiled shaders
ProgramObject = glCreateProgram();
glAttachShader(ProgramObject, VertexShaderObject);
glAttachShader(ProgramObject, FragmentShaderObject);
// Link the program object and print out the info log
glLinkProgram(ProgramObject);
CHECK_GL_ERRORS;
glGetProgramiv(ProgramObject, GL_LINK_STATUS, &linked);
printProgramInfoLog(ProgramObject);
if (!linked)
return 0;
return ProgramObject;
}
GLuint ShaderManager::compile(const char *shaderSource, GLuint shaderType) {
GLint compiled;
GLuint shaderObject = glCreateShader(shaderType);
glShaderSource(shaderObject, 1, &shaderSource, nullptr);
glCompileShader(shaderObject);
CHECK_GL_ERRORS;
glGetShaderiv(shaderObject, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
std::cerr << shaderSource << std::endl;
printShaderInfoLog(shaderObject);
std::cerr << "failed to compile shader\n";
}
return shaderObject;
}
GLuint ShaderManager::createProgram(const std::vector<GLuint> &objects) {
GLuint programObject = glCreateProgram();
for (unsigned int object : objects)
if (object)
glAttachShader(programObject, object);
glLinkProgram(programObject);
CHECK_GL_ERRORS;
GLint linked;
glGetProgramiv(programObject, GL_LINK_STATUS, &linked);
printProgramInfoLog(programObject);
if (!linked)
return 0;
return programObject;
}
} // circe namespace
| 33.378531 | 80 | 0.718009 | [
"object",
"vector"
] |
e5a1fdda09ca5509e85ec042bbfab455ea7142a8 | 1,467 | cpp | C++ | Elit3d/src/Panels/p1Inspector.cpp | christt105/Elit3D | 06e3fbab04df54c63057a3e85823a9c5e439e4ec | [
"BSD-2-Clause"
] | 26 | 2021-05-25T05:16:28.000Z | 2022-03-20T12:55:07.000Z | Elit3d/src/Panels/p1Inspector.cpp | christt105/Elit3D | 06e3fbab04df54c63057a3e85823a9c5e439e4ec | [
"BSD-2-Clause"
] | 1 | 2021-05-25T18:48:17.000Z | 2021-06-07T19:21:13.000Z | Elit3d/src/Panels/p1Inspector.cpp | christt105/TileMapEditor3D | 70b5e168c1b9c5b9882cabbb5ac3ed6890a87eef | [
"BSD-2-Clause"
] | 5 | 2021-04-16T12:18:05.000Z | 2021-11-24T13:59:46.000Z | #include "Panels/p1Inspector.h"
#include "Core/Application.h"
#include "Modules/m1Objects.h"
#include "Objects/Object.h"
#include "Tools/Map/MapLayer.h"
#include "Modules/m1Resources.h"
#include "Resources/r1Tileset.h"
#include "Resources/r1Map.h"
#include "Tools/FileSystem.h"
p1Inspector::p1Inspector(bool start_enabled, bool appear_mainmenubar, bool can_close)
: Panel("Inspector", start_enabled, appear_mainmenubar, can_close, ICON_FA_INFO_CIRCLE)
{
}
p1Inspector::~p1Inspector()
{
}
void p1Inspector::Update()
{
if (selected)
switch (type)
{
case p1Inspector::SelectedType::OBJECT: {
Object* sel = (Object*)selected;
if (sel != nullptr) {
ImGui::Checkbox("##active_object", &sel->active);
ImGui::SameLine();
ImGui::Text(sel->name.c_str());
for (auto i = sel->components.begin(); i != sel->components.end(); ++i) {
(*i)->OnInspector();
}
}
break;
}
case p1Inspector::SelectedType::LAYER:
((MapLayer*)selected)->OnInspector();
break;
case p1Inspector::SelectedType::EDITOR_MAP:
((r1Map*)selected)->OnInspector();
break;
case p1Inspector::SelectedType::RESOURCE:
{
auto r = App->resources->FindGet(((std::string*)selected)->c_str(), false);
if (r)
r->OnInspector();
break;
}
default:
break;
}
}
void p1Inspector::SetSelected(void* ptr, SelectedType t)
{
selected = ptr;
type = t;
if (type == p1Inspector::SelectedType::LAYER)
((MapLayer*)selected)->SetSelected();
}
| 23.285714 | 88 | 0.676892 | [
"object"
] |
e5ad4e4bb959b526b8e2e6ab00dc0a1aa3fa287f | 12,908 | cc | C++ | src/nnetbin/nnet-modify.cc | swang423/kaldi | 8ea96441148847223b25fde0564ef04a00683cee | [
"Apache-2.0"
] | null | null | null | src/nnetbin/nnet-modify.cc | swang423/kaldi | 8ea96441148847223b25fde0564ef04a00683cee | [
"Apache-2.0"
] | null | null | null | src/nnetbin/nnet-modify.cc | swang423/kaldi | 8ea96441148847223b25fde0564ef04a00683cee | [
"Apache-2.0"
] | null | null | null | // nnetbin/nnet-copy.cc
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "nnet/nnet-nnet.h"
#include "nnet/nnet-component.h"
#include "nnet/nnet-parallel-component.h"
#include "nnet/nnet-linear-transform.h"
#include "nnet/nnet-affine-transform.h"
#include "cudamatrix/cu-device.h"
#include "nnet/nnet-activation.h"
#include "nnet/nnet-various.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
using namespace kaldi::nnet1;
typedef kaldi::int32 int32;
const char *usage =
"NOT COMPLETE\n"
"Copy Neural Network model (and possibly change binary/text format)\n"
"Usage: nnet-copy [options] <model-in> <model-out>\n"
"e.g.:\n"
" nnet-copy --binary=false nnet.mdl nnet_txt.mdl\n";
bool binary_write = true;
int32 remove_first_components = 0;
int32 remove_last_components = 0;
BaseFloat dropout_rate = -1.0;
ParseOptions po(usage);
po.Register("binary", &binary_write, "Write output in binary mode");
po.Register("remove-first-layers", &remove_first_components,
"Deprecated, please use --remove-first-components");
po.Register("remove-last-layers", &remove_last_components,
"Deprecated, please use --remove-last-components");
po.Register("remove-first-components", &remove_first_components,
"Remove N first Components from the Nnet");
po.Register("remove-last-components", &remove_last_components,
"Remove N last layers Components from the Nnet");
po.Register("dropout-rate", &dropout_rate,
"Probability that neuron is dropped"
"(-1.0 keeps original value).");
std::string from_parallel_component;
po.Register("from-parallel-component", &from_parallel_component,
"Extract nested network from parallel component (two possibilities: "
"'3' = search for ParallelComponent and get its 3rd network; "
"'1:3' = get 3nd network from 1st component; ID = 1..N).");
int32 st_to_mt_dim = 0;
po.Register("st-to-mt-dim",&st_to_mt_dim, "Assume the output layer is affine! Add auxiliary output of specified dimension to nnet, assuming from 1 task up to 2.");
int32 mt_to_st_dim = 0;
po.Register("mt-to-st-dim",&mt_to_st_dim, "Remove auxiliary output from nnet, assuming from 2 tasks down to 1.");
bool st_to_mt_dup = false;
po.Register("st-to-mt-dup",&st_to_mt_dup, "If true, duplicate output with identity matrix");
bool set_linearity_to_identity = false;
po.Register("set-linearity-to-identity",&set_linearity_to_identity, "Set all affine to identity and bias to zero.");
float temperature = 1;
po.Register("temperature",&temperature,"Insert a Rescale layer before Softmax for soft target with temperature;\nSee Hinton's knowledge distillation.");
int32 st_to_mt_splice = 1;
po.Register("st-to-mt-splice",&st_to_mt_splice,"duplicate outputs with splice");
int32 mt_to_st_splice = 1;
po.Register("mt-to-st-splice",&mt_to_st_splice,"extract outputs with splice");
bool add_lin,add_lhn;
po.Register("add-lin", &add_lin, "add linear input layer");
po.Register("add-lhn", &add_lin, "add linear hidden layer before last non-linear");
po.Read(argc, argv);
if (po.NumArgs() != 2) {
po.PrintUsage();
exit(1);
}
KALDI_ASSERT(temperature>0);
std::string model_in_filename = po.GetArg(1),
model_out_filename = po.GetArg(2);
// load the network
Nnet nnet;
{
bool binary_read;
Input ki(model_in_filename, &binary_read);
nnet.Read(ki.Stream(), binary_read);
}
// eventually replace 'nnet' by nested network from <ParallelComponent>,
if (from_parallel_component != "") {
std::vector<int32> component_id_nested_id;
kaldi::SplitStringToIntegers(from_parallel_component, ":", false,
&component_id_nested_id);
// parse the argument,
int32 component_id = -1, nested_id = 0;
switch (component_id_nested_id.size()) {
case 1:
nested_id = component_id_nested_id[0];
break;
case 2:
component_id = component_id_nested_id[0];
nested_id = component_id_nested_id[1];
break;
default:
KALDI_ERR << "Check the csl '--from-parallel-component='"
<< from_parallel_component
<< " There must be 1 or 2 elements.";
}
// search for first <ParallelComponent> (we don't know component_id yet),
if (component_id == -1) {
for (int32 i = 0; i < nnet.NumComponents(); i++) {
if (nnet.GetComponent(i).GetType() == Component::kParallelComponent) {
component_id = i+1;
break;
}
}
}
// replace the nnet,
KALDI_ASSERT(nnet.GetComponent(component_id-1).GetType() ==
Component::kParallelComponent);
ParallelComponent& parallel_comp =
dynamic_cast<ParallelComponent&>(nnet.GetComponent(component_id-1));
nnet = parallel_comp.GetNestedNnet(nested_id-1); // replace!
}
// optionally remove N first components,
if (remove_first_components > 0) {
for (int32 i = 0; i < remove_first_components; i++) {
nnet.RemoveComponent(0);
}
}
// optionally remove N last components,
if (remove_last_components > 0) {
for (int32 i = 0; i < remove_last_components; i++) {
nnet.RemoveLastComponent();
}
}
// set all affine to unity
if (set_linearity_to_identity) {
for (int32 i = 0; i < nnet.NumComponents(); i++) {
if (nnet.GetComponent(i).GetType() == Component::kAffineTransform) {
AffineTransform* new_affine = dynamic_cast<AffineTransform*>(&nnet.GetComponent(i));
Matrix<BaseFloat> new_linearity(new_affine->GetLinearity().NumRows(),new_affine->GetLinearity().NumCols());
Vector<BaseFloat> new_bias(new_affine->GetBias().Dim());
new_linearity.SetUnit();
new_bias.SetZero();
new_affine->SetLinearity(CuMatrix<BaseFloat>(new_linearity));
new_affine->SetBias(CuVector<BaseFloat>(new_bias));
AffineTransform new_affine_instance = *new_affine;
nnet.ReplaceComponent(i,new_affine_instance);
//nnet.ReplaceComponent(i,*new_affine);
}
}
}
if(mt_to_st_splice>1){
int32 num_comp = nnet.NumComponents();
KALDI_ASSERT(nnet.GetComponent(num_comp-1).GetType() == Component::kAffineTransform);
int32 all_context = mt_to_st_splice * 2 + 1;
const AffineTransform& affine = dynamic_cast<AffineTransform&>(nnet.GetComponent(num_comp-1));
CuMatrix<BaseFloat> linearity_mt = CuMatrix<BaseFloat>(affine.GetLinearity());
CuVector<BaseFloat> bias_mt = CuVector<BaseFloat>(affine.GetBias());
KALDI_ASSERT(bias_mt.Dim()%all_context==0);
int32 dim_single = bias_mt.Dim()/all_context;
// KALDI_LOG << "dim single: " << dim_single;
CuMatrix<BaseFloat> linearity_st(dim_single,linearity_mt.NumCols());
CuVector<BaseFloat> bias_st(dim_single);
// KALDI_LOG << "linearity: " << mt_to_st_splice << " " ;
linearity_st.CopyFromMat(linearity_mt.RowRange(mt_to_st_splice*dim_single,dim_single));
bias_st.CopyFromVec(bias_mt.Range(mt_to_st_splice*dim_single,dim_single));
AffineTransform* affine_st = new AffineTransform(linearity_st.NumCols(),dim_single);
affine_st->SetLinearity(linearity_st);
affine_st->SetBias(bias_st);
nnet.ReplaceComponent(num_comp-1,*affine_st);
}
//make output splice
if(st_to_mt_splice>1){
int32 num_comp = nnet.NumComponents();
KALDI_ASSERT(nnet.GetComponent(num_comp-1).GetType() == Component::kAffineTransform);
const AffineTransform& affine = dynamic_cast<AffineTransform&>(nnet.GetComponent(num_comp-1));
CuMatrix<BaseFloat> linearity_st = CuMatrix<BaseFloat>(affine.GetLinearity());
CuVector<BaseFloat> bias_st = CuVector<BaseFloat>(affine.GetBias());
CuMatrix<BaseFloat> linearity_mt(linearity_st.NumRows()*st_to_mt_splice,linearity_st.NumCols());
CuVector<BaseFloat> bias_mt(bias_st.Dim()*st_to_mt_splice);
for(int32 kk = 0; kk<st_to_mt_splice; kk++){
linearity_mt.RowRange(kk*linearity_st.NumRows(),linearity_st.NumRows()).CopyFromMat(linearity_st);
bias_mt.Range(kk*bias_st.Dim(),bias_st.Dim()).CopyFromVec(bias_st);
}
AffineTransform* affine_mt = new AffineTransform(linearity_st.NumCols(),linearity_st.NumRows()*st_to_mt_splice);
affine_mt->SetLinearity(linearity_mt);
affine_mt->SetBias(bias_mt);
nnet.ReplaceComponent(num_comp-1,*affine_mt);
}
//create mt, init with rand
if(st_to_mt_dim >0){
int32 num_comp = nnet.NumComponents();
// if(nnet.GetComponent(num_comp-1).GetType() == Component::kAffineTransform){//regression network
KALDI_ASSERT(nnet.GetComponent(num_comp-1).GetType() == Component::kAffineTransform);
const AffineTransform& affine = dynamic_cast<AffineTransform&>(nnet.GetComponent(num_comp-1));
CuMatrix<BaseFloat> linearity_st = CuMatrix<BaseFloat>(affine.GetLinearity());
CuVector<BaseFloat> bias_st = CuVector<BaseFloat>(affine.GetBias());
CuMatrix<BaseFloat> linearity_mt(linearity_st.NumRows()+st_to_mt_dim,linearity_st.NumCols());
CuVector<BaseFloat> bias_mt(bias_st.Dim()+st_to_mt_dim);
linearity_mt.RowRange(0,linearity_st.NumRows()).CopyFromMat(linearity_st);
linearity_mt.RowRange(linearity_st.NumRows(),st_to_mt_dim).SetRandn();
bias_mt.Range(0,bias_st.Dim()).CopyFromVec(bias_st);
bias_mt.Range(bias_st.Dim(),st_to_mt_dim).SetRandn();
AffineTransform* affine_mt = new AffineTransform(affine.InputDim(),linearity_st.NumRows()+st_to_mt_dim);
affine_mt->SetLinearity(linearity_mt);
affine_mt->SetBias(bias_mt);
nnet.ReplaceComponent(num_comp-1,*affine_mt);
// }
//For classifaction networks ending with softmax layers, the suggestion is to remove it first, split last affine, then use block softmax
}
if (mt_to_st_dim > 0){
KALDI_ASSERT(nnet.GetLastComponent().GetType() == Component::kAffineTransform);
Component* last_component = nnet.GetLastComponent().Copy();
AffineTransform* last_component_pt = dynamic_cast<AffineTransform*>(last_component);
CuMatrix<BaseFloat> last_lin;
last_lin = last_component_pt->GetLinearity();
CuVector<BaseFloat> last_bias;
last_bias = last_component_pt->GetBias();
CuMatrix<BaseFloat> new_last_lin;
CuVector<BaseFloat> new_last_bias;
int32 output_dim = last_lin.NumRows();
// KALDI_ASSERT(output_dim%2==0);
// KALDI_ASSERT(last_bias.Dim()==output_dim);
new_last_lin.Resize(output_dim - mt_to_st_dim,last_lin.NumCols());
new_last_bias.Resize(output_dim - mt_to_st_dim);
new_last_lin.CopyFromMat(last_lin.RowRange(0,output_dim-mt_to_st_dim));
new_last_bias.CopyFromVec(last_bias.Range(0,output_dim - mt_to_st_dim));
AffineTransform new_last_component = AffineTransform(last_lin.NumCols(),output_dim - mt_to_st_dim);
new_last_component.SetLinearity(new_last_lin);
new_last_component.SetBias(new_last_bias);
nnet.ReplaceComponent(nnet.NumComponents()-1,new_last_component);
}
//By default, we duplicate from 1 task to 2
if(st_to_mt_dup){
LinearTransform split_component = LinearTransform(nnet.OutputDim(),nnet.OutputDim()*2);
Matrix<BaseFloat> split_mat(nnet.OutputDim()*2,nnet.OutputDim());
split_mat.RowRange(0,nnet.OutputDim()).SetUnit();
split_mat.RowRange(nnet.OutputDim(),nnet.OutputDim()).SetUnit();
split_component.SetLinearity(CuMatrix<BaseFloat>(split_mat));
split_component.SetLearnRateCoef(0); //trainble = false
//split_component.SetBiasLearnRateCoef(0); //linear has no bias
nnet.AppendComponent(split_component);
}
// dropout,
if (dropout_rate != -1.0) {
nnet.SetDropoutRate(dropout_rate);
}
if (temperature > 1){
// int32 num_comp = nnet.NumComponents();
// KALDI_ASSERT(nnet.GetComponent(num_comp-1).GetType() == Component::kSoftmax);
// KALDI_ASSERT(components_[affine_index[i]]->GetType()==Component::kAffineTransform)
// const Softmax& softmax = dynamic_cast<Softmax&>(nnet.GetComponent(num_comp-1));
Component* last_component = nnet.GetLastComponent().Copy();
Rescale scale(last_component->InputDim(),last_component->InputDim());
Vector<BaseFloat> scale_vec(last_component->InputDim());
scale_vec.Set(1.0/temperature);
scale.SetParams(scale_vec);
scale.SetLearnRateCoef(0);
nnet.RemoveLastComponent();
nnet.AppendComponent(scale);
nnet.AppendComponent(*last_component);
}else if(temperature<1){
KALDI_WARN << "Temperature < 1 is not advised.";
}
if (add_lin){
}
if (add_lhn){
KALDI_ERR << "NOT IMPLEMENTED";
}
// store the network,
{
Output ko(model_out_filename, binary_write);
nnet.Write(ko.Stream(), binary_write);
}
KALDI_LOG << "Written 'nnet1' to " << model_out_filename;
return 0;
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 44.054608 | 164 | 0.702665 | [
"vector",
"model",
"transform"
] |
e5b00ac35ec79b2a49fbbaaeaf5102bad3c4f9dc | 747 | cpp | C++ | PrCmp/AtCoder-Beginner-Contest-174/D.cpp | ayhon/CPPWorkspace | 57d6410236096ffa0bae20b88b3e330632edc928 | [
"MIT"
] | null | null | null | PrCmp/AtCoder-Beginner-Contest-174/D.cpp | ayhon/CPPWorkspace | 57d6410236096ffa0bae20b88b3e330632edc928 | [
"MIT"
] | null | null | null | PrCmp/AtCoder-Beginner-Contest-174/D.cpp | ayhon/CPPWorkspace | 57d6410236096ffa0bae20b88b3e330632edc928 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using pi = pair<int, int>;
using vi = vector<int>;
using vpi = vector<pi>;
using vvi = vector<vi>;
using vvpi = vector<vpi>;
using pl = pair<long long, long long>;
using vl = vector<long long>;
using vpl = vector<pl>;
using vvl = vector<vl>;
using vvpl = vector<vpl>;
void resuelveCaso() {
int n; cin >> n;
vi stones(n, 0);
string s; cin >> s;
int numW = 0;
for(int i = 0; i < s.size(); i++) {
if(s[i] == 'W'){
numW++;
stones[n-i-1] = 1;
}
}
int moves = 0;
for(int i = 0; i < numW; i++) {
if (stones[i] == 0) moves++;
}
cout << moves << endl;
}
int main() {
int T = 1;
for (int i = 1; i <= T; i++) {
//cout << "Case #" << i << ": ";
resuelveCaso();
}
return 0;
}
| 16.977273 | 38 | 0.539491 | [
"vector"
] |
e5b1f79846069530bd3975bb82e001617926186b | 2,070 | hpp | C++ | src/gdx-cpp/graphics/g3d/loaders/wavefront/ObjLoader.hpp | aevum/libgdx-cpp | 88603a59af4d915259a841e13ce88f65c359f0df | [
"Apache-2.0"
] | 77 | 2015-01-28T17:21:49.000Z | 2022-02-17T17:59:21.000Z | src/gdx-cpp/graphics/g3d/loaders/wavefront/ObjLoader.hpp | aevum/libgdx-cpp | 88603a59af4d915259a841e13ce88f65c359f0df | [
"Apache-2.0"
] | 5 | 2015-03-22T23:14:54.000Z | 2020-09-18T13:26:03.000Z | src/gdx-cpp/graphics/g3d/loaders/wavefront/ObjLoader.hpp | aevum/libgdx-cpp | 88603a59af4d915259a841e13ce88f65c359f0df | [
"Apache-2.0"
] | 24 | 2015-02-12T04:34:37.000Z | 2021-06-19T17:05:23.000Z | /*
* ObjLoader.h
*
* Created on: Jan 20, 2013
* Author: anton
*/
#ifndef OBJLOADER_H_
#define OBJLOADER_H_
#include "gdx-cpp/graphics/g3d/loaders/StillModelLoader.hpp"
#include "gdx-cpp/graphics/Texture.hpp"
#include "gdx-cpp/graphics/g3d/model/still/StillSubMesh.hpp"
#include "gdx-cpp/graphics/Color.hpp"
#include "gdx-cpp/graphics/Texture.hpp"
#include "gdx-cpp/graphics/g3d/materials/TextureAttribute.hpp"
#include "gdx-cpp/graphics/g3d/materials/ColorAttribute.hpp"
#include <algorithm>
using namespace std;
using namespace gdx;
namespace gdx
{
class ObjLoader : public StillModelLoader
{
private:
class Group
{
friend class ObjLoader;
private:
string name;
string materialName;
vector<int> faces;
int numFaces;
bool hasNorms;
bool hasUVs;
Material* mat;
public:
Group ( string name ) {
this->name = name;
numFaces = 0;
hasNorms = false;
hasUVs = false;
materialName = "default";
mat = new Material ( "" );
}
};
class MtlLoader
{
private:
vector<Material*> materials;
//static AssetManager
static Texture* emptyTexture;
public:
MtlLoader();
void load ( string fileName, FileHandle& textureDir );
Material* getMaterial ( string name );
};
vector<float> verts;
vector<float> norms;
vector<float> uvs;
vector<Group*> groups;
Group* setActiveGroup ( const string& group );
int getIndex ( int index, int size );
void proccessVerteOrNormal ( string& line, const char* templ, vector<float>& container );
void proccessUV ( string& line, bool isFlip );
public:
ObjLoader();
virtual ~ObjLoader();
StillModel* loadObj ( const FileHandle& file, bool flipV = false );
StillModel* loadObj ( const FileHandle& file, FileHandle& textureDir, bool flipV );
StillModel* load ( const FileHandle& handle, ModelLoaderHints hints ) override;
};
}
#endif /* OBJLOADER_H_ */
| 24.352941 | 93 | 0.638164 | [
"vector",
"model"
] |
e5b9dcfd8d043db193d16664b6b7962de7c8a75e | 4,863 | cpp | C++ | test/test_Precedence.cpp | Mercerenies/latitude | 29b1697f1f615d52480197a52e20ff8c1872f07d | [
"MIT"
] | 3 | 2021-09-02T18:19:25.000Z | 2021-12-26T23:33:32.000Z | test/test_Precedence.cpp | Mercerenies/latitude | 29b1697f1f615d52480197a52e20ff8c1872f07d | [
"MIT"
] | 45 | 2017-11-28T15:13:59.000Z | 2022-02-19T18:45:46.000Z | test/test_Precedence.cpp | Mercerenies/proto-lang | 29b1697f1f615d52480197a52e20ff8c1872f07d | [
"MIT"
] | null | null | null | //// Copyright (c) 2018 Silvio Mayolo
//// See LICENSE.txt for licensing details
#include "catch2/catch.hpp"
#include "test.hpp"
#include "Precedence.hpp"
#include "Garnish.hpp"
TEST_CASE( "Operator table", "" ) {
// The operator table doesn't actually exist, per se, until the core
// library is loaded. So we'll mock it here.
ObjectPtr eq = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr plus = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr minus = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr times = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr pow = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr lex = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr meta = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr obj = clone(globalVM->reader.lit[Lit::OBJECT]);
ObjectPtr impl = clone(globalVM->reader.lit[Lit::OBJECT]);
eq->put(Symbols::get()["prec"], garnishObject(globalVM->reader, 5l));
eq->put(Symbols::get()["assoc"], eq);
eq->put(Symbols::get()["inner"], garnishObject(globalVM->reader, Symbols::get()["none"]));
plus->put(Symbols::get()["prec"], garnishObject(globalVM->reader, 10l));
plus->put(Symbols::get()["assoc"], plus);
plus->put(Symbols::get()["inner"], garnishObject(globalVM->reader, Symbols::get()["left"]));
minus->put(Symbols::get()["prec"], garnishObject(globalVM->reader, 10l));
minus->put(Symbols::get()["assoc"], minus);
minus->put(Symbols::get()["inner"], garnishObject(globalVM->reader, Symbols::get()["left"]));
times->put(Symbols::get()["prec"], garnishObject(globalVM->reader, 20l));
times->put(Symbols::get()["assoc"], times);
times->put(Symbols::get()["inner"], garnishObject(globalVM->reader, Symbols::get()["left"]));
pow->put(Symbols::get()["prec"], garnishObject(globalVM->reader, 30l));
pow->put(Symbols::get()["assoc"], pow);
pow->put(Symbols::get()["inner"], garnishObject(globalVM->reader, Symbols::get()["right"]));
lex->put(Symbols::get()["meta"], meta);
meta->put(Symbols::get()["operators"], obj);
obj->put(Symbols::get()["&impl"], impl);
impl->put(Symbols::get()["=="], eq);
impl->put(Symbols::get()["+"], plus);
impl->put(Symbols::get()["-"], minus);
impl->put(Symbols::get()["*"], times);
impl->put(Symbols::get()["^"], pow);
SECTION( "Getting the precedence table" ) {
OperatorTable table = getTable(lex);
auto eqData = table.lookup("==");
REQUIRE( eqData.precedence == 5 );
REQUIRE( eqData.associativity == Associativity::NONE );
auto minusData = table.lookup("-");
REQUIRE( minusData.precedence == 10 );
REQUIRE( minusData.associativity == Associativity::LEFT );
auto nonsenseData = table.lookup("&**=+");
REQUIRE( nonsenseData.precedence == DEFAULT_PRECEDENCE );
REQUIRE( nonsenseData.associativity == Associativity::LEFT );
}
SECTION( "Testing precedence" ) {
// Original:
// 1 + 2 - 3 * 4 == 5.
// Should result in:
// ((1 + 2) - (3 * 4)) == 5.
Expr* expr = new Expr();
// ---
Expr* curr = expr;
curr->lhs = new Expr();
curr->isOperator = true;
curr->name = new char[3]{'=', '=', '\0'};
curr->args = new List();
curr->args->car = new Expr();
curr->args->car->line = 5;
curr->args->cdr = new List();
// ---
curr = curr->lhs;
curr->lhs = new Expr();
curr->isOperator = true;
curr->name = new char[2]{'*', '\0'};
curr->args = new List();
curr->args->car = new Expr();
curr->args->car->line = 4;
curr->args->cdr = new List();
// ---
curr = curr->lhs;
curr->lhs = new Expr();
curr->isOperator = true;
curr->name = new char[2]{'-', '\0'};
curr->args = new List();
curr->args->car = new Expr();
curr->args->car->line = 3;
curr->args->cdr = new List();
// ---
curr = curr->lhs;
curr->lhs = new Expr();
curr->isOperator = true;
curr->name = new char[2]{'+', '\0'};
curr->args = new List();
curr->args->car = new Expr();
curr->args->car->line = 2;
curr->args->cdr = new List();
// ---
curr = curr->lhs;
curr->line = 1;
// --- ---
// Leaking memory, I think. The precedence code does some weird pointer stuff >.>
Expr* result = reorganizePrecedence(OperatorTable(impl), expr);
// ((1 + 2) - (3 * 4)) == 5.
REQUIRE( strcmp(result->name, "==") == 0 );
REQUIRE( strcmp(result->lhs->name, "-") == 0 );
REQUIRE( strcmp(result->lhs->lhs->name, "+") == 0 );
REQUIRE( strcmp(result->lhs->args->car->name, "*") == 0 );
REQUIRE( result->lhs->lhs->lhs->line == 1 );
REQUIRE( result->lhs->lhs->args->car->line == 2 );
REQUIRE( result->lhs->args->car->lhs->line == 3 );
REQUIRE( result->lhs->args->car->args->car->line == 4 );
REQUIRE( result->args->car->line == 5 );
cleanupE(result);
}
}
| 29.652439 | 95 | 0.590171 | [
"object"
] |
e5e0e4294d74fe4f3688ff1cf36162cf76ffccd4 | 1,643 | cpp | C++ | solutions/LeetCode/C++/228.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/228.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/228.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 4 ms submission
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string>ret;
if(nums.empty())
return ret;
int cur = nums[0];
for(int i = 0;i<nums.size();i++){
int cur = nums[i];
int nex= nums[i];
string range = to_string(cur);
while(i+1<nums.size() && nums[i+1] == nex+1){
i++;
nex = nums[i];
}
if(cur == nex)
ret.push_back(range);
else
ret.push_back(range + "->"+to_string(nex));
}
return ret;
}
};
__________________________________________________________________________________________________
sample 8384 kb submission
class Solution {
private:
string encode(int low, int high) {
if (low == high) {
return to_string(low);
}
return to_string(low) + "->" + to_string(high);
}
public:
vector<string> summaryRanges(vector<int>& nums) {
if (nums.empty()) {
return vector<string>();
}
int low = nums[0];
int high = nums[0];
vector<string> result;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] != (high + 1)) {
result.push_back(encode(low, high));
low = nums[i];
high = nums[i];
} else {
high = nums[i];
}
}
result.push_back(encode(low, high));
return result;
}
};
__________________________________________________________________________________________________
| 28.327586 | 98 | 0.576385 | [
"vector"
] |
e5e7754f0ba77e464b30f0ea94802c5f78628ac9 | 1,394 | cpp | C++ | ver1/answers/lp-03-20.cpp | aafulei/cppp5e | f8d254073866e3025c3a08b919d9bbe3965b6918 | [
"MIT"
] | null | null | null | ver1/answers/lp-03-20.cpp | aafulei/cppp5e | f8d254073866e3025c3a08b919d9bbe3965b6918 | [
"MIT"
] | null | null | null | ver1/answers/lp-03-20.cpp | aafulei/cppp5e | f8d254073866e3025c3a08b919d9bbe3965b6918 | [
"MIT"
] | null | null | null | // 17/10/22 = Sun
// 18/01/27 = Sat: new arithmetic for indexing; concise for loop
// Exercise 3.20: Read a set of integers into a vector. Print the sum of each pair of adjacent elements. Change your program so that it prints the sum of the first and last elements, followed by the sum of the second and second-to-last, and so on.
// To run, enter, for example "a <data\digits" in command prompt
// For completeness, test vectors of 0, 1, 2 elements.
// The first half of a vector is [0, v.size() / 2). (Excluding the mid-point if number of elements are odd). Be very careful of expression like (v.size() - 1) / 2, because if v is empty, this could be a disaster!
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
// Given {1, 2, 3, 4, 5}, returns {3, 5, 7, 9}, not {3, 7, 5}
void adj_pair_sum(vector<int> const& v)
{
for (decltype(v.size()) i = 1; i < v.size(); ++i)
cout << v[i-1] + v[i] << " ";
cout << endl;
}
// Given {1, 2, 3, 4, 5}, returns {6, 6, 3}, not {6, 6, 6}
void sym_pair_sum(vector<int> const& v)
{
auto sz = v.size();
for (decltype(sz) i = 0; i != sz / 2; ++i)
cout << v[i] + v[sz-1-i] << " ";
if (sz % 2 == 1)
cout << v[sz / 2];
cout << endl;
}
int main()
{
vector<int> v;
for (int i; cin >> i; v.push_back(i), cout << i << " ")
;
cout << endl;
adj_pair_sum(v);
sym_pair_sum(v);
return 0;
} | 29.041667 | 247 | 0.617647 | [
"vector"
] |
e5fe54ee66f921725e998cd652acdd7577be263f | 2,624 | cpp | C++ | problemes/probleme2xx/probleme238.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | 6 | 2015-10-13T17:07:21.000Z | 2018-05-08T11:50:22.000Z | problemes/probleme2xx/probleme238.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | problemes/probleme2xx/probleme238.cpp | ZongoForSpeed/ProjectEuler | 2e2d45f984d48a1da8275886c976f909a0de94ce | [
"MIT"
] | null | null | null | #include "problemes.h"
#include "chiffres.h"
#include "utilitaires.h"
#include <fstream>
typedef unsigned long long nombre;
typedef std::vector<nombre> vecteur;
ENREGISTRER_PROBLEME(238, "Infinite string tour") {
// Create a sequence of numbers using the "Blum Blum Shub" pseudo-random number generator:
//
// s0 = 14025256
// sn+1 = sn² mod 20300713
//
// Concatenate these numbers s0s1s2… to create a string w of infinite length.
// Then, w = 14025256741014958470038053646…
//
// For a positive integer k, if no substring of w exists with a sum of digits equal to k, p(k) is defined to be
// zero. If at least one substring of w exists with a sum of digits equal to k, we define p(k) = z, where z is the
// starting position of the earliest such substring.
//
// For instance:
//
// The substrings 1, 14, 1402, …
// with respective sums of digits equal to 1, 5, 7, …
// start at position 1, hence p(1) = p(5) = p(7) = … = 1.
//
// The substrings 4, 402, 4025, …
// with respective sums of digits equal to 4, 6, 11, …
// start at position 2, hence p(4) = p(6) = p(11) = … = 2.
//
// The substrings 02, 0252, …
// with respective sums of digits equal to 2, 9, …
// start at position 3, hence p(2) = p(9) = … = 3.
//
// Note that substring 025 starting at position 3, has a sum of digits equal to 7, but there was an earlier
// substring (starting at position 1) with a sum of digits equal to 7, so p(7) = 1, not 3.
//
// We can verify that, for 0 < k ≤ 10^3, ∑ p(k) = 4742.
//
// Find ∑ p(k), for 0 < k ≤ 2·10^15.
const nombre s0 = 14'025'256;
const nombre modulo = 20'300'713;
const nombre limite = 2'000'000'000'000'000;
nombre sn = s0;
std::vector<unsigned short> w;
do {
auto chiffres = chiffres::extraire_chiffres(sn);
w.insert(w.end(), chiffres.begin(), chiffres.end());
sn = (sn * sn) % modulo;
} while (sn != s0);
const nombre somme = std::reduce(w.begin(), w.end(), 0ULL);
vecteur p(somme, 0);
nombre compteur = 0;
for (size_t i = 0; i < w.size() && compteur <= somme; ++i) {
for (size_t j = 0, as = w[i]; j < w.size() && compteur <= somme; as += w[(++j + i) % w.size()]) {
if (p[as] != 0)
continue;
p[as] = i + 1;
++compteur;
}
}
nombre resultat = limite / somme;
for (nombre x = 1; x < somme; ++x)
resultat += p[x] * (1 + ((limite - x) / somme));
return std::to_string(resultat);
}
| 34.986667 | 118 | 0.564787 | [
"vector"
] |
f90494556df098277e033995dd6b1635a5b52ad8 | 14,508 | cpp | C++ | src/parsing/lexer.cpp | bridgekat/apimu | 2e401a01e0aad859dc1dd975dae164f622c48696 | [
"CC0-1.0"
] | 5 | 2021-12-12T22:10:57.000Z | 2022-03-10T21:01:48.000Z | src/parsing/lexer.cpp | bridgekat/apimu | 2e401a01e0aad859dc1dd975dae164f622c48696 | [
"CC0-1.0"
] | null | null | null | src/parsing/lexer.cpp | bridgekat/apimu | 2e401a01e0aad859dc1dd975dae164f622c48696 | [
"CC0-1.0"
] | null | null | null | #include "lexer.hpp"
#include <unordered_map>
#include <algorithm>
namespace Parsing {
constexpr unsigned int CodeUnits = Lexer::CodeUnits;
size_t cutFirstCodePoint(const string& s, size_t pos) {
if (pos >= s.size()) return 0;
size_t i = 1;
for (; pos + i < s.size(); i++) {
char8_t c = s[pos + i];
if ((c & 0b11000000) != 0b10000000) break; // NOLINT(cppcoreguidelines-avoid-magic-numbers)
}
return i;
}
optional<Token> Lexer::nextToken() {
string skipped;
while (!eof()) {
auto opt = run();
if (opt) {
if (!skipped.empty()) errors.push_back(ErrorInfo{ pos - skipped.size(), pos, skipped });
auto [len, id] = opt.value();
Token res{ id, pos, pos + len, str.substr(pos, len) };
pos += len;
return res;
}
// Mid: !opt
size_t len = cutFirstCodePoint(str, pos);
skipped += str.substr(pos, len);
pos += len;
}
// Mid: eof()
if (!skipped.empty()) errors.push_back(ErrorInfo{ pos - skipped.size(), pos, skipped });
return nullopt;
}
// Directly run NFA
optional<pair<size_t, size_t>> NFALexer::run() const {
optional<pair<size_t, size_t>> res = nullopt;
vector<State> s;
vector<bool> v(table.size(), false);
// A helper function
// Pre: the indices where v[] is true must match the elements of s
auto closure = [this] (vector<bool>& v, vector<State>& s) {
// Expand to epsilon closure (using DFS)
vector<State> stk = s;
while (!stk.empty()) {
State x = stk.back(); stk.pop_back();
for (auto [cc, u]: table[x].tr) if (cc == 0 && !v[u]) {
s.push_back(u);
stk.push_back(u);
v[u] = true;
}
}
};
// Initial states
for (const auto& initial: patterns) {
s.push_back(initial);
v[initial] = true;
}
closure(v, s);
for (size_t i = 0; pos + i < str.size(); i++) {
char8_t c = str[pos + i];
// Reset v[] to all false
for (State x: s) v[x] = false;
// Move one step
vector<State> t;
for (State x: s) for (auto [cc, u]: table[x].tr) if (cc == c && !v[u]) {
t.push_back(u);
v[u] = true;
}
closure(v, t);
s.swap(t);
// Update result if reaches accepting state
// Patterns with larger IDs have higher priority
optional<size_t> curr = nullopt;
for (State x: s) if (table[x].ac) {
if (!curr || curr.value() < table[x].ac.value()) curr = table[x].ac;
}
// Update longest match, if applicable
if (curr) res = { i + 1, curr.value() };
// Exit if no more possible matches
if (s.empty()) break;
}
return res;
}
using std::unordered_map;
// Function object for the DFA construction from NFA
class PowersetConstruction {
public:
const NFALexer& nfa;
DFALexer& dfa;
vector<bool> v;
unordered_map<vector<bool>, DFALexer::State> mp;
PowersetConstruction(const NFALexer& nfa, DFALexer& dfa):
nfa(nfa), dfa(dfa), v(), mp() {}
void closure(vector<NFALexer::State>& s) {
// Expand `s` and `v` to epsilon closure (using DFS)
vector<NFALexer::State> stk = s;
while (!stk.empty()) {
NFALexer::State nx = stk.back(); stk.pop_back();
for (auto [cc, nu]: nfa.table[nx].tr) if (cc == 0 && !v[nu]) {
s.push_back(nu);
stk.push_back(nu);
v[nu] = true;
}
}
};
#define clearv(s_) \
for (NFALexer::State i: s_) v[i] = false;
#define node(x_, s_) \
x_ = mp[s_] = dfa.table.size(); \
dfa.table.emplace_back()
#define trans(s_, c_, t_) \
dfa.table[s_].has[c_] = true; \
dfa.table[s_].tr[c_] = t_
// Invariant: all elements of v[] are false
void dfs(DFALexer::State x, const vector<NFALexer::State>& s) {
// Check if `s` contains accepting states
optional<size_t> curr;
for (auto ns: s) {
auto opt = nfa.table[ns].ac;
if (opt && (!curr || curr.value() < opt.value())) curr = opt;
}
dfa.table[x].ac = curr;
// Compute transitions
// Invariant: all elements of v[] are false at the end of the loop
for (unsigned int c = 1; c < CodeUnits; c++) {
// Compute u
vector<NFALexer::State> t;
for (auto nx: s) for (auto [cc, nu]: nfa.table[nx].tr) {
if (cc == c && !v[nu]) {
t.push_back(nu);
v[nu] = true;
}
}
if (t.empty()) continue; // No need to clear v: t is empty
closure(t);
// Look at u:
auto it = mp.find(v);
if (it != mp.end()) {
// Already seen
trans(x, c, it->second);
clearv(t);
} else {
// Haven't seen before, create new DFA node and recurse
node(DFALexer::State u, v);
trans(x, c, u);
clearv(t);
dfs(u, t);
}
}
}
void operator() () {
vector<NFALexer::State> s;
v.clear(); v.resize(nfa.table.size());
mp.clear();
// Initial states
for (const auto& initial: nfa.patterns) {
s.push_back(initial);
v[initial] = true;
}
closure(s);
node(dfa.initial, v);
clearv(s);
dfs(dfa.initial, s);
}
#undef node
#undef trans
#undef clearv
};
DFALexer::DFALexer(const NFALexer& nfa): Lexer(), table(), initial(0) {
PowersetConstruction(nfa, *this)();
}
// Function object for the DFA state minimization
// See: https://en.wikipedia.org/wiki/DFA_minimization#Hopcroft's_algorithm
// See: https://en.wikipedia.org/wiki/Partition_refinement
// Pre: the pattern IDs in accepting states are small nonnegative integers.
// (They are directly used as initial partition IDs)
class PartitionRefinement {
public:
using State = DFALexer::State;
using Entry = DFALexer::Entry;
struct List { List *l, *r; State x; };
Core::Allocator<List> pool;
DFALexer& dfa;
struct Class { size_t size; List* head; bool isDist; };
struct Identity { size_t cl; List* ptr; };
// Ephemeral states
vector<vector<pair<char8_t, State>>> rev; // Reverse edges
vector<Class> cl; // Classes (size, pointer to head, is used as distinguisher set)
vector<Identity> id; // Identities (class index, pointer to list)
vector<size_t> dist; // Indices of classes used as distinguisher sets
array<vector<State>, CodeUnits> dom; // Character -> domain
vector<vector<State>> interStates; // Class index -> list of intersecting states
explicit PartitionRefinement(DFALexer& dfa):
pool(), dfa(dfa), rev(), cl(), id(), dist(), dom(), interStates() {}
// Add DFA node `x` to class `i`, overwriting `id[x]`
void add(State x, size_t i) {
cl[i].size++;
List* l = cl[i].head, * r = l->r;
List* curr = pool.pushBack(List{ l, r, x });
l->r = r->l = curr;
id[x] = { i, curr };
}
// Remove DFA node `x` from its class, as indicated in `id[x]`
void remove(State x) {
auto [i, curr] = id[x];
List* l = curr->l, * r = curr->r;
l->r = r; r->l = l;
cl[i].size--;
}
// Create new class and return its ID (always = partition.size() - 1, just for convenience)
size_t newClass() {
List* head = pool.pushBack(List{ nullptr, nullptr, 0 });
head->l = head->r = head;
size_t index = cl.size();
cl.push_back(Class{ 0, head, false });
return index;
}
void operator() () {
auto& table = dfa.table;
auto& initial = dfa.initial;
// Add the dead state
State dead = table.size();
table.emplace_back();
State n = table.size();
size_t numPatterns = 0;
for (State i = 0; i < n; i++) {
if (table[i].ac) numPatterns = std::max(numPatterns, table[i].ac.value() + 1);
// Other states now have transitions to the dead state
// The dead state has all its transitions pointing to itself
for (unsigned int c = 1; c < CodeUnits; c++) if (!table[i].has[c]) table[i].tr[c] = dead;
}
// `has[]` can be ignored below
// Process reverse edges (arcs)
rev.clear(); rev.resize(n);
for (State i = 0; i < n; i++) {
for (unsigned int c = 1; c < CodeUnits; c++) rev[table[i].tr[c]].emplace_back(static_cast<char8_t>(c), i);
}
// Initial partition (numPatterns + 1 classes)
cl.clear();
for (size_t i = 0; i <= numPatterns; i++) newClass();
id.clear(); id.resize(n);
for (State i = 0; i < n; i++) {
if (table[i].ac) add(i, table[i].ac.value());
else add(i, numPatterns);
}
// All classes except the last one (just not needed) are used as initial distinguisher sets
dist.clear();
for (size_t i = 0; i < numPatterns; i++) {
dist.push_back(i);
cl[i].isDist = true;
}
interStates.clear();
while (!dist.empty()) {
size_t curr = dist.back();
dist.pop_back();
cl[curr].isDist = false;
// Calculate the domain sets for all c's
for (unsigned int c = 1; c < CodeUnits; c++) dom[c].clear();
for (const List* p = cl[curr].head->r; p != cl[curr].head; p = p->r) {
// "Examine transitions" - this occurs a limited number of times, see below
// Note that the total size of dom[] is bounded by this
for (auto [c, s]: rev[p->x]) dom[c].push_back(s);
}
for (unsigned int c = 1; c < CodeUnits; c++) {
// Inner loop: time complexity should be O(size of dom[c])
// Mid: all entries of interStates[] are empty
interStates.resize(cl.size());
for (State x: dom[c]) interStates[id[x].cl].push_back(x);
for (State x: dom[c]) {
size_t i = id[x].cl;
// If intersection has been processed before...
if (i >= interStates.size() || interStates[i].empty()) continue;
// If difference is empty...
if (interStates[i].size() == cl[i].size) {
interStates[i].clear();
continue;
}
// Create a new class for the "intersection"
size_t interi = newClass();
// Add elements into it...
for (State y: interStates[i]) {
remove(y);
add(y, interi);
}
// The original class now becomes the "set difference"!
// Avoid processing multiple times, also does the clearing
interStates[i].clear();
// See which splits will be used as distinguisher sets
if (cl[i].isDist || cl[interi].size <= cl[i].size) {
dist.push_back(interi);
cl[interi].isDist = true;
} else { // Mid: !cl[i].isDist && cl[i].size < cl[interi].size
dist.push_back(i);
cl[i].isDist = true;
}
}
// Mid: all interStates[] are empty
}
}
// Rebuild `table` and `initial`
vector<Entry> newTable(cl.size());
State newInitial = id[initial].cl, newDead = id[dead].cl;
for (State i = 0; i < table.size(); i++) {
State srci = id[i].cl;
for (unsigned int c = 1; c < CodeUnits; c++) {
State dsti = id[table[i].tr[c]].cl;
if (dsti != newDead) {
newTable[srci].has[c] = true;
newTable[srci].tr[c] = dsti;
}
}
if (table[i].ac) newTable[srci].ac = table[i].ac;
}
table.swap(newTable);
initial = newInitial;
// Remove the dead state
for (State i = 0; i + 1 < table.size(); i++) {
if (i >= newDead) table[i] = table[i + 1];
for (unsigned int c = 1; c < CodeUnits; c++) {
if (table[i].has[c] && table[i].tr[c] > newDead) table[i].tr[c]--;
}
}
table.pop_back();
if (initial > newDead) initial--;
/*
* ===== A hand-wavey argument for correctness =====
* Different classes -> different behaviors: by induction.
* Different behaviors -> different classes:
* (Lemma: for any two disjoint classes, a "distinguisher of them" must have existed.)
* For any states s, t arriving at different accepting states after taking the path a:
* Let the intermediate states be i1 ... in and j1 ... jn.
* For any k, some "distinguisher of ik and jk" must have existed: by induction.
* Initial (k = n): in and jn are different non/accepting values so they are in different initial partitions...
* Step (k < k' - 1):
* By the time the "distinguisher of ik' and jk'" is current,
* either ik and jk in the same class (it then get splitted, one of the split becomes distinguisher),
* or they are in different classes (by Lemma).
* So i1 and j1 (s and t) must be in different classes
* (All distinguishers are classes; all classes are disjoint).
*
* ===== A hand-wavey argument for time complexity =====
* (Lemma: if a class is ever used ("currented") as a distinguisher,
* the only overlapping distinguishers ever "currented" must come from its splits;
* but each split that can possibly be used as a distinguisher must ≤ half of the original size.)
* Associate each "examination of transition" with the current distinguisher set.
* The destination state `dst` of the transition must be in the distinguisher set!
* This set then splits, any split "ever used as distinguisher" that contains `dst` must ≤ half of the original size.
* So each transition may only be examined O(log n) times...
* Overall: O(|Σ|n log n)
*/
// How could a human ever come up with such an algorithm... 这玩意是人能发明出来的吗
}
};
void DFALexer::optimize() {
PartitionRefinement(*this)();
}
// Run DFA
optional<pair<size_t, size_t>> DFALexer::run() const {
optional<pair<size_t, size_t>> res = nullopt;
State s = initial;
for (size_t i = 0; pos + i < str.size(); i++) {
char8_t c = str[pos + i];
if (!table[s].has[c]) break;
s = table[s].tr[c];
// Update result if reaches accepting state
auto curr = table[s].ac;
if (curr) res = { i + 1, curr.value() };
}
return res;
}
}
| 34.875 | 124 | 0.54756 | [
"object",
"vector"
] |
f916929a55de329bdaf00d13e07aad959d62e3b3 | 2,852 | hpp | C++ | diffsim_torch3d/arcsim/src/simulation.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/simulation.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | diffsim_torch3d/arcsim/src/simulation.hpp | priyasundaresan/kaolin | ddae34ba5f09bffc4368c29bc50491c5ece797d4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#ifndef SIMULATION_HPP
#define SIMULATION_HPP
#include "cloth.hpp"
#include "constraint.hpp"
#include "handle.hpp"
#include "morph.hpp"
#include "obstacle.hpp"
#include "spline.hpp"
#include "timer.hpp"
#include <string>
#include <vector>
using torch::Tensor;
struct Wind {
Tensor density;
Tensor velocity;
Tensor drag;
};
struct Simulation {
// variables
Tensor time;
int frame, step;
std::vector<Cloth> cloths;
// constants
int frame_steps;
Tensor frame_time, step_time;
Tensor end_time;
int end_frame;
std::vector<Motion> motions;
std::vector<Handle*> handles;
std::vector<Obstacle> obstacles;
std::vector<Morph> morphs;
Tensor gravity;
Wind wind;
Tensor friction, obs_friction;
enum {Proximity, Physics, StrainLimiting, Collision, Remeshing, Separation,
PopFilter, Plasticity, nModules};
bool enabled[nModules];
Timer timers[nModules];
// handy pointers
std::vector<Mesh*> cloth_meshes, obstacle_meshes;
};
void prepare (Simulation &sim);
void relax_initial_state (Simulation &sim);
void advance_frame (Simulation &sim);
void advance_step (Simulation &sim);
// Helper functions
template <typename Prim> int size (const std::vector<Mesh*> &meshes);
template <typename Prim> int get_index (const Prim *p,
const std::vector<Mesh*> &meshes);
template <typename Prim> Prim *get (int i, const std::vector<Mesh*> &meshes);
std::vector<Tensor> node_positions (const std::vector<Mesh*> &meshes);
#endif
| 31.688889 | 79 | 0.731066 | [
"mesh",
"vector"
] |
f919bbf8330ade6dd6b1505a9ede6bbfbf54d2c6 | 3,933 | cpp | C++ | BlockGen/Factory.mako.cpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 2 | 2021-01-19T02:21:48.000Z | 2022-03-26T23:05:49.000Z | BlockGen/Factory.mako.cpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 3 | 2020-07-26T18:48:21.000Z | 2020-10-28T00:45:42.000Z | BlockGen/Factory.mako.cpp | pothosware/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T06:22:20.000Z | 2022-03-24T06:22:20.000Z | #include "OneToOneBlock.hpp"
#include "NToOneBlock.hpp"
#include "TwoToOneBlock.hpp"
#include "Utility.hpp"
#include <Pothos/Callable.hpp>
#include <Pothos/Framework.hpp>
#include <Pothos/Plugin.hpp>
#include <Pothos/Proxy.hpp>
#include <arrayfire.h>
#include <vector>
static const std::vector<Pothos::BlockRegistry> BlockRegistries =
{
%for block in oneToOneBlocks:
Pothos::BlockRegistry(
"/gpu/${block["header"]}/${block["blockName"]}",
%if block.get("pattern", "") == "FloatToComplex":
Pothos::Callable(&OneToOneBlock::makeFloatToComplex)
.bind<OneToOneFunc>(&af::${block["func"]}, 1)
%elif block.get("pattern", "") == "ComplexToFloat":
Pothos::Callable(&OneToOneBlock::makeComplexToFloat)
.bind<OneToOneFunc>(&af::${block["func"]}, 1)
%else:
Pothos::Callable(&OneToOneBlock::makeFromOneType)
.bind<OneToOneFunc>(&af::${block["func"]}, 1)
.bind<DTypeSupport>({
${"true" if block["supportedTypes"].get("supportInt", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportUInt", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportFloat", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportComplexFloat", block["supportedTypes"].get("supportAll", False)) else "false"},
}, 3)
%endif
),
%endfor
%for block in twoToOneBlocks:
Pothos::BlockRegistry(
"/gpu/${block["header"]}/${block["blockName"]}",
%if block.get("pattern", "") == "FloatToComplex":
Pothos::Callable(&TwoToOneBlock::makeFloatToComplex)
.bind<TwoToOneFunc>(&af::${block["func"]}, 1)
.bind<bool>(${"true" if block.get("allowZeroInBuffer1", True) else "false"}, 3)
%else:
Pothos::Callable(&TwoToOneBlock::makeFromOneType)
.bind<TwoToOneFunc>(&af::${block["blockName"]}, 1)
.bind<DTypeSupport>({
${"true" if block["supportedTypes"].get("supportInt", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportUInt", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportFloat", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportComplexFloat", block["supportedTypes"].get("supportAll", False)) else "false"},
}, 3)
.bind<bool>(${"true" if block.get("allowZeroInBuffer1", True) else "false"}, 4)
%endif
),
%endfor
%for block in NToOneBlocks:
Pothos::BlockRegistry(
"/gpu/${block["header"]}/${block["blockName"]}",
Pothos::Callable(&NToOneBlock::make)
%if "operator" in block:
.bind<NToOneFunc>(AF_ARRAY_OP_N_TO_ONE_FUNC(${block["operator"]}), 1)
%else:
.bind<NToOneFunc>(&af::${block["func"]}, 1)
%endif
.bind<DTypeSupport>({
${"true" if block["supportedTypes"].get("supportInt", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportUInt", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportFloat", block["supportedTypes"].get("supportAll", False)) else "false"},
${"true" if block["supportedTypes"].get("supportComplexFloat", block["supportedTypes"].get("supportAll", False)) else "false"},
}, 4)
.bind<bool>(${"true" if block.get("postBuffer", True) else "false"}, 5)
),
%endfor
};
pothos_static_block(register_pothos_gpu_docs)
{
%for doc in docs:
${doc}
%endfor
}
| 46.821429 | 143 | 0.613527 | [
"vector"
] |
f91cc263fe90cf38b9530f3bb07afbbddecade3e | 11,413 | cpp | C++ | sharvilZipf.cpp | Sharvilpr23/csc315Project2 | fbbd0de02f04925ad96e019c91987a1b7ace55d3 | [
"MIT"
] | null | null | null | sharvilZipf.cpp | Sharvilpr23/csc315Project2 | fbbd0de02f04925ad96e019c91987a1b7ace55d3 | [
"MIT"
] | null | null | null | sharvilZipf.cpp | Sharvilpr23/csc315Project2 | fbbd0de02f04925ad96e019c91987a1b7ace55d3 | [
"MIT"
] | null | null | null | /**************************************************************************//**
* @file
*
* @brief contains all of Sharvil's functions for project 2
******************************************************************************/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include "hash.h"
using namespace std;
string wordFilter(char *);
string charToString(char *);
void convertToLower(string &);
char *getCsvFilename(char *);
void rehash(HashTable &);
int digits(int n);
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* This function opens the input file. It checks that the number of command
* line arguments are 2. If the file fails to open, the function returns false,
* else true.
*
* @param[in, out] fin - an ifstream to open thr input file
* @param[in, out] filename - contains the name of the input file
*
* @returns true - File opened successfully
* @returns false - Files failed to open
*****************************************************************************/
bool openInputFile(ifstream &fin, char *filename)
{
fin.open(filename, ios::in);
if(!fin.is_open())
{
cout << "Failed to open input file" << endl;
return false;
}
return true;
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* This function opens a comma separated file. The function creates the .csv
* extension by manipulating the input file name.
*
* @param[in, out] filename - contains the name of the input file
* @param[in, out] csv_out - an ofstream to open the csv file
*
* @returns true - File opened successfully
* @returns false - Files failed to open
*****************************************************************************/
bool openCsvFile(char *filename, ofstream &csv_out)
{
char temp[100] = {};
int length = strlen(filename);
strncpy(temp, filename, length - 3);
strncat(temp, "csv", 3);
csv_out.open(temp, ios::out|ios::trunc);
if(!csv_out.is_open())
{
cout << "Failed to open .csv output file" << endl;
return false;
}
return true;
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* This function opeens a word file. The function creates the .wrd extension
* by manipulating the input file name.
*
* @param[in, out] filename - contains the name of the input file
* @param[in, out] wrd_out - an ofstream to open the wrd file
*
* @returns true - File opened successfully
* @returns false - Files failed to open
*****************************************************************************/
bool openWrdFile(char *filename, ofstream &wrd_out)
{
char temp[100] = {};
int length = strlen(filename);
strncpy(temp, filename, length - 3);
strncat(temp, "wrd", 3);
wrd_out.open(temp, ios::out | ios::trunc);
if(!wrd_out.is_open())
{
cout << "Failed to open .wrd output file" << endl;
return false;
}
return true;
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* This function opeens a word file. The function creates the .wrd extension
* by manipulating the input file name.
*
* @param[in, out] fin - an ifstream object that is used to open the input file
* @param[in, out] H - the hash table
*
* @returns none
*****************************************************************************/
void readData(ifstream &fin, HashTable &H)
{
string input;
const char *delimiters = "\"\\/, .{}[]();:|-_!@#%^&*$?<>+=~1234567890";
char *ptr;
//While there is data to read
while(fin >> input)
{
convertToLower(input); //convert the string to lower case
//Tokenize the input string by converting the string to char * and then
//getting the first word
ptr = strtok(const_cast<char *>(input.c_str()), delimiters);
while(ptr != NULL)
{
if(H.getLoadFactor() >= 0.75)
{
cout << "WARNING: Hash table (size " << H.getCapacity() <<
") is 75% full!" << endl;
H.sortTable();
rehash(H);
cout << "Rehashing to size " << H.getCapacity() << " ... "
<< "finished" << endl;
}
//Filter the word off whitespaces and ' at the front and end of the word
string key = wordFilter(ptr);
//If the word is non empty
if(key != "")
{
//Insert the key into the hash table
H.insertKey(key);
//Increment the total words by 1
H.incrementTotalWords();
}
ptr = strtok(NULL, delimiters); //get the next word
}
}
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* Rehash the data from the hash table of orginal size to one with more than
* double the size. The function stores all the non empty words and their
* frequencies into two temporary vectors. It then cleans teh hash table and
* resizes it to the new size. It then re-inserts all the words and their
* frequencies from the temporary vectors back into the hash table. It then
* clears the temporary vectors.
*
* @param[in, out] H - the hash table
*
* @returns none
*****************************************************************************/
void rehash(HashTable &H)
{
int i = 0;
//Temporary vectors to store words and frequencies
vector<string> temp_words;
vector<int> temp_freq;
//store the words and their frequencies
while(H.getFrequency(i) > 0)
{
temp_words.push_back(H.getWord(i));
temp_freq.push_back(H.getFrequency(i));
i++;
}
static int n = 0;
//Array with some prime values
int primes[10] = {2003, 4007, 8017, 16057, 32117, 64237, 128477, 256957,
513917, 1027841};
H.cleanandresize(primes[n]);
H.setCapacity(primes[n]); //Sets teh capacity to the new capacity
n++;
//Rehash the words back into the hash table
for(unsigned int i = 0; i < temp_words.size(); i++)
{
H.rehashInsertKey(temp_words[i], temp_freq[i]);
}
//Clean the temporary vectors
temp_words.clear();
temp_freq.clear();
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* Filters the word fromm whitespaces and ' chaarecters that are present at the
* beginning and the end of the word
*
* @param[in, out] ptr - the word
*
* @returns temp - filtered word
*****************************************************************************/
string wordFilter(char *ptr)
{
string temp = charToString(ptr); //Convert the word to string
//Remove ' charecters from the ends
while(temp.length() > 0 && (temp[0] == ' ' || temp[0] == '\''))
temp = temp.substr(1, temp.length() - 1);
//Remove white spaces from the ends
while(temp.length() > 0 && (temp[temp.length() - 1] == ' ' ||
temp[temp.length() - 1] == '\''))
temp = temp.substr(0, temp.length() - 1);
return temp;
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* Filters the word fromm whitespaces and ' chaarecters that are present at the
* beginning and the end of the word
*
* @param[in] input - the word
*
* @returns none
*****************************************************************************/
void convertToLower(string &input)
{
//Convert each charecter to lowercase
for(string::iterator it = input.begin(); it != input.end(); it++)
*it = tolower(*it);
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* Print the filename, total number of words and the number of distinct words.
* After this, print the rank, frequency and the rank x frequency values in the
* respective columns for each non empty word in the table
*
* @param[in] filename - name of the input file
* @param[in, out] csv_out - ofstream to print the data to a csv file
* @param[in, out] H - the hashtable
*
* @returns none
*****************************************************************************/
void writeToCsv(char *filename, ofstream &csv_out, HashTable &H)
{
int i = 0;
double rank = 0;
int num = 0;
csv_out << endl;
csv_out << "Zipf's Law" << endl;
csv_out << "----------" << endl;
csv_out << "File: " << filename << endl;
csv_out << "Total number of words = " << H.getTotalWords() << endl;
csv_out << "Number of distinct words = " << H.getCurrentSize() << endl;
csv_out << endl;
csv_out << " rank freq rank*freq" << endl;
csv_out << " ---- ---- ---------" << endl;
while(i < H.getCurrentSize())
{
rank = i + 1;
//While the words have the same frequency
while(H.getFrequency(i) == H.getFrequency(i + 1))
{
num++;
i++;
}
//Calculate the rank
if(num > 0)
rank = (rank + (rank + num)) / 2.0;
csv_out << fixed << showpoint << setprecision(1);
csv_out << rank << "," << H.getFrequency(i) << "," << double(rank * H.getFrequency(i)) << "\n";
num = 0;
i++;
}
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* Print the filename, total number of words and the number of distinct words.
* After this, print the words and their ranks and average rank with proper
* formatting
*
* @param[in, out] filename - name of the input file
* @param[in, out] wrd_out - ofstream to print the data to a wrd file
* @param[in, out] H - the hashtable
*
* @returns none
*****************************************************************************/
void writeToWrd(char *filename, ofstream &wrd_out, HashTable &H)
{
int i = 0;
wrd_out << endl;
wrd_out << "Zipf's Law" << endl;
wrd_out << "----------" << endl;
wrd_out << "File: " << filename << endl;
wrd_out << "Total number of words: " << H.getTotalWords() << endl;
wrd_out << "Number of distinct words: " << H.getCurrentSize() << endl;
wrd_out << endl;
wrd_out << "Word Frequencies" << setw(45) << "Ranks" << setw(13)
<< "Avg Rank" << endl;
wrd_out << "----------------" << setw(45) << "-----" << setw(13)
<< "--------" << endl;
while(i < H.getCurrentSize())
{
int j = 0;
int freq = H.getFrequency(i);
int num = digits(freq); //Calculate the number of digits
wrd_out << left << setw(15) << "Words occurring " << left <<
setw(num) << freq << left << setw(30 - num) << " times:" << setw(15)
<< right << i+1 << right << setw(13) << i + 1 << endl;
wrd_out << left << setw(15) << H.getWord(i);
i++;
while(i < H.getCurrentSize() && freq == H.getFrequency(i))
{
wrd_out << " " << left << setw(15) << H.getWord(i);
if(j % 2 == 0)
{
wrd_out << endl;
}
i++;
j++;
}
wrd_out << endl;
j = 0;
}
}
/** ***************************************************************************
* @author Sharvil Pai Raiker
*
* @par Description:
* Calculates the number of digits in the number
*
* @param[in] n - the number
*
* @returns i - number of digits
*****************************************************************************/
int digits(int n)
{
int i = 0;
while(n != 0)
{
n /= 10;
i++;
}
return i;
}
| 29.490956 | 98 | 0.531061 | [
"object",
"vector"
] |
f9261ecff91c0eaa01a5fad38e32167a8cc786c8 | 1,620 | cpp | C++ | Advanced C++ Course/Benjamin Rutan HW 3 Submission/3.1/3.1.1/3.1.1/Main.cpp | BRutan/Cpp | 8acbc6c341f49d6d83168ccd5ba49bd6824214f9 | [
"MIT"
] | null | null | null | Advanced C++ Course/Benjamin Rutan HW 3 Submission/3.1/3.1.1/3.1.1/Main.cpp | BRutan/Cpp | 8acbc6c341f49d6d83168ccd5ba49bd6824214f9 | [
"MIT"
] | null | null | null | Advanced C++ Course/Benjamin Rutan HW 3 Submission/3.1/3.1.1/3.1.1/Main.cpp | BRutan/Cpp | 8acbc6c341f49d6d83168ccd5ba49bd6824214f9 | [
"MIT"
] | null | null | null | /* Main.cpp (exercise 3.1.1)
Description:
* Solutions to exercise 3.1.1.
*/
#include <chrono>
#include <ctime>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include "Functions.hpp"
int main()
{
std::chrono::time_point <std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
/* 3.1.1 */
// b) Create thread for each callable object, with one being detached.
int totalCalls = 10;
std::thread funcObjThd(FObj(), "Function Object.", totalCalls);
std::thread freeFuncThd(freeFunc, "Free Function.", totalCalls);
std::thread lambdaThd([](const std::string &s, int count) { Iprint(s, count); }, "Free Lambda.", totalCalls);
std::thread boundMemberThd(boundMemberFunc, "Bound Member Function.", totalCalls);
std::thread storedLambdaThd(storedLambda, "Stored Lambda.", totalCalls);
storedLambdaThd.detach();
// c-d) Introduce code to check threads have completed:
try
{
if (funcObjThd.joinable())
funcObjThd.join();
if (freeFuncThd.joinable())
freeFuncThd.join();
if (lambdaThd.joinable())
lambdaThd.join();
if (boundMemberThd.joinable())
boundMemberThd.join();
if (storedLambdaThd.joinable())
storedLambdaThd.join();
}
catch (...)
{
funcObjThd.join();
freeFuncThd.join();
lambdaThd.join();
boundMemberThd.join();
storedLambdaThd.join();
}
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Elapsed time: " << elapsed_seconds.count() << "s\n";
system("pause");
return 0;
}
| 27 | 110 | 0.690741 | [
"object",
"vector"
] |
234fc91b06330e5db1a77e9e172e4a465ea7493a | 8,028 | cpp | C++ | src/test/check_assert.cpp | blakelapierre/bitcoin-cash-node | a61fc457449817bef5e280ba25bd9bcb6c921421 | [
"MIT"
] | null | null | null | src/test/check_assert.cpp | blakelapierre/bitcoin-cash-node | a61fc457449817bef5e280ba25bd9bcb6c921421 | [
"MIT"
] | null | null | null | src/test/check_assert.cpp | blakelapierre/bitcoin-cash-node | a61fc457449817bef5e280ba25bd9bcb6c921421 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/check_assert.h>
#include <tinyformat.h> // for strprintf()
#include <util/defer.h> // for Defer
#include <boost/cstdlib.hpp> // for boost::exit_test_failure
#include <algorithm>
#include <array>
#include <atomic>
#include <cassert>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
// If compiling with address or thread sanitizers, this facility doesn't work quite right due to code that ASAN/TSAN
// inserts, which interferes with our ability to trap the assert firing in the subprocess.
#if defined(__has_feature)
# if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer)
# define SKIP_SANITIZER_NOT_SUPPORTED
# endif
#endif
#if !defined(SKIP_SANITIZER_NOT_SUPPORTED) && \
__has_include(<unistd.h>) && __has_include(<poll.h>) && __has_include(<sys/types.h>) && __has_include(<sys/wait.h>)
#define IS_SUPPORTED
#include <poll.h> // for poll()
#include <sys/types.h> // for pid_t, etc
#include <sys/wait.h> // for waitpid()
#include <unistd.h> // for fork(), pipe(), dup2(), etc
#endif
CheckAssertResult CheckAssert(std::function<void()> func, std::string_view expectMessage) {
#ifdef IS_SUPPORTED
constexpr int exit_status_cannot_dup2 = 120, exit_status_aborted = boost::exit_test_failure;
static_assert(exit_status_cannot_dup2 != exit_status_aborted);
std::array<int, 2> pipe_stdout{{-1, -1}}, pipe_stderr{{-1, -1}};
Defer pipeCloser([&pipe_stdout, &pipe_stderr]{
// close all fds on scope end to not leak fds in case we throw, etc
for (auto & fds : {&pipe_stdout, &pipe_stderr}) {
for (int & fd : *fds) {
if (fd > -1) {
::close(fd);
fd = -1;
}
}
}
});
auto ChkRet = [](std::string_view call, int ret) {
if (ret != 0) {
throw std::runtime_error(strprintf("Error from `%s`: %s", std::string{call}, std::strerror(errno)));
}
};
// create 2 pipes (to replace stdout and stderr)
ChkRet("pipe", ::pipe(pipe_stdout.data()));
ChkRet("pipe", ::pipe(pipe_stderr.data()));
// fork and run the lambda in the child, checking if it assert()'ed (SIGABRT)
// we also capture stdout and stderr from the child via the pipe created above.
if (auto pid = ::fork(); pid == -1) {
// fork failed
ChkRet("fork", pid);
} else if (pid == 0) {
// child
const int fd_stdout = fileno(stdout); // should be 1
const int fd_stderr = fileno(stderr); // should be 2
if (fd_stdout < 0 || fd_stderr < 0
// make our pipe_stdout writing end be the new stdout
|| ::dup2(pipe_stdout[1], fd_stdout) != fd_stdout
// make our pipe_stderr writing end be the new stderr
|| ::dup2(pipe_stderr[1], fd_stderr) != fd_stderr) {
std::_Exit(exit_status_cannot_dup2);
}
::close(pipe_stdout[0]); ::close(pipe_stderr[0]); // close reading end in subprocess
pipe_stderr[0] = pipe_stderr[0] = -1;
try {
// lastly, call the function
func();
} catch (...) {}
// this should not be reached if the above resulted in an assert()
std::_Exit(0);
} else {
// parent
Defer pidKiller([&pid]{
// kill & reap child process if it hasn't already been reaped
if (pid > 0) {
::kill(pid, SIGKILL);
int status;
pid = ::waitpid(pid, &status, 0) == pid ? -1 : pid;
}
});
::close(pipe_stdout[1]); ::close(pipe_stderr[1]); // close writing end in parent process
pipe_stderr[1] = pipe_stderr[1] = -1;
std::string pipeData;
int hadError = 0, status = 0;
{
// set up subordinate thread to read pipe (stdout and stderr from child are combined into pipeData buffer)
std::atomic_bool stopFlag = false;
std::thread pipeReaderThr([&]{
std::vector<pollfd> fds;
for (int fd : {pipe_stdout[0], pipe_stderr[0]}) {
auto &p = fds.emplace_back();
p.fd = fd;
p.events = POLLIN;
}
while (!stopFlag) {
if (fds.empty()) return; // all file descriptors are closed, just return early
for (auto &p : fds) p.revents = 0; // reset pollfd state
const int r = ::poll(fds.data(), fds.size(), 10 /* msec */);
if (r > 0) {
auto do_read = [&pipeData](const pollfd &pfd) { // returns true if fd closed
if (!(pfd.revents & POLLIN)) return false;
std::array<char, 256> buf;
if (const auto nread = ::read(pfd.fd, buf.data(), buf.size()); nread > 0) {
pipeData.append(buf.data(), nread);
} else if (nread == 0 || (nread < 0 && errno != EAGAIN && errno != EINTR)) {
// file closed (all done) or error
return true;
}
return false;
};
// some fds are ready, read from pipe(s) that are ready
// if do_read() returns false, erase the element from the vector
fds.erase(std::remove_if(fds.begin(), fds.end(), do_read), fds.end());
} else if (r < 0) {
// some error
if (errno == EAGAIN || errno == EINTR) {
// try again
continue;
}
hadError = errno;
return;
}
}
});
Defer threadJoiner([&] {
stopFlag = true;
if (pipeReaderThr.joinable()) pipeReaderThr.join();
}); // just in case the below throws
const int ret = ::waitpid(pid, &status, 0);
ChkRet("waitpid", ret == pid ? 0 : -1);
pid = -1; // indicate pid is gone so that pidKiller above is a no-op
using namespace std::chrono_literals;
std::this_thread::sleep_for(10ms); // wait to read data
}
// at this point the pipe reader thread is stopped
if (hadError != 0) {
throw std::runtime_error(strprintf("Failed to read from pipe to subordinate process: %s",
std::strerror(hadError)));
}
if (WIFEXITED(status) && WEXITSTATUS(status) == exit_status_cannot_dup2) {
// special case, subordinate process cannot dup2()
throw std::runtime_error("Low-level error: failed to dup2() stdout/stderr");
}
// we expect the subordinate process to have exited with a SIGABRT
// however, if the boost execution monitor is running, no SIGABRT
// will have been sent for an assert() failure, instead the
// exit status will be 201.
if ((WIFSIGNALED(status) && WTERMSIG(status) == SIGABRT)
|| (WIFEXITED(status) && WEXITSTATUS(status) == exit_status_aborted)) {
if (expectMessage.empty() || pipeData.find(expectMessage) != pipeData.npos) {
return CheckAssertResult::AssertEncountered;
}
return CheckAssertResult::AssertEncounteredWrongMessage;
}
return CheckAssertResult::NoAssertEncountered;
}
#endif
return CheckAssertResult::Unsupported;
}
| 42.47619 | 119 | 0.54285 | [
"vector"
] |
23515e93cb678888e6c5f11aac610749201c71eb | 4,020 | cpp | C++ | 1169. Invalid Transactions.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | 1 | 2020-10-11T08:10:53.000Z | 2020-10-11T08:10:53.000Z | 1169. Invalid Transactions.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | null | null | null | 1169. Invalid Transactions.cpp | yuyangh/LeetCode | 5d81cbd975c0c1f2bbca0cb25cefe361a169e460 | [
"MIT"
] | null | null | null | //
// Created by Yuyang Huang on 10/23/21.
//
/*
* 1169. Invalid Transactions
* Medium
*
* A transaction is possibly invalid if:
* the amount exceeds $1000, or;
* if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.
* You are given an array of strings transaction where transactions[i]
* consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.
* Return a list of transactions that are possibly invalid. You may return the answer in any order.
*
* Example 1:
* Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
* Output: ["alice,20,800,mtv","alice,50,100,beijing"]
* Explanation: The first transaction is invalid
* because the second transaction occurs within a difference of 60 minutes,
* have the same name and is in a different city. Similarly the second one is invalid too.
*
* Example 2:
* Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
* Output: ["alice,50,1200,mtv"]
*
* Example 3:
* Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
* Output: ["bob,50,1200,mtv"
*
* Constraints:
* transactions.length <= 1000
* Each transactions[i] takes the form "{name},{time},{amount},{city}"
* Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.
* Each {time} consist of digits, and represent an integer between 0 and 1000.
* Each {amount} consist of digits, and represent an integer between 0 and 2000.
* */
#include "LeetCodeLib.h"
class Solution {
public:
/*
* Time complexity: O(n*n)
*/
vector<string> invalidTransactions(vector<string> &transactions) {
unordered_map<string, vector<Transaction>> data;
vector<string> result;
// parse each transaction
for (auto &transaction: transactions) {
stringstream ss(transaction);
string buffer;
vector<string> arr;
while (getline(ss, buffer, ',')) {
arr.push_back(buffer);
}
Transaction t(arr[0], stoi(arr[1]), stoi(arr[2]), arr[3], transaction);
data[t.name].emplace_back(t);
}
for (auto &person: data) {
unordered_set<int> invalidTransactionIdx;
auto &personTransactions = person.second;
// sort by time
sort(personTransactions.begin(), personTransactions.end());
for (int idx = 0; idx < personTransactions.size(); idx++) {
auto &transaction = personTransactions[idx];
if (transaction.amount > 1000) {
invalidTransactionIdx.emplace(idx);
}
// go through previous Transactions to find invalid pairs
for(int prevIdx=0;prevIdx<idx;prevIdx++){
auto &prevTransaction = personTransactions[prevIdx];
if (transaction.time - prevTransaction.time <= 60 &&
transaction.loc != prevTransaction.loc) {
invalidTransactionIdx.emplace(prevIdx);
invalidTransactionIdx.emplace(idx);
}
}
}
for (auto &idx: invalidTransactionIdx) {
result.emplace_back(personTransactions[idx].content);
}
}
return result;
}
private:
struct Transaction {
string name;
int time;
int amount;
string loc;
string content;
Transaction(string &name, int time, int amount, string &loc, string &verbo) : name(name), time(time),
amount(amount),
loc(loc), content(verbo) {};
Transaction() = default;
friend bool operator<(const Transaction &lhs, const Transaction &rhs) {
return lhs.time < rhs.time;
};
};
};
int main() {
Solution solution;
vector<string> transactions;
transactions = {"alice,20,800,mtv", "alice,50,100,beijing"};
PrintVector(solution.invalidTransactions(transactions));
transactions = {"alice,20,800,mtv", "alice,50,1200,mtv"};
PrintVector(solution.invalidTransactions(transactions));
transactions = {"alice,20,800,mtv", "bob,50,1200,mtv"};
PrintVector(solution.invalidTransactions(transactions));
} | 32.16 | 116 | 0.666418 | [
"vector"
] |
2355bf513099c8340886e4aaa929629ba868fb46 | 7,481 | cpp | C++ | src/Ctilemgr.cpp | DWCarrot/CppTileMgr | d7552f3b4d96cc685f9b10bcd4ec43d101b50da4 | [
"MIT"
] | null | null | null | src/Ctilemgr.cpp | DWCarrot/CppTileMgr | d7552f3b4d96cc685f9b10bcd4ec43d101b50da4 | [
"MIT"
] | null | null | null | src/Ctilemgr.cpp | DWCarrot/CppTileMgr | d7552f3b4d96cc685f9b10bcd4ec43d101b50da4 | [
"MIT"
] | null | null | null | // Ctilemgr.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include <string>
#include <string.h>
#include <exception>
#include "implement.h"
/*
RGBATuple c = { 0,0,0,0 };
uint8_t *cl = (uint8_t*)&c;
#define B1
bool setColor(uint8_t* pixel, int bw, int i, int j, void *args)
{
return memcpy(pixel, args, bw);
}
size_t func_ex(std::string & s)
{
if (s.length() < 3)
throw std::invalid_argument("length < 3");
return s.find('.');
}
void test1()
{
std::string s;
STBImage t, m;
Timer timer = Timer();
std::function<bool(uint8_t *pixel, int ch, int x, int y)> f = [](uint8_t* pixel, int bw, int i, int j) -> bool {return memcpy(pixel, cl, bw); };
#ifdef B1
std::cout << "iter,pointer\n\r";
t.allocate(256, 256, 4);
for (int i = 0; i < 100; ++i)
{
timer.start();
c = { 192, 168,137,255 };
t.iterate(0, 0, 128, 192, setColor, cl);
c = { 180, 243, 98, 65 };
t.iterate(82, 93, 240, 100, setColor, cl);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
}
t.save("t.png");
std::cout << "\n\r..end" << std::endl;
std::cout << "iter,std::function\n\r";
t.allocate(256, 256, 4);
for (int i = 0; i < 100; ++i)
{
timer.start();
c = { 192, 168,137,255 };
t.iterate(0, 0, 128, 192, f);
c = { 180, 243, 98, 65 };
t.iterate(82, 93, 240, 100, f);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
}
t.save("t.png");
std::cout << "\n\r..end" << std::endl;
std::cout << "inline\n\r";
t.allocate(256, 256, 4);
for (int i = 0; i < 100; ++i)
{
timer.start();
c = { 192, 168,137,255 };
t.set(c, 0, 0, 128, 192);
c = { 180, 243, 98, 65 };
t.set(c, 82, 93, 240, 100);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
}
t.save("t.png");
std::cout << "\n\r..end" << std::endl;
#endif // B1
std::cout << "iterator (" << sizeof(unsafe_iterator) << ")\n\r";
t.allocate(256, 256, 4);
#ifdef B1
for (int i = 0; i < 100; ++i)
{
#endif // B1
unsafe_iterator it;
timer.start();
c = { 192, 168,137,255 };
STBImage::unsafe_c_iterator_build(it, t, 0, 0, 128 - 0, 192 - 0);
while (STBImage::unsafe_c_iterator_next(it))
memcpy(it.next, &c, it.ch);
c = { 180, 243, 98, 65 };
STBImage::unsafe_c_iterator_build(it, t, 82, 93, 240 - 82, 100 - 93);
while (STBImage::unsafe_c_iterator_next(it))
memcpy(it.next, &c, it.ch);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
#ifdef B1
}
#endif // B1
int ap[] = { STBImage::ImageFmt::PNG, 2 };
t.save("t2.png", sizeof(ap) / sizeof(*ap), ap);
std::cout << "\n\r..end" << std::endl;
std::cout << "m: ";
m.allocate(256, 256, 3);
timer.start();
c = { 137, 165, 254, 255 };
m.set(c, 64, 64, 180, 130);
c = { 0,0,0,0 };
m.set(c, 80, 90, 110, 120);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
std::cout << std::endl;
t.save("t.png");
m.save("m.png");
STBImage c;
size_t a;
std::cout << "updateTile c1: ";
c = m.appendAlpha({0,0,0});
timer.start();
STBImage::cover_rgba(c, 0, 0, m, 0, 0, t, 0, 0, c.getW(), c.getH(), { 0,0,0 }, a);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
std::cout << std::endl;
c = c.removeAlpha({0,0,0}).scale(c.getW() / 2, c.getH() / 2, STBImage::ScaleOpts::FILTER_DEFAULT, STBImage::ScaleOpts::EDGE_CLAMP, STBImage::ResizeFlag_ALPHA_PREMULTIPLIED);
printf("===size: %d, %d, (%d)\n\r", c.getW(), c.getH(), c.getC());
c.save("c1.png");
std::cout << "updateTile c2: ";
c.allocate(256, 256, 3);
c = c.appendAlpha({ 0,0,0 });
timer.start();
STBImage::cover_rgba(c, 0, 0, t, 0, 0, m, 0, 0, c.getW(), c.getH(), { 0,0,0 }, a);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
std::cout << std::endl;
timer.start();
c = c.scale(c.getW() / 2, c.getH() / 2, STBImage::ScaleOpts::FILTER_DEFAULT, STBImage::ScaleOpts::EDGE_CLAMP, STBImage::ResizeFlag_ALPHA_PREMULTIPLIED);
timer.stop();
printf(" %6d", (int)(timer.get() * 1000 * 1000));
std::cout << std::endl;
printf("===size: %d, %d, (%d)\n\r", c.getW(), c.getH(), c.getC());
c.save("c2.png");
std::cout << std::endl;
}
#include<queue>
void test2()
{
std::string s;
std::queue<STBImage> q;
while (true)
{
std::cout << "File: ";
std::getline(std::cin, s);
if (s.empty())
break;
auto t = STBImage();
t.load(s);
q.push(t);
int len = q.size();
std::cout << "now: " << len << std::endl;
if (len >= 4)
{
if (t.allocate(1024, 1024, 4))
{
for(int ct = 0; !q.empty(); ++ct)
{
auto f = q.front();
q.pop();
if (f.getC() != 4)
f = f.appendAlpha({ 0,0,0 });
t.set(f, 0, 0, 512, 512, 512 * (ct & 0x1), 256 * (ct & 0x2));
}
t = t.scale(512, 512, STBImage::ScaleOpts::FILTER_DEFAULT, STBImage::ScaleOpts::EDGE_CLAMP, STBImage::ResizeFlag_ALPHA_PREMULTIPLIED);
t.save("h1.png");
t = t.removeAlpha({ 0,0,0 });
t.save("h2.png");
}
}
}
}
void test3()
{
Timer timer;
timer.start();
TileManager mgr(0, 5, 512, 512);
for (int y = -10; y < 10; ++y)
{
for (int x = -10; x < 10; ++x)
{
mgr.add(TileId(5, x, y));
}
}
timer.stop();
printf(" %6d\n", (int)(timer.get() * 1000 * 1000));
TileId p(0, 0, 0);
std::function<int(const TileId&, const std::set<TileId>&)> cb = [](TileId i, const std::set<TileId>& list)->int {return 1; printf("tile (%d,(%d,%d)) \n", i.z, i.x, i.y);};
for (auto i : mgr.getList())
{
if (i.z > mgr.zmin())
break;
timer.start();
mgr.route(i, cb);
timer.stop();
printf("(%d,(%d,%d))", i.z, i.x, i.y);
printf(" %6d\n", (int)(timer.get() * 1000 * 1000));
}
for (auto i : mgr.getList())
{
if (i.z > mgr.zmin())
break;
timer.start();
mgr.update(i);
timer.stop();
printf("(%d,(%d,%d))", i.z, i.x, i.y);
printf(" %6d\n", (int)(timer.get() * 1000 * 1000));
}
}
void test4()
{
std::cout << Miscellaneous::getCurrentDir() << std::endl;
std::vector<std::string> list = { "test/py2/","test/py1/3/" ,"test/py1/3/5/6/7/8/9/0" };
for (auto &s : list)
{
Miscellaneous::replaceSplit(s);
int e = Miscellaneous::mkdirs(s);
if (e != 0)
{
#ifdef _MSC_VER
char buf[256];
strerror_s(buf, 256, e);
perror(buf);
#else
perror(strerror(e));
#endif // _MSC_VER
}
else
{
puts(Miscellaneous::absolute(s).c_str());
}
}
}
void test5()
{
TileManager mgr(0, 5, 512, 512);
std::string s;
while (true)
{
std::getline(std::cin, s);
if (s.empty())
break;
if (s == "#build")
{
for (int i = 0; i <= 5; ++i)
{
std::cout << mgr.buildPath(TileId(i, (i * 13) ^ (~0), (i * 37) ^ (-62)), true) << std::endl;
}
}
std::cout << mgr.registerPath(s) << std::endl;
std::cout << mgr.buildPath(TileId(4, 0, -1)) << std::endl;
}
}
void test6()
{
std::string s;
while (true)
{
std::getline(std::cin, s);
if (s.empty())
break;
RGBTuple r1;
int x;
int y;
if (parseRGBTuple(r1, s) == 0)
printf("RGB: r=%d,g=%d,b=%d\n", r1.r, r1.g, r1.b);
if (parseRGBTuple2(r1, s) == 0)
printf("RGB#: r=%d,g=%d,b=%d\n", r1.r, r1.g, r1.b);
if(parseXY(x, y, s) == 0)
printf("XY: (%d,%d)\n", x, y);
}
}
*/
int main(int argc, char * const argv[])
{
demo(argc - 1, argv + 1);
return 0;
}
// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单
// 入门提示:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
| 20.896648 | 174 | 0.547119 | [
"vector"
] |
2362b0740623145d1a0a848b81a9df5d350f9cd5 | 3,117 | hpp | C++ | openFrameworks/apps/oldApps/v0.9.3/frocking/src/frocking.hpp | khattari540750/openFrameworks_practice | e61d219df99537f191f46c46a8bb509d8039e7ba | [
"MIT"
] | null | null | null | openFrameworks/apps/oldApps/v0.9.3/frocking/src/frocking.hpp | khattari540750/openFrameworks_practice | e61d219df99537f191f46c46a8bb509d8039e7ba | [
"MIT"
] | null | null | null | openFrameworks/apps/oldApps/v0.9.3/frocking/src/frocking.hpp | khattari540750/openFrameworks_practice | e61d219df99537f191f46c46a8bb509d8039e7ba | [
"MIT"
] | null | null | null | #pragma once
#include "ofMain.h"
#include "particle.hpp"
#include "ofxGui.h"
/*
class Frocking : public ofBaseApp
{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
private:
private: // moving head light control panel variables
ofxPanel controlPanel;
ofParameter<float> cohesionStrength;
ofParameter<int> cohesionRadius;
ofParameter<float> alignmentStrength;
ofParameter<int> alignmentRadius;
ofParameter<float> seperationStrength;
ofParameter<int> seperationRadius;
ofParameter<float> damping;
ofParameter<float> attractionStrength;
ofParameter<int> attractionRadius;
repulsive
};
*/
class Frocking : public ofBaseApp
{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
private:
vector <particle> particles;
private: // moving head light control panel variables
ofxPanel controlPanel;
ofParameter<float> cohesionStrength;
ofParameter<int> cohesionRadius;
ofParameter<float> alignmentStrength;
ofParameter<int> alignmentRadius;
ofParameter<float> seperationStrength;
ofParameter<int> seperationRadius;
ofParameter<float> damping;
};
/*
class ofApp : public ofBaseApp
{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
private:
ofEasyCam cam;
vector <particle> particles;
private: // moving head light control panel variables
ofxPanel controlPanel;
ofParameter<float> cohesionStrength;
ofParameter<int> cohesionRadius;
ofParameter<float> alignmentStrength;
ofParameter<int> alignmentRadius;
ofParameter<float> seperationStrength;
ofParameter<int> seperationRadius;
ofParameter<float> damping;
};
*/ | 19.853503 | 53 | 0.667308 | [
"vector"
] |
236571061a255758bc8f3d408e4fda0631859452 | 7,473 | cpp | C++ | main.cpp | pauloserrafh/opengl-learning | a6a154db3a121f3270c5bdf79ab7d5221c1dffd2 | [
"MIT"
] | null | null | null | main.cpp | pauloserrafh/opengl-learning | a6a154db3a121f3270c5bdf79ab7d5221c1dffd2 | [
"MIT"
] | null | null | null | main.cpp | pauloserrafh/opengl-learning | a6a154db3a121f3270c5bdf79ab7d5221c1dffd2 | [
"MIT"
] | null | null | null | #ifdef __APPLE__
#define GL_SILENCE_DEPRECATION
#endif
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <SDL2/SDL.h>
#include <string>
#include <iostream>
GLuint compileShader(GLuint shaderType, const std::string& source) {
GLuint shader;
GLint params;
const char* src;
char* tmp;
std::cout << "Compiling" <<
(shaderType == GL_VERTEX_SHADER ? " vertex " : " fragment ") <<
"shader " << std::endl;
shader = glCreateShader(shaderType);
src = source.c_str();
glShaderSource(shader, 1, &src, nullptr);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, ¶ms);
// params will contain the status of the compilation
if (params == GL_FALSE) {
// params will contain the length of the log message
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, ¶ms);
tmp = (char*) malloc(params*sizeof(char));
glGetShaderInfoLog(shader, params, ¶ms, tmp);
std::cout << "Error compiling shader: " << tmp << std::endl;
free(tmp);
glDeleteShader(shader);
return 0;
}
return shader;
}
GLuint createProgram() {
GLuint program;
GLuint vs, fs;
auto vertexSource =
#include "res/vertex.shader"
;
// std::cout << "Vertex: " << vertexSource << std::endl;
auto fragmentSource =
#include "res/fragment.shader"
;
program = glCreateProgram();
// Create and attach shaders to program
vs = compileShader(GL_VERTEX_SHADER, vertexSource);
glAttachShader(program, vs);
fs = compileShader(GL_FRAGMENT_SHADER, fragmentSource);
glAttachShader(program, fs);
glLinkProgram(program);
glValidateProgram(program);
// Clean-up
glDetachShader(program, vs);
glDetachShader(program, fs);
glDeleteShader(vs);
glDeleteShader(fs);
return program;
}
void createBackground() {
uint8_t points_size, indexes_size;
GLuint buffer, ibo;
/*
* Define the points to create a rectangle
* (At least) Two triangles can be created with
* the following points and then used to generate
* a rectangle.
*/
float points[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
/* Calculates the size of the array dinamically */
points_size = *(&points+1) - points;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, points_size*sizeof(float), points, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), 0);
/*
* Using the triangles:
* (-1, -1), (1, -1), (1, 1)
* (1, 1), (-1, 1), (-1, -1)
*/
GLuint indexes[] = {
0, 1, 2,
2, 3, 0
};
indexes_size = *(&indexes+1) - indexes;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexes_size*sizeof(GLuint), indexes, GL_STATIC_DRAW);
}
/*
* Initialize the uniform values defined on fragment shader
* (imported from ShaderToy).
*/
// TODO: Clean up shader and initialization to use only the
// bare minimum values.
void initializeUniforms(GLuint program) {
GLint location;
const GLfloat iChannelTimeValues[] = { 0.0f, 0.0f, 0.0f, 0.0f};
const GLfloat iChannelResolutionValues[] = { 640.0f, 480.0f, 1.0f, 0.0f};
// uniform vec3 iResolution; // viewport resolution (in pixels)
location = glGetUniformLocation(program, "iResolution");
glUniform3f(location, 640.0f, 480.0f, 1.0f);
// uniform float iTime; // shader playback time (in seconds)
location = glGetUniformLocation(program, "iTime");
glUniform1f(location, 0.0f);
// uniform float iTimeDelta; // render time (in seconds)
location = glGetUniformLocation(program, "iTimeDelta");
glUniform1f(location, 0.0f);
// uniform int iFrame; // shader playback frame
location = glGetUniformLocation(program, "iFrame");
glUniform1i(location, 0.0f);
// uniform float iChannelTime[4]; // channel playback time (in seconds)
location = glGetUniformLocation(program, "iChannelTime");
glUniform1fv(location, 4, iChannelTimeValues);
// uniform vec3 iChannelResolution[4]; // channel resolution (in pixels)
location = glGetUniformLocation(program, "iChannelResolution");
glUniform3fv(location, 4, iChannelResolutionValues);
// uniform vec4 iMouse; // mouse pixel coords. xy: current (if MLB down), zw: click
location = glGetUniformLocation(program, "iMouse");
glUniform4f(location, 0.0f, 0.0f, 0.0f, 0.0f);
// uniform sampler2D iChannel0; // input channel. XX = 2D/Cube
location = glGetUniformLocation(program, "iChannel0");
glUniform2f(location, 0.0f, 0.0f);
// uniform sampler2D iChannel1; // input channel. XX = 2D/Cube
location = glGetUniformLocation(program, "iChannel1");
glUniform2f(location, 0.0f, 0.0f);
// uniform sampler2D iChannel2; // input channel. XX = 2D/Cube
location = glGetUniformLocation(program, "iChannel2");
glUniform2f(location, 0.0f, 0.0f);
// uniform sampler2D iChannel3; // input channel. XX = 2D/Cube
location = glGetUniformLocation(program, "iChannel3");
glUniform2f(location, 0.0f, 0.0f);
// uniform vec4 iDate; // (year, month, day, time in seconds)
location = glGetUniformLocation(program, "iDate");
glUniform4f(location, 0.0f, 0.0f, 0.0f, 0.0f);
// uniform float iSampleRate; // sound sample rate (i.e., 44100)
location = glGetUniformLocation(program, "iSampleRate");
glUniform1f(location, 44100.0f);
}
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit()){
std::cout << "Error on glfwInit()" << std::endl;
return -1;
}
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
std::cout << "Error on glfwCreateWindow()" << std::endl;
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK) {
std::cout << "Error on glewInit" << std::endl;
}
std::cout << "GL_VERSION: " << glGetString(GL_VERSION) << std::endl;
createBackground();
GLuint program = createProgram();
glUseProgram(program);
initializeUniforms(program);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
/*
* iTime uniform parameter is the one used to rotate
* the camera.
*/
GLint location = glGetUniformLocation(program, "iTime");
glUniform1f(location, SDL_GetTicks()/100);
/* Draw the binded triangle on the middle of the screen */
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glDeleteProgram(program);
glfwTerminate();
return 0;
}
| 29.892 | 107 | 0.620099 | [
"render"
] |
236c7987cf9af14cb2b7397f7416d6a09762d497 | 489 | cpp | C++ | src/lambda/main.cpp | eastmoon/tutorial-c-boost | 06530df17ea1fafce54c820a50f9d092fbd3ec90 | [
"BSL-1.0"
] | null | null | null | src/lambda/main.cpp | eastmoon/tutorial-c-boost | 06530df17ea1fafce54c820a50f9d092fbd3ec90 | [
"BSL-1.0"
] | null | null | null | src/lambda/main.cpp | eastmoon/tutorial-c-boost | 06530df17ea1fafce54c820a50f9d092fbd3ec90 | [
"BSL-1.0"
] | null | null | null | #include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace boost::lambda;
int main()
{
// Create vector by array
// arr[number] = arr + number
// sizeof(arr) / sizeof(int) equal array length
int arr[] = {1,2,3};
std::vector<int> v (arr, arr + sizeof(arr) / sizeof(int) );
// iterator all value in vector and run lambda equation.
std::for_each(
v.begin(), v.end(), std::cout << (_1 * 3) << " " );
}
| 25.736842 | 63 | 0.607362 | [
"vector"
] |
236c96a22f16ba3a944284cad3e7ce1b0cabb051 | 7,798 | cpp | C++ | DOS_Boat_Source/RequireSpace.cpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | DOS_Boat_Source/RequireSpace.cpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | DOS_Boat_Source/RequireSpace.cpp | michaelslewis/DOS_Boat | 1c25f352d75555fa81bbd0f99c89aaed43739646 | [
"MIT"
] | null | null | null | /****************************************************************************
* Author: Michael S. Lewis *
* Date: 6/3/2016 *
* Description: RequireSpace.cpp is the RequireSpace class function *
* implementation file (for Final Project "DOS Boat"). *
* A Require Space tests whether a specific object is in *
* inventory before allowing the user to proceed to a *
* particular adjacent space. *
*****************************************************************************/
#include "RequireSpace.hpp"
#include "Babbage.hpp"
#include <iostream>
#include <cstdlib>
#include <string>
/****************************************************************************
* RequireSpace::RequireSpace() *
* Default constructor for the RequireSpace derived class. *
*****************************************************************************/
RequireSpace::RequireSpace() : Ocean()
{
// Empty function.
}
/****************************************************************************
* RequireSpace::RequireSpace(string, string, string, string, string) *
* Overloaded constructor for the RequireSpace derived class. *
*****************************************************************************/
RequireSpace::RequireSpace(std::string nameSpace, std::string spaceHeading,
std::string spaceType, std::string requiredItem, std::string restrictedArea) :
Ocean(nameSpace, spaceHeading, spaceType)
{
this->required = requiredItem;
this->restricted = restrictedArea;
}
/****************************************************************************
* RequireSpace::playSpace(Babbage*, bool) *
* Displays current space, description, calls the award function, offers *
* a hint, displays commands for headings, tells user the restricted heading *
* and which item will access it, then prompts for next move. *
*****************************************************************************/
void RequireSpace::playSpace(Babbage* babbage, bool displayHint)
{
std::cout << "You are " << this->name << "." << std::endl;
std::cout << this->description << std::endl;
if (displayHint)
{
babbage->getSpace()->displayHint();
}
std::cout << "Available directions: " << this->headings << std::endl;
std::cout << "You may proceed " << restricted << " only if you possess the " <<
required << "." << std::endl;
std::cout << "Checking inventory for the " << required << "..." << std::endl;
babbage->showInventory();
this->nextSpace(babbage);
}
/****************************************************************************
* RequireSpace::nextSpace(Babbage*) *
* Redefined to search through inventory for item required by current space, *
* then prompts for next move. Prevents move to space if required item is *
* in inventory, otherwise sets SS Babbage to next space. *
*****************************************************************************/
void RequireSpace::nextSpace(Babbage* babbage)
{
Ocean* nextOcean;
bool hasItem = false;
if (babbage->searchInventory(this->required) != -1)
{
hasItem = true;
}
do
{
char ch;
std::cout << "Please select the next move (eg. N for North, D for Dive, U for Up, etc.): ";
std::cin >> ch;
if (toupper(ch) == 'N')
{
if (this->restricted == "north" && !hasItem)
{
std::cout << "Captain! You currently do not possess the " << this->required << "." << std::endl;
std::cout << "I'm sorry, but for now, you may not proceed " << restricted << "." << std::endl;
nextOcean = NULL;
}
else if (this->north == NULL)
{
std::cout << "North is not available." << std::endl << std::endl
<< "Available choices: " << this->headings << std::endl
<< std::endl;
nextOcean = NULL;
}
else
{
std::cout << "You possess the necessary object and are able to proceed."
<< std::endl << std::endl;
nextOcean = this->north;
}
}
else if (toupper(ch) == 'S')
{
if (this->restricted == "south" && !hasItem)
{
std::cout << "Captain! You currently do not possess the " << this->required << "." << std::endl;
std::cout << "I'm sorry, but for now, you may not proceed " << restricted << "." << std::endl;
nextOcean = NULL;
}
else if (this->south == NULL)
{
std::cout << "South is not available." << std::endl << std::endl
<< "Available choices: " << this->headings << std::endl
<< std::endl;
nextOcean = NULL;
}
else
{
std::cout << "You possess the necessary object and are able to proceed." << std::endl << std::endl;
nextOcean = this->south;
}
}
else if (toupper(ch) == 'E')
{
if (this->restricted == "east" && !hasItem)
{
std::cout << "Captain! You currently do not possess the " << this->required << "." << std::endl;
std::cout << "I'm sorry, but for now, you may not proceed " << restricted << "." << std::endl;
nextOcean = NULL;
}
else if (this->east == NULL)
{
std::cout << "East is not available." << std::endl << std::endl
<< "Available choices: " << this->headings << std::endl
<< std::endl;
nextOcean = NULL;
}
else
{
std::cout << "You possess the necessary object and are able to proceed."
<< std::endl << std::endl;
nextOcean = this->east;
}
}
else if (toupper(ch) == 'W')
{
if (this->restricted == "west" && !hasItem)
{
std::cout << "Captain! You currently do not possess the " << this->required << "." << std::endl;
std::cout << "I'm sorry, but for now, you may not proceed " << restricted << "." << std::endl;
nextOcean = NULL;
}
else if (this->west == NULL)
{
std::cout << "West is not available." << std::endl << std::endl
<< "Available choices: " << this->headings << std::endl
<< std::endl;
nextOcean = NULL;
}
else
{
std::cout << "You possess the necessary object and are able to proceed."
<< std::endl << std::endl;
nextOcean = this->west;
}
}
else if (toupper(ch) == 'U')
{
if (this->restricted == "up" && !hasItem)
{
std::cout << "Captain! You currently do not possess the " << this->required << "." << std::endl;
std::cout << "I'm sorry, but for now, you may not proceed " << restricted << "." << std::endl;
nextOcean = NULL;
}
else if (this->up == NULL)
{
std::cout << "Up is not available." << std::endl << std::endl
<< "Available choices: " << this->headings << std::endl
<< std::endl;
nextOcean = NULL;
}
else
{
std::cout << "You possess the necessary object and are able to proceed." << std::endl << std::endl;
nextOcean = this->up;
}
}
else if (toupper(ch) == 'D')
{
if (this->restricted == "down" && !hasItem)
{
std::cout << "Captain! You currently do not possess the " << this->required << "." << std::endl;
std::cout << "I'm sorry, but for now, you may not proceed " << restricted << "." << std::endl;
nextOcean = NULL;
}
else if (this->down == NULL)
{
std::cout << "Down is not available." << std::endl << std::endl
<< "Available choices: " << this->headings << std::endl
<< std::endl;
nextOcean = NULL;
}
else
{
std::cout << "You possess the necessary object and are able to proceed." << std::endl << std::endl;
nextOcean = this->down;
}
}
else if (toupper(ch) == 'Q')
{
std::cout << "You've chosen to quit the game..." << std::endl
<< "Better luck next time." << std::endl;
exit(0);
}
else
{
std::cout << "Invalid input!" << std::endl;
nextOcean = NULL;
}
}
while (nextOcean == NULL);
babbage->setSpace(nextOcean);
}
| 34.504425 | 103 | 0.522185 | [
"object"
] |
23775ec25c8562aadf05f381d7828284891ecc04 | 28,545 | cpp | C++ | legacy/Plan v0.2.6.0 build 25 All/Plan/ToolbarEx.cpp | NN---/Plan | 47acb24c69d39de9e53396bc9eb3a4e6eeca6cca | [
"MIT"
] | null | null | null | legacy/Plan v0.2.6.0 build 25 All/Plan/ToolbarEx.cpp | NN---/Plan | 47acb24c69d39de9e53396bc9eb3a4e6eeca6cca | [
"MIT"
] | null | null | null | legacy/Plan v0.2.6.0 build 25 All/Plan/ToolbarEx.cpp | NN---/Plan | 47acb24c69d39de9e53396bc9eb3a4e6eeca6cca | [
"MIT"
] | null | null | null | // ToolBarEx.cpp : implementation file
//
#include "stdafx.h"
#include "ToolBarEx.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CToolBarEx
int CToolBarEx::m_nBarNumber = 0;
// for determining version of COMCTL32.DLL
#define VERSION_WIN4 MAKELONG(0, 4)
#define VERSION_IE3 MAKELONG(70, 4)
#define VERSION_IE4 MAKELONG(71, 4)
#define VERSION_IE401 MAKELONG(72, 4)
#define VERSION_IE5 MAKELONG(80, 5)
#define VERSION_IE5_2000 MAKELONG(81, 5)
struct AFX_DLLVERSIONINFO
{
DWORD cbSize;
DWORD dwMajorVersion; // Major version
DWORD dwMinorVersion; // Minor version
DWORD dwBuildNumber; // Build number
DWORD dwPlatformID; // DLLVER_PLATFORM_*
};
typedef HRESULT (CALLBACK* AFX_DLLGETVERSIONPROC)(AFX_DLLVERSIONINFO *);
static int _ComCtlVersion = -1;
static DWORD AFXAPI _GetComCtlVersion()
{
// return cached version if already determined...
if (_ComCtlVersion != -1)
return _ComCtlVersion;
// otherwise determine comctl32.dll version via DllGetVersion
HINSTANCE hInst = ::GetModuleHandleA("COMCTL32.DLL");
ASSERT(hInst != NULL);
AFX_DLLGETVERSIONPROC pfn;
pfn = (AFX_DLLGETVERSIONPROC)GetProcAddress(hInst, "DllGetVersion");
DWORD dwVersion = VERSION_WIN4;
if (pfn != NULL)
{
AFX_DLLVERSIONINFO dvi;
memset(&dvi, 0, sizeof(dvi));
dvi.cbSize = sizeof(dvi);
HRESULT hr = (*pfn)(&dvi);
if (SUCCEEDED(hr))
{
ASSERT(dvi.dwMajorVersion <= 0xFFFF);
ASSERT(dvi.dwMinorVersion <= 0xFFFF);
dwVersion = MAKELONG(dvi.dwMinorVersion, dvi.dwMajorVersion);
}
}
_ComCtlVersion = dwVersion;
return dwVersion;
}
CToolBarEx::CToolBarEx()
{
m_pControls = NULL;
m_pDropButtons = NULL; // list of drop-down buttons
m_bShowDropdownArrowWhenVertical = FALSE;
m_bHideChildWndOnVertical=TRUE;
++m_nBarNumber;
CWinApp *pApp = AfxGetApp();
ASSERT_VALID(pApp);
m_strValueName.Format( _T("ToolBarEx%d"), m_nBarNumber );
m_strSubKey.Format( _T("Software\\%s\\%s\\Settings"),
pApp->m_pszRegistryKey, pApp->m_pszProfileName );
}
CToolBarEx::~CToolBarEx()
{
while (m_pDropButtons)
{
CDropDownButtonInfo* pnext = m_pDropButtons->pNext;
delete m_pDropButtons;
m_pDropButtons = pnext;
}
if( m_pControls )
{
for( POSITION pos = m_pControls->GetHeadPosition() ; pos ; )
{
delete m_pControls->GetNext(pos);
}
delete m_pControls;
}
}
BEGIN_MESSAGE_MAP(CToolBarEx, CToolBar)
//{{AFX_MSG_MAP(CToolBarEx)
ON_WM_RBUTTONDOWN()
ON_WM_CREATE()
//}}AFX_MSG_MAP
ON_NOTIFY_REFLECT(TBN_DROPDOWN, OnToolBarBtnDropDown)
ON_NOTIFY_REFLECT(TBN_BEGINADJUST, OnToolBarBeginAdjust)
ON_NOTIFY_REFLECT(TBN_CUSTHELP, OnToolBarCustomHelp)
ON_NOTIFY_REFLECT(TBN_ENDADJUST, OnToolBarEndAdjust)
ON_NOTIFY_REFLECT(TBN_GETBUTTONINFO, OnToolBarGetButtonInfo)
ON_NOTIFY_REFLECT(TBN_QUERYDELETE, OnToolBarQueryDelete)
ON_NOTIFY_REFLECT(TBN_QUERYINSERT, OnToolBarQueryInsert)
ON_NOTIFY_REFLECT(TBN_RESET, OnToolBarReset)
ON_NOTIFY_REFLECT(TBN_TOOLBARCHANGE, OnToolBarChange)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CToolBarEx message handlers
//////////////////////////////////////////////////////////////////////
// 1999 Kirk Stowell - Inserts a control into the toolbar at the given button id.
//
CWnd* CToolBarEx::InsertControl( CRuntimeClass* pClass, LPCTSTR lpszWindowName, CRect& rect, UINT nID, DWORD dwStyle )
{
CWnd *pCtrl = NULL;
if( pClass->IsDerivedFrom( RUNTIME_CLASS( CComboBox ))) // CComboBox control.
{
pCtrl = new CComboBox;
ASSERT_VALID( pCtrl );
if(((CComboBox*)pCtrl)->Create( WS_CHILD|WS_VISIBLE|dwStyle, rect, this, nID ) == FALSE )
{
delete pCtrl;
return NULL;
}
}
else if( pClass->IsDerivedFrom( RUNTIME_CLASS( CEdit ))) // CEdit control.
{
pCtrl = new CEdit;
ASSERT_VALID( pCtrl );
if(((CEdit*)pCtrl)->Create( WS_CHILD|WS_VISIBLE|dwStyle, rect, this, nID ) == FALSE )
{
delete pCtrl;
return NULL;
}
}
else if( pClass->IsDerivedFrom( RUNTIME_CLASS( CButton ))) // CButton control.
{
pCtrl = new CButton;
ASSERT_VALID( pCtrl );
if(((CButton*)pCtrl)->Create( lpszWindowName, WS_CHILD|WS_VISIBLE|dwStyle, rect, this, nID ) == FALSE )
{
delete pCtrl;
return NULL;
}
}
else if( pClass->IsDerivedFrom( RUNTIME_CLASS( CWnd ))) // CWnd object.
{
pCtrl = new CWnd;
ASSERT_VALID( pCtrl );
#ifdef _UNICODE
TCHAR szClassName[ 256 ];
MultiByteToWideChar( CP_ACP,
MB_PRECOMPOSED,
pClass->m_lpszClassName,
-1,
szClassName,
255 );
if(((CWnd*)pCtrl)->Create( szClassName, lpszWindowName, WS_CHILD|WS_VISIBLE|dwStyle, rect, this, nID ) == FALSE )
{
delete pCtrl;
return NULL;
}
#else
if(((CWnd*)pCtrl)->Create( pClass->m_lpszClassName, lpszWindowName, WS_CHILD|WS_VISIBLE|dwStyle, rect, this, nID ) == FALSE )
{
delete pCtrl;
return NULL;
}
#endif
}
else // An invalid object was passed in
{
ASSERT( FALSE );
return NULL;
}
// if our object list has not been allocated, do it now...
if( m_pControls == NULL )
{
m_pControls = new CObList();
ASSERT( m_pControls );
}
// we have to remember this control, so we can delete it later
m_pControls->AddTail( pCtrl );
return InsertControl( pCtrl, rect, nID );
}
CWnd* CToolBarEx::InsertControl(CWnd* pCtrl, CRect & rect, UINT nID)
{
ASSERT_VALID( pCtrl );
// make sure the id is valid, and set the button
// style for a seperator.
int nIndex = CommandToIndex( nID ) ;
if (nIndex>-1)
{
ASSERT( nIndex >= 0 );
SetButtonInfo( nIndex, nID, TBBS_SEPARATOR, rect.Width());
// insert the control into the toolbar.
GetItemRect( nIndex, &rect );
pCtrl->SetWindowPos(0, rect.left, rect.top, 0, 0,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOCOPYBITS );
pCtrl->SetFont( GetFont( ));
BOOL bVert = (m_dwStyle & CBRS_ORIENT_VERT) != 0;
if (bVert && m_bHideChildWndOnVertical)
{
int nState=GetToolBarCtrl().GetState(nIndex);
GetToolBarCtrl().SetState(nID,(nState | TBSTATE_HIDDEN));
pCtrl->ShowWindow( SW_HIDE );
}
else
{
int nState=GetToolBarCtrl().GetState(nIndex);
GetToolBarCtrl().SetState(nIndex,(nState & ~TBSTATE_HIDDEN));
pCtrl->ShowWindow( SW_SHOW );
}
}
else
{
pCtrl->ShowWindow( SW_HIDE);
}
return pCtrl;
}
BOOL CToolBarEx::AddDropDownButton(UINT nIDButton, UINT nIDMenu,BOOL bArrow)
{
ASSERT_VALID(this);
CDropDownButtonInfo* pb = FindDropDownButtonInfo(nIDButton);
if (!pb)
{
pb = new CDropDownButtonInfo;
ASSERT(pb);
pb->pNext = m_pDropButtons;
m_pDropButtons = pb;
}
pb->idButton = nIDButton;
pb->idMenu = nIDMenu;
int iButton = CommandToIndex(nIDButton);
DWORD dwStyle = GetButtonStyle(iButton);
dwStyle |= TBSTYLE_DROPDOWN;
SetButtonStyle(iButton, dwStyle);
if (bArrow)
GetToolBarCtrl().SetExtendedStyle(TBSTYLE_EX_DRAWDDARROWS);
return TRUE;
}
CToolBarEx::CDropDownButtonInfo* CToolBarEx::FindDropDownButtonInfo(UINT nID)
{
for (CDropDownButtonInfo* pb = m_pDropButtons; pb; pb = pb->pNext)
{
if (pb->idButton == nID)
return pb;
}
return NULL;
}
void CToolBarEx::OnToolBarBtnDropDown(NMHDR* pNMHDR, LRESULT* pRes)
{
UNUSED_ALWAYS( pRes );
const NMTOOLBAR& nmtb = *(NMTOOLBAR*)pNMHDR;
// get location of button
CRect rc;
GetToolBarCtrl().GetRect(nmtb.iItem, rc);
ClientToScreen(&rc);
// call virtual function to display dropdown menu
OnDropDownButtonInfo(nmtb, nmtb.iItem, rc);
}
void CToolBarEx::OnDropDownButtonInfo(const NMTOOLBAR& nmtb, UINT nID, CRect rc)
{
UNUSED_ALWAYS( nID );
CDropDownButtonInfo* pb = FindDropDownButtonInfo(nmtb.iItem);
if (pb && pb->idMenu) {
// load and display popup menu
CMenu menu;
VERIFY(menu.LoadMenu(pb->idMenu));
CMenu* pPopup = (CMenu*)menu.GetSubMenu(0);
ASSERT(pPopup);
pPopup->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_VERTICAL,
rc.left, rc.bottom, AfxGetMainWnd(), &rc);
}
}
// This function saves the state (visible buttons, toolbar position, etc.)
// of the toolbar, using the registry key provided to the Create(...) function.
void CToolBarEx::SaveState()
{
// if there is an associated registry subkey
if (m_strSubKey.GetLength())
{
// save the toolbar state to the registry
GetToolBarCtrl().SaveState( HKEY_CURRENT_USER, m_strSubKey, m_strValueName );
}
}
// This function restores the state (visible buttons, toolbar position, etc.)
// of the toolbar, using the registry key provided to the Create(...) function.
void CToolBarEx::RestoreState()
{
// if there is an associated registry subkey
if (m_strSubKey.GetLength())
{
// restore the toolbar state from the registry
GetToolBarCtrl().RestoreState( HKEY_CURRENT_USER, m_strSubKey, m_strValueName );
}
//position the child windows
PositionControls();
}
// This function is called when the user begins dragging a toolbar
// button or when the customization dialog is being populated with
// toolbar information. Basically, *pResult should be populated with
// your answer to the question, "is the user allowed to delete this
// button?".
void CToolBarEx::OnToolBarQueryDelete(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pNMHDR );
/* NMTOOLBAR * tbStruct; // data needed by customize dialog box
// init the pointer
tbStruct = (TBNOTIFY *)pNMHDR;
if (tbStruct->tbButton.idCommand &&
GetToolBarCtrl().IsButtonHidden(tbStruct->tbButton.idCommand))
*pResult = FALSE;
else */
*pResult = TRUE;
}
// This function is called when the user begins dragging a toolbar
// button or when the customization dialog is being populated with
// toolbar information. Basically, *pResult should be populated with
// your answer to the question, "is the user allowed to insert a
// button to the left of this one?".
void CToolBarEx::OnToolBarQueryInsert(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pNMHDR );
/* NMTOOLBAR * tbStruct; // data needed by customize dialog box
// init the pointer
tbStruct = (TBNOTIFY *)pNMHDR;
if (tbStruct->tbButton.idCommand &&
GetToolBarCtrl().IsButtonHidden(tbStruct->tbButton.idCommand))
*pResult = FALSE;
else */
*pResult = TRUE;
}
// This function is called whenever the user makes a change to the
// layout of the toolbar. Calling the mainframe's RecalcLayout forces
// the toolbar to repaint itself.
void CToolBarEx::OnToolBarChange(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pNMHDR );
UNUSED_ALWAYS( pResult );
PositionControls();
// force the frame window to recalculate the size
GetParentFrame()->RecalcLayout();
OnIdleUpdateCmdUI(TRUE, 0L);
}
// This function is called when the user initially calls up the toolbar
// customization dialog box.
void CToolBarEx::OnToolBarBeginAdjust(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pNMHDR );
UNUSED_ALWAYS( pResult );
}
// This function is called when the user clicks on the help button on the
// toolbar customization dialog box.
void CToolBarEx::OnToolBarCustomHelp(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pNMHDR );
UNUSED_ALWAYS( pResult );
TRACE(_T("Help on Customize Toolbar called.\n"));
}
// This function is called when the user dismisses the toolbar customization
// dialog box.
void CToolBarEx::OnToolBarEndAdjust(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pNMHDR );
UNUSED_ALWAYS( pResult );
// save the state of the toolbar for reinitialization
SaveState();
}
// This function is called to populate the toolbar customization dialog box
// with information regarding all of the possible toolbar buttons.
void CToolBarEx::OnToolBarGetButtonInfo(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pResult );
TBNOTIFY* tbStruct; // data needed by customize dialog box
// init the pointer
tbStruct = (TBNOTIFY *)pNMHDR;
// if the index is valid
if ((0 <= tbStruct->iItem) && (tbStruct->iItem < m_ToolBarInfo.GetSize()))
{
// copy the stored button structure
tbStruct->tbButton = m_ToolBarInfo[tbStruct->iItem].tbButton;
if (GetToolBarCtrl().IsButtonHidden(tbStruct->tbButton.idCommand))
*pResult = FALSE;
// copy the text for the button label in the dialog
strcpy(tbStruct->pszText, m_ToolBarInfo[tbStruct->iItem].btnText);
// indicate valid data was sent
*pResult = TRUE;
}
// else there is no button for this index
else
{
*pResult = FALSE;
}
}
// This function is called when the user clicks on the reset button on the
// toolbar customization dialog box.
void CToolBarEx::OnToolBarReset(NMHDR *pNMHDR, LRESULT *pResult)
{
UNUSED_ALWAYS( pNMHDR );
UNUSED_ALWAYS( pResult );
// restore the toolbar to the way it was before entering customization
RestoreState();
GetParentFrame()->RecalcLayout();
OnIdleUpdateCmdUI(TRUE, 0L);
*pResult = TRUE;
}
void CToolBarEx::OnRButtonDown(UINT nFlags, CPoint point)
{
if( GetToolBarCtrl().GetButtonCount() && m_ToolBarInfo.GetSize())
{
CPoint pt( point );
ClientToScreen( &pt );
// load and display popup menu
CMenu popupMenu;
VERIFY(popupMenu.CreatePopupMenu());
popupMenu.InsertMenu(0, MF_BYPOSITION, ID_CUSTOMIZE_BAR, _T("&Customize..."));
int nResult = popupMenu.TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_VERTICAL|TPM_RETURNCMD,pt.x, pt.y, this );
if( nResult == ID_CUSTOMIZE_BAR )
{
// open the customization dialog.
GetToolBarCtrl().Customize();
}
}
else
{
CToolBar::OnRButtonDown(nFlags, point);
}
}
void CToolBarEx::SetToolBarInfoForCustomization()
{
m_ToolBarInfo.RemoveAll();
for (int i=0;i<GetToolBarCtrl().GetButtonCount();i++)
{
CToolBarButtonInfo tbButtonInfo;
GetToolBarCtrl().GetButton(i,&tbButtonInfo.tbButton);
CString str;
str.LoadString(tbButtonInfo.tbButton.idCommand);
int nPos= str.ReverseFind(_T('\n'));
tbButtonInfo.btnText=str.Right(str.GetLength()-nPos-1);
m_ToolBarInfo.Add(tbButtonInfo);
}
ModifyStyle(0, CCS_ADJUSTABLE);
}
/////////////////////////////////////////////////////////////////////////////////////////
// Overrides
int CToolBarEx::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CToolBar::OnCreate(lpCreateStruct) == -1)
return -1;
_GetComCtlVersion();
ASSERT(_ComCtlVersion>0);
return 0;
}
void CToolBarEx::OnBarStyleChange(DWORD dwOldStyle, DWORD dwNewStyle)
{
CToolBar::OnBarStyleChange(dwOldStyle,dwNewStyle);
PositionControls();
}
void CToolBarEx::PositionControls()
{
//move child windows to correct postion
BOOL bReCalc=FALSE;
BOOL bVert = (m_dwStyle & CBRS_ORIENT_VERT) != 0;
// now we do the position & size in two pass
//Firstly set the size of buttons
CWnd *pWnd = GetWindow(GW_CHILD);
while(pWnd)
{
ASSERT_VALID(pWnd);
int id =pWnd->GetDlgCtrlID();
CRect rt;
pWnd->GetWindowRect(rt);
///////////////////////////
int nIndex = CommandToIndex( id ) ;
if (nIndex>-1)
{
ASSERT( nIndex >= 0 );
SetButtonInfo( nIndex, id, TBBS_SEPARATOR, rt.Width());
if (bVert && m_bHideChildWndOnVertical)
{
//int nState=GetToolBarCtrl().GetState(nIndex);
GetToolBarCtrl().HideButton(id,TRUE);
}
else
{
//int nState=GetToolBarCtrl().GetState(nIndex);
GetToolBarCtrl().HideButton(id,FALSE);
}
}
//////////////////////////
if (!bReCalc) bReCalc=TRUE;
pWnd=pWnd->GetNextWindow();
}
// second pass
//Now place the windows
pWnd = GetWindow(GW_CHILD);
while(bReCalc && pWnd)
{
ASSERT_VALID(pWnd);
int id =pWnd->GetDlgCtrlID();
CRect rect;
///////////////////////////
// make sure the id is valid, and set the button
// style for a seperator.
int nIndex = CommandToIndex( id ) ;
if (nIndex>-1)
{
ASSERT( nIndex >= 0 );
// insert the control into the toolbar.
GetItemRect( nIndex, &rect );
pWnd->SetWindowPos(0, rect.left, rect.top, 0, 0,
SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOCOPYBITS );
pWnd->SetFont( GetFont( ));
if (bVert && m_bHideChildWndOnVertical)
pWnd->ShowWindow( SW_HIDE );
else
pWnd->ShowWindow( SW_SHOW );
}
else
{
pWnd->ShowWindow( SW_HIDE);
}
//////////////////////////
pWnd=pWnd->GetNextWindow();
}
if (bReCalc)
{
GetToolBarCtrl().AutoSize();
m_bDelayedButtonLayout=TRUE;
}
}
CSize CToolBarEx::GetButtonSize(TBBUTTON* pData, int iButton, DWORD dwMode)
{
ASSERT(_ComCtlVersion > 0);
// Get the actual size of the button, not what's in m_sizeButton.
// Make sure to do SendMessage instead of calling MFC's GetItemRect,
// which has all sorts of bad side-effects! (Go ahead, take a look at it.)
//
CRect rc;
SendMessage(TB_GETITEMRECT, iButton, (LPARAM)&rc);
CSize sz = rc.Size();
// do not allow sepearot to be greater than Button height ( Have to check this)
sz.cy = min(sz.cy ,HIWORD(GetToolBarCtrl().GetButtonSize()));
DWORD dwStyle = pData[iButton].fsStyle;
BOOL bVertDocked= (!(dwMode&LM_HORZ) && !(dwMode&LM_STRETCH) ) ;
// special cas for custom controls
if (m_bHideChildWndOnVertical)
{
if ((dwStyle & TBSTYLE_SEP) &&
(pData[iButton].idCommand!=0))
{
if (bVertDocked)
{
sz.cx=sz.cy=0;
}
else
{
// we will get 0,0 on hidden things
if (GetToolBarCtrl().IsButtonHidden(pData[iButton].idCommand))
{
CWnd * pWnd =GetDlgItem(pData[iButton].idCommand);
ASSERT_VALID(pWnd);
CRect rt;
pWnd->GetWindowRect(rt);
sz=rt.Size();
}
}
}
}
////////////////
// Now must do special case for various versions of comctl32.dll,
//
if ((pData[iButton].fsState & TBSTATE_WRAP))
{
if (dwStyle & TBSTYLE_SEP)
{
CWnd *pWnd =GetDlgItem(pData[iButton].idCommand);
// Check seperator is child window
if (!pWnd)
{
// this is the last separator in the row (eg vertically docked)
// fudge the height, and ignore the width. TB_GETITEMRECT will return
// size = (8 x 22) even for a separator in vertical toolbar
//
if (_ComCtlVersion <= VERSION_IE3)
sz.cy -= 3; // empircally good fudge factor
else if (_ComCtlVersion != VERSION_IE4)
sz.cy = sz.cx;
sz.cx = 0; // separator takes no width if it's the last one
}
else
{
// Do not set value in case of the child window
//WE should never get here
ASSERT_VALID(pWnd);
ASSERT(FALSE);
}
}
}
// drop down arrow check
if ((dwStyle & TBSTYLE_DROPDOWN) &&
(bVertDocked) &&
!m_bShowDropdownArrowWhenVertical )
{
// ignore width of dropdown
sz.cx = sz.cy;
}
return sz;
}
////////////////////////////////////////////////////////////
#define CX_OVERLAP 0
CSize CToolBarEx::CalcSize(TBBUTTON* pData, int nCount,DWORD dwMode)
{
ASSERT(pData != NULL && nCount > 0);
CPoint cur(0,0);
CSize sizeResult(0,0);
int cyTallestOnRow = 0;
int nButtons=0;
for (int i = 0; i < nCount; i++)
{
// also calculate for hidden custom controls
if ( (pData[i].fsState & TBSTATE_HIDDEN) &&
!((pData[i].fsStyle & TBSTYLE_SEP) && (pData[i].idCommand!=0)))
continue;
// Load actual size of button into a local variable
//
CSize m_sizeButton = GetButtonSize(pData, i,dwMode);
// I also changed the logic below to be more correct.
cyTallestOnRow = max(cyTallestOnRow, m_sizeButton.cy);
sizeResult.cx = max(cur.x + m_sizeButton.cx, sizeResult.cx);
sizeResult.cy = max(cur.y + m_sizeButton.cy, sizeResult.cy);
cur.x += m_sizeButton.cx - CX_OVERLAP;
if (!(pData[i].fsState & TBSTATE_HIDDEN)) nButtons++;
if (pData[i].fsState & TBSTATE_WRAP)
{
//only seperator is present
if ((nButtons==1) && (pData[i].fsStyle & TBSTYLE_SEP))
{
cyTallestOnRow = HIWORD(GetToolBarCtrl().GetButtonSize());
}
cur.x = 0;
cur.y += cyTallestOnRow;
cyTallestOnRow = 0;
if (pData[i].fsStyle & TBSTYLE_SEP)
cur.y += m_sizeButton.cy;
nButtons=0;
}
}
return sizeResult;
}
int CToolBarEx::WrapToolBar(TBBUTTON* pData, int nCount, int nWidth, DWORD dwMode)
{
ASSERT(pData != NULL && nCount > 0);
int nResult = 0;
int x = 0;
for (int i = 0; i < nCount; i++)
{
pData[i].fsState &= ~TBSTATE_WRAP;
// also calculate for hidden custom controls
if ( (pData[i].fsState & TBSTATE_HIDDEN) &&
!((pData[i].fsStyle & TBSTYLE_SEP) && (pData[i].idCommand!=0)))
continue;
int dx, dxNext;
// Load actual size of button into a local variable
CSize m_sizeButton = GetButtonSize(pData, i,dwMode);
dx = m_sizeButton.cx;
dxNext = dx - CX_OVERLAP;
if (x + dx > nWidth)
{
BOOL bFound = FALSE;
for (int j = i; j >= 0 && !(pData[j].fsState & TBSTATE_WRAP); j--)
{
// Find last separator that isn't hidden
// a separator that has a command ID is not
// a separator, but a custom control.
if ((pData[j].fsStyle & TBSTYLE_SEP) &&
(pData[j].idCommand == 0)
&& !(pData[j].fsState & TBSTATE_HIDDEN))
{
bFound = TRUE; i = j; x = 0;
pData[j].fsState |= TBSTATE_WRAP;
nResult++;
break;
}
}
if (!bFound)
{
for (int j = i - 1; j >= 0 && !(pData[j].fsState & TBSTATE_WRAP); j--)
{
// Never wrap anything that is hidden,
// or any custom controls
if ((pData[j].fsState & TBSTATE_HIDDEN) ||
((pData[j].fsStyle & TBSTYLE_SEP) &&
(pData[j].idCommand != 0)))
continue;
bFound = TRUE; i = j; x = 0;
pData[j].fsState |= TBSTATE_WRAP;
nResult++;
break;
}
if (!bFound)
x += dxNext;
}
}
else
x += dxNext;
}
return nResult + 1;
}
/////////////////////////////////////////////////////////////////////////////////////////////
void CToolBarEx::SizeToolBar(TBBUTTON* pData, int nCount, int nLength, BOOL bVert, DWORD dwMode)
{
ASSERT(pData != NULL && nCount > 0);
if (!bVert)
{
int nMin, nMax, nTarget, nCurrent, nMid;
// Wrap ToolBar as specified
nMax = nLength;
nTarget = WrapToolBar(pData, nCount, nMax,dwMode);
// Wrap ToolBar vertically
nMin = 0;
nCurrent = WrapToolBar(pData, nCount, nMin,dwMode);
if (nCurrent != nTarget)
{
while (nMin < nMax)
{
nMid = (nMin + nMax) / 2;
nCurrent = WrapToolBar(pData, nCount, nMid,dwMode);
if (nCurrent == nTarget)
nMax = nMid;
else
{
if (nMin == nMid)
{
WrapToolBar(pData, nCount, nMax,dwMode);
break;
}
nMin = nMid;
}
}
}
CSize size = CalcSize(pData, nCount,dwMode);
WrapToolBar(pData, nCount, size.cx,dwMode);
}
else
{
CSize sizeMax, sizeMin, sizeMid;
// Wrap ToolBar vertically
WrapToolBar(pData, nCount, 0,dwMode);
sizeMin = CalcSize(pData, nCount,dwMode);
// Wrap ToolBar horizontally
WrapToolBar(pData, nCount, 32767,dwMode);
sizeMax = CalcSize(pData, nCount,dwMode);
while (sizeMin.cx < sizeMax.cx)
{
sizeMid.cx = (sizeMin.cx + sizeMax.cx) / 2;
WrapToolBar(pData, nCount, sizeMid.cx,dwMode);
sizeMid = CalcSize(pData, nCount,dwMode);
if (nLength < sizeMid.cy)
{
if (sizeMin == sizeMid)
{
WrapToolBar(pData, nCount, sizeMax.cx,dwMode);
return;
}
sizeMin = sizeMid;
}
else if (nLength > sizeMid.cy)
sizeMax = sizeMid;
else
return;
}
}
}
struct _AFX_CONTROLPOS
{
int nIndex, nID;
CRect rectOldPos;
};
CSize CToolBarEx::CalcLayout(DWORD dwMode, int nLength)
{
ASSERT_VALID(this);
ASSERT(::IsWindow(m_hWnd));
if (dwMode & LM_HORZDOCK)
ASSERT(dwMode & LM_HORZ);
int nCount;
TBBUTTON* pData = NULL;
CSize sizeResult(0,0);
//BLOCK: Load Buttons
{
nCount = DefWindowProc(TB_BUTTONCOUNT, 0, 0);
if (nCount != 0)
{
int i;
pData = new TBBUTTON[nCount];
for (i = 0; i < nCount; i++)
_GetButton(i, &pData[i]);
}
}
if (nCount > 0)
{
if (!(m_dwStyle & CBRS_SIZE_FIXED))
{
BOOL bDynamic = m_dwStyle & CBRS_SIZE_DYNAMIC;
if (bDynamic && (dwMode & LM_MRUWIDTH))
SizeToolBar(pData, nCount, m_nMRUWidth,FALSE,dwMode);
else if (bDynamic && (dwMode & LM_HORZDOCK))
SizeToolBar(pData, nCount, 32767,FALSE,dwMode);
else if (bDynamic && (dwMode & LM_VERTDOCK))
SizeToolBar(pData, nCount, 0,FALSE,dwMode);
else if (bDynamic && (nLength != -1))
{
CRect rect; rect.SetRectEmpty();
CalcInsideRect(rect, (dwMode & LM_HORZ));
BOOL bVert = (dwMode & LM_LENGTHY);
int nLen = nLength + (bVert ? rect.Height() : rect.Width());
SizeToolBar(pData, nCount, nLen, bVert,dwMode);
}
else if (bDynamic && (m_dwStyle & CBRS_FLOATING))
SizeToolBar(pData, nCount, m_nMRUWidth,FALSE,dwMode);
else
SizeToolBar(pData, nCount, (dwMode & LM_HORZ) ? 32767 : 0,FALSE,dwMode);
}
sizeResult = CalcSize(pData, nCount,dwMode);
if (dwMode & LM_COMMIT)
{
_AFX_CONTROLPOS* pControl = NULL;
int nControlCount = 0;
BOOL bIsDelayed = m_bDelayedButtonLayout;
m_bDelayedButtonLayout = FALSE;
for (int i = 0; i < nCount; i++)
if ((pData[i].fsStyle & TBSTYLE_SEP) && (pData[i].idCommand != 0))
nControlCount++;
if (nControlCount > 0)
{
pControl = new _AFX_CONTROLPOS[nControlCount];
nControlCount = 0;
for(int i = 0; i < nCount; i++)
{
if ((pData[i].fsStyle & TBSTYLE_SEP) && (pData[i].idCommand != 0))
{
pControl[nControlCount].nIndex = i;
pControl[nControlCount].nID = pData[i].idCommand;
CRect rect;
GetItemRect(i, &rect);
ClientToScreen(&rect);
pControl[nControlCount].rectOldPos = rect;
nControlCount++;
}
}
}
if ((m_dwStyle & CBRS_FLOATING) && (m_dwStyle & CBRS_SIZE_DYNAMIC))
m_nMRUWidth = sizeResult.cx;
for (i = 0; i < nCount; i++)
_SetButton(i, &pData[i]);
if (nControlCount > 0)
{
for (int i = 0; i < nControlCount; i++)
{
CWnd* pWnd = GetDlgItem(pControl[i].nID);
if (pWnd != NULL)
{
CRect rect;
pWnd->GetWindowRect(&rect);
CPoint pt = rect.TopLeft() - pControl[i].rectOldPos.TopLeft();
GetItemRect(pControl[i].nIndex, &rect);
pt = rect.TopLeft() + pt;
pWnd->SetWindowPos(NULL, pt.x, pt.y, 0, 0, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER);
}
}
delete[] pControl;
}
m_bDelayedButtonLayout = bIsDelayed;
}
delete[] pData;
}
//BLOCK: Adjust Margins
{
CRect rect; rect.SetRectEmpty();
CalcInsideRect(rect, (dwMode & LM_HORZ));
sizeResult.cy -= rect.Height();
sizeResult.cx -= rect.Width();
CSize size = CControlBar::CalcFixedLayout((dwMode & LM_STRETCH), (dwMode & LM_HORZ));
sizeResult.cx = max(sizeResult.cx, size.cx);
sizeResult.cy = max(sizeResult.cy, size.cy);
}
return sizeResult;
}
CSize CToolBarEx::CalcFixedLayout(BOOL bStretch, BOOL bHorz)
{
DWORD dwMode = bStretch ? LM_STRETCH : 0;
dwMode |= bHorz ? LM_HORZ : 0;
return CalcLayout(dwMode);
}
CSize CToolBarEx::CalcDynamicLayout(int nLength, DWORD dwMode)
{
if ((nLength == -1) && !(dwMode & LM_MRUWIDTH) && !(dwMode & LM_COMMIT) &&
((dwMode & LM_HORZDOCK) || (dwMode & LM_VERTDOCK)))
{
return CalcFixedLayout(dwMode & LM_STRETCH, dwMode & LM_HORZDOCK);
}
return CalcLayout(dwMode, nLength);
}
/////////////////////////////////////////////////////////////////////////////
// CToolBarEx attribute access
void CToolBarEx::_GetButton(int nIndex, TBBUTTON* pButton) const
{
CToolBarEx* pBar = (CToolBarEx*)this;
VERIFY(pBar->DefWindowProc(TB_GETBUTTON, nIndex, (LPARAM)pButton));
// TBSTATE_ENABLED == TBBS_DISABLED so invert it
pButton->fsState ^= TBSTATE_ENABLED;
}
void CToolBarEx::_SetButton(int nIndex, TBBUTTON* pButton)
{
// get original button state
TBBUTTON button;
VERIFY(DefWindowProc(TB_GETBUTTON, nIndex, (LPARAM)&button));
// prepare for old/new button comparsion
button.bReserved[0] = 0;
button.bReserved[1] = 0;
// TBSTATE_ENABLED == TBBS_DISABLED so invert it
pButton->fsState ^= TBSTATE_ENABLED;
pButton->bReserved[0] = 0;
pButton->bReserved[1] = 0;
// nothing to do if they are the same
if (memcmp(pButton, &button, sizeof(TBBUTTON)) != 0)
{
// don't redraw everything while setting the button
DWORD dwStyle = GetStyle();
ModifyStyle(WS_VISIBLE, 0);
VERIFY(DefWindowProc(TB_DELETEBUTTON, nIndex, 0));
VERIFY(DefWindowProc(TB_INSERTBUTTON, nIndex, (LPARAM)pButton));
ModifyStyle(0, dwStyle & WS_VISIBLE);
// invalidate appropriate parts
if (((pButton->fsStyle ^ button.fsStyle) & TBSTYLE_SEP) ||
((pButton->fsStyle & TBSTYLE_SEP) && pButton->iBitmap != button.iBitmap))
{
// changing a separator
Invalidate();
}
else
{
// invalidate just the button
CRect rect;
if (DefWindowProc(TB_GETITEMRECT, nIndex, (LPARAM)&rect))
InvalidateRect(rect);
}
}
}
| 24.272959 | 127 | 0.662358 | [
"object"
] |
2378c5fe028a8195ac29dcd796d8c7a91fea3087 | 2,043 | hpp | C++ | Applications/DaftEngineApp/src/Widgets/SettingWidgets/TransformSettings.hpp | DaftMat/Daft-Engine | e3d918b4b876d17abd889b9b6b13bd858a079538 | [
"MIT"
] | 1 | 2020-10-26T02:36:58.000Z | 2020-10-26T02:36:58.000Z | Applications/DaftEngineApp/src/Widgets/SettingWidgets/TransformSettings.hpp | DaftMat/Daft-Engine | e3d918b4b876d17abd889b9b6b13bd858a079538 | [
"MIT"
] | 6 | 2020-02-14T21:45:52.000Z | 2020-09-23T17:58:58.000Z | Applications/DaftEngineApp/src/Widgets/SettingWidgets/TransformSettings.hpp | DaftMat/Daft-Engine | e3d918b4b876d17abd889b9b6b13bd858a079538 | [
"MIT"
] | null | null | null | //
// Created by mathis on 12/07/2020.
//
#pragma once
#include <API.hpp>
#include <Core/Materials/SettingManager.hpp>
#include <Core/OpenGL.hpp>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QLabel>
#include <QtWidgets/QWidget>
#include <array>
#include <memory>
namespace daft::app {
/**
* A class to edit the transformations of the selected object.
*/
class ENGINE_API TransformSettings : public QWidget {
Q_OBJECT
public:
/**
* Constructor.
* @param settings - library of the selected object's settings.
* @param enablePos - is position transformation enabled
* @param enableRot - is rotation transformation enabled
* @param enableSca - is scale transformation enabled
* @param parent - parent of the widget.
*/
explicit TransformSettings(daft::core::SettingManager settings, bool enablePos = true, bool enableRot = true,
bool enableSca = true, QWidget *parent = nullptr);
/**
* Transformation settings constant reference getter.
* @return const ref to the transformation settings of the drawable.
*/
[[nodiscard]] const core::SettingManager &transforms() const { return m_settings; }
/**
* Mouse press action
* @param event - mouse infos
*/
void mousePressEvent(QMouseEvent *event) override;
public slots:
void onTransformChanged();
void on_titleClicked();
signals:
void settingChanged();
void titleClicked();
void updateEvent();
private:
enum class Type { POSITION, ROTATION, SCALE };
using QDoubleSpinBoxPtr = QDoubleSpinBox *;
QWidget *createTransformWidget(Type type);
std::array<QDoubleSpinBoxPtr, 3> m_position{nullptr, nullptr, nullptr};
std::array<QDoubleSpinBoxPtr, 3> m_rotations{nullptr, nullptr, nullptr};
std::array<QDoubleSpinBoxPtr, 3> m_scale{nullptr, nullptr, nullptr};
daft::core::SettingManager m_settings;
std::unique_ptr<QLabel> m_title;
std::unique_ptr<QWidget> m_widget;
};
} // namespace daft::app | 29.185714 | 113 | 0.688693 | [
"object"
] |
237b17d92e9f6879e0e5a08e29a1f42bf1435601 | 35,802 | cpp | C++ | src/CX_SlideBuffer.cpp | hardmanko/ofxCX | 0d1276e4ba8c25a0803da7b03088da24d8871f38 | [
"MIT"
] | 7 | 2015-02-19T21:21:34.000Z | 2022-03-18T13:38:20.000Z | src/CX_SlideBuffer.cpp | hardmanko/ofxCX | 0d1276e4ba8c25a0803da7b03088da24d8871f38 | [
"MIT"
] | null | null | null | src/CX_SlideBuffer.cpp | hardmanko/ofxCX | 0d1276e4ba8c25a0803da7b03088da24d8871f38 | [
"MIT"
] | 4 | 2018-02-16T12:56:13.000Z | 2022-03-23T01:27:33.000Z | #include "CX_SlideBuffer.h"
#include "CX_Logger.h"
#include "CX_Private.h"
namespace CX {
///////////////////////////
// CX_SlideBuffer::Slide //
///////////////////////////
void CX_SlideBuffer::Slide::renderSlide(CX_Display* disp) {
if (_status >= PresentationStatus::RenderStarted) {
//warn that slide was re-rendered?
}
disp->beginDrawingToBackBuffer();
if (this->drawingFunction != nullptr) {
this->drawingFunction();
} else if (this->framebuffer != nullptr) {
ofPushStyle();
ofDisableAlphaBlending();
ofSetColor(255);
this->framebuffer->draw(0, 0);
ofPopStyle();
}
disp->endDrawingToBackBuffer();
_fenceSync.startSync();
_status = PresentationStatus::RenderStarted;
}
bool CX_SlideBuffer::Slide::isRendering(void) const {
return _status == PresentationStatus::RenderStarted && _fenceSync.isSyncing();
}
void CX_SlideBuffer::Slide::updateRenderStatus(void) {
if (!isRendering()) {
return;
}
_fenceSync.updateSync();
if (_fenceSync.syncComplete()) {
this->presInfo.renderStartTime = _fenceSync.getStartTime();
if (_fenceSync.syncSuccess()) {
this->presInfo.renderCompleteTime = _fenceSync.getSyncTime();
// It seems like the rendering should be marked as complete regardless of success
// but not setting it to RenderComplete on sync failure allows other stuff to see
// that the render did not complete.
_status = PresentationStatus::RenderComplete;
}
}
}
void CX_SlideBuffer::Slide::swappedIn(CX_Millis swapTime, FrameNumber swapFrame) {
if (isInactive()) {
Instances::Log.error("CX_SlideBuffer") << "Slide \"" << this->name << "\" swapped in when it was inactive.";
return;
}
//if (_status == PresentationStatus::OnScreen) {
// already on screen. this is legal in case of repeated rendering and swapping
//}
this->updateRenderStatus(); // one last check of the fence sync. this does not require a guard, like checking that the fence sync is incomplete.
if (_status == PresentationStatus::RenderStarted) {
// warning: swapped before rendering complete
presInfo.swappedBeforeRenderingComplete = true;
presInfo.renderCompleteTime = CX_Millis(-1);
} else if (_status == PresentationStatus::RenderComplete) {
presInfo.swappedBeforeRenderingComplete = false;
}
_fenceSync.clear(); // done with fence sync
actual.startTime = swapTime;
actual.startFrame = swapFrame;
_status = PresentationStatus::OnScreen;
if (slidePresentedCallback) {
slidePresentedCallback();
}
}
void CX_SlideBuffer::Slide::swappedOut(CX_Millis swapTime, FrameNumber swapFrame) {
if (_status != PresentationStatus::OnScreen) {
Instances::Log.error("CX_SlideBuffer") << "Slide \"" << this->name << "\" swapped out when it was not on screen.";
// warn: not on screen when swapped out
}
actual.timeDuration = swapTime - actual.startTime;
actual.frameDuration = swapFrame - actual.startFrame;
_status = PresentationStatus::Finished;
}
bool CX_SlideBuffer::Slide::isInactive(void) const {
return _status == PresentationStatus::NotStarted || _status == PresentationStatus::Finished;
}
bool CX_SlideBuffer::Slide::isActive(void) const {
return !isInactive();
}
bool CX_SlideBuffer::Slide::isOnScreen(void) const {
return _status == PresentationStatus::OnScreen;
}
bool CX_SlideBuffer::Slide::isPreparingToSwap(void) const {
return _status == PresentationStatus::RenderStarted || _status == PresentationStatus::RenderComplete;
}
bool CX_SlideBuffer::Slide::isPreparedToSwap(void) const {
return _status == PresentationStatus::RenderComplete;
}
void CX_SlideBuffer::Slide::deallocateFramebuffer(void) {
if (framebuffer) {
framebuffer->allocate(0, 0);
framebuffer = nullptr;
}
}
void CX_SlideBuffer::Slide::resetPresentationInfo(void) {
actual = SlideTimingInfo();
presInfo = SlidePresentationInfo();
_status = PresentationStatus::NotStarted;
_fenceSync.clear();
}
////////////////////
// CX_SlideBuffer //
////////////////////
CX_SlideBuffer::CX_SlideBuffer(void) :
_renderingToCurrentSlide(false)
{
setup(&Instances::Disp); // wow, really?
}
CX_SlideBuffer::CX_SlideBuffer(CX_Display* disp) :
CX_SlideBuffer()
{
setup(disp);
}
void CX_SlideBuffer::setup(CX_Display* disp) {
Configuration config;
config.display = disp;
setup(config);
}
void CX_SlideBuffer::setup(Configuration config) {
_config = config;
}
const CX_SlideBuffer::Configuration& CX_SlideBuffer::getConfiguration(void) const {
return _config;
}
bool CX_SlideBuffer::_appendSlide(Slide&& slide) {
if (slide.name == "") {
slide.name = "Slide " + ofToString(_slides.size() + 1);
}
if (slide.intended.timeDuration <= CX_Millis(0) && slide.intended.frameDuration == 0) {
CX::Instances::Log.warning("CX_SlideBuffer") << "Slide named \"" << slide.name << "\" with timeDuration <= 0 and frameDuration == 0 ignored.";
return false;
}
bool fboReady = slide.framebuffer != nullptr && slide.framebuffer->isAllocated();
if (!fboReady && slide.drawingFunction == nullptr) {
CX::Instances::Log.error("CX_SlideBuffer") << "appendSlide(): For slide named \"" << slide.name <<
"\", the framebuffer was not allocated and the drawing function was a nullptr, so the frame was ignored.";
return false;
}
//if (_slides.size() > 0) {
// Slide& prevSlide = _slides.back();
// prevSlide.intended.timeDuration = slide.intended.startTime - prevSlide.intended.startTime;
//}
_slides.push_back(std::move(slide));
CX::Instances::Log.verbose("CX_SlideBuffer") << "Slide #" << (_slides.size() - 1) << " (" << _slides.back().name <<
") appended.";
return true;
}
/*! Add a fully configured slide to the end of the list of slides.
Use of this function is discouraged. It is better to use `beginDrawingNextSlide()` or `appendSlideFunction()`.
The user code must configure a few components of the slide:
+ If the framebuffer will be used, the framebuffer must be allocated and drawn to.
+ If the drawing function will be used, a valid function pointer must be given. A check is made that either the
drawing function is set or the framebuffer is allocated and an error is logged if neither is configured.
+ The intended duration must be set.
+ The name may be set (optional). If equal to the empty string (`""`; the default), the name will be set to
"Slide N", where N is the slide number, indexed from 0.
\param slide The slide to append.
*/
void CX_SlideBuffer::appendSlide(Slide slide) {
endDrawingCurrentSlide();
_appendSlide(std::move(slide));
}
/*! Appends a slide to the slide presenter that will call the given drawing function when it comes time
to render the slide to the back buffer. This approach has the advantage over using framebuffers that
it takes essentially zero time to append a function to the list of slides, whereas a framebuffer must
be allocated, which takes time. Additionally, because framebuffers must be allocated, they use video
memory, so if you are using a very large number of slides, you could potentially run out of video memory.
Also, when it comes time to draw the slide to the back buffer, it may be faster to draw directly to the
back buffer than to copy an FBO to the back buffer (although this depends on various factors).
\param drawingFunction A pointer to a function that will draw the slide to the back buffer. The contents of
the back buffer are not cleared before this function is called, so the function must clear the background
to the desired color.
\param slideDuration The amount of time to present the slide for. If this is less than or equal to 0, the slide will be ignored.
\param slideName The name of the slide. This can be anything and is purely for the user to use to help identify the slide. If equal
to the empty string (`""`; the default), the name will be set to "Slide N", where N is the slide number, indexed from 0.
\note See \ref visualStimuli for more information about framebuffers.
One of the most tedious parts of using drawing functions is the fact that they can take no arguments. Here are two
ways to get around that limitation using `std::bind` and function objects ("functors"):
\code{.cpp}
#include "CX.h"
CX_SlidePresenter SlidePresenter;
//This is the function we want to use to draw a stimulus, but it takes two
//arguments. It needs to take 0 arguments in order to be used by the CX_SlidePresenter.
void drawRectangle(ofRectangle r, ofColor col) {
ofBackground(0);
ofSetColor(col);
ofRect(r);
}
//One option is to use a functor to shift around where the arguments to the function come from. With a
//functor, like rectFunctor, below, you can define an operator() that takes no arguments directly, but gets its
//data from the position and color members of the structure. Because rectFunctor has operator(), it looks
//like a function and can be called like a function, so you can use instances of it as drawing functions.
struct rectFunctor {
ofRectangle position;
ofColor color;
void operator() (void) {
drawRectangle(position, color);
}
};
void runExperiment(void) {
SlidePresenter.setup(&Disp);
//Here we use the functor. We set up the values for position and color and then give the functor to `appendSlideFunction()`.
rectFunctor rf;
rf.position = ofRectangle(100, 100, 50, 80);
rf.color = ofColor(0, 255, 0);
SlidePresenter.appendSlideFunction(2000.0, "functor rect", rf);
//The other method is to use std::bind to "bake in" values for the arguments of drawRectangle. We will
//set up the rectPos and rectColor values to bind to the arguments of drawRectangle.
ofRectangle rectPos(100, 50, 100, 30);
ofColor rectColor(255, 255, 0);
//With the call to std::bind, we bake in the values rectPos and rectColor to their respective arguments,
//resulting in a function that takes 0 arguments, which we pass into appendSlideFunction().
SlidePresenter.appendSlideFunction(2000.0, "bind rect", std::bind(drawRectangle, rectPos, rectColor));
SlidePresenter.startSlidePresentation();
while (SlidePresenter.isPresentingSlides()) {
SlidePresenter.update();
}
}
\endcode
*/
void CX_SlideBuffer::appendSlideFunction(CX_Millis timeDuration, std::function<void(void)> drawingFunction, std::string slideName, FrameNumber frameDuration) {
endDrawingCurrentSlide();
if (drawingFunction == nullptr) {
CX::Instances::Log.error("CX_SlideBuffer") << "appendSlideFunction(): nullptr to drawing function given.";
return;
}
Slide slide;
slide.name = slideName;
slide.intended.timeDuration = timeDuration;
slide.intended.frameDuration = frameDuration;
slide.drawingFunction = drawingFunction;
_appendSlide(std::move(slide));
}
/*! Prepares the framebuffer of the next slide for drawing so that any drawing
commands given between a call to beginDrawingNextSlide() and endDrawingCurrentSlide()
will cause stimuli to be drawn to the framebuffer of the next slide.
\param slideDuration The amount of time to present the slide for. If this is less than or equal to 0, the slide will be ignored.
\param slideName The name of the slide. This can be anything and is purely for the user to use to help identify the slide. If equal
to the empty string (`""`; the default), the name will be set to "Slide N", where N is the slide number, indexed from 0.
\code{.cpp}
CX_SlideBuffer sp; //Assume that this has been set up.
sp.beginDrawingNextSlide(2000, "circles");
ofBackground(50);
ofSetColor(255, 0, 0);
ofCirlce(100, 100, 30);
ofCircle(210, 50, 20);
sp.endDrawingCurrentSlide();
\endcode
*/
void CX_SlideBuffer::beginDrawingNextSlide(CX_Millis timeDuration, std::string slideName, FrameNumber frameDuration) {
endDrawingCurrentSlide();
if (!_config.display->renderingOnThisThread()) {
CX::Instances::Log.error("CX_SlideBuffer") << "Cannot draw slides while the rendering context is on the display thread. "
"You must disable the frame queue with CX_DisplayThread::enableFrameQueue()";
return;
}
if (_config.display == nullptr) {
CX::Instances::Log.error("CX_SlideBuffer") << "Cannot draw slides without a valid CX_Display attached. "
"Call setup() before calling beginDrawingNextSlide().";
return;
}
// Always make a new one
_currentSlide = std::make_shared<Slide>();
_currentSlide->name = slideName;
_currentSlide->intended.timeDuration = timeDuration;
_currentSlide->intended.frameDuration = frameDuration;
CX::Instances::Log.verbose("CX_SlideBuffer") << "Allocating framebuffer...";
_currentSlide->framebuffer = std::make_shared<ofFbo>();
ofRectangle resolution = _config.display->getResolution();
_currentSlide->framebuffer->allocate(resolution.x, resolution.y,
GL_RGB, //Because we are always drawing over the whole display, there is no reason to have an alpha channel
CX::Util::getMsaaSampleCount());
Instances::Log.verbose("CX_SlideBuffer") << "Finished allocating.";
// Not done in this class any more
//_slides.back().intended.frameCount = _calculateFrameCount(slideDuration);
Instances::Log.verbose("CX_SlideBuffer") << "Beginning to draw to framebuffer.";
_currentSlide->framebuffer->begin();
_renderingToCurrentSlide = true;
}
/*! Ends drawing to the framebuffer of the slide that is currently being drawn to. See beginDrawingNextSlide(). Calling this function is optional: It will be called for you as needed. */
void CX_SlideBuffer::endDrawingCurrentSlide(void) {
if (!_config.display->renderingOnThisThread()) {
return;
}
if (_currentSlide == nullptr) {
// Nothing being drawn
return;
}
if (_renderingToCurrentSlide) {
_currentSlide->framebuffer->end();
_renderingToCurrentSlide = false;
}
_appendSlide(std::move(*_currentSlide));
_currentSlide = nullptr;
}
/*! \brief Clears all of the slides contained in the slide buffer. */
void CX_SlideBuffer::clear(void) {
_slides.clear();
}
bool CX_SlideBuffer::slideExists(std::string name) const {
int index = _namedSlideIndex(name);
return index > 0;
}
/*! Gets a pointer to the slide with the given name, if any. If the named slide is not found,
a `nullptr` is returned. It is the users responsibility to either
exception is thrown and an error is logged (although you will never see the log
message unless the exception is caught).
\param name The name of the slide to get.
\return A reference to the named slide.
\note Because the user supplies slide names, there is no guarantee that any given slide name will
be unique. Because of this, this function simply returns a reference to the first slide for which
the name matches.
*/
CX_SlideBuffer::Slide* CX_SlideBuffer::getSlide(std::string name) {
int index = _namedSlideIndex(name);
if (index < 0) {
Instances::Log.error("CX_SlideBuffer") << "getSlide(): No slide found with name \"" << name << "\".";
return nullptr;
}
return getSlide((size_t)index);
}
CX_SlideBuffer::Slide* CX_SlideBuffer::operator[](std::string name) {
return getSlide(name);
}
CX_SlideBuffer::Slide* CX_SlideBuffer::operator[](size_t index) {
return getSlide(index);
}
bool CX_SlideBuffer::deleteSlide(std::string name) {
int index = _namedSlideIndex(name);
if (index < 0) {
return false;
}
_slides.erase(_slides.begin() + index);
return true;
}
int CX_SlideBuffer::_namedSlideIndex(std::string name) const {
for (int i = 0; i < _slides.size(); i++) {
if (_slides[i].name == name) {
return i;
}
}
return -1;
}
bool CX_SlideBuffer::slideExists(size_t index) const {
return index < _slides.size();
}
CX_SlideBuffer::Slide* CX_SlideBuffer::getSlide(size_t index) {
if (!slideExists(index)) {
Instances::Log.error("CX_SlideBuffer") << "getSlide(): No slide found at index \"" << index << "\".";
return nullptr;
}
return &_slides[index];
}
bool CX_SlideBuffer::deleteSlide(size_t index) {
if (!slideExists(index)) {
return false;
}
_slides.erase(_slides.begin() + index);
return true;
}
size_t CX_SlideBuffer::size(void) const {
return _slides.size();
}
std::vector<CX_SlideBuffer::Slide>& CX_SlideBuffer::getSlides(void) {
return _slides;
}
/*! Checks the timing data from the last presentation of slides for presentation errors. Currently it checks to
see if the intended frame count matches the actual frame count of each slide, which indicates if the duration was
correct. It also checks to make sure that the framebuffer was copied to the back buffer before the onset of the
slide. If not, vertical tearing might have occurred when the back buffer, containing a partially copied slide, was
swapped in.
\return A struct with information about the errors that occurred on the last presentation of slides.
\note If clearSlides() has been called since the end of the presentation, this does nothing as its data has been cleared.
\note If this function is called during slide presentation, the returned struct will have the presentationErrorsSuccessfullyChecked
member set to false and an error will be logged.
*/
CX_SlideBuffer::PresentationErrorInfo CX_SlideBuffer::checkForPresentationErrors(void) const {
CX_SlideBuffer::PresentationErrorInfo errors;
for (size_t i = 0; i < _slides.size(); i++) {
const CX_SlideBuffer::Slide &sl = _slides.at(i);
bool errorOnThisSlide = false;
if (sl.intended.frameDuration != sl.actual.frameDuration) {
//This error does not apply to the last slide because the duration of the last slide is undefined.
if (i != _slides.size() - 1) {
errors.incorrectFrameCounts++;
errorOnThisSlide = true;
}
}
if (sl.presInfo.swappedBeforeRenderingComplete) {
//if (sl.presInfo.renderCompleteTime > sl.actual.startTime) {
errors.lateCopiesToBackBuffer++;
errorOnThisSlide = true;
}
if (sl.actual.startTime > sl.intended.startTime) {
errors.lateStarts++;
errorOnThisSlide = true;
}
if (errorOnThisSlide) {
errors.namesOfSlidesWithErrors.push_back(sl.name);
}
}
//errors.presentationErrorsSuccessfullyChecked = true;
return errors;
}
/*! This function prints a ton of data relating to the last presentation of slides.
It prints the total number of errors and the types of the errors. For each slide,
it prints the slide index and name, and various information about the slide presentation
timing.
All of the printed information can also be accessed by with getSlide().
\return A string containing formatted presentation information. Errors are marked with two
asterisks (**).
*/
std::string CX_SlideBuffer::printLastPresentationInformation(void) const {
PresentationErrorInfo errors = checkForPresentationErrors();
std::stringstream s;
s << "Errors: " << errors.totalErrors() << endl;
if (errors.totalErrors() > 0) {
s << "Incorrect frame counts: " << errors.incorrectFrameCounts << endl;
s << "Late copies to back buffer: " << errors.lateCopiesToBackBuffer << endl;
}
s << endl;
for (size_t i = 0; i < _slides.size(); i++) {
const Slide& slide = _slides[i];
s << "-----------------------------------" << endl;
s << "Index: " << i;
s << " Name: " << slide.name << endl;
s << "Measure:\tIntended,\tActual" << endl;
s << "Start time: \t" << slide.intended.startTime << ", " << slide.actual.startTime;
if (slide.actual.startTime > slide.intended.startTime) {
s << "**";
}
s << endl;
s << "Time duration: \t" << slide.intended.timeDuration << ", " << slide.actual.timeDuration << endl;
s << "Start frame:\t" << slide.intended.startFrame << ", " << slide.actual.startFrame << endl;
s << "Frame duration:\t" << slide.intended.frameDuration << ", " << slide.actual.frameDuration;
if (slide.intended.frameDuration != slide.actual.frameDuration) {
if (i != (_slides.size() - 1)) {
s << "**"; //Mark the error, but not for the last slide
}
}
s << endl;
s << "Render start: " << slide.presInfo.renderStartTime.millis() << std::endl <<
"Render complete: " << slide.presInfo.renderCompleteTime.millis();
if (slide.presInfo.swappedBeforeRenderingComplete) {
s << "**"; //Mark the error
}
s << std::endl << std::endl;
}
return s.str();
}
/*! This function produces a CX_DataFrame with the following information related to slide
presentation for each slide (drawn directly from the CX_SlideBuffer::Slide struct used by each
slide): name, intended and actual timing information, and copyToBackBufferCompleteTime. In
addition, the slide index is given.
The column names are "index", "name", "copyToBackBufferCompleteTime",
"actual.startTime", "actual.timeDuration", "actual.startFrame", and "actual.frameDuration".
Plus, for the intended timings, replace "actual" with "intended" for the 4 intended timings
columns.
\return The data frame.
*/
CX_DataFrame CX_SlideBuffer::getLastPresentationInformation(void) const {
CX_DataFrame df;
for (size_t i = 0; i < _slides.size(); i++) {
const Slide& slide = _slides[i];
df(i, "index") = i;
df(i, "name") = slide.name;
df(i, "actual.startTime") = slide.actual.startTime;
df(i, "actual.timeDuration") = slide.actual.timeDuration;
df(i, "actual.startFrame") = slide.actual.startFrame;
df(i, "actual.frameDuration") = slide.actual.frameDuration;
df(i, "intended.startTime") = slide.intended.startTime;
df(i, "intended.timeDuration") = slide.intended.timeDuration;
df(i, "intended.startFrame") = slide.intended.startFrame;
df(i, "intended.frameDuration") = slide.intended.frameDuration;
df(i, "presInfo.renderStartTime") = slide.presInfo.renderStartTime;
df(i, "presInfo.renderCompleteTime") = slide.presInfo.renderCompleteTime;
df(i, "presInfo.swappedBeforeRenderingComplete") = slide.presInfo.swappedBeforeRenderingComplete;
}
return df;
}
/*! Gets a vector containing the durations of the slides from the last presentation of slides.
Note that these durations may be wrong. If checkForPresentationErrors() does not detect any errors,
the durations are likely to be right, but there is no guarantee.
\return A vector containing the durations. The duration corresponding to the first slide added
to the slide presenter will be at index 0.
\note The duration of the last slide is meaningless. As far as the slide presenter is concerned,
as soon as the last slide is put on the screen, it is done presenting the slides. Because the
slide presenter is not responsible for removing the last slide from the screen, it has no idea
about the duration of that slide. */
std::vector<CX_Millis> CX_SlideBuffer::getActualTimeDurations(void) {
/*
if (isLocked()) {
CX::Instances::Log.error("CX_SlidePresenter") << "getActualPresentationDurations called during slide presentation."
" Wait until presentation is done to call this function.";
return std::vector<CX_Millis>();
}
*/
vector<CX_Millis> durations(_slides.size());
for (size_t i = 0; i < _slides.size(); i++) {
durations[i] = _slides[i].actual.timeDuration;
}
return durations;
}
/*! Gets a vector containing the number of frames that each of the slides from the last presentation
of slides was presented for. Note that these frame counts may be wrong. If checkForPresentationErrors()
not detect any errors, the frame counts are likely to be right, but there is no guarantee.
\return A vector containing the frame counts. The frame count corresponding to the first slide added
to the slide presenter will be at index 0.
\note The frame count of the last slide is meaningless. As far as the slide presenter is concerned,
as soon as the last slide is put on the screen, it is done presenting the slides. Because the
slide presenter is not responsible for removing the last slide from the screen, it has no idea
about the duration of that slide. */
std::vector<FrameNumber> CX_SlideBuffer::getActualFrameDurations(void) {
/*
if (isLocked()) {
CX::Instances::Log.error("CX_SlidePresenter") << "getActualFrameCounts called during slide presentation."
" Wait until presentation is done to call this function.";
return std::vector<FrameNumber>();
}
*/
vector<FrameNumber> frameCount(_slides.size());
for (size_t i = 0; i < _slides.size(); i++) {
frameCount[i] = _slides[i].actual.frameDuration;
}
return frameCount;
}
//////////////////////////////////
// CX_SlideBufferPlaybackHelper //
//////////////////////////////////
bool CX_SlideBufferPlaybackHelper::setup(const Configuration& config) {
if (config.slideBuffer == nullptr) {
return false;
}
_config = config;
if (_config.display == nullptr) {
_config.display = _config.slideBuffer->getConfiguration().display;
}
return true;
}
/*
void CX_SlideBufferPlaybackHelper::setup(CX_SlideBuffer* sb, CX_Display* disp) {
_config.slideBuffer = sb;
if (disp) {
_config.display = disp;
} else {
_config.display = _config.slideBuffer->getConfiguration().display;
}
}
*/
const CX_SlideBufferPlaybackHelper::Configuration& CX_SlideBufferPlaybackHelper::getConfiguration(void) const {
return _config;
}
// returns true if slides swapped in and out
void CX_SlideBufferPlaybackHelper::bufferSwap(CX_Millis swapTime, FrameNumber swapFrame) {
CX_SlideBuffer::Slide* nextSlide = getNextSlide();
if (nextSlide) {
if (!nextSlide->isPreparingToSwap()) {
_slideAdvancedOnLastSwap = false;
return; // If the next slide is not preparing to swap, this swap does not change what is on screen
}
if (!nextSlide->isPreparedToSwap()) {
Instances::Log.warning("CX_SlideBufferPlaybackHelper") << "The next slide was not prepared to swap in but a buffer swap took place.";
}
nextSlide->swappedIn(swapTime, swapFrame);
}
CX_SlideBuffer::Slide* currentSlide = getCurrentSlide();
if (currentSlide) {
currentSlide->swappedOut(swapTime, swapFrame);
}
// Oncea all of the buffer swap logic is complete, then the slide that is now on screen gets set at the current slide
_currentSlide++;
_slideAdvancedOnLastSwap = true;
return;
}
bool CX_SlideBufferPlaybackHelper::slideAdvancedOnLastSwap(void) {
return _slideAdvancedOnLastSwap;
}
bool CX_SlideBufferPlaybackHelper::currentSlideIsFirstSlide(void) const {
return _currentSlide == 0;
}
bool CX_SlideBufferPlaybackHelper::currentSlideIsLastSlide(void) const {
return _currentSlide >= 0 && _currentSlide == (_config.slideBuffer->size() - 1);
}
void CX_SlideBufferPlaybackHelper::renderNextSlide(void) {
CX_SlideBuffer::Slide* nextSlide = getNextSlide();
if (nextSlide) {
nextSlide->renderSlide(_config.display);
}
}
void CX_SlideBufferPlaybackHelper::reRenderCurrentSlide(void) {
CX_SlideBuffer::Slide* currentSlide = getCurrentSlide();
if (currentSlide) {
currentSlide->renderSlide(_config.display);
}
}
CX_SlideBuffer::Slide* CX_SlideBufferPlaybackHelper::getPreviousSlide(void) {
int index = _currentSlide - 1;
if (!_playing || index < 0 || index >= _config.slideBuffer->size()) {
return nullptr;
}
return _config.slideBuffer->getSlide(index);
}
CX_SlideBuffer::Slide* CX_SlideBufferPlaybackHelper::getCurrentSlide(void) {
if (!_playing || _currentSlide < 0 || _currentSlide >= _config.slideBuffer->size()) {
return nullptr;
}
return _config.slideBuffer->getSlide(_currentSlide);
}
CX_SlideBuffer::Slide* CX_SlideBufferPlaybackHelper::getNextSlide(void) {
int index = _currentSlide + 1;
if (!_playing || index < 0 || index >= _config.slideBuffer->size()) {
return nullptr;
}
return _config.slideBuffer->getSlide(index);
}
void CX_SlideBufferPlaybackHelper::setIntendedStartFramesUsingTimeDurations(FrameNumber startFrame, CX_Millis nominalFramePeriod) {
for (size_t i = 0; i < _config.slideBuffer->size(); i++) {
CX_SlideBuffer::Slide* slide = _config.slideBuffer->getSlide(i);
slide->intended.startFrame = startFrame;
slide->intended.frameDuration = Util::round(slide->intended.timeDuration / nominalFramePeriod, 0, Util::Rounding::ToNearest);
if (slide->intended.frameDuration == 0) {
// warn?
slide->intended.frameDuration = 1;
}
startFrame += slide->intended.frameDuration;
}
}
void CX_SlideBufferPlaybackHelper::setIntendedStartFramesUsingFrameDurations(FrameNumber startFrame) {
for (size_t i = 0; i < _config.slideBuffer->size(); i++) {
CX_SlideBuffer::Slide* slide = _config.slideBuffer->getSlide(i);
slide->intended.startFrame = startFrame;
startFrame += slide->intended.frameDuration;
}
}
void CX_SlideBufferPlaybackHelper::setIntendedStartTimesUsingTimeDurations(CX_Millis startTime) {
for (size_t i = 0; i < _config.slideBuffer->size(); i++) {
CX_SlideBuffer::Slide* slide = _config.slideBuffer->getSlide(i);
slide->intended.startTime = startTime;
startTime += slide->intended.timeDuration;
}
}
void CX_SlideBufferPlaybackHelper::setIntendedStartTimesUsingFrameDurations(CX_Millis startTime, CX_Millis nominalFramePeriod) {
for (size_t i = 0; i < _config.slideBuffer->size(); i++) {
CX_SlideBuffer::Slide* slide = _config.slideBuffer->getSlide(i);
slide->intended.startTime = startTime;
startTime += slide->intended.frameDuration * nominalFramePeriod;
}
}
void CX_SlideBufferPlaybackHelper::setIntendedStartOfRemainingSlidesFromCurrentSlide(bool setTime, bool setFrames) {
CX_SlideBuffer::Slide* currentSlide = getCurrentSlide();
if (!currentSlide) {
return;
}
// _currentSlide must be >= 0
size_t nextSlideIndex = _currentSlide + 1;
CX_Millis nextSlideStartTime = currentSlide->actual.startTime + currentSlide->intended.timeDuration;
FrameNumber nextSlideStartFrame = currentSlide->actual.startFrame + currentSlide->intended.frameDuration;
for (size_t i = nextSlideIndex; i < _config.slideBuffer->size(); i++) {
CX_SlideBuffer::Slide* slide = _config.slideBuffer->getSlide(i);
if (setTime) {
slide->intended.startTime = nextSlideStartTime;
nextSlideStartTime += slide->intended.timeDuration;
}
if (setFrames) {
slide->intended.startFrame = nextSlideStartFrame;
nextSlideStartFrame += slide->intended.frameDuration;
}
}
}
void CX_SlideBufferPlaybackHelper::setIntendedStartTimesOfRemainingSlidesFromCurrentSlide(void) {
setIntendedStartOfRemainingSlidesFromCurrentSlide(true, false);
}
void CX_SlideBufferPlaybackHelper::setIntendedStartFramesOfRemainingSlidesFromCurrentSlide(void) {
setIntendedStartOfRemainingSlidesFromCurrentSlide(false, true);
}
void CX_SlideBufferPlaybackHelper::resetPresentationInfo(void) {
_playing = false;
_currentSlide = -1;
for (size_t i = 0; i < _config.slideBuffer->size(); i++) {
_config.slideBuffer->getSlide(i)->resetPresentationInfo();
}
}
bool CX_SlideBufferPlaybackHelper::startPlaying(void) {
if (_config.slideBuffer->size() == 0) {
return false;
}
resetPresentationInfo();
_currentSlide = -1; // the slide before the first on screen slide
_slideAdvancedOnLastSwap = false;
_playing = true;
return true;
}
void CX_SlideBufferPlaybackHelper::updatePlayback(void) {
if (!isPlaying()) {
return;
}
CX_SlideBuffer::Slide* nextSlide = getNextSlide();
if (nextSlide && nextSlide->isRendering()) {
nextSlide->updateRenderStatus();
}
}
bool CX_SlideBufferPlaybackHelper::isPlaying(void) {
if (!getNextSlide()) {
_playing = false;
}
return _playing;
}
void CX_SlideBufferPlaybackHelper::stopPlaying(void) {
_playing = false;
}
/////////////////////////////////////
// CX_SlideBufferPredicatePlayback //
/////////////////////////////////////
bool CX_SlideBufferPredicatePlayback::setup(const Configuration& config) {
if (!config.hasSwappedPredicate && !config.shouldSwapPredicate) {
/// must provide at least one of hasSwappedPredicate or shouldSwapPredicate
return false;
}
if (!config.renderNextPredicate) {
return false;
}
std::lock_guard<std::recursive_mutex> lock(_mutex);
_config = config;
{
CX_SlideBufferPlaybackHelper::Configuration hc;
hc.display = _config.display;
hc.slideBuffer = _config.slideBuffer;
_helper.setup(hc);
}
return true;
}
CX_SlideBufferPredicatePlayback::Configuration CX_SlideBufferPredicatePlayback::getConfiguration(void) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
return _config;
}
/*
bool CX_SlideBufferPredicatePlayback::startPlaying(CX_Millis intendedStartTime, FrameNumber intendedStartFrame) {
StartConfig sc;
sc.intendedStartTime = intendedStartTime;
sc.intendedStartFrame = intendedStartFrame;
return startPlaying(sc);
}
*/
bool CX_SlideBufferPredicatePlayback::startPlaying(StartConfig sc) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!_helper.startPlaying()) {
Instances::Log.error("CX_SlideBufferPredicatePlayback") << "startPlaying(): Could not start playing.";
return false;
}
CX_SlideBuffer::Slide* firstSlide = _helper.getNextSlide(); // There must be a next slide if _helper.startPlaying() returns true
firstSlide->intended.startTime = sc.intendedStartTime;
firstSlide->intended.startFrame = sc.intendedStartFrame;
if (_config.useTimeDurations) {
if (sc.intendedStartTime != CX_Millis::max()) {
_helper.setIntendedStartTimesUsingTimeDurations(sc.intendedStartTime);
}
if (sc.intendedStartFrame != std::numeric_limits<FrameNumber>::max()) {
_helper.setIntendedStartFramesUsingTimeDurations(sc.intendedStartFrame, _config.display->getFramePeriod());
}
} else {
if (sc.intendedStartTime != CX_Millis::max()) {
_helper.setIntendedStartTimesUsingFrameDurations(sc.intendedStartTime, _config.display->getFramePeriod());
}
if (sc.intendedStartFrame != std::numeric_limits<FrameNumber>::max()) {
_helper.setIntendedStartFramesUsingFrameDurations(sc.intendedStartFrame);
}
}
return true;
}
/*
bool CX_SlideBufferPredicatePlayback::startPlaying(void) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_helper.startPlaying();
return true;
}
*/
bool CX_SlideBufferPredicatePlayback::isPlaying(void) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
return _helper.isPlaying();
}
void CX_SlideBufferPredicatePlayback::updatePlayback(void) {
if (!isPlaying()) {
return;
}
updatePlaybackSwapping();
updatePlaybackRendering();
}
void CX_SlideBufferPredicatePlayback::stopPlaying(void) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
_helper.stopPlaying();
}
CX_SlideBufferPredicatePlayback::SlideHelperLP CX_SlideBufferPredicatePlayback::getLockedHelperPointer(void) {
return SlideHelperLP(&_helper, _mutex);
}
CX_SlideBufferPredicatePlayback::SlideBufferLP CX_SlideBufferPredicatePlayback::getSlideBufferLP(void) {
return SlideBufferLP(_config.slideBuffer, _mutex);
}
/*
bool CX_SlideBufferPredicatePlayback::play(void) {
if (!startPlaying()) {
return false;
}
while (isPlaying()) {
updatePlayback();
}
return true;
}
*/
void CX_SlideBufferPredicatePlayback::updatePlaybackSwapping(void) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!isPlaying()) {
return;
}
bool shouldSwap = _config.shouldSwapPredicate && _config.shouldSwapPredicate();
if (shouldSwap) {
_config.display->swapBuffers();
}
bool hasSwapped = shouldSwap || (_config.hasSwappedPredicate && _config.hasSwappedPredicate());
if (hasSwapped) {
Sync::SwapData newest = _config.display->swapData.getLastSwapData();
_helper.bufferSwap(newest.time, newest.unit);
if ((_config.propagateDelays || _helper.currentSlideIsFirstSlide()) && _helper.slideAdvancedOnLastSwap()) {
_helper.setIntendedStartOfRemainingSlidesFromCurrentSlide(true, true);
}
}
_predArgs.hasSwapped = hasSwapped;
}
void CX_SlideBufferPredicatePlayback::updatePlaybackRendering(void) {
std::lock_guard<std::recursive_mutex> lock(_mutex);
if (!isPlaying()) {
return;
}
bool renderNext = _config.renderNextPredicate && _config.renderNextPredicate(_predArgs);
if (renderNext) {
_helper.renderNextSlide();
}
bool reRenderCurrent = _config.reRenderCurrentPredicate && _config.reRenderCurrentPredicate(_predArgs);
if (reRenderCurrent) {
_helper.reRenderCurrentSlide();
}
_helper.updatePlayback(); // Where should this go? Here seems ok
if (_config.deallocateCompletedSlides && _predArgs.hasSwapped) {
CX_SlideBuffer::Slide* previous = _helper.getPreviousSlide();
if (previous) {
previous->deallocateFramebuffer();
}
}
_predArgs.hasSwapped = false;
}
} // namespace CX | 30.917098 | 186 | 0.739372 | [
"render",
"vector"
] |
238c735aa8ea4d42f1e8b7ebcb4324075c69a2d6 | 16,733 | cc | C++ | icl/filesystem_utils.cc | viettrungluu-cr/icl | 906eb067dee0084eee868d6f9d60f2eea393da4f | [
"BSD-3-Clause"
] | null | null | null | icl/filesystem_utils.cc | viettrungluu-cr/icl | 906eb067dee0084eee868d6f9d60f2eea393da4f | [
"BSD-3-Clause"
] | null | null | null | icl/filesystem_utils.cc | viettrungluu-cr/icl | 906eb067dee0084eee868d6f9d60f2eea393da4f | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "icl/filesystem_utils.h"
#include <assert.h>
//FIXME
//#include "base/files/file_util.h"
//#include "base/logging.h"
//#include "base/strings/string_util.h"
//#include "base/strings/utf_string_conversions.h"
//#include "tools/gn/location.h"
//#include "tools/gn/settings.h"
//#include "tools/gn/source_dir.h"
namespace icl {
namespace {
enum DotDisposition {
// The given dot is just part of a filename and is not special.
NOT_A_DIRECTORY,
// The given dot is the current directory.
DIRECTORY_CUR,
// The given dot is the first of a double dot that should take us up one.
DIRECTORY_UP
};
// When we find a dot, this function is called with the character following
// that dot to see what it is. The return value indicates what type this dot is
// (see above). This code handles the case where the dot is at the end of the
// input.
//
// |*consumed_len| will contain the number of characters in the input that
// express what we found.
DotDisposition ClassifyAfterDot(const std::string& path,
size_t after_dot,
size_t* consumed_len) {
if (after_dot == path.size()) {
// Single dot at the end.
*consumed_len = 1;
return DIRECTORY_CUR;
}
if (path[after_dot] == '/') {
// Single dot followed by a slash.
*consumed_len = 2; // Consume the slash
return DIRECTORY_CUR;
}
if (path[after_dot] == '.') {
// Two dots.
if (after_dot + 1 == path.size()) {
// Double dot at the end.
*consumed_len = 2;
return DIRECTORY_UP;
}
if (path[after_dot + 1] == '/') {
// Double dot folowed by a slash.
*consumed_len = 3;
return DIRECTORY_UP;
}
}
// The dots are followed by something else, not a directory.
*consumed_len = 1;
return NOT_A_DIRECTORY;
}
//FIXME
/*
// A wrapper around FilePath.GetComponents that works the way we need. This is
// not super efficient since it does some O(n) transformations on the path. If
// this is called a lot, we might want to optimize.
std::vector<base::FilePath::StringType> GetPathComponents(
const base::FilePath& path) {
std::vector<base::FilePath::StringType> result;
path.GetComponents(&result);
if (result.empty())
return result;
// GetComponents will preserve the "/" at the beginning, which confuses us.
// We don't expect to have relative paths in this function.
// Don't use IsSeparator since we always want to allow backslashes.
if (result[0] == FILE_PATH_LITERAL("/") ||
result[0] == FILE_PATH_LITERAL("\\"))
result.erase(result.begin());
return result;
}
// Provides the equivalent of == for filesystem strings, trying to do
// approximately the right thing with case.
bool FilesystemStringsEqual(const base::FilePath::StringType& a,
const base::FilePath::StringType& b) {
// Assume case-sensitive filesystems on non-Windows.
return a == b;
}
// Helper function for computing subdirectories in the build directory
// corresponding to absolute paths. This will try to resolve the absolute
// path as a source-relative path first, and otherwise it creates a
// special subdirectory for absolute paths to keep them from colliding with
// other generated sources and outputs.
void AppendFixedAbsolutePathSuffix(const BuildSettings* build_settings,
const SourceDir& source_dir,
OutputFile* result) {
const std::string& build_dir = build_settings->build_dir().value();
if (base::StartsWith(source_dir.value(), build_dir,
base::CompareCase::SENSITIVE)) {
size_t build_dir_size = build_dir.size();
result->value().append(&source_dir.value()[build_dir_size],
source_dir.value().size() - build_dir_size);
} else {
result->value().append("ABS_PATH");
const std::string& src_dir_value = source_dir.value();
result->value().append(src_dir_value);
}
}
*/
} // namespace
//FIXME
/*
size_t FindExtensionOffset(const std::string& path) {
for (int i = static_cast<int>(path.size()); i >= 0; i--) {
if (path[i] == '/')
break;
if (path[i] == '.')
return i + 1;
}
return std::string::npos;
}
StringPiece FindExtension(const std::string* path) {
size_t extension_offset = FindExtensionOffset(*path);
if (extension_offset == std::string::npos)
return StringPiece();
return StringPiece(&path->data()[extension_offset],
path->size() - extension_offset);
}
size_t FindFilenameOffset(const std::string& path) {
for (int i = static_cast<int>(path.size()) - 1; i >= 0; i--) {
if (path[i] == '/')
return i + 1;
}
return 0; // No filename found means everything was the filename.
}
StringPiece FindFilename(const std::string* path) {
size_t filename_offset = FindFilenameOffset(*path);
if (filename_offset == 0)
return StringPiece(*path); // Everything is the file name.
return StringPiece(&(*path).data()[filename_offset],
path->size() - filename_offset);
}
StringPiece FindFilenameNoExtension(const std::string* path) {
if (path->empty())
return StringPiece();
size_t filename_offset = FindFilenameOffset(*path);
size_t extension_offset = FindExtensionOffset(*path);
size_t name_len;
if (extension_offset == std::string::npos)
name_len = path->size() - filename_offset;
else
name_len = extension_offset - filename_offset - 1;
return StringPiece(&(*path).data()[filename_offset], name_len);
}
void RemoveFilename(std::string* path) {
path->resize(FindFilenameOffset(*path));
}
StringPiece FindDir(const std::string* path) {
size_t filename_offset = FindFilenameOffset(*path);
if (filename_offset == 0u)
return StringPiece();
return StringPiece(path->data(), filename_offset);
}
StringPiece FindLastDirComponent(const SourceDir& dir) {
const std::string& dir_string = dir.value();
if (dir_string.empty())
return StringPiece();
int cur = static_cast<int>(dir_string.size()) - 1;
DCHECK(dir_string[cur] == '/');
int end = cur;
cur--; // Skip before the last slash.
for (; cur >= 0; cur--) {
if (dir_string[cur] == '/')
return StringPiece(&dir_string[cur + 1], end - cur - 1);
}
return StringPiece(&dir_string[0], end);
}
*/
bool IsPathAbsolute(const StringPiece& path) {
if (path.empty())
return false;
if (path[0] != '/')
return false; // Doesn't begin with a slash, is relative.
// Double forward slash at the beginning means source-relative (we don't
// allow backslashes for denoting this).
if (path.size() > 1 && path[1] == '/')
return false;
return true;
}
bool IsPathSourceAbsolute(const StringPiece& path) {
return (path.size() >= 2 && path[0] == '/' && path[1] == '/');
}
bool MakeAbsolutePathRelativeIfPossible(const StringPiece& source_root,
const StringPiece& path,
std::string* dest) {
assert(IsPathAbsolute(source_root));
assert(IsPathAbsolute(path));
dest->clear();
if (source_root.size() > path.size())
return false; // The source root is longer: the path can never be inside.
// On non-Windows this is easy. Since we know both are absolute, just do a
// prefix check.
if (path.substr(0, source_root.size()) == source_root) {
// The base may or may not have a trailing slash, so skip all slashes from
// the path after our prefix match.
size_t first_after_slash = source_root.size();
while (first_after_slash < path.size() && path[first_after_slash] == '/')
first_after_slash++;
dest->assign("//"); // Result is source root relative.
dest->append(&path.data()[first_after_slash],
path.size() - first_after_slash);
return true;
}
return false;
}
void NormalizePath(std::string* path, const StringPiece& source_root) {
char* pathbuf = path->empty() ? nullptr : &(*path)[0];
// top_index is the first character we can modify in the path. Anything
// before this indicates where the path is relative to.
size_t top_index = 0;
bool is_relative = true;
if (!path->empty() && pathbuf[0] == '/') {
is_relative = false;
if (path->size() > 1 && pathbuf[1] == '/') {
// Two leading slashes, this is a path into the source dir.
top_index = 2;
} else {
// One leading slash, this is a system-absolute path.
top_index = 1;
}
}
size_t dest_i = top_index;
for (size_t src_i = top_index; src_i < path->size(); /* nothing */) {
if (pathbuf[src_i] == '.') {
if (src_i == 0 || pathbuf[src_i - 1] == '/') {
// Slash followed by a dot, see if it's something special.
size_t consumed_len;
switch (ClassifyAfterDot(*path, src_i + 1, &consumed_len)) {
case NOT_A_DIRECTORY:
// Copy the dot to the output, it means nothing special.
pathbuf[dest_i++] = pathbuf[src_i++];
break;
case DIRECTORY_CUR:
// Current directory, just skip the input.
src_i += consumed_len;
break;
case DIRECTORY_UP:
// Back up over previous directory component. If we're already
// at the top, preserve the "..".
if (dest_i > top_index) {
// The previous char was a slash, remove it.
dest_i--;
}
if (dest_i == top_index) {
if (is_relative) {
// We're already at the beginning of a relative input, copy the
// ".." and continue. We need the trailing slash if there was
// one before (otherwise we're at the end of the input).
pathbuf[dest_i++] = '.';
pathbuf[dest_i++] = '.';
if (consumed_len == 3)
pathbuf[dest_i++] = '/';
// This also makes a new "root" that we can't delete by going
// up more levels. Otherwise "../.." would collapse to
// nothing.
top_index = dest_i;
} else if (top_index == 2 && !source_root.empty()) {
// |path| was passed in as a source-absolute path. Prepend
// |source_root| to make |path| absolute. |source_root| must not
// end with a slash unless we are at root.
assert(source_root.size() == 1u ||
source_root[source_root.size() - 1u] != '/');
size_t source_root_len = source_root.size();
path->insert(0, source_root.data(), source_root_len);
// |path| is now absolute, so |top_index| is 1. |dest_i| and
// |src_i| should be incremented to keep the same relative
// position. Comsume the leading "//" by decrementing |dest_i|.
top_index = 1;
pathbuf = &(*path)[0];
dest_i += source_root_len - 2;
src_i += source_root_len;
// Just find the previous slash or the beginning of input.
while (dest_i > 0 && pathbuf[dest_i - 1] != '/')
dest_i--;
}
// Otherwise we're at the beginning of a system-absolute path, or
// a source-absolute path for which we don't know the absolute
// path. Don't allow ".." to go up another level, and just eat it.
} else {
// Just find the previous slash or the beginning of input.
while (dest_i > 0 && pathbuf[dest_i - 1] != '/')
dest_i--;
}
src_i += consumed_len;
}
} else {
// Dot not preceeded by a slash, copy it literally.
pathbuf[dest_i++] = pathbuf[src_i++];
}
} else if (pathbuf[src_i] == '/') {
if (src_i > 0 && pathbuf[src_i - 1] == '/') {
// Two slashes in a row, skip over it.
src_i++;
} else {
// Just one slash, copy it, normalizing to foward slash.
pathbuf[dest_i] = '/';
dest_i++;
src_i++;
}
} else {
// Input nothing special, just copy it.
pathbuf[dest_i++] = pathbuf[src_i++];
}
}
path->resize(dest_i);
}
//FIXME
/*
//FIXME this should be static/anonymized
std::string MakeRelativePath(const std::string& input,
const std::string& dest) {
std::string ret;
// Skip the common prefixes of the source and dest as long as they end in
// a [back]slash.
size_t common_prefix_len = 0;
size_t max_common_length = std::min(input.size(), dest.size());
for (size_t i = common_prefix_len; i < max_common_length; i++) {
if (input[i] == '/' && dest[i] == '/')
common_prefix_len = i + 1;
else if (input[i] != dest[i])
break;
}
// Invert the dest dir starting from the end of the common prefix.
for (size_t i = common_prefix_len; i < dest.size(); i++) {
if (dest[i] == '/')
ret.append("../");
}
// Append any remaining unique input.
ret.append(&input[common_prefix_len], input.size() - common_prefix_len);
// If the result is still empty, the paths are the same.
if (ret.empty())
ret.push_back('.');
return ret;
}
std::string RebasePath(const std::string& input,
const SourceDir& dest_dir,
const StringPiece& source_root) {
std::string ret;
DCHECK(source_root.empty() || !source_root.ends_with("/"));
bool input_is_source_path = (input.size() >= 2 &&
input[0] == '/' && input[1] == '/');
if (!source_root.empty() &&
(!input_is_source_path || !dest_dir.is_source_absolute())) {
std::string input_full;
std::string dest_full;
if (input_is_source_path) {
source_root.AppendToString(&input_full);
input_full.push_back('/');
input_full.append(input, 2, std::string::npos);
} else {
input_full.append(input);
}
if (dest_dir.is_source_absolute()) {
source_root.AppendToString(&dest_full);
dest_full.push_back('/');
dest_full.append(dest_dir.value(), 2, std::string::npos);
} else {
dest_full.append(dest_dir.value());
}
bool remove_slash = false;
if (input_full.empty() || input_full.back() != '/') {
input_full.push_back('/');
remove_slash = true;
}
ret = MakeRelativePath(input_full, dest_full);
if (remove_slash && ret.size() > 1)
ret.resize(ret.size() - 1);
return ret;
}
ret = MakeRelativePath(input, dest_dir.value());
return ret;
}
std::string DirectoryWithNoLastSlash(const SourceDir& dir) {
std::string ret;
if (dir.value().empty()) {
// Just keep input the same.
} else if (dir.value() == "/") {
ret.assign("/.");
} else if (dir.value() == "//") {
ret.assign("//.");
} else {
ret.assign(dir.value());
ret.resize(ret.size() - 1);
}
return ret;
}
SourceDir SourceDirForPath(const base::FilePath& source_root,
const base::FilePath& path) {
std::vector<base::FilePath::StringType> source_comp =
GetPathComponents(source_root);
std::vector<base::FilePath::StringType> path_comp =
GetPathComponents(path);
// See if path is inside the source root by looking for each of source root's
// components at the beginning of path.
bool is_inside_source;
if (path_comp.size() < source_comp.size() || source_root.empty()) {
// Too small to fit.
is_inside_source = false;
} else {
is_inside_source = true;
for (size_t i = 0; i < source_comp.size(); i++) {
if (!FilesystemStringsEqual(source_comp[i], path_comp[i])) {
is_inside_source = false;
break;
}
}
}
std::string result_str;
size_t initial_path_comp_to_use;
if (is_inside_source) {
// Construct a source-relative path beginning in // and skip all of the
// shared directories.
result_str = "//";
initial_path_comp_to_use = source_comp.size();
} else {
// Not inside source code, construct a system-absolute path.
result_str = "/";
initial_path_comp_to_use = 0;
}
for (size_t i = initial_path_comp_to_use; i < path_comp.size(); i++) {
result_str.append(FilePathToUTF8(path_comp[i]));
result_str.push_back('/');
}
return SourceDir(result_str);
}
SourceDir SourceDirForCurrentDirectory(const base::FilePath& source_root) {
base::FilePath cd;
base::GetCurrentDirectory(&cd);
return SourceDirForPath(source_root, cd);
}
*/
} // namespace icl
| 32.874263 | 80 | 0.61053 | [
"vector"
] |
2399878e5dbaae398bb435819bb148908bab5b46 | 1,766 | cpp | C++ | Sliding window/Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold.cpp | HectorTa1989/LeetCode-Cpp | 506c92d5b0f3084e6a5099b99a3cffdd327211d9 | [
"MIT"
] | null | null | null | Sliding window/Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold.cpp | HectorTa1989/LeetCode-Cpp | 506c92d5b0f3084e6a5099b99a3cffdd327211d9 | [
"MIT"
] | null | null | null | Sliding window/Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold.cpp | HectorTa1989/LeetCode-Cpp | 506c92d5b0f3084e6a5099b99a3cffdd327211d9 | [
"MIT"
] | null | null | null | /*Given an array of integers arr and two integers k and threshold.
Return the number of sub-arrays of size k and average greater than or equal to threshold.
Example 1:
Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
Output: 3
Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively.
All other sub-arrays of size 3 have averages less than 4 (the threshold).
Example 2:
Input: arr = [1,1,1,1,1], k = 1, threshold = 0
Output: 5 */
class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
double sum = 0;
double div = k;
int n = arr.size();
for(int i = 0; i < k; i++){
sum += arr[i];
}
int ret = 0;
for(int i = 0, j = k; j < n; i ++, j++){
if(sum / div >= threshold ){
ret++;
}
sum -= arr[i];
sum += arr[j];
}
if(sum / div >= threshold ){
ret++;
}
return ret;
}
};
//
class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
threshold *= k;
int sum = accumulate(arr.begin(), arr.begin() + k, 0);
int result = (sum >= threshold);
for (int i = k; i < arr.size(); ++i) {
sum += arr[i] - arr[i-k];
result += (sum >= threshold);
}
return result;
}
};
//https://zxi.mytechroad.com/blog/sliding-window/leetcode-1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/
class Solution {
public:
int numOfSubarrays(vector<int>& arr, int k, int threshold) {
int ans = 0;
int sum = 0;
for (int i = 0; i < arr.size(); ++i) {
sum += arr[i];
if (i + 1 >= k) {
if (threshold * k <= sum) ++ans;
sum -= arr[i + 1 - k];
}
}
return ans;
}
}; | 26.757576 | 141 | 0.547565 | [
"vector"
] |
239b5876cd1078afb59a7c9b3fe7f239236b48f4 | 1,179 | cpp | C++ | gui/widgets/checkbox.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | 6 | 2021-11-12T15:03:53.000Z | 2022-01-28T18:30:33.000Z | gui/widgets/checkbox.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | null | null | null | gui/widgets/checkbox.cpp | goossens/ObjectTalk | ca1d4f558b5ad2459b376102744d52c6283ec108 | [
"MIT"
] | null | null | null | // ObjectTalk Scripting Language
// Copyright (c) 1993-2022 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include "ot/function.h"
#include "ot/vm.h"
#include "checkbox.h"
//
// OtCheckboxClass::init
//
void OtCheckboxClass::init(const std::string& l, bool chk, OtObject cb) {
// save label and callback
label = l;
checked = chk;
callback = cb;
}
//
// OtCheckboxClass::render
//
void OtCheckboxClass::render() {
if (ImGui::Checkbox(label.c_str(), &checked)) {
OtVM::callMemberFunction(callback, "__call__", OtObjectCreate(checked));
}
}
//
// OtCheckboxClass::getMeta
//
OtType OtCheckboxClass::getMeta() {
static OtType type = nullptr;
if (!type) {
type = OtTypeClass::create<OtCheckboxClass>("Checkbox", OtWidgetClass::getMeta());
type->set("__init__", OtFunctionClass::create(&OtCheckboxClass::init));
}
return type;
}
//
// OtCheckboxClass::create
//
OtCheckbox OtCheckboxClass::create() {
OtCheckbox checkbox = std::make_shared<OtCheckboxClass>();
checkbox->setType(getMeta());
return checkbox;
}
| 17.863636 | 84 | 0.695505 | [
"render"
] |
239b941af81b51c857ef167504dd685d375d475a | 17,122 | cpp | C++ | src/apGLTextureMiplevelData.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | 1 | 2017-01-28T14:12:29.000Z | 2017-01-28T14:12:29.000Z | src/apGLTextureMiplevelData.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | null | null | null | src/apGLTextureMiplevelData.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | 2 | 2016-09-21T12:28:23.000Z | 2019-11-01T23:07:02.000Z | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file apGLTextureMiplevelData.cpp
///
//==================================================================================
// ----------------------------- apGLTextureMiplevelData.cpp ------------------------------
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTOSWrappers/Include/osChannel.h>
// Local:
#include <AMDTAPIClasses/Include/apGLTextureMiplevelData.h>
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::apGLTextureMiplevelData
// Description: Constructor
// Return Val:
// Author: AMD Developer Tools Team
// Date: 19/11/2008
// ---------------------------------------------------------------------------
apGLTextureMiplevelData::apGLTextureMiplevelData(): _textureName(0), _textureType(AP_UNKNOWN_TEXTURE_TYPE),
_fboName(0), _requestedInternalPixelFormat(GL_NONE), _texelDataFormat(OA_TEXEL_FORMAT_UNKNOWN), _dataType(OA_UNKNOWN_DATA_TYPE),
_width(0), _height(0), _depth(0), _borderWidth(0), _minLevel(0), _maxLevel(1000), _pbufferName(-1),
_pbufferStaticBuffer(AP_DISPLAY_BUFFER_UNKNOWN), _bufferName(0), _bufferInternalFormat(GL_NONE),
_openCLImageIndex(-1), _openCLImageName(-1), _openCLSpyID(-1)
{
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::readSelfFromChannel
// Description:
// Arguments: osChannel& ipcChannel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 19/11/2008
// Note: The complement to this function is apGLTexture::writeThumbnailDataToChannel
// ---------------------------------------------------------------------------
bool apGLTextureMiplevelData::readSelfFromChannel(osChannel& ipcChannel)
{
bool retVal = true;
// Read the texture attributes into the channel:
gtUInt32 paramAsUInt32 = 0;
ipcChannel >> paramAsUInt32;
_textureName = (GLuint)paramAsUInt32;
gtInt32 paramAsInt32 = 0;
ipcChannel >> paramAsInt32;
_textureType = (apTextureType)paramAsInt32;
ipcChannel >> paramAsUInt32;
_fboName = (GLuint)paramAsUInt32;
ipcChannel >> paramAsInt32;
_requestedInternalPixelFormat = (GLenum)paramAsInt32;
ipcChannel >> paramAsUInt32;
_texelDataFormat = (oaTexelDataFormat)paramAsUInt32;
ipcChannel >> paramAsUInt32;
_dataType = (oaDataType)paramAsUInt32;
// Read texture dimensions:
gtUInt64 paramAsUInt64 = 0;
ipcChannel >> paramAsUInt64;
_width = (GLsizei)paramAsUInt64;
ipcChannel >> paramAsUInt64;
_height = (GLsizei)paramAsUInt64;
ipcChannel >> paramAsUInt64;
_depth = (GLsizei)paramAsUInt64;
ipcChannel >> paramAsUInt64;
_borderWidth = (GLint)paramAsUInt64;
// Read amount of mip levels:
ipcChannel >> paramAsUInt32;
_minLevel = (GLuint)paramAsUInt32;
ipcChannel >> paramAsUInt32;
_maxLevel = (GLuint)paramAsUInt32;
// Read pbuffer details:
ipcChannel >> paramAsInt32;
_pbufferName = (int)paramAsInt32;
ipcChannel >> paramAsInt32;
_pbufferStaticBuffer = (apDisplayBuffer)paramAsInt32;
// Read texture buffer details:
ipcChannel >> paramAsUInt32;
_bufferName = (GLuint)paramAsUInt32;
ipcChannel >> paramAsInt32;
_bufferInternalFormat = (GLenum)paramAsInt32;
ipcChannel >> paramAsInt32;
_openCLImageIndex = paramAsInt32;
ipcChannel >> paramAsInt32;
_openCLImageName = paramAsInt32;
ipcChannel >> paramAsInt32;
_openCLSpyID = paramAsInt32;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::~apGLTextureMiplevelData
// Description: Destructor
// Return Val:
// Author: AMD Developer Tools Team
// Date: 19/11/2008
// ---------------------------------------------------------------------------
apGLTextureMiplevelData::~apGLTextureMiplevelData()
{
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::type
// Description: Returns my transferable object type.
// Author: AMD Developer Tools Team
// Date: 19/11/2008
// ---------------------------------------------------------------------------
osTransferableObjectType apGLTextureMiplevelData::type() const
{
return OS_TOBJ_ID_GL_TEXTURE_THUMBNAIL_DATA;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::amountOfTextureDataFiles
// Description:
// Returns the amount of texture data file paths according to the texture type.
// Notice that some of the paths may be empty.
// Author: AMD Developer Tools Team
// Date: 19/11/2008
// ---------------------------------------------------------------------------
int apGLTextureMiplevelData::amountOfTextureDataFiles() const
{
int retVal = 1;
if (_textureType == AP_CUBE_MAP_TEXTURE)
{
retVal = 6;
}
return retVal;
};
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::getDimensions
// Description: Get the texture thumbnail data dimensions
// Arguments: GLsizei& width
// GLsizei& height
// GLsizei& depth
// GLsizei& borderWidth
// Return Val: void
// Author: AMD Developer Tools Team
// Date: 20/11/2008
// ---------------------------------------------------------------------------
void apGLTextureMiplevelData::getDimensions(GLsizei& width, GLsizei& height, GLsizei& depth, GLsizei& borderWidth)const
{
width = _width;
height = _height;
depth = _depth;
borderWidth = _borderWidth;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::writeSelfIntoChannel
// Description: Thus function should not be called.
// Arguments: osChannel& ipcChannel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 20/11/2008
// ---------------------------------------------------------------------------
bool apGLTextureMiplevelData::writeSelfIntoChannel(osChannel& ipcChannel) const
{
(void)(ipcChannel); // unused
GT_ASSERT(false);
return false;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::getPBufferName
// Description: Returns the id of the pbuffer attached with CGLTexImagePBuffer
// Author: AMD Developer Tools Team
// Date: 22/12/2009
// ---------------------------------------------------------------------------
int apGLTextureMiplevelData::getPBufferName() const
{
return _pbufferName;
}
// ---------------------------------------------------------------------------
// Name: apGLTexture::setPBufferName
// Description: Sets the id of the pbuffer attached with CGLTexImagePBuffer
// Author: AMD Developer Tools Team
// Date: 22/12/2009
// ---------------------------------------------------------------------------
void apGLTextureMiplevelData::setPBufferName(int pbuffer)
{
_pbufferName = pbuffer;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::getPBufferStaticBuffer
// Description: Returns the source static buffer (which buffer is used to fill
// the texture) - according to the CGL spec, should only be
// GL_FRONT or GL_BACK.
// Author: AMD Developer Tools Team
// Date: 22/12/2009
// ---------------------------------------------------------------------------
apDisplayBuffer apGLTextureMiplevelData::getPBufferStaticBuffer() const
{
return _pbufferStaticBuffer;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::setPBufferStaticBuffer
// Description:
// Arguments: apDisplayBuffer staticBuffer
// Return Val: void
// Author: AMD Developer Tools Team
// Date: 22/12/2009
// ---------------------------------------------------------------------------
void apGLTextureMiplevelData::setPBufferStaticBuffer(apDisplayBuffer staticBuffer)
{
_pbufferStaticBuffer = staticBuffer;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureData::apGLTextureData
// Description: Constructor
// Return Val:
// Author: AMD Developer Tools Team
// Date: 16/5/2010
// ---------------------------------------------------------------------------
apGLTextureData::apGLTextureData(): _textureName(0), _textureType(AP_UNKNOWN_TEXTURE_TYPE), _minLevel(0), _maxLevel(1000),
_openCLImageIndex(-1), _openCLImageName(-1), _openCLSpyID(-1)
{
}
// ---------------------------------------------------------------------------
// Name: apGLTextureData::readSelfFromChannel
// Description:
// Arguments: osChannel& ipcChannel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 16/5/2010
// Note: The complement to this function is apGLTexture::writeTextureDataToChannel
// ---------------------------------------------------------------------------
bool apGLTextureData::readSelfFromChannel(osChannel& ipcChannel)
{
bool retVal = true;
// Read the texture attributes into the channel:
gtUInt32 textureNameAsUInt32 = 0;
ipcChannel >> textureNameAsUInt32;
_textureName = (GLuint)textureNameAsUInt32;
gtInt32 varAsInt32 = 0;
ipcChannel >> varAsInt32;
_textureType = (apTextureType)varAsInt32;
// Read amount of mip levels:
gtUInt32 minLevelAsUInt32 = 0;
ipcChannel >> minLevelAsUInt32;
_minLevel = (GLuint)minLevelAsUInt32;
gtUInt32 maxLevelAsUInt32 = 0;
ipcChannel >> maxLevelAsUInt32;
_maxLevel = (GLuint)maxLevelAsUInt32;
// Read the OpenCL share information:
ipcChannel >> varAsInt32;
_openCLImageIndex = varAsInt32;
ipcChannel >> varAsInt32;
_openCLImageName = varAsInt32;
ipcChannel >> varAsInt32;
_openCLSpyID = varAsInt32;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureData::~apGLTextureData
// Description: Destructor
// Return Val:
// Author: AMD Developer Tools Team
// Date: 16/5/2010
// ---------------------------------------------------------------------------
apGLTextureData::~apGLTextureData()
{
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::type
// Description: Returns my transferable object type.
// Author: AMD Developer Tools Team
// Date: 16/5/2010
// ---------------------------------------------------------------------------
osTransferableObjectType apGLTextureData::type() const
{
return OS_TOBJ_ID_GL_TEXTURE_DATA;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMiplevelData::writeSelfIntoChannel
// Description: Thus function should not be called.
// Arguments: osChannel& ipcChannel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 16/5/2010
// ---------------------------------------------------------------------------
bool apGLTextureData::writeSelfIntoChannel(osChannel& ipcChannel) const
{
(void)(ipcChannel); // unused
GT_ASSERT(false);
return false;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMemoryData::apGLTextureMemoryData
// Description: Constructor
// Return Val:
// Author: AMD Developer Tools Team
// Date: 24/5/2010
// ---------------------------------------------------------------------------
apGLTextureMemoryData::apGLTextureMemoryData():
_textureName(0), _textureType(AP_UNKNOWN_TEXTURE_TYPE), _minLevel(0), _maxLevel(1000),
_width(0), _height(0), _depth(0), _memorySize(0), _isMemoryEstimated(false), _isMemoryCalculated(false),
_bufferInternalFormat(GL_NONE), _usedInternalPixelFormat(GL_NONE), _requestedInternalPixelFormat(GL_NONE),
_mipmapType(AP_MIPMAP_NONE), _openCLImageIndex(-1), _openCLImageName(-1), _openCLSpyID(-1)
{
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMemoryData::readSelfFromChannel
// Description:
// Arguments: osChannel& ipcChannel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 24/5/2010
// Note: The complement to this function is apGLTexture::writeTextureMemoryDataToChannel
// ---------------------------------------------------------------------------
bool apGLTextureMemoryData::readSelfFromChannel(osChannel& ipcChannel)
{
bool retVal = true;
// Read the texture attributes into the channel:
gtUInt32 textureNameAsUInt32 = 0;
ipcChannel >> textureNameAsUInt32;
_textureName = (GLuint)textureNameAsUInt32;
gtInt32 textureTypeAsInt32 = 0;
ipcChannel >> textureTypeAsInt32;
_textureType = (apTextureType)textureTypeAsInt32;
// Read amount of mip levels:
gtUInt32 minLevelAsUInt32 = 0;
ipcChannel >> minLevelAsUInt32;
_minLevel = (GLuint)minLevelAsUInt32;
gtUInt32 maxLevelAsUInt32 = 0;
ipcChannel >> maxLevelAsUInt32;
_maxLevel = (GLuint)maxLevelAsUInt32;
gtUInt64 paramAsUInt64 = 0;
ipcChannel >> paramAsUInt64;
_width = (GLsizei)paramAsUInt64;
ipcChannel >> paramAsUInt64;
_height = (GLsizei)paramAsUInt64;
ipcChannel >> paramAsUInt64;
_depth = (GLsizei)paramAsUInt64;
ipcChannel >> paramAsUInt64;
_memorySize = (GLsizei)paramAsUInt64;
ipcChannel >> _isMemoryEstimated;
ipcChannel >> _isMemoryCalculated;
gtInt32 paramAsInt32 = 0;
ipcChannel >> paramAsInt32;
_bufferInternalFormat = (GLenum)paramAsInt32;
ipcChannel >> paramAsInt32;
_usedInternalPixelFormat = (GLenum)paramAsInt32;
ipcChannel >> paramAsInt32;
_requestedInternalPixelFormat = (GLenum)paramAsInt32;
ipcChannel >> paramAsInt32;
_mipmapType = (apTextureMipMapType)paramAsInt32;
ipcChannel >> paramAsInt32;
_openCLImageIndex = paramAsInt32;
ipcChannel >> paramAsInt32;
_openCLImageName = paramAsInt32;
ipcChannel >> paramAsInt32;
_openCLSpyID = paramAsInt32;
return retVal;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMemoryData::~apGLTextureMemoryData
// Description: Destructor
// Return Val:
// Author: AMD Developer Tools Team
// Date: 24/5/2010
// ---------------------------------------------------------------------------
apGLTextureMemoryData::~apGLTextureMemoryData()
{
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMemoryData::type
// Description: Returns my transferable object type.
// Author: AMD Developer Tools Team
// Date: 24/5/2010
// ---------------------------------------------------------------------------
osTransferableObjectType apGLTextureMemoryData::type() const
{
return OS_TOBJ_ID_GL_TEXTURE_MEMORY_DATA;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMemoryData::writeSelfIntoChannel
// Description: Thus function should not be called.
// Arguments: osChannel& ipcChannel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 24/5/2010
// ---------------------------------------------------------------------------
bool apGLTextureMemoryData::writeSelfIntoChannel(osChannel& ipcChannel) const
{
(void)(ipcChannel); // unused
GT_ASSERT(false);
return false;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMemoryData::getDimensions
// Description:
// Arguments: GLsizei& width
// GLsizei& height
// GLsizei& depth
// Return Val: void
// Author: AMD Developer Tools Team
// Date: 24/5/2010
// ---------------------------------------------------------------------------
void apGLTextureMemoryData::getDimensions(GLsizei& width, GLsizei& height, GLsizei& depth) const
{
width = _width;
height = _height;
depth = _depth;
}
// ---------------------------------------------------------------------------
// Name: apGLTextureMemoryData::getMemorySize
// Description:
// Arguments: gtSize_t& memorySize
// bool& isMemorySizeEstimated
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 24/5/2010
// ---------------------------------------------------------------------------
bool apGLTextureMemoryData::getMemorySize(gtSize_t& memorySize, bool& isMemorySizeEstimated) const
{
memorySize = _memorySize;
isMemorySizeEstimated = _isMemoryEstimated;
return _isMemoryCalculated;
}
| 34.10757 | 132 | 0.556127 | [
"object"
] |
239d0fe6dcffbe681a3967f4ec9d521e2bc5a250 | 19,028 | cpp | C++ | moos-ivp/ivp/src/lib_ivpbuild/OF_Reflector.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/lib_ivpbuild/OF_Reflector.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | moos-ivp/ivp/src/lib_ivpbuild/OF_Reflector.cpp | EasternEdgeRobotics/2018 | 24df2fe56fa6d172ba3c34c1a97f249dbd796787 | [
"MIT"
] | null | null | null | /*****************************************************************/
/* NAME: Michael Benjamin */
/* ORGN: Dept of Mechanical Eng / CSAIL, MIT Cambridge MA */
/* FILE: OF_Reflector.cpp */
/* DATE: Aug 29th 2005 (derived from OFR_AOF built long ago) */
/* */
/* This file is part of IvP Helm Core Libs */
/* */
/* IvP Helm Core Libs is free software: you can redistribute it */
/* and/or modify it under the terms of the Lesser GNU General */
/* Public License as published by the Free Software Foundation, */
/* either version 3 of the License, or (at your option) any */
/* later version. */
/* */
/* IvP Helm Core Libs 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 Lesser GNU General Public License for more */
/* details. */
/* */
/* You should have received a copy of the Lesser GNU General */
/* Public License along with MOOS-IvP. If not, see */
/* <http://www.gnu.org/licenses/>. */
/*****************************************************************/
#include <iostream>
#include <cstdlib>
#include "OF_Reflector.h"
#include "BuildUtils.h"
#include "IvPFunction.h"
#include "Regressor.h"
#include "RT_Uniform.h"
#include "RT_Smart.h"
#include "RT_Directed.h"
#include "RT_AutoPeak.h"
#include "MBUtils.h"
using namespace std;
//-------------------------------------------------------------
// Procedure: Constructor
// Notes: g_degree=1 makes piecewise linear functions.
// g_degree=0 makes piecewise constant functions.
// g_aof is the underlying function to be approximated.
OF_Reflector::OF_Reflector(const AOF *g_aof, int g_degree)
{
m_aof = g_aof;
m_pdmap = 0;
m_regressor = new Regressor(m_aof, g_degree);
if(m_aof)
m_domain = m_aof->getDomain();
m_rt_uniform = new RT_Uniform(m_regressor);
m_rt_smart = new RT_Smart(m_regressor);
m_rt_directed = new RT_Directed(m_regressor);
m_rt_autopeak = new RT_AutoPeak(m_regressor);
m_uniform_amount = 1;
m_smart_amount = 0;
m_smart_percent = 0;
m_smart_thresh = 0;
m_auto_peak = false;
m_qlevels = 8;
}
//-------------------------------------------------------------
// Procedure: Destructor
OF_Reflector::~OF_Reflector()
{
// The PDMap is typically null in normal operation, after a
// call to extractOF() is made. But if for some reason the
// user used the reflector to create a PDMap, but then never
// extracted it, the memory is free here.
if(m_pdmap)
delete(m_pdmap);
delete(m_regressor);
delete(m_rt_uniform);
delete(m_rt_smart);
delete(m_rt_directed);
delete(m_rt_autopeak);
}
//-------------------------------------------------------------
// Procedure: extractOF
// Purpose: Build and return for the caller an IvP objective
// function built from the pdmap. Once this is done
// the caller "owns" the PDMap. The reason for this is
// that the pdmap is assumed to be too expensive to
// replicate for certain applications.
IvPFunction *OF_Reflector::extractOF(bool normalize)
{
// Check for a NULL pdmap. This may be the case if the user made
// an error in parameterizing the reflector, and a failed create
// ensued and the user did not notice.
if(!m_pdmap)
return(0);
// By default, the pdap is normalized before handing over
if(normalize)
m_pdmap->normalize(0.0, 100.0);
// The pdmap now "belongs" to the IvPFunction, given to the caller.
// The pdmap memory from the heap now belongs to the caller
IvPFunction *new_ipf = new IvPFunction(m_pdmap);
m_pdmap = 0;
return(new_ipf);
}
//-------------------------------------------------------------
// Procedure: clearPDMap()
void OF_Reflector::clearPDMap()
{
if(m_pdmap) {
delete(m_pdmap);
m_pdmap = 0;
}
}
//-------------------------------------------------------------
// Procedure: create
// Note: Returns the number of pieces made in the new PDMap.
// A return of zero indicates an error.
int OF_Reflector::create(const string params)
{
if(!setParam(params))
return(0);
else
return(create());
}
//-------------------------------------------------------------
// Procedure: setParam
bool OF_Reflector::setParam(string str)
{
bool ok = true;
str = tolower(stripBlankEnds(str));
vector<string> svector = parseString(str, '#');
int vsize = svector.size();
if(vsize == 0) {
addWarning("setParam(string) Empty list of param/value pairs");
return(false);
}
for(int i=0; i<vsize; i++) {
svector[i] = stripBlankEnds(svector[i]);
vector<string> tvector = parseString(svector[i], '=');
if(tvector.size() == 2) {
string param = tvector[0];
string value = tvector[1];
ok = ok && setParam(param, value);
}
}
return(ok);
}
//-------------------------------------------------------------
// Procedure: setParam
// Note: Care must be taken to add a refine_region and refine_piece
// only in pairs. A refine_region must be added first, followed
// by a refine_piece. A refine_region can only be added when
// the count of the two vectors are equal, and a refine_piece
// can be added only if there is currently one more
// refine_region than the number of refine_pieces. If there is
// a syntax error on adding a refine_region, false is simply
// returned. If there is a syntax error on the refine-piece add,
// a single refine-region is popped from its vector.
//
// Note: The above strategy assumes that if the creation process is
// commenced with one more refine_region than refine_piece,
// then the extra refine_region is simply disregarded.
bool OF_Reflector::setParam(string param, string value)
{
param = tolower(stripBlankEnds(param));
value = tolower(stripBlankEnds(value));
if(param == "strict_range") {
if((value != "true") && (value != "false")) {
addWarning("strict_range value must be true/false");
return(false);
}
if(m_regressor)
m_regressor->setStrictRange(value=="true");
}
else if((param=="uniform_amount")||(param=="uniform_amt")) {
int uniform_amount = atoi(value.c_str());
if(!isNumber(value)) {
addWarning(param + " value must be numerical");
return(false);
}
if(!isNumber(value) || (uniform_amount < 1)) {
addWarning(param + " value must be >= 1");
return(false);
}
m_uniform_amount = uniform_amount;
}
else if(param=="queue_levels") {
int queue_levels = atoi(value.c_str());
if(!isNumber(value)) {
addWarning(param + " value must be numerical");
return(false);
}
if(!isNumber(value) || (queue_levels < 1)) {
addWarning(param + " value must be >= 1");
return(false);
}
m_qlevels = queue_levels;
}
else if((param=="uniform_piece")||(param=="uniform_box")) {
IvPBox foo = stringToPointBox(value, m_domain, ',', ':');
m_uniform_piece = foo;
if(m_uniform_piece.null()) {
addWarning(param + " value is ill-defined");
return(false);
}
}
else if(param=="uniform_grid") {
m_uniform_grid = stringToPointBox(value, m_domain, ',', ':');
if(m_uniform_grid.null()) {
addWarning(param + " value is ill-defined");
return(false);
}
}
else if((param=="refine_region")||(param=="focus_region")) {
if(m_refine_regions.size() != m_refine_pieces.size()) {
addWarning(param + " and refine_piece must be added in pairs");
return(false);
}
IvPBox refine_region = stringToRegionBox(value, m_domain, ',', ':');
if(refine_region.null()) {
//cout << "Bad Region Box" << endl;
addWarning(param + " value is ill-defined");
return(false);
}
else
m_refine_regions.push_back(refine_region);
}
else if((param=="refine_piece")||(param=="focus_box")) {
if((m_refine_regions.size() - m_refine_pieces.size()) != 1) {
addWarning(param + " and refine_region must be added in pairs");
return(false);
}
IvPBox refine_piece = stringToPointBox(value, m_domain, ',', ':');
if(refine_piece.null()) {
m_refine_regions.pop_back();
addWarning(param + " value is ill-defined");
return(false);
}
m_refine_pieces.push_back(refine_piece);
}
else if(param == "refine_clear") {
m_refine_regions.clear();
m_refine_pieces.clear();
}
else if(param == "refine_point") {
IvPBox refine_point = stringToPointBox(value, m_domain, ',', ':');
if(refine_point.null() || !refine_point.isPtBox()) {
addWarning(param + " value is ill-defined");
return(false);
}
m_refine_points.push_back(refine_point);
}
else if((param=="smart_amount")||(param=="priority_amt")) {
int smart_amount = atoi(value.c_str());
if(!isNumber(value)) {
addWarning(param + " value must be numerical");
return(false);
}
if(smart_amount < 0) {
addWarning(param + " value must be >= 0");
return(false);
}
m_smart_amount = smart_amount;
}
else if(param == "smart_percent") {
int smart_percent = atoi(value.c_str());
if(!isNumber(value)) {
addWarning("smart_percent value must be numerical");
return(false);
}
if(smart_percent < 0) {
addWarning("smart_percent value must be >= 0");
return(false);
}
m_smart_percent = smart_percent;
}
else if((param=="smart_thresh")||(param=="priority_thresh")) {
double smart_thresh = atof(value.c_str());
if(!isNumber(value)) {
addWarning(param + " value must be numerical");
return(false);
}
if(smart_thresh < 0) {
addWarning(param + " value must be >= 0");
return(false);
}
m_smart_thresh = smart_thresh;
}
else if(param == "auto_peak") {
if((value != "true") && (value != "false")) {
addWarning("auto_peak value must be true/false");
return(false);
}
m_auto_peak = (value == "true");
}
else if(param == "auto_peak_max_pcs") {
if(!isNumber(value)) {
addWarning("auto_peak_max_pcs value must be numerical");
return(false);
}
int auto_peak_max_pcs = atoi(value.c_str());
if(auto_peak_max_pcs <= 0) {
addWarning("auto_peak_max_pcs value must be > 0");
return(false);
}
m_auto_peak_max_pcs = auto_peak_max_pcs;
}
else {
addWarning(param + ": undefined parameter");
return(false);
}
return(true);
}
//-------------------------------------------------------------
// Procedure: setParam
bool OF_Reflector::setParam(string param, double value)
{
param = tolower(stripBlankEnds(param));
if((param=="uniform_amount")||(param=="uniform_amt")) {
if(value < 1) {
addWarning(param + " value must be >= 1");
return(false);
}
m_uniform_amount = (int)(value);
}
else if((param=="smart_amount")||(param=="priority_amt")) {
if(value < 0) {
addWarning(param + " value must be >= 0");
return(false);
}
m_smart_amount = (int)(value);
}
else if(param == "smart_percent") {
if(value < 0) {
addWarning(param + " value must be >= 0");
return(false);
}
m_smart_percent = (int)(value);
}
else if(param=="smart_thresh") {
if(value < 0) {
addWarning(param + " value must be >= 0");
return(false);
}
m_smart_thresh = value;
}
else {
addWarning(param + ": undefined parameter");
return(false);
}
return(true);
}
//-------------------------------------------------------------
// Procedure: setParam
// Note: Care must be taken to add a refine_region and refine_piece
// only in pairs. A refine_region must be added first, followed
// by a refine_piece. A refine_region can only be added when
// the count of the two vectors are equal, and a refine_piece
// can be added only if there is currently one more
// refine_region than the number of refine_pieces. If there is
// a syntax error on adding a refine_region, false is simply
// returned. If there is a syntax error on the refine-piece add,
// a single refine-region is popped from its vector.
//
// Note: The above strategy assumes that if the creation process is
// commenced with one more refine_region than refine_piece,
// then the extra refine_region is simply disregarded.
bool OF_Reflector::setParam(string param, IvPBox gbox)
{
param = tolower(stripBlankEnds(param));
if((param=="uniform_piece")||(param=="uniform_box")) {
m_uniform_piece = gbox;
if(m_uniform_piece.null()) {
addWarning(param + " box value is ill-defined");
return(false);
}
}
else if(param=="uniform_grid") {
m_uniform_grid = gbox;
if(m_uniform_grid.null()) {
addWarning(param + " box value is ill-defined");
return(false);
}
}
else if((param=="refine_region")||(param=="focus_region")) {
if(m_refine_regions.size() != m_refine_pieces.size()) {
addWarning(param + " and refine_piece must be added in pairs");
return(false);
}
if(gbox.null()) {
addWarning(param + " box value is ill-defined");
return(false);
}
else
m_refine_regions.push_back(gbox);
}
else if((param=="refine_piece")||(param=="focus_box")) {
if((m_refine_regions.size() - m_refine_pieces.size()) != 1) {
addWarning(param + " and refine_region must be added in pairs");
return(false);
}
if(gbox.null()) {
m_refine_regions.pop_back();
addWarning(param + " box value is ill-defined");
return(false);
}
m_refine_pieces.push_back(gbox);
}
else if(param == "refine_point") {
IvPBox refine_point = gbox;
if(refine_point.null() || !refine_point.isPtBox()) {
addWarning(param + " box value is ill-defined");
return(false);
}
m_refine_points.push_back(refine_point);
}
else {
addWarning(param + ": undefined parameter");
return(false);
}
return(true);
}
//-------------------------------------------------------------
// Procedure: create
int OF_Reflector::create(int unif_amt, int smart_amt, double smart_thresh)
{
clearPDMap();
if(!m_aof)
return(0);
if(unif_amt >= 0)
m_uniform_amount = unif_amt;
if(smart_amt >= 0)
m_smart_amount = smart_amt;
if(smart_thresh >= 0)
m_smart_thresh = smart_thresh;
// ============= Stage 1 - Uniform Pieces ======================
// Make the initial uniform function based on the specified piece.
// If no piece specified, base it on specified amount, default=1.
int qlevels = 0;
if((m_smart_amount > 0) || (m_smart_percent > 0))
qlevels = m_qlevels;
PQueue pqueue(qlevels);
m_pqueue = pqueue;
// Make a local copy of the uniform piece member variable
IvPBox uniform_piece = m_uniform_piece;
if(m_uniform_piece.null())
uniform_piece = genUnifBox(m_domain, m_uniform_amount);
// Now check that our local copy, however made, is not null
if(!uniform_piece.null() && !m_uniform_grid.null())
m_pdmap = m_rt_uniform->create(&uniform_piece, &m_uniform_grid, m_pqueue);
else if(!uniform_piece.null())
m_pdmap = m_rt_uniform->create(&uniform_piece, 0, m_pqueue);
m_uniform_piece_str = "count:";
if(m_pdmap)
m_uniform_piece_str += intToString(m_pdmap->size());
else
m_uniform_piece_str += "0";
if((int)(m_domain.size()) == uniform_piece.getDim()) {
unsigned int dsize = m_domain.size();
for(unsigned int i=0; i<dsize; i++) {
int len = uniform_piece.pt(i,1) + 1;
m_uniform_piece_str += ", ";
m_uniform_piece_str += (m_domain.getVarName(i) + ":");
m_uniform_piece_str += intToString(len);
}
}
if(!m_pdmap) // This should never happen, but check anyway.
return(0);
// ============= Stage 2 - Directed Refinement ================
int pcs_before_dref = m_pdmap->size();
int i;
int reg_size = m_refine_regions.size();
int pce_size = m_refine_pieces.size();
if(reg_size > pce_size)
reg_size = pce_size;
for(i=0; i<reg_size; i++) {
IvPBox region = m_refine_regions[i];
IvPBox resbox = m_refine_pieces[i];
PDMap *new_pdmap = m_rt_directed->create(m_pdmap, region,
resbox, m_pqueue);
if(new_pdmap != 0)
m_pdmap = new_pdmap;
}
int pcs_after_dref = m_pdmap->size();
int pcs_made_dref = pcs_after_dref - pcs_before_dref;
m_uniform_piece_str += ", dref_pcs:";
m_uniform_piece_str += (intToString(pcs_made_dref) + ", ");
if(!m_pdmap) // This should never happen, but check anyway.
return(0);
// ============= Stage 3 - Smart Refinement ================
int pcs_before_sref = m_pdmap->size();
if(!m_pqueue.null()) {
if((m_smart_amount > 0) || (m_smart_percent > 0)) {
int psize = m_pdmap->size();
int use_amt = m_smart_amount;
int pct_amt = (psize * m_smart_percent) / 100;
if(pct_amt > m_smart_amount)
use_amt = pct_amt;
PDMap *new_pdmap = m_rt_smart->create(m_pdmap, m_pqueue, use_amt,
m_smart_thresh);
if(new_pdmap != 0)
m_pdmap = new_pdmap;
}
}
int pcs_after_sref = m_pdmap->size();
int pcs_made_sref = pcs_after_sref - pcs_before_sref;
m_uniform_piece_str += ", sref_pcs:";
m_uniform_piece_str += (intToString(pcs_made_sref));
if(!m_pdmap) // This should never happen, but check anyway.
return(0);
// ============= Stage 4 - AutoPeak Refinement ================
//cout << "In OF_Reflector::autopeak " << endl;
if(m_auto_peak) {
//cout << " - performing autopeak " << endl;
PDMap *new_pdmap = m_rt_autopeak->create(m_pdmap);
if(new_pdmap != 0)
m_pdmap = new_pdmap;
}
if(m_pdmap)
return(m_pdmap->size());
else
return(0);
}
//-------------------------------------------------------------
// Procedure: addWarning
void OF_Reflector::addWarning(string new_warning)
{
if(m_warnings != "")
m_warnings += " # ";
m_warnings += new_warning;
}
//-------------------------------------------------------------
// Procedure: getMessage()
string OF_Reflector::getMessage(unsigned int ix) const
{
if(m_regressor)
return(m_regressor->getMessage(ix));
return("");
}
//-------------------------------------------------------------
// Procedure: getMessageCnt()
unsigned int OF_Reflector::getMessageCnt() const
{
if(m_regressor)
return(m_regressor->getMessageCnt());
return(0);
}
| 30.690323 | 78 | 0.589605 | [
"vector"
] |
239d7f194ffafb6dbd3d5c298e6bd2f4540bf6eb | 40,675 | cpp | C++ | B2G/gecko/netwerk/streamconv/converters/nsIndexedToHTML.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/netwerk/streamconv/converters/nsIndexedToHTML.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/netwerk/streamconv/converters/nsIndexedToHTML.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsIndexedToHTML.h"
#include "nsNetUtil.h"
#include "netCore.h"
#include "nsStringStream.h"
#include "nsIFileURL.h"
#include "nsEscape.h"
#include "nsIDirIndex.h"
#include "prtime.h"
#include "nsDateTimeFormatCID.h"
#include "nsURLHelper.h"
#include "nsCRT.h"
#include "nsIPlatformCharset.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefLocalizedString.h"
#include "nsIChromeRegistry.h"
NS_IMPL_ISUPPORTS4(nsIndexedToHTML,
nsIDirIndexListener,
nsIStreamConverter,
nsIRequestObserver,
nsIStreamListener)
static void AppendNonAsciiToNCR(const nsAString& in, nsAFlatString& out)
{
nsAString::const_iterator start, end;
in.BeginReading(start);
in.EndReading(end);
while (start != end) {
if (*start < 128) {
out.Append(*start++);
} else {
out.AppendLiteral("&#x");
nsAutoString hex;
hex.AppendInt(*start++, 16);
out.Append(hex);
out.Append((PRUnichar)';');
}
}
}
nsresult
nsIndexedToHTML::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult) {
nsresult rv;
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsIndexedToHTML* _s = new nsIndexedToHTML();
if (_s == nullptr)
return NS_ERROR_OUT_OF_MEMORY;
rv = _s->QueryInterface(aIID, aResult);
return rv;
}
nsresult
nsIndexedToHTML::Init(nsIStreamListener* aListener) {
nsXPIDLString ellipsis;
nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
if (prefs) {
nsCOMPtr<nsIPrefLocalizedString> prefVal;
prefs->GetComplexValue("intl.ellipsis",
NS_GET_IID(nsIPrefLocalizedString),
getter_AddRefs(prefVal));
if (prefVal)
prefVal->ToString(getter_Copies(ellipsis));
}
if (ellipsis.IsEmpty())
mEscapedEllipsis.AppendLiteral("…");
else
mEscapedEllipsis.Adopt(nsEscapeHTML2(ellipsis.get(), ellipsis.Length()));
nsresult rv = NS_OK;
mListener = aListener;
mDateTime = do_CreateInstance(NS_DATETIMEFORMAT_CONTRACTID, &rv);
if (NS_FAILED(rv))
return rv;
nsCOMPtr<nsIStringBundleService> sbs =
do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
rv = sbs->CreateBundle(NECKO_MSGS_URL, getter_AddRefs(mBundle));
mExpectAbsLoc = false;
return rv;
}
NS_IMETHODIMP
nsIndexedToHTML::Convert(nsIInputStream* aFromStream,
const char* aFromType,
const char* aToType,
nsISupports* aCtxt,
nsIInputStream** res) {
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
nsIndexedToHTML::AsyncConvertData(const char *aFromType,
const char *aToType,
nsIStreamListener *aListener,
nsISupports *aCtxt) {
return Init(aListener);
}
NS_IMETHODIMP
nsIndexedToHTML::OnStartRequest(nsIRequest* request, nsISupports *aContext) {
nsString buffer;
nsresult rv = DoOnStartRequest(request, aContext, buffer);
if (NS_FAILED(rv)) {
request->Cancel(rv);
}
rv = mListener->OnStartRequest(request, aContext);
if (NS_FAILED(rv)) return rv;
// The request may have been canceled, and if that happens, we want to
// suppress calls to OnDataAvailable.
request->GetStatus(&rv);
if (NS_FAILED(rv)) return rv;
// Push our buffer to the listener.
rv = FormatInputStream(request, aContext, buffer);
return rv;
}
nsresult
nsIndexedToHTML::DoOnStartRequest(nsIRequest* request, nsISupports *aContext,
nsString& aBuffer) {
nsresult rv;
nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
nsCOMPtr<nsIURI> uri;
rv = channel->GetURI(getter_AddRefs(uri));
if (NS_FAILED(rv)) return rv;
channel->SetContentType(NS_LITERAL_CSTRING("text/html"));
mParser = do_CreateInstance("@mozilla.org/dirIndexParser;1",&rv);
if (NS_FAILED(rv)) return rv;
rv = mParser->SetListener(this);
if (NS_FAILED(rv)) return rv;
rv = mParser->OnStartRequest(request, aContext);
if (NS_FAILED(rv)) return rv;
nsAutoCString baseUri, titleUri;
rv = uri->GetAsciiSpec(baseUri);
if (NS_FAILED(rv)) return rv;
titleUri = baseUri;
nsCString parentStr;
// XXX - should be using the 300: line from the parser.
// We can't guarantee that that comes before any entry, so we'd have to
// buffer, and do other painful stuff.
// I'll deal with this when I make the changes to handle welcome messages
// The .. stuff should also come from the lower level protocols, but that
// would muck up the XUL display
// - bbaetz
bool isScheme = false;
bool isSchemeFile = false;
if (NS_SUCCEEDED(uri->SchemeIs("ftp", &isScheme)) && isScheme) {
// strip out the password here, so it doesn't show in the page title
// This is done by the 300: line generation in ftp, but we don't use
// that - see above
nsAutoCString pw;
rv = uri->GetPassword(pw);
if (NS_FAILED(rv)) return rv;
if (!pw.IsEmpty()) {
nsCOMPtr<nsIURI> newUri;
rv = uri->Clone(getter_AddRefs(newUri));
if (NS_FAILED(rv)) return rv;
rv = newUri->SetPassword(EmptyCString());
if (NS_FAILED(rv)) return rv;
rv = newUri->GetAsciiSpec(titleUri);
if (NS_FAILED(rv)) return rv;
}
nsAutoCString path;
rv = uri->GetPath(path);
if (NS_FAILED(rv)) return rv;
if (!path.EqualsLiteral("//") && !path.LowerCaseEqualsLiteral("/%2f")) {
rv = uri->Resolve(NS_LITERAL_CSTRING(".."),parentStr);
if (NS_FAILED(rv)) return rv;
}
} else if (NS_SUCCEEDED(uri->SchemeIs("file", &isSchemeFile)) && isSchemeFile) {
nsCOMPtr<nsIFileURL> fileUrl = do_QueryInterface(uri);
nsCOMPtr<nsIFile> file;
rv = fileUrl->GetFile(getter_AddRefs(file));
if (NS_FAILED(rv)) return rv;
file->SetFollowLinks(true);
nsAutoCString url;
rv = net_GetURLSpecFromFile(file, url);
if (NS_FAILED(rv)) return rv;
baseUri.Assign(url);
nsCOMPtr<nsIFile> parent;
rv = file->GetParent(getter_AddRefs(parent));
if (parent && NS_SUCCEEDED(rv)) {
net_GetURLSpecFromDir(parent, url);
if (NS_FAILED(rv)) return rv;
parentStr.Assign(url);
}
// Directory index will be always encoded in UTF-8 if this is file url
rv = mParser->SetEncoding("UTF-8");
NS_ENSURE_SUCCESS(rv, rv);
} else if (NS_SUCCEEDED(uri->SchemeIs("jar", &isScheme)) && isScheme) {
nsAutoCString path;
rv = uri->GetPath(path);
if (NS_FAILED(rv)) return rv;
// a top-level jar directory URL is of the form jar:foo.zip!/
// path will be of the form foo.zip!/, and its last two characters
// will be "!/"
//XXX this won't work correctly when the name of the directory being
//XXX displayed ends with "!", but then again, jar: URIs don't deal
//XXX particularly well with such directories anyway
if (!StringEndsWith(path, NS_LITERAL_CSTRING("!/"))) {
rv = uri->Resolve(NS_LITERAL_CSTRING(".."), parentStr);
if (NS_FAILED(rv)) return rv;
}
}
else {
// default behavior for other protocols is to assume the channel's
// URL references a directory ending in '/' -- fixup if necessary.
nsAutoCString path;
rv = uri->GetPath(path);
if (NS_FAILED(rv)) return rv;
if (baseUri.Last() != '/') {
baseUri.Append('/');
path.Append('/');
uri->SetPath(path);
}
if (!path.EqualsLiteral("/")) {
rv = uri->Resolve(NS_LITERAL_CSTRING(".."), parentStr);
if (NS_FAILED(rv)) return rv;
}
}
nsString buffer;
buffer.AppendLiteral("<!DOCTYPE html>\n"
"<html>\n<head>\n"
"<meta http-equiv=\"content-type\" content=\"text/html; charset=");
// Get the encoding from the parser
// XXX - this won't work for any encoding set via a 301: line in the
// format - this output stuff would need to move to OnDataAvailable
// for that.
nsXPIDLCString encoding;
rv = mParser->GetEncoding(getter_Copies(encoding));
if (NS_FAILED(rv)) return rv;
AppendASCIItoUTF16(encoding, buffer);
buffer.AppendLiteral("\">\n"
"<style type=\"text/css\">\n"
":root {\n"
" font-family: sans-serif;\n"
"}\n"
"img {\n"
" border: 0;\n"
"}\n"
"th {\n"
" text-align: start;\n"
" white-space: nowrap;\n"
"}\n"
"th > a {\n"
" color: inherit;\n"
"}\n"
"table[order] > thead > tr > th {\n"
" cursor: pointer;\n"
"}\n"
"table[order] > thead > tr > th::after {\n"
" display: none;\n"
" width: .8em;\n"
" -moz-margin-end: -.8em;\n"
" text-align: end;\n"
"}\n"
"table[order=\"asc\"] > thead > tr > th::after {\n"
" content: \"\\2193\"; /* DOWNWARDS ARROW (U+2193) */\n"
"}\n"
"table[order=\"desc\"] > thead > tr > th::after {\n"
" content: \"\\2191\"; /* UPWARDS ARROW (U+2191) */\n"
"}\n"
"table[order][order-by=\"0\"] > thead > tr > th:first-child > a ,\n"
"table[order][order-by=\"1\"] > thead > tr > th:first-child + th > a ,\n"
"table[order][order-by=\"2\"] > thead > tr > th:first-child + th + th > a {\n"
" text-decoration: underline;\n"
"}\n"
"table[order][order-by=\"0\"] > thead > tr > th:first-child::after ,\n"
"table[order][order-by=\"1\"] > thead > tr > th:first-child + th::after ,\n"
"table[order][order-by=\"2\"] > thead > tr > th:first-child + th + th::after {\n"
" display: inline-block;\n"
"}\n"
"table.remove-hidden > tbody > tr.hidden-object {\n"
" display: none;\n"
"}\n"
"td > a {\n"
" display: inline-block;\n"
"}\n"
"/* name */\n"
"th:first-child {\n"
" -moz-padding-end: 2em;\n"
"}\n"
"/* size */\n"
"th:first-child + th {\n"
" -moz-padding-end: 1em;\n"
"}\n"
"td:first-child + td {\n"
" text-align: end;\n"
" -moz-padding-end: 1em;\n"
" white-space: nowrap;\n"
"}\n"
"/* date */\n"
"td:first-child + td + td {\n"
" -moz-padding-start: 1em;\n"
" -moz-padding-end: .5em;\n"
" white-space: nowrap;\n"
"}\n"
"/* time */\n"
"td:last-child {\n"
" -moz-padding-start: .5em;\n"
" white-space: nowrap;\n"
"}\n"
".symlink {\n"
" font-style: italic;\n"
"}\n"
".dir ,\n"
".symlink ,\n"
".file {\n"
" -moz-margin-start: 20px;\n"
"}\n"
".dir::before ,\n"
".file > img {\n"
" -moz-margin-end: 4px;\n"
" -moz-margin-start: -20px;\n"
" vertical-align: middle;\n"
"}\n"
".dir::before {\n"
" content: url(resource://gre/res/html/folder.png);\n"
"}\n"
"</style>\n"
"<link rel=\"stylesheet\" media=\"screen, projection\" type=\"text/css\""
" href=\"chrome://global/skin/dirListing/dirListing.css\">\n"
"<script type=\"application/javascript\">\n"
"var gTable, gOrderBy, gTBody, gRows, gUI_showHidden;\n"
"document.addEventListener(\"DOMContentLoaded\", function() {\n"
" gTable = document.getElementsByTagName(\"table\")[0];\n"
" gTBody = gTable.tBodies[0];\n"
" if (gTBody.rows.length < 2)\n"
" return;\n"
" gUI_showHidden = document.getElementById(\"UI_showHidden\");\n"
" var headCells = gTable.tHead.rows[0].cells,\n"
" hiddenObjects = false;\n"
" function rowAction(i) {\n"
" return function(event) {\n"
" event.preventDefault();\n"
" orderBy(i);\n"
" }\n"
" }\n"
" for (var i = headCells.length - 1; i >= 0; i--) {\n"
" var anchor = document.createElement(\"a\");\n"
" anchor.href = \"\";\n"
" anchor.appendChild(headCells[i].firstChild);\n"
" headCells[i].appendChild(anchor);\n"
" headCells[i].addEventListener(\"click\", rowAction(i), true);\n"
" }\n"
" if (gUI_showHidden) {\n"
" gRows = Array.slice(gTBody.rows);\n"
" hiddenObjects = gRows.some(function (row) row.className == \"hidden-object\");\n"
" }\n"
" gTable.setAttribute(\"order\", \"\");\n"
" if (hiddenObjects) {\n"
" gUI_showHidden.style.display = \"block\";\n"
" updateHidden();\n"
" }\n"
"}, \"false\");\n"
"function compareRows(rowA, rowB) {\n"
" var a = rowA.cells[gOrderBy].getAttribute(\"sortable-data\") || \"\";\n"
" var b = rowB.cells[gOrderBy].getAttribute(\"sortable-data\") || \"\";\n"
" var intA = +a;\n"
" var intB = +b;\n"
" if (a == intA && b == intB) {\n"
" a = intA;\n"
" b = intB;\n"
" } else {\n"
" a = a.toLowerCase();\n"
" b = b.toLowerCase();\n"
" }\n"
" if (a < b)\n"
" return -1;\n"
" if (a > b)\n"
" return 1;\n"
" return 0;\n"
"}\n"
"function orderBy(column) {\n"
" if (!gRows)\n"
" gRows = Array.slice(gTBody.rows);\n"
" var order;\n"
" if (gOrderBy == column) {\n"
" order = gTable.getAttribute(\"order\") == \"asc\" ? \"desc\" : \"asc\";\n"
" } else {\n"
" order = \"asc\";\n"
" gOrderBy = column;\n"
" gTable.setAttribute(\"order-by\", column);\n"
" gRows.sort(compareRows);\n"
" }\n"
" gTable.removeChild(gTBody);\n"
" gTable.setAttribute(\"order\", order);\n"
" if (order == \"asc\")\n"
" for (var i = 0; i < gRows.length; i++)\n"
" gTBody.appendChild(gRows[i]);\n"
" else\n"
" for (var i = gRows.length - 1; i >= 0; i--)\n"
" gTBody.appendChild(gRows[i]);\n"
" gTable.appendChild(gTBody);\n"
"}\n"
"function updateHidden() {\n"
" gTable.className = gUI_showHidden.getElementsByTagName(\"input\")[0].checked ?\n"
" \"\" :\n"
" \"remove-hidden\";\n"
"}\n"
"</script>\n");
buffer.AppendLiteral("<link rel=\"icon\" type=\"image/png\" href=\"");
nsCOMPtr<nsIURI> innerUri = NS_GetInnermostURI(uri);
if (!innerUri)
return NS_ERROR_UNEXPECTED;
nsCOMPtr<nsIFileURL> fileURL(do_QueryInterface(innerUri));
//XXX bug 388553: can't use skinnable icons here due to security restrictions
if (fileURL) {
//buffer.AppendLiteral("chrome://global/skin/dirListing/local.png");
buffer.AppendLiteral("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB"
"AAAAAQCAYAAAAf8%2F9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
"ZSBJbWFnZVJlYWR5ccllPAAAAjFJREFUeNqsU8uOElEQPffR"
"3XQ3ONASdBJCSBxHos5%2B3Bg3rvkCv8PElS78gPkO%2FATj"
"QoUdO2ftrJiRh6aneTb9sOpC4weMN6lcuFV16pxDIfI8x12O"
"YIDhcPiu2Wx%2B%2FHF5CW1Z6Jyegt%2FTNEWSJIjjGFEUIQ"
"xDrFYrWFSzXC4%2FdLvd95pRKpXKy%2BpRFZ7nwaWo1%2BsG"
"nQG2260BKJfLKJVKGI1GEEJw7ateryd0v993W63WEwjgxfn5"
"obGYzgCbzcaEbdsIggDj8Riu6z6iUk9SYZMSx8W0LMsM%2FS"
"KK75xnJlIq80anQXdbEp0OhcPJ0eiaJnGRMEyyPDsAKKUM9c"
"lkYoDo3SZJzzSdp0VSKYmfV1co%2Bz580kw5KDIM8RbRfEnU"
"f1HzxtQyMAGcaGruTKczMzEIaqhKifV6jd%2BzGQQB5llunF"
"%2FM52BizC2K5sYPYvZcu653tjOM9O93wnYc08gmkgg4VAxi"
"xfqFUJT36AYBZGd6PJkFCZnnlBxMp38gqIgLpZB0y4Nph18l"
"yWh5FFbrOSxbl3V4G%2BVB7T4ajYYxTyuLtO%2BCvWGgJE1M"
"c7JNsJEhvgw%2FQV4fo%2F24nbEsX2u1d5sVyn8sJO0ZAQiI"
"YnFh%2BxrfLz%2Fj29cBS%2FO14zg3i8XigW3ZkErDtmKoeM"
"%2BAJGRMnXeEPGKf0nCD1ydvkDzU9Jbc6OpR7WIw6L8lQ%2B"
"4pQ1%2FlPF0RGM9Ns91Wmptk0GfB4EJkt77vXYj%2F8m%2B8"
"y%2FkrwABHbz2H9V68DQAAAABJRU5ErkJggg%3D%3D");
} else {
//buffer.AppendLiteral("chrome://global/skin/dirListing/remote.png");
buffer.AppendLiteral("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB"
"AAAAAQCAYAAAAf8%2F9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
"ZSBJbWFnZVJlYWR5ccllPAAAAeBJREFUeNqcU81O20AQ%2Ft"
"Z2AgQSYQRqL1UPVG2hAUQkxLEStz4DrXpLpD5Drz31Cajax%"
"2Bghhx6qHIJURBTxIwQRwopCBbZjHMcOTrzermPipsSt1Iw0"
"3p3ZmW%2B%2B2R0TxhgOD34wjCHZlQ0iDYz9yvEfhxMTCYhE"
"QDIZhkxKd2sqzX2TOD2vBQCQhpPefng1ZP2dVPlLLdpL8SEM"
"cxng%2Fbs0RIHhtgs4twxOh%2BHjZxvzDx%2F3GQQiDFISiR"
"BLFMPKTRMollzcWECrDVhtxtdRVsL9youPxGj%2FbdfFlUZh"
"tDyYbYqWRUdai1oQRZ5oHeHl2gNM%2B01Uqio8RlH%2Bnsaz"
"JzNwXcq1B%2BiXPHprlEEymeBfXs1w8XxxihfyuXqoHqpoGj"
"ZM04bddgG%2F9%2B8WGj87qDdsrK9m%2BoA%2BpbhQTDh2l1"
"%2Bi2weNbSHMZyjvNXmVbqh9Fj5Oz27uEoP%2BSTxANruJs9"
"L%2FT6P0ewqPx5nmiAG5f6AoCtN1PbJzuRyJAyDBzzSQYvEr"
"f06yYxhGXlEa8H2KVGoasjwLx3Ewk858opQWXm%2B%2Fib9E"
"QrBzclLLLy89xYvlpchvtixcX6uo1y%2FzsiwHrkIsgKbp%2"
"BYWFOWicuqppoNTnStHzPFCPQhBEBOyGAX4JMADFetubi4BS"
"YAAAAABJRU5ErkJggg%3D%3D");
}
buffer.AppendLiteral("\">\n<title>");
// Everything needs to end in a /,
// otherwise we end up linking to file:///foo/dirfile
if (!mTextToSubURI) {
mTextToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
}
nsXPIDLString unEscapeSpec;
rv = mTextToSubURI->UnEscapeAndConvert(encoding, titleUri.get(),
getter_Copies(unEscapeSpec));
// unescape may fail because
// 1. file URL may be encoded in platform charset for backward compatibility
// 2. query part may not be encoded in UTF-8 (see bug 261929)
// so try the platform's default if this is file url
if (NS_FAILED(rv) && isSchemeFile) {
nsCOMPtr<nsIPlatformCharset> platformCharset(do_GetService(NS_PLATFORMCHARSET_CONTRACTID, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString charset;
rv = platformCharset->GetCharset(kPlatformCharsetSel_FileName, charset);
NS_ENSURE_SUCCESS(rv, rv);
rv = mTextToSubURI->UnEscapeAndConvert(charset.get(), titleUri.get(),
getter_Copies(unEscapeSpec));
}
if (NS_FAILED(rv)) return rv;
nsXPIDLString htmlEscSpec;
htmlEscSpec.Adopt(nsEscapeHTML2(unEscapeSpec.get(),
unEscapeSpec.Length()));
nsXPIDLString title;
const PRUnichar* formatTitle[] = {
htmlEscSpec.get()
};
rv = mBundle->FormatStringFromName(NS_LITERAL_STRING("DirTitle").get(),
formatTitle,
sizeof(formatTitle)/sizeof(PRUnichar*),
getter_Copies(title));
if (NS_FAILED(rv)) return rv;
// we want to convert string bundle to NCR
// to ensure they're shown in any charsets
AppendNonAsciiToNCR(title, buffer);
buffer.AppendLiteral("</title>\n");
// If there is a quote character in the baseUri, then
// lets not add a base URL. The reason for this is that
// if we stick baseUri containing a quote into a quoted
// string, the quote character will prematurely close
// the base href string. This is a fall-back check;
// that's why it is OK to not use a base rather than
// trying to play nice and escaping the quotes. See bug
// 358128.
if (baseUri.FindChar('"') == kNotFound)
{
// Great, the baseUri does not contain a char that
// will prematurely close the string. Go ahead an
// add a base href.
buffer.AppendLiteral("<base href=\"");
NS_ConvertUTF8toUTF16 utf16BaseURI(baseUri);
nsString htmlEscapedUri;
htmlEscapedUri.Adopt(nsEscapeHTML2(utf16BaseURI.get(), utf16BaseURI.Length()));
buffer.Append(htmlEscapedUri);
buffer.AppendLiteral("\" />\n");
}
else
{
NS_ERROR("broken protocol handler didn't escape double-quote.");
}
nsAutoString direction(NS_LITERAL_STRING("ltr"));
nsCOMPtr<nsIXULChromeRegistry> reg =
mozilla::services::GetXULChromeRegistryService();
if (reg) {
bool isRTL = false;
reg->IsLocaleRTL(NS_LITERAL_CSTRING("global"), &isRTL);
if (isRTL) {
direction.AssignLiteral("rtl");
}
}
buffer.AppendLiteral("</head>\n<body dir=\"");
buffer.Append(direction);
buffer.AppendLiteral("\">\n<h1>");
const PRUnichar* formatHeading[] = {
htmlEscSpec.get()
};
rv = mBundle->FormatStringFromName(NS_LITERAL_STRING("DirTitle").get(),
formatHeading,
sizeof(formatHeading)/sizeof(PRUnichar*),
getter_Copies(title));
if (NS_FAILED(rv)) return rv;
AppendNonAsciiToNCR(title, buffer);
buffer.AppendLiteral("</h1>\n");
if (!parentStr.IsEmpty()) {
nsXPIDLString parentText;
rv = mBundle->GetStringFromName(NS_LITERAL_STRING("DirGoUp").get(),
getter_Copies(parentText));
if (NS_FAILED(rv)) return rv;
buffer.AppendLiteral("<p id=\"UI_goUp\"><a class=\"up\" href=\"");
NS_ConvertUTF8toUTF16 utf16ParentStr(parentStr);
nsString htmlParentStr;
htmlParentStr.Adopt(nsEscapeHTML2(utf16ParentStr.get(), utf16ParentStr.Length()));
buffer.Append(htmlParentStr);
buffer.AppendLiteral("\">");
AppendNonAsciiToNCR(parentText, buffer);
buffer.AppendLiteral("</a></p>\n");
}
if (isSchemeFile) {
nsXPIDLString showHiddenText;
rv = mBundle->GetStringFromName(NS_LITERAL_STRING("ShowHidden").get(),
getter_Copies(showHiddenText));
if (NS_FAILED(rv)) return rv;
buffer.AppendLiteral("<p id=\"UI_showHidden\" style=\"display:none\"><label><input type=\"checkbox\" checked onchange=\"updateHidden()\">");
AppendNonAsciiToNCR(showHiddenText, buffer);
buffer.AppendLiteral("</label></p>\n");
}
buffer.AppendLiteral("<table>\n");
nsXPIDLString columnText;
buffer.AppendLiteral(" <thead>\n"
" <tr>\n"
" <th>");
rv = mBundle->GetStringFromName(NS_LITERAL_STRING("DirColName").get(),
getter_Copies(columnText));
if (NS_FAILED(rv)) return rv;
AppendNonAsciiToNCR(columnText, buffer);
buffer.AppendLiteral("</th>\n"
" <th>");
rv = mBundle->GetStringFromName(NS_LITERAL_STRING("DirColSize").get(),
getter_Copies(columnText));
if (NS_FAILED(rv)) return rv;
AppendNonAsciiToNCR(columnText, buffer);
buffer.AppendLiteral("</th>\n"
" <th colspan=\"2\">");
rv = mBundle->GetStringFromName(NS_LITERAL_STRING("DirColMTime").get(),
getter_Copies(columnText));
if (NS_FAILED(rv)) return rv;
AppendNonAsciiToNCR(columnText, buffer);
buffer.AppendLiteral("</th>\n"
" </tr>\n"
" </thead>\n");
buffer.AppendLiteral(" <tbody>\n");
aBuffer = buffer;
return rv;
}
NS_IMETHODIMP
nsIndexedToHTML::OnStopRequest(nsIRequest* request, nsISupports *aContext,
nsresult aStatus) {
if (NS_SUCCEEDED(aStatus)) {
nsString buffer;
buffer.AssignLiteral("</tbody></table></body></html>\n");
aStatus = FormatInputStream(request, aContext, buffer);
}
mParser->OnStopRequest(request, aContext, aStatus);
mParser = 0;
return mListener->OnStopRequest(request, aContext, aStatus);
}
nsresult
nsIndexedToHTML::FormatInputStream(nsIRequest* aRequest, nsISupports *aContext, const nsAString &aBuffer)
{
nsresult rv = NS_OK;
// set up unicode encoder
if (!mUnicodeEncoder) {
nsXPIDLCString encoding;
rv = mParser->GetEncoding(getter_Copies(encoding));
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsICharsetConverterManager> charsetConverterManager;
charsetConverterManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
rv = charsetConverterManager->GetUnicodeEncoder(encoding.get(),
getter_AddRefs(mUnicodeEncoder));
if (NS_SUCCEEDED(rv))
rv = mUnicodeEncoder->SetOutputErrorBehavior(nsIUnicodeEncoder::kOnError_Replace,
nullptr, (PRUnichar)'?');
}
}
// convert the data with unicode encoder
char *buffer = nullptr;
int32_t dstLength;
if (NS_SUCCEEDED(rv)) {
int32_t unicharLength = aBuffer.Length();
rv = mUnicodeEncoder->GetMaxLength(PromiseFlatString(aBuffer).get(),
unicharLength, &dstLength);
if (NS_SUCCEEDED(rv)) {
buffer = (char *) nsMemory::Alloc(dstLength);
NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);
rv = mUnicodeEncoder->Convert(PromiseFlatString(aBuffer).get(), &unicharLength,
buffer, &dstLength);
if (NS_SUCCEEDED(rv)) {
int32_t finLen = 0;
rv = mUnicodeEncoder->Finish(buffer + dstLength, &finLen);
if (NS_SUCCEEDED(rv))
dstLength += finLen;
}
}
}
// if conversion error then fallback to UTF-8
if (NS_FAILED(rv)) {
rv = NS_OK;
if (buffer) {
nsMemory::Free(buffer);
buffer = nullptr;
}
}
nsCOMPtr<nsIInputStream> inputData;
if (buffer) {
rv = NS_NewCStringInputStream(getter_AddRefs(inputData), Substring(buffer, dstLength));
nsMemory::Free(buffer);
NS_ENSURE_SUCCESS(rv, rv);
rv = mListener->OnDataAvailable(aRequest, aContext,
inputData, 0, dstLength);
}
else {
NS_ConvertUTF16toUTF8 utf8Buffer(aBuffer);
rv = NS_NewCStringInputStream(getter_AddRefs(inputData), utf8Buffer);
NS_ENSURE_SUCCESS(rv, rv);
rv = mListener->OnDataAvailable(aRequest, aContext,
inputData, 0, utf8Buffer.Length());
}
return (rv);
}
NS_IMETHODIMP
nsIndexedToHTML::OnDataAvailable(nsIRequest *aRequest,
nsISupports *aCtxt,
nsIInputStream* aInput,
uint64_t aOffset,
uint32_t aCount) {
return mParser->OnDataAvailable(aRequest, aCtxt, aInput, aOffset, aCount);
}
NS_IMETHODIMP
nsIndexedToHTML::OnIndexAvailable(nsIRequest *aRequest,
nsISupports *aCtxt,
nsIDirIndex *aIndex) {
nsresult rv;
if (!aIndex)
return NS_ERROR_NULL_POINTER;
nsString pushBuffer;
pushBuffer.AppendLiteral("<tr");
nsXPIDLString description;
aIndex->GetDescription(getter_Copies(description));
if (description.First() == PRUnichar('.'))
pushBuffer.AppendLiteral(" class=\"hidden-object\"");
pushBuffer.AppendLiteral(">\n <td sortable-data=\"");
// The sort key is the name of the item, prepended by either 0, 1 or 2
// in order to group items.
uint32_t type;
aIndex->GetType(&type);
switch (type) {
case nsIDirIndex::TYPE_SYMLINK:
pushBuffer.AppendInt(0);
break;
case nsIDirIndex::TYPE_DIRECTORY:
pushBuffer.AppendInt(1);
break;
case nsIDirIndex::TYPE_FILE:
case nsIDirIndex::TYPE_UNKNOWN:
pushBuffer.AppendInt(2);
break;
}
PRUnichar* escaped = nsEscapeHTML2(description.get(), description.Length());
pushBuffer.Append(escaped);
pushBuffer.AppendLiteral("\"><a class=\"");
switch (type) {
case nsIDirIndex::TYPE_DIRECTORY:
pushBuffer.AppendLiteral("dir");
break;
case nsIDirIndex::TYPE_SYMLINK:
pushBuffer.AppendLiteral("symlink");
break;
case nsIDirIndex::TYPE_FILE:
case nsIDirIndex::TYPE_UNKNOWN:
pushBuffer.AppendLiteral("file");
break;
}
pushBuffer.AppendLiteral("\"");
// Truncate long names to not stretch the table
//XXX this should be left to the stylesheet (bug 391471)
nsString escapedShort;
if (description.Length() > 71) {
nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
nsCOMPtr<nsIURI> uri;
rv = channel->GetURI(getter_AddRefs(uri));
if (NS_FAILED(rv)) return rv;
//XXX this potentially truncates after a combining char (bug 391472)
nsXPIDLString descriptionAffix;
descriptionAffix.Assign(description);
descriptionAffix.Cut(0, descriptionAffix.Length() - 25);
if (NS_IS_LOW_SURROGATE(descriptionAffix.First()))
descriptionAffix.Cut(0, 1);
description.Truncate(NS_MIN<uint32_t>(71, description.Length() - 28));
if (NS_IS_HIGH_SURROGATE(description.Last()))
description.Truncate(description.Length() - 1);
escapedShort.Adopt(nsEscapeHTML2(description.get(), description.Length()));
escapedShort.Append(mEscapedEllipsis);
// add ZERO WIDTH SPACE (U+200B) for wrapping
escapedShort.AppendLiteral("​");
nsString tmp;
tmp.Adopt(nsEscapeHTML2(descriptionAffix.get(), descriptionAffix.Length()));
escapedShort.Append(tmp);
pushBuffer.AppendLiteral(" title=\"");
pushBuffer.Append(escaped);
pushBuffer.AppendLiteral("\"");
}
if (escapedShort.IsEmpty())
escapedShort.Assign(escaped);
nsMemory::Free(escaped);
pushBuffer.AppendLiteral(" href=\"");
nsXPIDLCString loc;
aIndex->GetLocation(getter_Copies(loc));
if (!mTextToSubURI) {
mTextToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
}
nsXPIDLCString encoding;
rv = mParser->GetEncoding(getter_Copies(encoding));
if (NS_FAILED(rv)) return rv;
nsXPIDLString unEscapeSpec;
rv = mTextToSubURI->UnEscapeAndConvert(encoding, loc,
getter_Copies(unEscapeSpec));
if (NS_FAILED(rv)) return rv;
// need to escape links
nsAutoCString escapeBuf;
NS_ConvertUTF16toUTF8 utf8UnEscapeSpec(unEscapeSpec);
// Adding trailing slash helps to recognize whether the URL points to a file
// or a directory (bug #214405).
if ((type == nsIDirIndex::TYPE_DIRECTORY) &&
(utf8UnEscapeSpec.Last() != '/')) {
utf8UnEscapeSpec.Append('/');
}
// now minimally re-escape the location...
uint32_t escFlags;
// for some protocols, we expect the location to be absolute.
// if so, and if the location indeed appears to be a valid URI, then go
// ahead and treat it like one.
if (mExpectAbsLoc &&
NS_SUCCEEDED(net_ExtractURLScheme(utf8UnEscapeSpec, nullptr, nullptr, nullptr))) {
// escape as absolute
escFlags = esc_Forced | esc_OnlyASCII | esc_AlwaysCopy | esc_Minimal;
}
else {
// escape as relative
// esc_Directory is needed because directories have a trailing slash.
// Without it, the trailing '/' will be escaped, and links from within
// that directory will be incorrect
escFlags = esc_Forced | esc_OnlyASCII | esc_AlwaysCopy | esc_FileBaseName | esc_Colon | esc_Directory;
}
NS_EscapeURL(utf8UnEscapeSpec.get(), utf8UnEscapeSpec.Length(), escFlags, escapeBuf);
// esc_Directory does not escape the semicolons, so if a filename
// contains semicolons we need to manually escape them.
// This replacement should be removed in bug #473280
escapeBuf.ReplaceSubstring(";", "%3b");
NS_ConvertUTF8toUTF16 utf16URI(escapeBuf);
nsString htmlEscapedURL;
htmlEscapedURL.Adopt(nsEscapeHTML2(utf16URI.get(), utf16URI.Length()));
pushBuffer.Append(htmlEscapedURL);
pushBuffer.AppendLiteral("\">");
if (type == nsIDirIndex::TYPE_FILE || type == nsIDirIndex::TYPE_UNKNOWN) {
pushBuffer.AppendLiteral("<img src=\"moz-icon://");
int32_t lastDot = escapeBuf.RFindChar('.');
if (lastDot != kNotFound) {
escapeBuf.Cut(0, lastDot);
NS_ConvertUTF8toUTF16 utf16EscapeBuf(escapeBuf);
nsString htmlFileExt;
htmlFileExt.Adopt(nsEscapeHTML2(utf16EscapeBuf.get(), utf16EscapeBuf.Length()));
pushBuffer.Append(htmlFileExt);
} else {
pushBuffer.AppendLiteral("unknown");
}
pushBuffer.AppendLiteral("?size=16\" alt=\"");
nsXPIDLString altText;
rv = mBundle->GetStringFromName(NS_LITERAL_STRING("DirFileLabel").get(),
getter_Copies(altText));
if (NS_FAILED(rv)) return rv;
AppendNonAsciiToNCR(altText, pushBuffer);
pushBuffer.AppendLiteral("\">");
}
pushBuffer.Append(escapedShort);
pushBuffer.AppendLiteral("</a></td>\n <td");
if (type == nsIDirIndex::TYPE_DIRECTORY || type == nsIDirIndex::TYPE_SYMLINK) {
pushBuffer.AppendLiteral(">");
} else {
int64_t size;
aIndex->GetSize(&size);
if (uint64_t(size) != UINT64_MAX) {
pushBuffer.AppendLiteral(" sortable-data=\"");
pushBuffer.AppendInt(size);
pushBuffer.AppendLiteral("\">");
nsAutoString sizeString;
FormatSizeString(size, sizeString);
pushBuffer.Append(sizeString);
} else {
pushBuffer.AppendLiteral(">");
}
}
pushBuffer.AppendLiteral("</td>\n <td");
PRTime t;
aIndex->GetLastModified(&t);
if (t == -1) {
pushBuffer.AppendLiteral("></td>\n <td>");
} else {
pushBuffer.AppendLiteral(" sortable-data=\"");
pushBuffer.AppendInt(static_cast<int64_t>(t));
pushBuffer.AppendLiteral("\">");
nsAutoString formatted;
mDateTime->FormatPRTime(nullptr,
kDateFormatShort,
kTimeFormatNone,
t,
formatted);
AppendNonAsciiToNCR(formatted, pushBuffer);
pushBuffer.AppendLiteral("</td>\n <td>");
mDateTime->FormatPRTime(nullptr,
kDateFormatNone,
kTimeFormatSeconds,
t,
formatted);
// use NCR to show date in any doc charset
AppendNonAsciiToNCR(formatted, pushBuffer);
}
pushBuffer.AppendLiteral("</td>\n</tr>");
return FormatInputStream(aRequest, aCtxt, pushBuffer);
}
NS_IMETHODIMP
nsIndexedToHTML::OnInformationAvailable(nsIRequest *aRequest,
nsISupports *aCtxt,
const nsAString& aInfo) {
nsAutoString pushBuffer;
PRUnichar* escaped = nsEscapeHTML2(PromiseFlatString(aInfo).get());
if (!escaped)
return NS_ERROR_OUT_OF_MEMORY;
pushBuffer.AppendLiteral("<tr>\n <td>");
pushBuffer.Append(escaped);
nsMemory::Free(escaped);
pushBuffer.AppendLiteral("</td>\n <td></td>\n <td></td>\n <td></td>\n</tr>\n");
return FormatInputStream(aRequest, aCtxt, pushBuffer);
}
void nsIndexedToHTML::FormatSizeString(int64_t inSize, nsString& outSizeString)
{
outSizeString.Truncate();
if (inSize > int64_t(0)) {
// round up to the nearest Kilobyte
int64_t upperSize = (inSize + int64_t(1023)) / int64_t(1024);
outSizeString.AppendInt(upperSize);
outSizeString.AppendLiteral(" KB");
}
}
nsIndexedToHTML::nsIndexedToHTML() {
}
nsIndexedToHTML::~nsIndexedToHTML() {
}
| 40.272277 | 148 | 0.537824 | [
"object",
"3d"
] |
23ae64ec97c6cf6da41a849367db0ae20087be04 | 14,921 | hh | C++ | src/libtrio/related_sample_util.hh | StephenTanner/gvcftools | 5702a67fe5e744065b5462760b6c0bba38d8d9ea | [
"BSL-1.0"
] | 26 | 2015-11-30T18:53:11.000Z | 2021-11-12T07:48:37.000Z | src/libtrio/related_sample_util.hh | StephenTanner/gvcftools | 5702a67fe5e744065b5462760b6c0bba38d8d9ea | [
"BSL-1.0"
] | 5 | 2015-08-06T18:32:55.000Z | 2020-03-08T18:13:22.000Z | src/libtrio/related_sample_util.hh | ctsa/gvcftools | 7e854392c94c63410a846d29a97b95a6f1435576 | [
"BSL-1.0"
] | 8 | 2015-07-20T09:53:07.000Z | 2018-06-10T09:55:31.000Z | // -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2009-2012 Illumina, Inc.
//
// 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.
//
//
/// \file
///
/// \author Chris Saunders
///
#pragma once
#include "compat_util.hh"
#include "parse_util.hh"
#include "pos_type.hh"
#include "reference_contig_segment.hh"
#include "trio_option_util.hh"
#include "vcf_util.hh"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iosfwd>
#include <string>
#include <vector>
inline
double
ratio(const unsigned n, const unsigned d) {
return ((d==0)? 0. : (static_cast<double>(n)/static_cast<double>(d)));
}
template <int SAMPLE_SIZE>
struct site_stats_core {
site_stats_core()
: ref_size(0)
, known_size(0)
, some_mapped(0)
, some_called(0)
, all_mapped(0)
, all_called(0)
, incorrect(0)
, snp_correct(0)
{
for (unsigned st(0); st<SAMPLE_SIZE; ++st) {
sample_mapped[st] = 0;
sample_called[st] = 0;
sample_snp[st] = 0;
sample_snp_het[st] = 0;
sample_snp_correct_het[st] = 0;
sample_snp_correct_hom[st] = 0;
}
}
unsigned ref_size;
unsigned known_size;
unsigned some_mapped;
unsigned some_called;
unsigned all_mapped;
unsigned all_called;
unsigned incorrect;
unsigned snp_correct;
unsigned sample_mapped[SAMPLE_SIZE];
unsigned sample_called[SAMPLE_SIZE];
unsigned sample_snp[SAMPLE_SIZE];
unsigned sample_snp_het[SAMPLE_SIZE];
unsigned sample_snp_correct_het[SAMPLE_SIZE];
unsigned sample_snp_correct_hom[SAMPLE_SIZE];
};
struct snp_param {
snp_param()
: min_gqx(0)
, min_qd(0)
, min_pos_rank_sum(0)
, is_min_qd(false)
, is_min_pos_rank_sum(false)
{}
double min_gqx;
double min_qd;
double min_pos_rank_sum;
bool is_min_qd;
bool is_min_pos_rank_sum;
std::vector<info_filter> infof;
};
struct snp_type_info {
snp_type_info(const snp_param& sp)
: _sp(sp)
, _chromcol(0)
, _poscol(1)
{}
bool
get_is_call(char** word,
const pos_t pos,
pos_t& skip_call_begin_pos,
pos_t& skip_call_end_pos) const {
//update_skip_call_range(word,pos,is_indel,skip_call_begin_pos,skip_call_end_pos);
bool is_bad_call(0!=strcmp(word[VCFID::FILT],"PASS"));
if (is_bad_call) return false;
if (_sp.min_gqx > 0) {
float gqx(0);
if (get_format_float(word,"GQX",gqx)) {
if (gqx<_sp.min_gqx) return false;
}
}
#if 0
if (_sp.vcf_min_ref_qual > 0) {
const char* qword(word[QVAR_COL]);
if (strcmp(".",qword)!=0) {
unsigned digt_code[2];
if (get_digt_code(word, digt_code) &&
(digt_code[0]==0) &&
(digt_code[1]==0)) {
float qual(casava::blt_util::parse_double(qword));
if (qual<_sp.vcf_min_ref_qual) return false;
}
}
}
#endif
if (_sp.is_min_qd) {
float qd(0);
if (get_info_float(word[VCFID::INFO],"QD",qd)) {
if (qd<_sp.min_qd) return false;
}
}
if (_sp.is_min_pos_rank_sum) {
float pos_rank_sum(0);
if (get_info_float(word[VCFID::INFO],"BaseQRankSum",pos_rank_sum)) {
if (pos_rank_sum<_sp.min_pos_rank_sum) return false;
}
}
// handle the custom info filters:
if (! _sp.infof.empty()) {
for (unsigned i(0); i<_sp.infof.size(); ++i) {
float record_val(0);
if (get_info_float(word[VCFID::INFO],_sp.infof[i].key.c_str(),record_val)) {
if (_sp.infof[i].is_min) {
if (record_val<_sp.infof[i].val) return false;
} else {
if (record_val>_sp.infof[i].val) return false;
}
}
}
}
return (pos<skip_call_begin_pos || pos>=skip_call_end_pos);
}
bool
get_site_allele(std::vector<char>& allele,
const char* const* word,
const unsigned offset,
const char ref_base) const;
bool
get_indel_allele(
std::string& indel_ref,
std::vector<std::string>& allele,
const char* const* word) const;
unsigned
total(const char* const* word) const {
unsigned dp;
if (! get_format_unsigned(word,"DP",dp)) return 0;
return dp;
}
unsigned
col_count() const { return 10; }
const char*
chrom(const char* const* word) const {
return word[_chromcol];
}
pos_t
pos(const char* const* word) const {
const char* s(word[_poscol]);
return parse_type<pos_t>(s);
}
// Size of the site or multisite locus in reference bases.
// returns false on error
bool
get_nonindel_ref_length(const pos_t pos, const bool is_indel, const char* const* word, unsigned& result) const {
result=0;
if (is_indel) return true;
const unsigned reflen(strlen(word[VCFID::REF]));
unsigned iend;
if (! get_info_unsigned(word[VCFID::INFO],"END",iend)) {
result=reflen;
} else {
if ( ! (iend>=pos && (reflen <= ((iend+1)-pos))) ) return false;
result = (iend+1)-pos;
}
return true;
}
// this detects both indels and unequal or equal length 'block-subsitutions'
bool
get_is_indel(const char* const* word) const {
const char* alt(word[VCFID::ALT]);
const char* tmp_ptr;
// no alternate:
if (0==strcmp(alt,".")) return false;
// breakend:
if (NULL != (tmp_ptr=strchr(alt,'.'))) return true;
const unsigned reflen(strlen(word[VCFID::REF]));
// if alt is not '.' and reflen > 1, then this must be some sort of indel/subst:
// pathological case is alt=".,." ... don't worry about that one.
if (reflen>1) return true;
// after the above test, we're essentially just looking for an alt with
// length greater than one, indicating an insertion:
while (NULL != (tmp_ptr=strchr(alt,','))) {
if ((tmp_ptr-alt)!=static_cast<pos_t>(reflen)) return true;
alt = tmp_ptr+1;
}
return (strlen(alt)!=reflen);
}
private:
static
bool
get_info_float(const char* info,
const char* key,
float& val);
static
bool
get_info_unsigned(const char* info,
const char* key,
unsigned& val);
static
bool
get_format_float(const char* const* word,
const char* key,
float& val);
static
bool
get_format_unsigned(const char* const* word,
const char* key,
unsigned& val);
// Size of the locus in reference bases. This has been assumed to
// be 1 until vcf support was added.
unsigned
get_ref_length(const char* const* word) const {
return strlen(word[VCFID::REF]);
}
// if the current locus is an indel, mark out its range as no-call:
//
void
update_skip_call_range(const char* const* word,
const pos_t pos,
const bool is_indel,
pos_t& skip_call_begin_pos,
pos_t& skip_call_end_pos) const {
const unsigned locus_size=get_ref_length(word);
if (locus_size<=1) return;
if (! is_indel) return;
// follow CASAVA begin-end convention: 0-indexed and end goes 1 past range
const pos_t indel_begin_pos(pos+1);
const pos_t indel_end_pos(pos+locus_size);
if (skip_call_end_pos<pos) {
skip_call_begin_pos=indel_begin_pos;
}
skip_call_end_pos=std::max(skip_call_end_pos,indel_end_pos);
}
// data:
const snp_param& _sp;
const unsigned _chromcol;
const unsigned _poscol;
// cache this to avoid malloc cost:
mutable std::vector<int> _gtcode;
};
// used to be a big struct!!
struct sample_info {
std::string file;
};
struct shared_crawler_options {
shared_crawler_options()
: region_begin(0),
region_end(0),
is_murdock_mode(false),
_sti(_sp)
{}
snp_param& sp() { return _sp; }
const snp_type_info& sti() const { return _sti; }
bool is_region() const { return (! region.empty()); }
std::string region;
int region_begin;
int region_end;
bool is_murdock_mode;
private:
snp_param _sp;
snp_type_info _sti;
};
struct tabix_streamer;
// Extend the concept of pos to include indel status, so that positions with
// the same number sort with site record first, followed by indel record.
// This is the same ordering that's in the vcf already
//
struct vcf_pos {
vcf_pos()
: pos(0), is_indel(false)
{}
bool
operator<(const vcf_pos& rhs) const {
if (pos<rhs.pos) return true;
if (pos==rhs.pos) {
return ((!is_indel) && rhs.is_indel);
}
return false;
}
bool
operator==(const vcf_pos& rhs) const {
return ((pos==rhs.pos) && (is_indel==rhs.is_indel));
}
pos_t pos;
bool is_indel;
};
std::ostream&
operator<<(std::ostream& os, const vcf_pos& vpos);
struct site_crawler {
site_crawler(const sample_info& si,
const unsigned sample_id,
const shared_crawler_options& opt,
const char* chr_region,
const reference_contig_segment& ref_seg,
const bool is_store_header = false,
const bool is_return_indels = false);
~site_crawler();
const char*
sample_name() const {
return _sample_name.c_str();
}
// dump all but last line of header to os if is_store_header was set;
void
dump_header(std::ostream& os) const;
void
update(const bool is_store_header = false);
bool
is_pos_valid() const { return (! _is_sample_end_state); }
void
dump_line(std::ostream& os) const;
void
dump_state(std::ostream& os) const;
const char*
chrom() const {
static const char* unknown = "unknown";
if (NULL == _chrom) return unknown;
return _chrom;
}
const char*
word(const unsigned i) const {
static const char* unknown = "";
if (NULL == _word) return unknown;
if (_n_word <= i) return unknown;
return _word[i];
}
unsigned
get_allele_size() const {
if (! _is_site_allele_current) update_site_allele();
return _site_allele.size();
}
char
get_allele(const unsigned index) const {
if (! _is_site_allele_current) update_site_allele();
if (index>get_allele_size()) return 'N';
return _site_allele[index];
}
unsigned
get_indel_allele_size() const {
if (! _is_indel_allele_current) update_indel_allele();
return _indel_allele.size();
}
const std::string&
get_indel_allele(const unsigned index) const {
static const std::string nullStr("X");
if (! _is_indel_allele_current) update_indel_allele();
if (index>get_indel_allele_size()) return nullStr;
return _indel_allele[index];
}
const std::string&
get_indel_ref() const {
if (! _is_indel_allele_current) update_indel_allele();
return _indel_ref;
}
pos_t
pos() const {
return vpos().pos;
}
bool
is_indel() const {
return vpos().is_indel;
}
vcf_pos
vpos() const {
return _vpos;
}
bool
is_any_call() const
{
return _is_call;
}
bool
is_site_call() const {
return (_is_call && (!is_indel()));
}
bool
is_indel_call() const {
return (_is_call && (is_indel()));
}
unsigned
n_total() const {
return _n_total;
}
private:
bool
update_allele() const;
bool
update_site_allele() const;
bool
update_indel_allele() const;
bool
process_record_line(char* line);
vcf_pos _vpos;
bool _is_call;
unsigned _n_total;
// information from header (sample_name is always stored but full header is optional
std::vector<std::string> _header;
std::string _sample_name;
const char* _chrom;
const sample_info _si;
//const unsigned _sample_id; // only used for debugging...
const shared_crawler_options& _opt;
const char* _chr_region;
bool _is_return_indels;
tabix_streamer* _tabs;
bool _is_sample_begin_state;
bool _is_sample_end_state;
unsigned _next_file;
const reference_contig_segment& _ref_seg;
enum { MAX_WORD=50 };
char* _word[MAX_WORD];
unsigned _n_word;
unsigned _locus_size;
unsigned _locus_offset;
mutable pos_t _skip_call_begin_pos;
mutable pos_t _skip_call_end_pos;
mutable bool _is_site_allele_current;
mutable bool _is_indel_allele_current;
mutable std::vector<char> _site_allele;
mutable std::string _indel_ref;
mutable std::vector<std::string> _indel_allele;
};
struct pos_reporter {
pos_reporter(const std::string& filename,
const std::vector<std::string>& sample_label);
~pos_reporter();
void
print_pos(const site_crawler* sa);
private:
bool is_pos_report;
std::ofstream* pos_fs_ptr;
unsigned sample_size;
const std::vector<std::string>& _sample_label;
};
| 25.289831 | 116 | 0.597011 | [
"vector"
] |
23bbd157eef3eaf84f9f20acf2bd4eeaad13726a | 1,421 | cpp | C++ | codeforces/B - Curiosity Has No Limits/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/B - Curiosity Has No Limits/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/B - Curiosity Has No Limits/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Oct/21/2018 14:35
* solution_verdict: Accepted language: GNU C++14
* run_time: 78 ms memory_used: 7600 KB
* problem: https://codeforces.com/contest/1072/problem/B
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e5;
int aa[N+2],bb[N+2],vis[N+2][4],n;
vector<int>ans;
void dfs(int st,int ls)
{
if(st>n)
{
cout<<"YES"<<endl;
for(auto x:ans)
cout<<x<<" ";
cout<<endl;
exit(0);
}
if(vis[st][ls])return ;
vis[st][ls]=1;
for(int i=0;i<=3;i++)
{
if(((ls|i)==aa[st-1])&&((ls&i)==bb[st-1]))
{
ans.push_back(i);
dfs(st+1,i);
ans.pop_back();
}
}
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
cin>>n;
for(int i=1;i<n;i++)
cin>>aa[i];
for(int i=1;i<n;i++)
cin>>bb[i];
ans.push_back(0);
dfs(2,0);ans.pop_back();
ans.push_back(1);
dfs(2,1);ans.pop_back();
ans.push_back(2);
dfs(2,2);ans.pop_back();
ans.push_back(3);
dfs(2,3);ans.pop_back();
cout<<"NO"<<endl;
return 0;
} | 26.811321 | 111 | 0.416608 | [
"vector"
] |
23ccbc8e2e88bb3d5a4398e1ff7798f4bc5342cd | 17,255 | cpp | C++ | src/GRASP-TSPTW/src/metaheuristic/model/solution.cpp | mesax1/Eafit-UdeA-Amazon-Last-Mile-Routing-Challenge | 51c4f1cf14529eee558395c4cf90c4685f786fbe | [
"Apache-2.0"
] | 2 | 2021-08-19T06:28:57.000Z | 2021-12-31T15:06:23.000Z | src/GRASP-TSPTW/src/metaheuristic/model/solution.cpp | mesax1/Eafit-UdeA-Amazon-Last-Mile-Routing-Challenge | 51c4f1cf14529eee558395c4cf90c4685f786fbe | [
"Apache-2.0"
] | null | null | null | src/GRASP-TSPTW/src/metaheuristic/model/solution.cpp | mesax1/Eafit-UdeA-Amazon-Last-Mile-Routing-Challenge | 51c4f1cf14529eee558395c4cf90c4685f786fbe | [
"Apache-2.0"
] | null | null | null | #include "./solution.h"
#include <boost/format.hpp>
#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <sstream>
#include <set>
#include <unordered_map>
using namespace std;
//TSP INSTANCES
TSPVehicle::TSPVehicle(const TSPVehicle& other_vehicle)
:Q(other_vehicle.Q)
,customers(other_vehicle.customers)
, load(other_vehicle.load)
, currentTime(other_vehicle.currentTime)
, currentCustomer(other_vehicle.currentCustomer)
, cost(other_vehicle.cost)
, arrivalTime(other_vehicle.arrivalTime)
{
}
TSPVehicle::TSPVehicle(int n_cust, int Q)
{
/**
* Vehicle object that carries the goods
*/
this->Q = Q;
this->customers = {};
this->load = 0;
this->currentTime = 0;
this->currentCustomer = 0; // starting location is depot
this->cost = 0;
this->arrivalTime = {};
}
TSPVehicle::~TSPVehicle()
{
}
void TSPVehicle::add_customer(TSPCustomer& customer, const TSPInstance& instance)
{
/**
* Add customer to vehicle route
* @param customer Object of class Node
* @param instance Object of class TSPInstance
*/
this->customers.push_back(&customer);
this->currentTime += instance.time_matrix[this->currentCustomer][customer.id];
this->currentCustomer = customer.id;
this->arrivalTime.push_back(currentTime);
customer.visited_time = this->currentTime;
if (customer.id == instance.depot_pos){
customer.visited_time = 0;
}
this->currentTime += customer.service_time;
this->load += customer.demand;
}
void TSPVehicle::insert_customer(TSPCustomer& customer, int position, const TSPInstance& instance)
{
this->customers.insert(this->customers.begin() + position, &customer); // Insert customer between customerBefore and customerAfter
this->load += customer.demand;
}
void TSPVehicle::remove_customer(int position, const TSPInstance& instance)
{
this->load -= this->customers[position]->demand;
this->customers.erase(this->customers.begin() + position);
}
TSPCustomer::TSPCustomer()
{
}
TSPCustomer::TSPCustomer(const TSPCustomer& other_customer)
: id(other_customer.id)
, time_window(other_customer.time_window)
, demand(other_customer.demand)
, vehicle_route(other_customer.vehicle_route)
, isRouted(other_customer.isRouted)
, service_time(other_customer.service_time)
, visited_time(other_customer.visited_time)
, zone_id(other_customer.zone_id)
{
}
TSPCustomer::TSPCustomer(int id, vector<float> time_window, float service_time, float demand, string zone_id)
{
this->id = id;
this->time_window = time_window;
this->service_time = service_time;
this->visited_time = -1;
this->vehicle_route = -1;
this->isRouted = false;
this->demand = demand;
this->zone_id = zone_id;
}
TSPCustomer::~TSPCustomer()
{
}
TSPSolution::TSPSolution()
{
}
TSPSolution::TSPSolution(const TSPInstance& instance, int n_vehicles)
{
this->vehicles = vector<TSPVehicle*>();
for(int n = 0; n < n_vehicles; n++) {
this->vehicles.push_back(new TSPVehicle(instance.n_cust, instance.Q));
}
this->customers = vector<TSPCustomer*>();
for(int n = 0; n < instance.n_cust; n++) {
TSPCustomer *cliente = new TSPCustomer(n, instance.time_windows[n], instance.service_time[n], instance.demands[n], instance.zone_id[n]);
this->customers.push_back(cliente);
}
this->cost = 0;
this->n_vehicles = n_vehicles;
this->time_cost = 0;
this->heading_penalization_cost = 0;
this->angle_penalization_cost = 0;
this->time_window_cost = 0;
this->zone_time_penalization_cost = 0;
this->zone_distance_penalization_cost = 0;
}
TSPSolution::TSPSolution(const TSPSolution& otherSolution)
: vehicles(otherSolution.vehicles)
, customers(otherSolution.customers)
, cost(otherSolution.cost)
, n_vehicles(otherSolution.n_vehicles)
, time_cost(otherSolution.time_cost)
, heading_penalization_cost(otherSolution.heading_penalization_cost)
, angle_penalization_cost(otherSolution.angle_penalization_cost)
, time_window_cost(otherSolution.time_window_cost)
, zone_time_penalization_cost(otherSolution.zone_time_penalization_cost)
, zone_distance_penalization_cost(otherSolution.zone_distance_penalization_cost)
{
}
TSPSolution::~TSPSolution()
{
for(int i = this->customers.size() - 1; i > -1; i--) {
TSPCustomer* c = this->customers[i];
//delete c;
this->customers[i] = nullptr;
}
customers.clear();
for(int i = this->vehicles.size() - 1; i > -1; i--) {
TSPVehicle* v = this->vehicles[i];
//delete v;
this->vehicles[i] = nullptr;
}
vehicles.clear();
}
float TSPSolution::compute_cost(const TSPInstance& instance)
{
this->cost = 0;
int prev = -1;
int curr = -1;
bool first_it;
for(auto& vehicle : this->vehicles) {
prev = -1;
curr = -1;
first_it = true;
for(int i = 0; i < vehicle->customers.size(); i++) {
curr = vehicle->customers[i]->id;
this->cost += instance.service_time[curr];
if(prev != -1) {
this->cost += instance.time_matrix[prev][curr];
}
prev = curr;
}
}
return this->cost;
}
float TSPSolution::compute_prob_cost(const TSPInstance& instance)
{
std::unordered_map<std::string, int> * solution_zones_order = new std::unordered_map<std::string, int> ();
float m_time_cost = 0;
float m_time_window_cost = 0;
float m_heading_penalization_cost = 0;
float m_angle_penalization_cost = 0;
float m_zone_time_penalization_cost = 0;
float m_zone_distance_penalization_cost = 0;
float m_normalized_time_cost = 0;
this->cost = 0;
int prev = -1;
int curr = -1;
string current_zone;
int zone_order_counter = 0;
bool first_it;
for(auto& vehicle : this->vehicles) {
prev = -1;
curr = -1;
first_it = true;
for(int i = 0; i < vehicle->customers.size(); i++) {
curr = vehicle->customers[i]->id;
current_zone = vehicle->customers[i]->zone_id;
m_time_cost += instance.service_time[curr];
if(prev != -1) {
m_time_cost += instance.time_matrix[prev][curr];
unordered_map<string, int>::iterator it = solution_zones_order->find(current_zone);
// key already present in the map
if (it != solution_zones_order->end()) {
}
else { // key not found
solution_zones_order->insert(make_pair(current_zone ,zone_order_counter));
zone_order_counter++;
}
auto current_customer = vehicle->customers[i];
if (current_customer->time_window[0] > -1) {
if ((m_time_cost < current_customer->time_window[0]) ||
(m_time_cost > current_customer->time_window[1])) {
m_time_window_cost += 1;
}
}
}
prev = curr;
}
}
int x_ij = 0;
int immediate_x_ij = 0;
float p_ij = 0.0;
float angle_ij = 0.0;
float zone_distance_ij = 0.0;
float zone_time_ij = 0.0;
string zone_1;
string zone_2;
for (int i=0; i < instance.historic_zones_id.size(); i++){
zone_1 = instance.historic_zones_id[i];
for (int j=0; j < instance.historic_zones_id.size(); j++){
zone_2 = instance.historic_zones_id[j];
if (solution_zones_order->at(zone_1) <= solution_zones_order->at(zone_2)){
x_ij = 1;
}
else{
x_ij = 0;
}
if (solution_zones_order->at(zone_1) - solution_zones_order->at(zone_2) == -1){
immediate_x_ij = 1;
}
else{
immediate_x_ij = 0;
}
p_ij = instance.probabilities_df.at(zone_1).at(zone_2);
angle_ij = instance.angles_df.at(zone_1).at(zone_2);
zone_time_ij = instance.zones_time_matrix_df.at(zone_1).at(zone_2);
zone_distance_ij = instance.zones_distance_matrix_df.at(zone_1).at(zone_2);
m_heading_penalization_cost += ( ((x_ij * (1-p_ij)) ))/ instance.n_cust;
m_angle_penalization_cost += ((immediate_x_ij * (angle_ij)) / (instance.historic_zones_id.size()));
m_zone_time_penalization_cost += ((immediate_x_ij * (zone_time_ij)) / (instance.historic_zones_id.size()));
m_zone_distance_penalization_cost += ((immediate_x_ij * (zone_distance_ij)) / (instance.historic_zones_id.size()));
}
}
m_normalized_time_cost = (m_time_cost) / instance.worst_initial_cost;
m_time_window_cost = m_time_window_cost / instance.n_cust;
this->time_cost = m_normalized_time_cost;
this->heading_penalization_cost = m_heading_penalization_cost;
this->angle_penalization_cost = m_angle_penalization_cost;
this->time_window_cost = m_time_window_cost;
this->zone_time_penalization_cost = m_zone_time_penalization_cost;
this->zone_distance_penalization_cost = m_zone_distance_penalization_cost;
this->cost = m_normalized_time_cost + m_heading_penalization_cost + m_angle_penalization_cost +
m_zone_time_penalization_cost + m_zone_distance_penalization_cost + m_time_window_cost;
delete solution_zones_order;
return this->cost;
}
ostringstream& TSPSolution::TSP_output_number_solutions() const
{
vector<string> lines = {};
string chain;
vector<int> customers_ids;
for(auto& vehicle : this->vehicles) {
customers_ids = vector<int>();
for(auto& customer : vehicle->customers) {
// if(customer->id != 99)
customers_ids.push_back(customer->id);
}
chain = ""; // revisar este metodo
int cont = 0;
for(auto& id : customers_ids) {
if(cont == customers_ids.size() - 1) {
chain += to_string(id);
} else {
chain += (boost::format("%1% ") % id).str();
}
cont++;
}
lines.push_back(chain);
}
ostringstream* vts = new ostringstream();
// Convert all but the last element to avoid a trailing ","
copy(lines.begin(), lines.end() - 1, ostream_iterator<string>(*vts, "\n"));
// Now add the last element with no delimiter
*vts << lines.back();
return *vts;
}
template < typename Type > std::string to_str (const Type & t)
{
std::ostringstream os;
os << t;
return os.str ();
}
ostringstream& TSPSolution::TSP_output_string_solutions(const TSPInstance& instance) const
{
vector<string> lines = {};
string chain;
vector<string> customers_ids;
for(auto& vehicle : this->vehicles) {
customers_ids = vector<string>();
for(auto& customer : vehicle->customers) {
customers_ids.push_back(instance.customers_map.at(customer->id));
}
int cont = 0;
for(auto& id : customers_ids) {
if(cont == customers_ids.size() - 1) {
chain += id;
} else {
chain += (boost::format("%1%, ") % id).str();
}
cont++;
}
lines.push_back(chain);
}
ostringstream* vts = new ostringstream();
// Convert all but the last element to avoid a trailing ","
copy(lines.begin(), lines.end() - 1, ostream_iterator<string>(*vts, "\n"));
// Now add the last element with no delimiter
*vts << lines.back();
return *vts;
}
ostringstream& TSPSolution::TSP_output_string_local_optimas(const TSPInstance& instance) const
{
vector<string> lines = {};
string chain;
string chain_2;
vector<string> customers_ids;
vector<string> zones_ids;
set <string> zones_ids_set;
for(auto& vehicle : this->vehicles) {
customers_ids = vector<string>();
zones_ids = vector<string>();
for(auto& customer : vehicle->customers) {
customers_ids.push_back(instance.customers_map.at(customer->id));
auto it = zones_ids_set.find(customer->zone_id);
if (it != zones_ids_set.end())
{
// Do something with it, no more lookup needed.
}
else
{
zones_ids_set.insert(customer->zone_id);
zones_ids.push_back(customer->zone_id);
}
}
int cont = 0;
int cont_2 = 0;
for(auto& id : customers_ids) {
if(cont == customers_ids.size() - 1) {
chain += id;
} else {
chain += (boost::format("%1%, ") % id).str();
}
cont++;
}
lines.push_back(chain);
for(auto& id : zones_ids) {
if(cont_2 == zones_ids.size() - 1) {
chain_2 += id;
} else {
chain_2 += (boost::format("%1%, ") % id).str();
}
cont_2++;
}
lines.push_back(chain_2);
}
lines.push_back(to_str(this->cost));
lines.push_back(to_str(this->time_cost));
lines.push_back(to_str(this->heading_penalization_cost));
lines.push_back(to_str(this->angle_penalization_cost));
lines.push_back(to_str(this->time_window_cost));
lines.push_back(to_str(this->zone_time_penalization_cost));
lines.push_back(to_str(this->zone_distance_penalization_cost));
ostringstream* vts = new ostringstream();
// Convert all but the last element to avoid a trailing ","
copy(lines.begin(), lines.end() - 1, ostream_iterator<string>(*vts, "\n"));
// Now add the last element with no delimiter
*vts << lines.back();
return *vts;
}
/*
vector<string> store_output_info(const TSPInstance& instance, TSPSolution* current_solution){
vector<string> lines = {};
string chain;
string chain_2;
vector<string> customers_ids;
vector<string> zones_ids;
set <string> zones_ids_set;
for(auto& vehicle : current_solution->vehicles) {
customers_ids = vector<string>();
zones_ids = vector<string>();
for(auto& customer : vehicle->customers) {
customers_ids.push_back(instance.customers_map.at(customer->id));
auto it = zones_ids_set.find(customer->zone_id);
if (it != zones_ids_set.end())
{
// Do something with it, no more lookup needed.
}
else
{
zones_ids_set.insert(customer->zone_id);
zones_ids.push_back(customer->zone_id);
}
}
int cont = 0;
int cont_2 = 0;
for(auto& id : customers_ids) {
if(cont == customers_ids.size() - 1) {
chain += id;
} else {
chain += (boost::format("%1%, ") % id).str();
}
cont++;
}
lines.push_back(chain);
for(auto& id : zones_ids) {
if(cont_2 == zones_ids.size() - 1) {
chain_2 += id;
} else {
chain_2 += (boost::format("%1%, ") % id).str();
}
cont_2++;
}
lines.push_back(chain_2);
}
lines.push_back(to_str(current_solution->cost));
lines.push_back(to_str(current_solution->time_cost));
lines.push_back(to_str(current_solution->heading_penalization_cost));
lines.push_back(to_str(current_solution->angle_penalization_cost));
lines.push_back(to_str(current_solution->time_window_cost));
lines.push_back(to_str(current_solution->zone_time_penalization_cost));
lines.push_back(to_str(current_solution->zone_distance_penalization_cost));
return lines;
}
*/
ostringstream& TSPSolution::TSP_output_string_zones(const TSPInstance& instance) const
{
vector<string> lines = {};
string chain;
vector<string> zones_ids;
set <string> zones_ids_set;
for(auto& vehicle : this->vehicles) {
zones_ids = vector<string>();
for(auto& customer : vehicle->customers) {
auto it = zones_ids_set.find(customer->zone_id);
if (it != zones_ids_set.end())
{
// Do something with it, no more lookup needed.
}
else
{
zones_ids_set.insert(customer->zone_id);
zones_ids.push_back(customer->zone_id);
}
}
int cont = 0;
for(auto& id : zones_ids) {
if(cont == zones_ids.size() - 1) {
chain += id;
} else {
chain += (boost::format("%1%, ") % id).str();
}
cont++;
}
lines.push_back(chain);
}
ostringstream* vts = new ostringstream();
// Convert all but the last element to avoid a trailing ","
copy(lines.begin(), lines.end() - 1, ostream_iterator<string>(*vts, "\n"));
// Now add the last element with no delimiter
*vts << lines.back();
return *vts;
}
| 32.072491 | 144 | 0.602086 | [
"object",
"vector"
] |
23d32b16caa86cf5ce208cb188a4f49de1d4b57f | 563 | cpp | C++ | nowcoder/22065/K.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | nowcoder/22065/K.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | nowcoder/22065/K.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
char fuck[20];
vector<int> pos, neg;
int main() {
int n;
scanf("%d", &n);
for (int i = 1, x; i <= n; ++ i) {
scanf("%s%d", fuck, &x);
if (fuck[0] == '+') pos.push_back(x);
else neg.push_back(x);
}
sort(pos.begin(), pos.end());
sort(neg.begin(), neg.end());
long long ans = 0;
for (size_t ns = 0, ps = 0; ns < neg.size(); ++ ns) {
while (ps < pos.size() && pos[ps] <= neg[ns]) ++ ps;
ans += pos.size() - ps;
}
printf("%.15lf\n", (double) ans / pos.size() / neg.size());
} | 20.107143 | 61 | 0.502664 | [
"vector"
] |
23d7b3f7530e8a8dda4b560bdd7536ccdd0b3920 | 9,963 | cpp | C++ | SOURCE_FILES_SECONDARY/Source/MainComponent.cpp | tobemo/SPAI_project_2019_group1 | 8ab8d841b984ff7bd5ab344601e0ed567bb93ef9 | [
"MIT"
] | null | null | null | SOURCE_FILES_SECONDARY/Source/MainComponent.cpp | tobemo/SPAI_project_2019_group1 | 8ab8d841b984ff7bd5ab344601e0ed567bb93ef9 | [
"MIT"
] | null | null | null | SOURCE_FILES_SECONDARY/Source/MainComponent.cpp | tobemo/SPAI_project_2019_group1 | 8ab8d841b984ff7bd5ab344601e0ed567bb93ef9 | [
"MIT"
] | null | null | null | /*
==============================================================================
This file was auto-generated!
==============================================================================
*/
#include "MainComponent.h"
//==============================================================================
MainComponent::MainComponent()
{
// Make sure you set the size of the component after
// you add any child components.
addAndMakeVisible(titleLabel);
titleLabel.setText("ConnexSound", dontSendNotification);
titleLabel.setFont (Font (28.0f, Font::bold));
addAndMakeVisible(ipInputLabel);
addAndMakeVisible(ipLabel);
ipLabel.setText("IP Address", dontSendNotification);
ipLabel.setFont (Font (12.0f, Font::bold));
ipInputLabel.setEditable(true);
ipInputLabel.setColour (Label::backgroundColourId, Colours::lightgrey);
ipInputLabel.onTextChange = [this] {
ipAddr = ipInputLabel.getText();
};
addAndMakeVisible(portInputLabel);
addAndMakeVisible(portLabel);
portLabel.setText("Port Number", dontSendNotification);
portLabel.setFont (Font (12.0f, Font::bold));
portInputLabel.setEditable(true);
portInputLabel.setColour (Label::backgroundColourId, Colours::lightgrey);
portInputLabel.onTextChange = [this] {
std::string text = (portInputLabel.getText()).toStdString();
std::istringstream iss (text);
iss >> portNumber;
};
addAndMakeVisible(resampleInputLabel);
addAndMakeVisible(resampleLabel);
resampleLabel.setText("Resample Index", dontSendNotification);
resampleLabel.setFont (Font (12.0f, Font::bold));
resampleInputLabel.setEditable(true);
resampleInputLabel.setColour (Label::backgroundColourId, Colours::lightgrey);
resampleInputLabel.onTextChange = [this] {
};
addAndMakeVisible(filePathInputLabel);
addAndMakeVisible(filePathLabel);
filePathLabel.setText("File Path", dontSendNotification);
filePathLabel.setFont (Font (12.0f, Font::bold));
filePathInputLabel.setEditable(true);
filePathInputLabel.setColour (Label::backgroundColourId, Colours::lightgrey);
filePathInputLabel.onTextChange = [this] {
pathName = filePathInputLabel.getText();
};
addAndMakeVisible(startRecordingButton);
startRecordingButton.onClick = [this] {
if(ipAddr == ""){
String error = "Invallid Ip Address";
NativeMessageBox::showMessageBoxAsync (AlertWindow::WarningIcon, "Input error",
error);
}
else if(portNumber <= 0){
String error = "Invallid Port Number";
NativeMessageBox::showMessageBoxAsync (AlertWindow::WarningIcon, "Input error",
error);
}
else if(pathName == ""){
String error = "Invallid Path Name";
NativeMessageBox::showMessageBoxAsync (AlertWindow::WarningIcon, "Input error",
error);
}
else {
writeSocket.bindToPort(portNumber);
#if (JUCE_ANDROID || JUCE_IOS)
auto parentDir = File::getSpecialLocation (File::tempDirectory);
#else
auto parentDir = File::getSpecialLocation (File::userDocumentsDirectory);
#endif
lastRecording = parentDir.getNonexistentChildFile (pathName, ".wav");
startRecording = true;
}
};
addAndMakeVisible(stopRecordingButton);
stopRecordingButton.onClick = [this] {
startRecording = false;
writeWAV(toFileBuffer, lastRecording);
toFileBuffer.clear();
};
setSize (800, 600);
// Some platforms require permissions to open input channels so request that here
if (RuntimePermissions::isRequired (RuntimePermissions::recordAudio)
&& ! RuntimePermissions::isGranted (RuntimePermissions::recordAudio))
{
RuntimePermissions::request (RuntimePermissions::recordAudio,
[&] (bool granted) { if (granted) setAudioChannels (2, 2); });
}
else
{
// Specify the number of input and output channels that we want to open
setAudioChannels (2, 2);
}
AudioDeviceManager::AudioDeviceSetup deviceSetup = AudioDeviceManager::AudioDeviceSetup();
deviceSetup.bufferSize = BUFFERSIZE;
deviceManager.initialise (2, 2, 0, true, "" , &deviceSetup);
}
MainComponent::~MainComponent()
{
// This shuts down the audio device and clears the audio source.
shutdownAudio();
}
//==============================================================================
void MainComponent::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
{
// This function will be called when the audio device is started, or when
// its settings (i.e. sample rate, block size, etc) are changed.
// You can use this function to initialise any resources you might need,
// but be careful - it will be called on the audio thread, not the GUI thread.
// For more details, see the help for AudioProcessor::prepareToPlay()
}
void MainComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
{
// Your audio-processing code goes here!
// For more details, see the help for AudioProcessor::getNextAudioBlock()
// Right now we are not producing any data, in which case we need to clear the buffer
// (to prevent the output of random noise)
if(startRecording){
auto * inBuff = bufferToFill.buffer->getReadPointer(0, bufferToFill.startSample);
for(int i=0; i<bufferToFill.numSamples; i++){
toFileBuffer.push_back(inBuff[i]);
}
writeSocket.write(ipAddr, portNumber, inBuff, sizeof(float)*bufferToFill.numSamples);
}
bufferToFill.clearActiveBufferRegion();
}
void MainComponent::releaseResources()
{
// This will be called when the audio device stops, or when it is being
// restarted due to a setting change.
// For more details, see the help for AudioProcessor::releaseResources()
}
//==============================================================================
void MainComponent::paint (Graphics& g)
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
// You can add your drawing code here!
}
void MainComponent::resized()
{
// This is called when the MainContentComponent is resized.
// If you add any child components, this is where you should
// update their positions.
int x = 10;
int y = 10;
int buttonWidth = 140;
int buttonHeight = 60;
int inputHeight = 50;
titleLabel.setBounds(x, y, 200, 40);
ipInputLabel.setBounds(x+100, getHeight()/2-45-inputHeight, 200, 30);
portInputLabel.setBounds(x+100,getHeight()/2-inputHeight,200,30);
resampleInputLabel.setBounds(x+100, getHeight()/2+45-inputHeight, 200, 30);
filePathInputLabel.setBounds(x, getHeight()/2+100, getWidth()-2*x, 30);
startRecordingButton.setBounds(x, getHeight()-y*8, buttonWidth, buttonHeight);
stopRecordingButton.setBounds(getWidth()-buttonWidth-x, getHeight()-y*8, buttonWidth, buttonHeight);
ipLabel.setBounds(x, getHeight()/2-45+4-inputHeight, 100, 20);
portLabel.setBounds(x, getHeight()/2+4-inputHeight, 100, 20);
resampleLabel.setBounds(x, getHeight()/2+45+4-inputHeight, 100, 20);
filePathLabel.setBounds(x, getHeight()/2+75, getWidth()-2*x, 20);
}
void MainComponent::writeWAV(std::vector<float> samples, File file) {
float *h1 = samples.data();
float** h2 = &h1;
AudioBuffer<float> buffer(1, samples.size());
buffer.setDataToReferTo(h2, 1, samples.size());
File tempFile = (file);
tempFile.create();
const StringPairArray& metadataValues("");
AudioBuffer<float> fileBuffer;
WavAudioFormat wav;
ScopedPointer <OutputStream> outStream(tempFile.createOutputStream());
if (outStream != nullptr){
ScopedPointer <AudioFormatWriter> writer(wav.createWriterFor(outStream, 44100, 1, (int)32, metadataValues, 0));
if (writer != nullptr){
outStream.release();
writer->writeFromAudioSampleBuffer(buffer, 0, samples.size());
}
writer = nullptr;
}
#if (JUCE_ANDROID || JUCE_IOS)
SafePointer<MainComponent> safeThis (this);
File fileToShare = lastRecording;
ContentSharer::getInstance()->shareFiles (Array<URL> ({URL (fileToShare)}),
[safeThis, fileToShare] (bool success, const String& error)
{
if (fileToShare.existsAsFile())
fileToShare.deleteFile();
if (! success && error.isNotEmpty())
{
NativeMessageBox::showMessageBoxAsync (AlertWindow::WarningIcon,
"Sharing Error",
error);
std::cout << "Pathname :" << fileToShare.getFullPathName() << std::endl;
}
});
#endif
}
| 40.831967 | 136 | 0.576935 | [
"vector",
"solid"
] |
23da04474921c6d602d63e55ea0d5b8cfd2868d7 | 43,464 | hpp | C++ | linq/include/linq/enumerable.hpp | FelixCpp/linq | c8612d6a02b31b10844ac2dcd1b15e72e0657cd4 | [
"MIT"
] | null | null | null | linq/include/linq/enumerable.hpp | FelixCpp/linq | c8612d6a02b31b10844ac2dcd1b15e72e0657cd4 | [
"MIT"
] | null | null | null | linq/include/linq/enumerable.hpp | FelixCpp/linq | c8612d6a02b31b10844ac2dcd1b15e72e0657cd4 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <linq/ranges/iterator_range.hpp>
#include <linq/ranges/repeat_range.hpp>
#include <linq/ranges/empty_range.hpp>
#include <linq/ranges/increment_range.hpp>
#include <linq/ranges/except_range.hpp>
#include <linq/ranges/concat_range.hpp>
#include <linq/ranges/where_range.hpp>
#include <linq/ranges/select_range.hpp>
#include <linq/ranges/intersect_with_range.hpp>
#include <linq/ranges/distinct_range.hpp>
#include <linq/ranges/skip_range.hpp>
#include <linq/ranges/take_range.hpp>
#include <linq/ranges/skip_while_range.hpp>
#include <linq/ranges/take_while_range.hpp>
#include <linq/ranges/reverse_range.hpp>
#include <linq/ranges/orderby_range.hpp>
#include <linq/ranges/thenby_range.hpp>
#include <linq/ranges/select_many_range.hpp>
#include <linq/ranges/pairwise_range.hpp>
#include <linq/ranges/join_range.hpp>
#include <linq/ranges/union_range.hpp>
#include <linq/ranges/shuffle_range.hpp>
#include <linq/ranges/zip_with_range.hpp>
#include <linq/ranges/container.hpp>
#include <linq/utils/array_traits.hpp>
#include <linq/utils/concepts.hpp>
namespace linq
{
template<typename TKey, typename TValue>
class lookup;
template<range_concept TRange>
class enumerable
{
public:
/// <summary>
/// type definitions
/// </summary>
using range_type = TRange;
using value_type = typename TRange::value_type;
using return_type = typename TRange::return_type;
private:
template<typename TLambda, typename TResult> inline static constexpr bool is_lambda = std::is_invocable_v<TLambda, value_type> && std::is_same_v<std::invoke_result_t<TLambda, value_type>, TResult>;
template<typename TPredicate> inline static constexpr bool is_predicate = is_lambda<TPredicate, bool>;
template<typename TAction> inline static constexpr bool is_action = is_lambda<TAction, void>;
public:
/// <summary>
/// Constructs an enumerable with
/// a given range
/// </summary>
/// <param name="range">the range to operate on</param>
_NODISCARD_CTOR explicit enumerable(const range_type & range)
: range(range)
{
}
/// <summary>
/// Returns the range of the enumerable
/// </summary>
_NODISCARD const range_type & get_range() const
{
return this->range;
}
/// <summary>
/// Creates a new enumerable which ignores the values
/// stored in the except_range
/// </summary>
/// <param name="collection">an enumerable holding each value to ignore</param>
template<range_concept TExceptRange>
_NODISCARD enumerable<except_range<range_type, TExceptRange>> except(const enumerable<TExceptRange> & collection) const
{
return enumerable<except_range<range_type, TExceptRange>>(
except_range<range_type, TExceptRange>(this->range, collection.get_range())
);
}
/// <summary>
/// Concatenates two range
/// </summary>
/// <param name="collection">an enumerable holding the range to concatenate behind the existing range</param>
/// <returns>an enumerable holding values from the previous and the concatenated ranges</returns>
template<range_concept TConcatRange>
_NODISCARD enumerable<concat_range<range_type, TConcatRange>> concat(const enumerable<TConcatRange> & collection) const
{
return enumerable<concat_range<range_type, TConcatRange>>(
concat_range<range_type, TConcatRange>(this->range, collection.get_range())
);
}
/// <summary>
/// Iterates over the range and filter values based on
/// the given predicate
/// </summary>
/// <param name="predicate">the predicate which checks if the value gets filtered or stays in the range</param>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD enumerable<where_range<range_type, TPredicate>> where(const TPredicate & predicate) const
{
return enumerable<where_range<range_type, TPredicate>>(
where_range<range_type, TPredicate>(this->range, predicate)
);
}
/// <summary>
/// Transforms the original value into anything else
/// </summary>
/// <typeparam name="TLambda">the lambda to invoke</typeparam>
/// <typeparam name="TResult">the result type</typeparam>
/// <param name="transformation">the transformation for each value</param>
template<typename TLambda, typename TResult = std::invoke_result_t<TLambda, value_type>>
_NODISCARD enumerable<select_range<range_type, TLambda>> select(const TLambda & transformation) const
{
return enumerable<select_range<range_type, TLambda>>(
select_range<range_type, TLambda>(this->range, transformation)
);
}
/// <summary>
/// Combines two ranges together and returns an enumerable
/// of the values which are duplicated in both ranges
/// </summary>
/// <param name="collection">an enumerable holding the range to compare against</param>
/// <returns>an enumerable holding values which both ranges contain</returns>
template<range_concept TIntersectsRange>
_NODISCARD enumerable<intersect_with_range<range_type, TIntersectsRange>> intersect_with(const enumerable<TIntersectsRange> & collection) const
{
return enumerable<intersect_with_range<range_type, TIntersectsRange>>(
intersect_with_range<range_type, TIntersectsRange>(this->range, collection.get_range())
);
}
/// <summary>
/// Removes all duplicates from the range
/// </summary>
_NODISCARD enumerable<distinct_range<range_type>> distinct() const
{
return enumerable<distinct_range<range_type>>(
distinct_range<range_type>(this->range)
);
}
/// <summary>
/// Skips a certain amount of elements at the front
/// of the range
/// </summary>
/// <param name="count">the number of elements to skip</param>
_NODISCARD enumerable<skip_range<range_type>> skip(size_t count) const
{
return enumerable<skip_range<range_type>>(
skip_range<range_type>(this->range, count)
);
}
/// <summary>
/// Takes a certain amount of elements at the front
/// of the range
/// </summary>
/// <param name="count">the number of elements to take</param>
_NODISCARD enumerable<take_range<range_type>> take(size_t count) const
{
return enumerable<take_range<range_type>>(
take_range<range_type>(this->range, count)
);
}
/// <summary>
/// Skips as long as the predicate returns
/// true on these elements
/// </summary>
/// <param name="predicate">the predicate to check against each value</param>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD enumerable<skip_while_range<range_type, TPredicate>> skip_while(const TPredicate & predicate) const
{
return enumerable<skip_while_range<range_type, TPredicate>>(
skip_while_range<range_type, TPredicate>(this->range, predicate)
);
}
/// <summary>
/// Takes as long as the predicate returns
/// true on these elements
/// </summary>
/// <param name="predicate">the predicate to check against each value</param>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD enumerable<take_while_range<range_type, TPredicate>> take_while(const TPredicate & predicate) const
{
return enumerable<take_while_range<range_type, TPredicate>>(
take_while_range<range_type, TPredicate>(this->range, predicate)
);
}
/// <summary>
/// Reverses the range
/// </summary>
_NODISCARD enumerable<reverse_range<range_type>> reverse() const
{
return enumerable<reverse_range<range_type>>(
reverse_range<range_type>(this->range)
);
}
/// <summary>
/// creates a list based on the values of the range
/// </summary>
_NODISCARD std::list<value_type> to_list() const
{
range_type copy = this->range;
std::list<value_type> values;
while (copy.move_next())
{
values.push_back(copy.get_value());
}
return values;
}
/// <summary>
/// creates a vector based on the values of the range
/// </summary>
_NODISCARD std::vector<value_type> to_vector(size_t capacity = 16) const
{
range_type copy = this->range;
std::vector<value_type> values;
values.reserve(capacity);
while (copy.move_next())
{
values.push_back(copy.get_value());
}
return values;
}
/// <summary>
/// Iterates through the range and performs an action
/// for each value
/// </summary>
/// <param name="action">the action to perform for each value</param>
template<typename TAction, typename = std::enable_if_t<is_action<TAction>>>
_NODISCARD void for_each(const TAction & action) const
{
range_type copy = this->range;
while (copy.move_next())
{
action(copy.get_value());
}
}
/// <summary>
/// Iterates through the range and performs an action
/// for each value
/// </summary>
/// <param name="action">the action to perform for each value</param>
template<typename TAction, typename = std::enable_if_t<std::is_same_v<std::invoke_result_t<TAction, value_type, size_t>, void>>>
_NODISCARD void indexed_for_each(const TAction & action) const
{
range_type copy = this->range;
for(size_t index = 0; copy.move_next(); index++)
{
action(copy.get_value(), index);
}
}
#ifndef min
/// <summary>
/// Determines the lowest value of
/// the range
/// </summary>
_NODISCARD value_type min() const
{
range_type copy = this->range;
if (!copy.move_next())
throw sequence_empty_exception();
auto record = copy.get_value();
while (copy.move_next())
{
const auto value = copy.get_value();
if (value < record)
record = value;
}
return record;
}
/// <summary>
/// Determines the lowest value of
/// the range
/// </summary>
/// <param name="transformation">a transformation function for each element</param>
template<typename TLambda, typename TResult = std::invoke_result_t<TLambda, value_type>>
_NODISCARD TResult min(const TLambda & transformation) const
{
range_type copy = this->range;
if (!copy.move_next())
throw sequence_empty_exception();
auto record = transformation(copy.get_value());
while (copy.move_next())
{
const auto value = transformation(copy.get_value());
if (value < record)
record = value;
}
return record;
}
#endif // !min
#ifndef max
/// <summary>
/// Determines the highest value of
/// the range
/// </summary>
_NODISCARD value_type max() const
{
range_type copy = this->range;
if (!copy.move_next())
throw sequence_empty_exception();
auto record = copy.get_value();
while (copy.move_next())
{
const auto value = copy.get_value();
if (value > record)
record = value;
}
return record;
}
/// <summary>
/// Determines the highest value of
/// the range
/// </summary>
/// <param name="transformation">a transformation function for each element</param>
template<typename TLambda, typename TResult = std::invoke_result_t<TLambda, value_type>>
_NODISCARD TResult max(const TLambda & transformation) const
{
range_type copy = this->range;
if (!copy.move_next())
throw sequence_empty_exception();
auto record = transformation(copy.get_value());
while (copy.move_next())
{
const auto value = transformation(copy.get_value());
if (value > record)
record = value;
}
return record;
}
#endif // !max
/// <summary>
/// Determines the number of elements held by the range
/// </summary>
/// <returns>the number of elements</returns>
_NODISCARD size_t count() const
{
range_type copy = this->range;
size_t count = 0;
while (copy.move_next())
++count;
return count;
}
/// <summary>
/// Determines the number of elements held by the range satisfying
/// the condition of the predicate
/// </summary>
/// <param name="predicate">a predicate for each element deciding whether to count that element or not</param>
/// <returns>the number of elements satisfying the predicate</returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD size_t count(const TPredicate & predicate) const
{
range_type copy = this->range;
size_t count = 0;
while (copy.move_next())
if (predicate(copy.get_value()))
++count;
return count;
}
/// <summary>
/// Determines whether the range has an element or
/// is empty
/// </summary>
/// <returns>True if the range has at least one element to process</returns>
_NODISCARD bool any() const
{
range_type copy = this->range;
return copy.move_next();
}
/// <summary>
/// Iterates through the range and checks the predicate on each value of
/// the range
/// </summary>
/// <param name="predicate">the predicate which needs to be satisfied by each range-value</param>
/// <returns></returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD bool any(const TPredicate & predicate) const
{
range_type copy = this->range;
while (copy.move_next())
{
if (predicate(copy.get_value()))
return true;
}
return false;
}
/// <summary>
/// Iterates through the range and checks the predicate on each value of
/// the range
/// </summary>
/// <param name="predicate">the predicate which needs to be satisfied by each range-value</param>
/// <returns></returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD bool all(const TPredicate & predicate) const
{
range_type copy = this->range;
while (copy.move_next())
{
if (!predicate(copy.get_value()))
return false;
}
return true;
}
/// <summary>
/// searches for a value by iterating through the range and
/// comparing each value with the given one using the == operator
/// </summary>
/// <param name="value">the value to search for</param>
/// <returns>True if the value was found</returns>
_NODISCARD bool contains(const value_type & value) const
{
range_type copy = this->range;
while (copy.move_next())
{
if (copy.get_value() == value)
return true;
}
return false;
}
/// <summary>
/// iterates through the range and tries to satisfy the predicate
/// </summary>
/// <param name="predicate">the predicate to satisfy</param>
/// <returns>True if the predicate returned once</returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD bool contains_if(const TPredicate & predicate) const
{
range_type copy = this->range;
while (copy.move_next())
{
if (predicate(copy.get_value()))
return true;
}
return false;
}
/// <summary>
/// Determines the average of the range
/// </summary>
/// <returns>the average of the range</returns>
_NODISCARD value_type avg() const
{
range_type copy = this->range;
// we don't have any elements to work with
if (!copy.move_next())
throw sequence_empty_exception();
auto value = copy.get_value();
size_t count = 1;
while (copy.move_next())
{
value += copy.get_value();
++count;
}
return value / count;
}
/// <summary>
/// Determines the average of the range
/// </summary>
/// <param name="transformation">a function to transform the values of the range</param>
/// <returns>the average of the range</returns>
template<typename TTransformation, typename TResult = std::invoke_result_t<TTransformation, value_type>>
_NODISCARD TResult avg(const TTransformation & transformation) const
{
range_type copy = this->range;
// we don't have any elements to work with
if (!copy.move_next())
throw sequence_empty_exception();
auto value = transformation(copy.get_value());
size_t count = 1;
while (copy.move_next())
{
value += transformation(copy.get_value());
++count;
}
return value / count;
}
/// <summary>
/// Determines the sum of the range
/// </summary>
/// <returns>the sum of the range</returns>
_NODISCARD value_type sum() const
{
range_type copy = this->range;
// we don't have any elements to work with
if (!copy.move_next())
throw sequence_empty_exception();
auto value = copy.get_value();
while (copy.move_next())
{
value += copy.get_value();
}
return value;
}
/// <summary>
/// Determines the sum of the range
/// </summary>
/// <param name="transformation">a function to transform the values of the range</param>
/// <returns>the sum of the range</returns>
template<typename TTransformation, typename TResult = std::invoke_result_t<TTransformation, value_type>>
_NODISCARD TResult sum(const TTransformation & transformation) const
{
range_type copy = this->range;
// we don't have any elements to work with
if (!copy.move_next())
throw sequence_empty_exception();
auto value = transformation(copy.get_value());
while (copy.move_next())
{
value += transformation(copy.get_value());
}
return value;
}
/// <summary>
/// aggregates each value with an accumulator starting at a certain seed
/// </summary>
/// <typeparam name="TAccumulate">the starting-value for the aggregation</typeparam>
/// <typeparam name="TAccumulator">the accumulator to use for each value in the list</typeparam>
/// <param name="seed">the starting value of the aggregation</param>
/// <param name="accumulator">a function to accumulate a value for each element in the list</param>
template<typename TAccumulate, typename TAccumulator, typename = std::enable_if_t<std::is_same_v<std::invoke_result_t<TAccumulator, TAccumulate, value_type>, TAccumulate>>>
_NODISCARD TAccumulate aggregate(const TAccumulate & seed, const TAccumulator & accumulator) const
{
range_type copy = this->range;
auto value = seed;
while (copy.move_next())
{
value = accumulator(value, copy.get_value());
}
return value;
}
/// <summary>
/// aggregates each value with an accumulator starting at a certain seed
/// and returns the transformed result
/// </summary>
/// <typeparam name="TAccumulate">the starting-value for the aggregation</typeparam>
/// <typeparam name="TAccumulator">the accumulator to use for each value in the list</typeparam>
/// <typeparam name="TTransformation">the transformation type used for the final result</typeparam>
/// <typeparam name="TResult">result-type of the transformation</typeparam>
/// <param name="seed">the starting value of the aggregation</param>
/// <param name="accumulator">a function to accumulate a value for each element in the list</param>
/// <param name="transformation">the transformation for the result</param>
template<typename TAccumulate, typename TAccumulator, typename TTransformation, typename = std::enable_if_t<std::is_same_v<std::invoke_result_t<TAccumulator, TAccumulate, value_type>, TAccumulate>>>
_NODISCARD std::invoke_result_t<TTransformation, TAccumulate> aggregate(const TAccumulate & seed, const TAccumulator & accumulator, const TTransformation & transformation) const
{
return transformation(this->aggregate(seed, accumulator));
}
/// <summary>
/// Looks up a specific element at a certain index
/// in the range.
///
/// This method throws
/// an index_out_of_bounds_exception in case
/// the index is too low or too high
/// </summary>
/// <param name="index">the index of the element</param>
/// <returns>the value stored behind that index</returns>
_NODISCARD value_type element_at(const size_t index) const
{
range_type copy = this->range;
size_t current = 0;
while (current <= index)
{
if (!copy.move_next())
{
throw index_out_of_bounds_exception();
}
current++;
}
return copy.get_value();
}
/// <summary>
/// Looks up a specific element at a certain index
/// in the range.
///
/// If the index is out of bounds, the default is returned.
///
/// </summary>
/// <param name="index">the index of the element</param>
/// <returns>the value stored behind that index</returns>
_NODISCARD value_type element_at_default(const size_t index) const
{
range_type copy = this->range;
size_t current = 0;
while (current <= index)
{
if (!copy.move_next())
{
return value_type{};
}
current++;
}
return copy.get_value();
}
/// <summary>
/// Determines the first element of
/// the range.
/// If the range is empty, a sequence_empty_exception will
/// be thrown
/// </summary>
_NODISCARD value_type first() const
{
range_type copy = this->range;
if (copy.move_next())
return copy.get_value();
throw sequence_empty_exception();
}
/// <summary>
/// Determines the first element of the range.
/// If the range is empty, the default will be returned
/// </summary>
template<typename = std::enable_if_t<std::is_default_constructible_v<value_type>>>
_NODISCARD value_type first_or_default() const
{
range_type copy = this->range;
if (copy.move_next())
return copy.get_value();
return value_type{};
}
/// <summary>
/// Determines the first element of the range which satisfies the predicate.
/// If the range is empty, a sequence_empty_exception will be thrown.
///
/// </summary>
/// <param name="predicate">the predicate to satisfy</param>
/// <returns>the first element in the range which satisfies the predicate</returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD return_type first(const TPredicate & predicate) const
{
range_type copy = this->range;
while (copy.move_next())
{
const auto value = copy.get_value();
if (predicate(value))
return value;
}
throw sequence_empty_exception();
}
/// <summary>
/// Determines the first element of the range which satisfies the predicate.
/// If the range is empty, the default will be returned.
///
/// </summary>
/// <param name="predicate">the predicate to satisfy</param>
/// <returns>the first element in the range which satisfies the predicate</returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate> && std::is_default_constructible_v<value_type>>>
_NODISCARD value_type first_or_default(const TPredicate & predicate) const
{
range_type copy = this->range;
while (copy.move_next())
{
const auto value = copy.get_value();
if (predicate(value))
return value;
}
return value_type{};
}
/// <summary>
/// Returns the first value or the given fallback value if there is not a single value stored
/// in the underlying range
/// </summary>
/// <param name="fallback_value">the value to return if there is no first value stored</param>
_NODISCARD value_type first_or(const value_type& fallback_value) const
{
// make a copy of the underlying range since we don't want to change it
range_type copy = this->range;
// check if the have any value to process
if(!copy.move_next())
{
// return the fallback
return fallback_value;
}
// we're ready to return a value from the underlying range
return copy.get_value();
}
/// <summary>
/// Tries to return the first value that satisfies the given predicate
/// </summary>
/// <typeparam name="TPredicate">the predicate type (lambda)</typeparam>
/// <param name="fallback_value">the value to return if no value of the underlying range satisfied the predicate</param>
/// <param name="predicate">the predicate to execute for each value of the underlying range</param>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD value_type first_or(const value_type& fallback_value, const TPredicate& predicate) const
{
range_type copy = this->range;
while (copy.move_next())
{
// store the current value in a temporary variable
const auto current_value = copy.get_value();
// check the predicate
if(predicate(current_value))
{
// the predicate is satisfied - return the value
return current_value;
}
}
// we have to return the fallback since no value satisfied the predicate
return fallback_value;
}
/// <summary>
/// Determines the last element of
/// the range.
/// If the range is empty, a sequence_empty_exception will
/// be thrown
/// </summary>
_NODISCARD return_type last() const
{
range_type copy = this->range;
if (!copy.move_next())
throw sequence_empty_exception();
auto result = copy.get_value();
while (copy.move_next())
{
result = copy.get_value();
}
return result;
}
/// <summary>
/// Determines the last element of the range.
/// If the range is empty, the default will be returned
/// </summary>
template<typename = std::enable_if_t<std::is_default_constructible_v<value_type>>>
_NODISCARD value_type last_or_default() const
{
range_type copy = this->range;
if (!copy.move_next())
return value_type{};
auto result = copy.get_value();
while (copy.move_next())
{
result = copy.get_value();
}
return result;
}
/// <summary>
/// Determines the last element of the range which satisfies the predicate.
/// If the range is empty, a sequence_empty_exception will be thrown.
///
/// </summary>
/// <param name="predicate">the predicate to satisfy</param>
/// <returns>the last element in the range which satisfies the predicate</returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD return_type last(const TPredicate & predicate) const
{
range_type copy = this->range;
if (!copy.move_next())
throw sequence_empty_exception();
auto result = copy.get_value();
bool updated = false;
while (copy.move_next())
{
const auto value = copy.get_value();
if (predicate(value))
{
result = value;
updated = true;
}
}
if (updated)
return result;
if (predicate(result))
return result;
throw sequence_empty_exception();
}
/// <summary>
/// Determines the last element of the range which satisfies the predicate.
/// If the range is empty, the default will be returned.
///
/// </summary>
/// <param name="predicate">the predicate to satisfy</param>
/// <returns>the last element in the range which satisfies the predicate</returns>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate> && std::is_default_constructible_v<value_type>>>
_NODISCARD value_type last_or_default(const TPredicate & predicate) const
{
range_type copy = this->range;
if (!copy.move_next())
return value_type{};
auto result = copy.get_value();
bool updated = false;
while (copy.move_next())
{
const auto value = copy.get_value();
if (predicate(value))
{
result = value;
updated = true;
}
}
if (updated)
return result;
if (predicate(result))
return result;
return value_type{};
}
/// <summary>
/// Tries to get the last value from the range.
/// If there is no last element (in case the range is empty)
/// the given parameter will be returned.
/// </summary>
_NODISCARD value_type last_or(const value_type& fallback_value) const
{
// make a copy since the underlying range shouldn't change
range_type copy = this->range;
// try to move forward
if(!copy.move_next())
{
// we don't have any value to process.
return fallback_value;
}
// store the value somewhere to return it later on
value_type result = copy.get_value();
// iterate through the whole range
while(copy.move_next())
{
result = copy.get_value(); // update the value
}
return result;
}
/// <summary>
/// Tries to get the last value that matches the given predicate
/// and returns it.
/// </summary>
/// <typeparam name="TPredicate">the predicate type (lambda)</typeparam>
/// <param name="fallback_value">the value to return if the predicate never gets satisfied</param>
/// <param name="predicate">the predicate to check against each value of the underlying range</param>
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD value_type last_or(const value_type& fallback_value, const TPredicate& predicate) const
{
// make a copy since the underlying range shouldn't change
range_type copy = this->range;
// try to move forward in order to see if we have any value
// to process
if(!copy.move_next())
{
return fallback_value; // return the fallback value
}
// store the value somewhere. This can be done since we've already stepped forward
value_type result = copy.get_value();
// a boolean that stores whether we've already used the predicate on the
// 'result' variable or not
bool checked = false;
while(copy.move_next())
{
// get the current value we're operating on
const auto current_value = copy.get_value();
// check the value using the predicate
if(predicate(current_value))
{
result = current_value; // update the value
checked = true; // mark the value as checked
}
}
// did we updated & checked the value?
if (checked)
// simply return the result
return result;
// use the predicate
if(predicate(result))
{
// we're good to return the result since the predicate returned true
return result;
}
// return the fallback value
return fallback_value;
}
_NODISCARD value_type random() const
{
return shuffle().first();
}
template<typename TSelector, typename = std::enable_if_t<std::is_invocable_v<TSelector, value_type>>>
_NODISCARD enumerable<orderby_range<range_type, TSelector>> orderby(const TSelector & selector) const
{
return orderby_ascending(selector);
}
template<typename TSelector, typename = std::enable_if_t<std::is_invocable_v<TSelector, value_type>>>
_NODISCARD enumerable<orderby_range<range_type, TSelector>> orderby_ascending(const TSelector & selector) const
{
return enumerable<orderby_range<range_type, TSelector>>(
orderby_range<range_type, TSelector>(this->range, selector, true)
);
}
template<typename TSelector, typename = std::enable_if_t<std::is_invocable_v<TSelector, value_type>>>
_NODISCARD enumerable<orderby_range<range_type, TSelector>> orderby_descending(const TSelector & selector) const
{
return enumerable<orderby_range<range_type, TSelector>>(
orderby_range<range_type, TSelector>(this->range, selector, false)
);
}
template<typename TSelector, typename = std::enable_if_t<std::is_invocable_v<TSelector, value_type>>>
_NODISCARD enumerable<thenby_range<range_type, TSelector>> thenby(const TSelector & selector) const
{
return thenby_ascending(selector);
}
template<typename TSelector, typename = std::enable_if_t<std::is_invocable_v<TSelector, value_type>>>
_NODISCARD enumerable<thenby_range<range_type, TSelector>> thenby_ascending(const TSelector & selector) const
{
return enumerable<thenby_range<range_type, TSelector>>(
thenby_range<range_type, TSelector>(this->range, selector, true)
);
}
template<typename TSelector, typename = std::enable_if_t<std::is_invocable_v<TSelector, value_type>>>
_NODISCARD enumerable<thenby_range<range_type, TSelector>> thenby_descending(const TSelector & selector) const
{
return enumerable<thenby_range<range_type, TSelector>>(
thenby_range<range_type, TSelector>(this->range, selector, false)
);
}
template<range_concept TOtherRange>
_NODISCARD bool sequence_equal(const enumerable<TOtherRange> & enumerable) const
{
range_type lhs = this->range;
TOtherRange rhs = enumerable.get_range();
while (true)
{
const bool lhs_move = lhs.move_next();
const bool rhs_move = rhs.move_next();
if (lhs_move != rhs_move)
{
return false;
}
if (!lhs_move && !rhs_move)
{
return true;
}
if (lhs.get_value() != rhs.get_value())
{
return false;
}
}
}
template<range_concept TOtherRange, typename TPredicate, typename = std::enable_if_t<std::is_same_v<std::invoke_result_t<TPredicate, value_type, typename enumerable<TOtherRange>::value_type>, bool>>>
_NODISCARD bool sequence_equal(const enumerable<TOtherRange> & enumerable, const TPredicate & predicate) const
{
range_type lhs = this->range;
TOtherRange rhs = enumerable.get_range();
while (true)
{
const bool lhs_move = lhs.move_next();
const bool rhs_move = rhs.move_next();
if (lhs_move != rhs_move)
{
return false;
}
if (!lhs_move && !rhs_move)
{
return true;
}
if (!predicate(lhs.get_value(), rhs.get_value()))
{
return false;
}
}
}
template<typename TEnumerableSelection, typename = std::enable_if_t<std::is_invocable_v<TEnumerableSelection, typename range_type::value_type>>>
_NODISCARD enumerable<select_many_range<range_type, TEnumerableSelection>> select_many(const TEnumerableSelection & selection) const
{
return enumerable<select_many_range<range_type, TEnumerableSelection>>(
select_many_range<range_type, TEnumerableSelection>(this->range, selection)
);
}
_NODISCARD enumerable<pairwise_range<range_type>> pairwise() const
{
return enumerable<pairwise_range<range_type>>(
pairwise_range<range_type>(this->range)
);
}
_NODISCARD std::basic_string<char> concatenate(
const std::string & separator,
size_t capacity = 16
) const
{
return concatenate_impl<char>(this->range, separator, capacity);
}
_NODISCARD std::basic_string<wchar_t> concatenate(
const std::wstring & separator,
size_t capacity = 16
) const
{
return concatenate_impl<wchar_t>(this->range, separator, capacity);
}
template<
enumerable_concept TEnumerable,
typename TLhsIdSelection,
typename TRhsIdSelection,
typename TJoinSelection,
typename = std::enable_if_t<
std::is_invocable_v<TLhsIdSelection, value_type> &&
std::is_invocable_v<TRhsIdSelection, typename TEnumerable::value_type> &&
std::is_invocable_v<TJoinSelection, typename range_type::value_type, typename TEnumerable::value_type>
>
>
_NODISCARD enumerable<join_range<range_type, TEnumerable, TLhsIdSelection, TRhsIdSelection, TJoinSelection>> join(
const TEnumerable & enumerable_value,
const TLhsIdSelection & lhs_id_selection,
const TRhsIdSelection & rhs_id_selection,
const TJoinSelection & join_selection
) const
{
return enumerable<join_range<range_type, TEnumerable, TLhsIdSelection, TRhsIdSelection, TJoinSelection>>(
join_range<range_type, TEnumerable, TLhsIdSelection, TRhsIdSelection, TJoinSelection>(
this->range,
enumerable_value.get_range(),
lhs_id_selection,
rhs_id_selection,
join_selection
)
);
}
template<template<typename, typename> typename TMap = std::map, typename TKeySelection, typename = std::enable_if_t<std::is_invocable_v<TKeySelection, value_type>>>
_NODISCARD TMap<std::invoke_result_t<TKeySelection, value_type>, value_type> to_map(const TKeySelection & key_selection) const
{
range_type copy = this->range;
TMap<std::invoke_result_t<TKeySelection, value_type>, value_type> result;
while (copy.move_next())
{
const auto value = copy.get_value();
const auto key = key_selection(value);
result.insert({ key, value });
}
return result;
}
template<template<typename> typename TSet = std::set>
_NODISCARD TSet<value_type> to_set() const
{
range_type copy = this->range;
TSet<value_type> result;
while (copy.move_next())
{
result.insert(copy.get_value());
}
return result;
}
template<template<typename> typename TQueue = std::queue>
_NODISCARD TQueue<value_type> to_queue() const
{
range_type copy = this->range;
TQueue<value_type> result;
while (copy.move_next())
{
result.push(copy.get_value());
}
return result;
}
_NODISCARD std::stack<value_type> to_stack() const
{
range_type copy = this->range;
std::stack<value_type> result;
while (copy.move_next())
{
result.push(copy.get_value());
}
return result;
}
template<typename TEnumerable>
_NODISCARD enumerable<union_range<range_type, TEnumerable>> union_with(const TEnumerable & enumerable_range) const
{
return enumerable<union_range<range_type, TEnumerable>>(
union_range<range_type, TEnumerable>(
this->range,
enumerable_range.get_range()
)
);
}
_NODISCARD enumerable<shuffle_range<range_type>> shuffle() const
{
return enumerable<shuffle_range<range_type>>(
shuffle_range<range_type>(this->range)
);
}
template<typename TKeySelector>
_NODISCARD lookup<std::invoke_result_t<TKeySelector, value_type>, value_type> to_lookup(const TKeySelector & selector) const
{
using key_type = std::invoke_result_t<TKeySelector, value_type>;
return lookup<key_type, value_type>(this->range, selector);
}
template<typename TValue, typename = std::enable_if_t<std::is_convertible_v<value_type, TValue>>>
_NODISCARD auto cast() const
{
return this->select([](const value_type & value)
{
return static_cast<TValue>(value);
});
}
_NODISCARD value_type single() const
{
range_type copy = this->range;
if (!copy.move_next())
throw invalid_operation_exception();
return copy.get_value();
}
template<typename TPredicate, typename = std::enable_if_t<is_predicate<TPredicate>>>
_NODISCARD value_type single(const TPredicate & predicate) const
{
range_type copy = this->range;
while (copy.move_next())
{
const return_type value = copy.get_value();
if (predicate(value))
return value;
}
throw invalid_operation_exception();
}
template<enumerable_concept TEnumerable>
_NODISCARD enumerable<zip_with_range<range_type, typename TEnumerable::range_type>> zip_with(const TEnumerable & other) const
{
return enumerable<zip_with_range<range_type, typename TEnumerable::range_type>>(
zip_with_range<range_type, typename TEnumerable::range_type>(this->range, other.get_range())
);
}
_NODISCARD constexpr container<range_type> to_container() const
{
return container<range_type>(this->range);
}
template<typename TAction, typename = std::enable_if_t<is_action<TAction>>>
_NODISCARD constexpr const enumerable & inline_for_each(const TAction & action) const
{
range_type copy = this->range;
while (copy.move_next())
{
action(copy.get_value());
}
return *this;
}
template<typename TAction, typename = std::enable_if_t<std::is_same_v<std::invoke_result_t<TAction, value_type, size_t>, void>>>
_NODISCARD constexpr const enumerable & indexed_inline_for_each(const TAction & action) const
{
range_type copy = this->range;
for(size_t i = 0; copy.move_next(); i++)
{
action(copy.get_value(), i);
}
return *this;
}
private:
template<typename TChar>
static _NODISCARD std::basic_string<TChar> concatenate_impl(
range_type range,
const std::basic_string<TChar> & separator,
size_t capacity
)
{
std::vector<TChar> buffer;
buffer.reserve(capacity);
bool first = true;
while (range.move_next())
{
if(first)
{
first = false;
} else
{
buffer.insert(buffer.end(), separator.begin(), separator.end());
}
const auto current_value = range.get_value();
buffer.insert(buffer.end(), current_value.begin(), current_value.end());
}
return std::basic_string<TChar>(buffer.begin(), buffer.end());
}
private:
/// <summary>
/// Member attributes
/// </summary>
range_type range;
};
/// <summary>
/// Creates an enumerable from
/// an array
/// </summary>
/// <typeparam name="TArray">type of an array element</typeparam>
/// <param name="array">array instance</param>
/// <returns>an enumerable of type iterator_range</returns>
template<typename TArray, int ArraySize>
_NODISCARD enumerable<iterator_range<typename array_traits<TArray[ArraySize]>::iterator>> from(const TArray(& array)[ArraySize])
{
using iterator = typename array_traits<TArray[ArraySize]>::iterator;
const iterator begin = array;
const iterator end = array + ArraySize;
return enumerable<iterator_range<iterator>>(
iterator_range<iterator>(begin, end)
);
}
/// <summary>
/// Creates an enumerable from
/// a container object
/// </summary>
/// <typeparam name="TContainer">a container type which has the begin and end method</typeparam>
/// <param name="container">the container holding the values to store</param>
/// <returns>An enumerable object holding the values provided from the container</returns>
template<container_concept TContainer>
_NODISCARD enumerable<iterator_range<typename TContainer::const_iterator>> from(
const TContainer & container
)
{
return enumerable<iterator_range<typename TContainer::const_iterator>>(
iterator_range<typename TContainer::const_iterator>(
container.begin(),
container.end()
)
);
}
/// <summary>
/// Constructs an enumerable object from a raw iterator
/// </summary>
/// <typeparam name="TIterator">the iterator-type</typeparam>
/// <param name="begin">begin of the iterator</param>
/// <param name="end">end of the iterator</param>
/// <returns>enumerable object holding the iterator as range</returns>
template<typename TIterator>
_NODISCARD enumerable<iterator_range<TIterator>> from(
const TIterator & begin,
const TIterator & end
)
{
return enumerable<iterator_range<TIterator>>(
iterator_range<TIterator>(begin, end)
);
}
/// <summary>
/// Creates a repeating range for n times
/// </summary>
/// <typeparam name="TValue">the value-type of the specific value to repeat</typeparam>
/// <param name="value">the actual value to repeat</param>
/// <param name="repetitions">the number of times to repeat the value</param>
template<typename TValue>
_NODISCARD enumerable<repeat_range<TValue>> repeat(const TValue & value, size_t repetitions)
{
return enumerable<repeat_range<TValue>>(
repeat_range<TValue>(value, repetitions)
);
}
/// <summary>
/// Creates an empty range
/// </summary>
/// <typeparam name="TValue">the value-type of the non-existing value</typeparam>
template<typename TValue>
_NODISCARD enumerable<empty_range<TValue>> empty()
{
return enumerable<empty_range<TValue>>(
empty_range<TValue>()
);
}
/// <summary>
/// Creates an incrementing range
/// </summary>
/// <typeparam name="TValue">the value-type of the start, end and incrementing values</typeparam>
/// <param name="start">inclusive starting value</param>
/// <param name="end">inclusive end value</param>
/// <param name="increment">the amount to increment in each iteration</param>
template<typename TValue>
_NODISCARD enumerable<increment_range<TValue>> range(
const TValue & start,
const TValue & end,
const TValue & increment
)
{
return enumerable<increment_range<TValue>>(
increment_range<TValue>(start, end, increment)
);
}
}
#include <linq/ranges/lookup.hpp> | 28.765056 | 205 | 0.695334 | [
"object",
"vector",
"transform"
] |
23dca76df99f72cb5c4dad2d9031c67a0a12b833 | 1,275 | cpp | C++ | source/containers/vector.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 44 | 2020-10-03T21:37:52.000Z | 2022-03-26T10:08:46.000Z | source/containers/vector.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 1 | 2021-01-01T23:22:39.000Z | 2021-01-01T23:22:39.000Z | source/containers/vector.cpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | null | null | null | // Copyright David Stone 2015.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <containers/vector.hpp>
#include "test_append_from_capacity.hpp"
#include "test_sequence_container.hpp"
#include "test_reserve_and_capacity.hpp"
#include "../test_int.hpp"
namespace {
static_assert(containers_test::test_sequence_container<containers::vector<int>>());
static_assert(containers_test::test_sequence_container<containers::vector<bounded_test::integer>>());
static_assert(containers_test::test_reserve_and_capacity<containers::vector<int>>());
static_assert(containers_test::test_reserve_and_capacity<containers::vector<bounded_test::integer>>());
static_assert(containers_test::test_append_from_capacity<containers::vector<int>>());
static_assert(containers_test::test_append_from_capacity<containers::vector<bounded_test::integer>>());
static_assert(std::is_convertible_v<containers::vector<bounded_test::integer> const &, std::span<bounded_test::integer const>>);
static_assert(std::is_convertible_v<containers::vector<bounded_test::integer> &, std::span<bounded_test::integer>>);
struct recursive {
containers::vector<recursive, 1> m;
};
} // namespace
| 39.84375 | 128 | 0.8 | [
"vector"
] |
23e62ba24534ea23e7d498d999f84c9d9ab2c0e7 | 15,102 | cpp | C++ | SimpleEditor/Source/SimpleEditor/PluginsManager.cpp | PetrKudr/simpleeditor | 04d73aeee6c8293ae52c8279acb88635aa12df3b | [
"MIT"
] | null | null | null | SimpleEditor/Source/SimpleEditor/PluginsManager.cpp | PetrKudr/simpleeditor | 04d73aeee6c8293ae52c8279acb88635aa12df3b | [
"MIT"
] | null | null | null | SimpleEditor/Source/SimpleEditor/PluginsManager.cpp | PetrKudr/simpleeditor | 04d73aeee6c8293ae52c8279acb88635aa12df3b | [
"MIT"
] | null | null | null | #include "PluginsManager.hpp"
#include "PluginUtils.hpp"
#include "resources\res.hpp"
#include "notepad.hpp"
#include "base/variables.h"
#include <sstream>
#include <list>
#include <algorithm>
#include <cwchar>
using namespace std;
/*
********************************************************************************************************
* Personal Service *
********************************************************************************************************
*/
PersonalPluginService::PersonalPluginService(__in LPCWSTR guid, __in const std::wstring &pluginRootPath) : myPluginGuid(guid), myPluginRootPath(pluginRootPath) {}
int PersonalPluginService::GetVersion() const
{
return PS_VERSION;
}
LPCWSTR PersonalPluginService::GetRootPath() const
{
return myPluginRootPath.c_str();
}
LPCWSTR PersonalPluginService::GetLanguage() const
{
return g_languageName;
}
void PersonalPluginService::RequestCallback(bool async, void *param)
{
//wchar_t *box = new wchar_t[wcslen(myPluginGuid) + 1];
//wcscpy(box, myPluginGuid);
CNotepad ¬epad = CNotepad::Instance();
if (async)
PostMessage(notepad.Interface.GetHWND(), NPD_EMITPLUGINNOTIFICATION, (WPARAM)myPluginGuid, (LPARAM)param);
else
SendMessage(notepad.Interface.GetHWND(), NPD_EMITPLUGINNOTIFICATION, (WPARAM)myPluginGuid, (LPARAM)param);
}
int PersonalPluginService::GetEditorsNumber()
{
CNotepad ¬epad = CNotepad::Instance();
return notepad.Documents.GetDocsNumber();
}
void PersonalPluginService::GetAllEditorsIds(__out PluginBuffer<int> *buffer)
{
std::vector<int> ids;
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.GetDocIds(ids);
if (ids.size() > buffer->GetBufferSize())
buffer->IncreaseBufferSize(ids.size() - buffer->GetBufferSize());
int *unwrappedBuffer = buffer->GetBuffer();
for (size_t i = 0; i < ids.size(); i++)
unwrappedBuffer[i] = ids[i];
checkError();
}
int PersonalPluginService::GetCurrentEditor()
{
CNotepad ¬epad = CNotepad::Instance();
int id = notepad.Documents.GetIdFromIndex(notepad.Documents.Current());
checkError();
return id;
}
void PersonalPluginService::SetCurrentEditor(__in int id)
{
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.SetActive(notepad.Documents.GetIndexFromID(id));
checkError();
}
void PersonalPluginService::SetBOMFlag(__in int id, __in bool bom)
{
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.SetBOM(notepad.Documents.GetIndexFromID(id), bom);
checkError();
}
void PersonalPluginService::SetEditorModificationFlag(__in int id, __in bool modified)
{
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.SetModified(notepad.Documents.GetIndexFromID(id), modified);
checkError();
}
void PersonalPluginService::OpenEditor(__in LPCWSTR path, __in LPCWSTR coding, __in bool activate, __in bool openInCurrent, __in void *reserved)
{
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.Open(path, coding, OPEN, activate, openInCurrent);
checkError();
}
void PersonalPluginService::SaveEditor(__in int id, __in LPCWSTR path, __in LPCWSTR coding, __in bool bom, __in void *reserved)
{
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.Save(notepad.Documents.GetIndexFromID(id), path, coding, bom);
checkError();
}
void PersonalPluginService::Create(__in LPCWSTR caption)
{
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.Create(caption);
checkError();
}
void PersonalPluginService::Close(__in int id)
{
CNotepad ¬epad = CNotepad::Instance();
notepad.Documents.Close(notepad.Documents.GetIndexFromID(id));
checkError();
}
HWND PersonalPluginService::GetEditorWindow(int id)
{
CNotepad ¬epad = CNotepad::Instance();
HWND hwnd = notepad.Documents.GetHWND(notepad.Documents.GetIndexFromID(id));
checkError();
return hwnd;
}
void PersonalPluginService::GetEditorFilePath(__in int id, __out wchar_t path[MAX_PATH])
{
CNotepad ¬epad = CNotepad::Instance();
wcscpy(path, notepad.Documents.GetPath(notepad.Documents.GetIndexFromID(id)).c_str());
checkError();
}
void PersonalPluginService::GetEditorName(__in int id, __out wchar_t name[MAX_PATH])
{
CNotepad ¬epad = CNotepad::Instance();
wcscpy(name, notepad.Documents.GetName(notepad.Documents.GetIndexFromID(id)).c_str());
checkError();
}
void PersonalPluginService::GetEditorCoding(__in int id, __out PluginBuffer<wchar_t> *buffer)
{
CNotepad ¬epad = CNotepad::Instance();
LPCWSTR coding = notepad.Documents.GetCoding(notepad.Documents.GetIndexFromID(id));
size_t codingLength = coding != 0 ? wcslen(coding) : 0;
if (buffer->GetBufferSize() < codingLength)
buffer->IncreaseBufferSize(buffer->GetBufferSize() - codingLength + 1);
wcscpy(buffer->GetBuffer(), coding);
checkError();
}
bool PersonalPluginService::GetEditorBOMFlag(__in int id)
{
CNotepad ¬epad = CNotepad::Instance();
bool bomFlag = notepad.Documents.NeedBOM(notepad.Documents.GetIndexFromID(id));
checkError();
return bomFlag;
}
bool PersonalPluginService::GetEditorModificationFlag(__in int id)
{
CNotepad ¬epad = CNotepad::Instance();
bool modified = notepad.Documents.IsModified(notepad.Documents.GetIndexFromID(id));
checkError();
return modified;
}
void PersonalPluginService::NotifyParameterChanged(PluginParameter param)
{
CNotepad &Notepad = CNotepad::Instance();
Notepad.PluginManager.ProcessPluginParameterChange(myPluginGuid, param);
}
bool PersonalPluginService::RegisterEncoder(Encoder *encoder)
{
CNotepad &Notepad = CNotepad::Instance();
return Notepad.Documents.CodingManager.RegisterEncoder(encoder);
}
bool PersonalPluginService::UnregisterEncoder(LPCWSTR id)
{
CNotepad &Notepad = CNotepad::Instance();
return Notepad.Documents.CodingManager.UnregisterEncoder(id);
}
int PersonalPluginService::GetLastError() const
{
return myLastError.code;
}
void PersonalPluginService::GetLastErrorMessage(__out PluginBuffer<wchar_t> *buffer) const
{
if (buffer->GetBufferSize() < myLastError.message.size())
buffer->IncreaseBufferSize(myLastError.message.size() - buffer->GetBufferSize() + 1);
wcscpy(buffer->GetBuffer(), myLastError.message.c_str());
}
void PersonalPluginService::ShowError(const LPCWSTR message) const
{
CNotepad ¬epad = CNotepad::Instance();
std::wstring msg(message);
notepad.Interface.Dialogs.ShowError(notepad.Interface.GetHWND(), msg);
}
void PersonalPluginService::checkError()
{
const NotepadError &error = CError::GetError();
myLastError.code = error.code;
if (myLastError.message.compare(error.message) != 0)
myLastError.message = error.message;
if (error.code != NOTEPAD_NO_ERROR)
CError::SetError(NOTEPAD_NO_ERROR);
}
/*
********************************************************************************************************
* Plugin Manager *
********************************************************************************************************
*/
struct PluginRootsCollector
{
list<wstring> pluginRoots;
void operator()(const WIN32_FIND_DATA &fd)
{
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (wcscmp(fd.cFileName, L".") != 0 && wcscmp(fd.cFileName, L"..") != 0)
pluginRoots.push_back(wstring(fd.cFileName));
}
}
};
struct PluginsCollector
{
list<wstring> plugins;
void operator()(const WIN32_FIND_DATA &fd)
{
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
plugins.push_back(wstring(fd.cFileName));
}
};
static bool comaparePluginsByPriority(const InternalPlugin *first, const InternalPlugin *second)
{
return first->GetPlugin()->GetPriority() < second->GetPlugin()->GetPriority();
}
bool CPluginManager::Init(const wstring &root)
{
this->root = root;
list<wstring> plugins;
if (!listPluginsInPath(root, plugins))
return false;
for (list<wstring>::const_iterator iter = plugins.begin(); iter != plugins.end(); iter++)
{
if (!loadPlugin(*iter))
{
CNotepad &Notepad = CNotepad::Instance();
Notepad.Interface.Dialogs.ShowError(Notepad.Interface.GetHWND(), CError::GetError().message);
CError::SetError(NOTEPAD_NO_ERROR);
}
}
myPlugins.sort(comaparePluginsByPriority);
preparePlugins();
return true;
}
const list<InternalPlugin*>& CPluginManager::ListPlugins()
{
return myPlugins;
}
const InternalPlugin* CPluginManager::GetPlugin(LPCWSTR guid)
{
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
{
if (wcscmp((*iter)->GetPlugin()->GetGUID(), guid) == 0)
return *iter;
}
return 0;
}
bool CPluginManager::EnablePlugin(LPCWSTR guid)
{
return false;
}
bool CPluginManager::DisablePlugin(LPCWSTR guid)
{
return false;
}
void CPluginManager::NotifyPlugin(LPCWSTR guid, const PluginNotification ¬ification)
{
const InternalPlugin *internalPlugin = GetPlugin(guid);
if (internalPlugin)
internalPlugin->GetPlugin()->ProcessNotification(¬ification);
}
void CPluginManager::NotifyPlugins(const PluginNotification ¬ification)
{
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
(*iter)->GetPlugin()->ProcessNotification(¬ification);
}
void CPluginManager::ExecuteMenuCommand(int commandId)
{
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
{
InternalPlugin* internalPlugin = *iter;
if (commandId >= internalPlugin->GetPluginMenuFirstId() && commandId < internalPlugin->GetPluginMenuLastId())
{
Plugin *plugin = internalPlugin->GetPlugin();
plugin->ExecuteMenuCommand(commandId);
break;
}
}
}
void CPluginManager::ProcessPluginParameterChange(LPCWSTR guid, PluginParameter param)
{
switch (param)
{
case PP_MENU:
break;
}
}
CPluginManager::~CPluginManager()
{
list<LPCWSTR> ids;
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
ids.push_back((*iter)->GetPlugin()->GetGUID());
for (list<LPCWSTR>::const_iterator iter = ids.begin(); iter != ids.end(); iter++)
unloadPlugin(*iter);
}
bool CPluginManager::listPluginsInPath(__in const wstring &root, __out list<wstring> &plugins)
{
wstring errorMessage;
PluginRootsCollector rootsCollector;
PluginUtils::SearchFiles(root + wstring(FILE_SEPARATOR) + wstring(L"*"), rootsCollector);
for (list<wstring>::const_iterator rootIter = rootsCollector.pluginRoots.begin(); rootIter != rootsCollector.pluginRoots.end(); rootIter++)
{
PluginsCollector pluginsCollector;
PluginUtils::SearchFiles(root + FILE_SEPARATOR + (*rootIter) + FILE_SEPARATOR + wstring(L"*.dll"), pluginsCollector);
for (list<wstring>::const_iterator pluginIter = pluginsCollector.plugins.begin(); pluginIter != pluginsCollector.plugins.end(); pluginIter++)
plugins.push_back((*rootIter) + FILE_SEPARATOR + (*pluginIter));
}
return true;
}
LPCWSTR CPluginManager::loadPlugin(__in const wstring &path)
{
// Check if plugin is already loaded
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
{
if ((*iter)->GetPath().compare(path) == 0)
return (*iter)->GetPlugin()->GetGUID();
}
std::wstring pluginPath = root + FILE_SEPARATOR + path;
HMODULE hmodule = LoadLibrary(pluginPath.c_str());
if (!hmodule)
{
CError::SetError(NOTEPAD_CANNOT_LOAD_DLL, pluginPath.c_str());
goto plugin_load_error;
}
Plugin *plugin = 0;
PersonalPluginService *service = 0;
CreatePluginProc createProc = (CreatePluginProc)GetProcAddress(hmodule, CREATE_PLUGIN_PROC);
DeletePluginProc deleteProc = (DeletePluginProc)GetProcAddress(hmodule, DELETE_PLUGIN_PROC);
if (0 != createProc && 0 != deleteProc)
{
plugin = createProc();
if (plugin != 0)
{
// Check if we already have plugin with the same guid
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
{
if (wcscmp((*iter)->GetPlugin()->GetGUID(), plugin->GetGUID()) == 0)
{
CError::SetError(NOTEPAD_CANNOT_INITIALIZE_PLUGIN, plugin->GetName());
goto plugin_load_error;
}
}
// Initialize plugin
service = new PersonalPluginService(plugin->GetGUID(), pluginPath.substr(0, pluginPath.rfind(L'\\')));
if (plugin->Init(hmodule, service))
{
InternalPlugin *internalPlugin = new InternalPlugin(plugin, service, hmodule, path, deleteProc);
myPlugins.push_back(internalPlugin);
return plugin->GetGUID();
}
else
{
CError::SetError(NOTEPAD_CANNOT_INITIALIZE_PLUGIN, plugin->GetName());
goto plugin_load_error;
}
}
}
else
{
CError::SetError(NOTEPAD_DLL_DOES_NOT_CONTAIN_PLUGIN, pluginPath.c_str());
goto plugin_load_error;
}
plugin_load_error:
if (plugin)
deleteProc(plugin);
if (service)
delete service;
if (hmodule)
FreeLibrary(hmodule);
return 0;
}
bool CPluginManager::unloadPlugin(LPCWSTR guid)
{
InternalPlugin *descriptor = 0;
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
{
if (wcscmp((*iter)->GetPlugin()->GetGUID(), guid) == 0)
{
descriptor = *iter;
myPlugins.erase(iter);
break;
}
}
if (descriptor != 0)
delete descriptor;
return true;
}
void CPluginManager::preparePlugins()
{
preparePluginsMenuItems();
}
void CPluginManager::preparePluginsMenuItems()
{
int currentMenuId = IDM_FIRST_PLUGIN_COMMAND;
for (list<InternalPlugin*>::const_iterator iter = myPlugins.begin(); iter != myPlugins.end(); iter++)
{
InternalPlugin *internalPlugin = *iter;
int itemsNumber = internalPlugin->GetPlugin()->GetMenuItemsNumber();
if (itemsNumber > 0)
{
internalPlugin->SetPluginMenuFirstId(currentMenuId);
internalPlugin->SetPluginMenuLastId(currentMenuId += itemsNumber);
}
else
{
internalPlugin->SetPluginMenuFirstId(-1);
internalPlugin->SetPluginMenuLastId(-1);
}
}
}
void CPluginManager::onPluginMenuChange()
{
CNotepad &Notepad = CNotepad::Instance();
Notepad.ClearPluginsMenu(Notepad.Interface.Controlbar.GetPluginsMenu());
Notepad.ClearPluginsMenu(Notepad.Interface.Controlbar.GetPluginsPopupMenu());
preparePluginsMenuItems();
} | 29.324272 | 163 | 0.668852 | [
"vector"
] |
23e8a50d69e93c10aa11fc889ddc765059102220 | 1,706 | cpp | C++ | Solutions/codechef/TOTR.cpp | eashwaranRaghu/Data-Structures-and-Algorithms | 3aad0f1da3d95b572fbb1950c770198bd042a80f | [
"MIT"
] | 6 | 2020-01-29T14:05:56.000Z | 2021-04-24T04:37:27.000Z | Solutions/codechef/TOTR.cpp | eashwaranRaghu/Data-Structures-and-Algorithms | 3aad0f1da3d95b572fbb1950c770198bd042a80f | [
"MIT"
] | null | null | null | Solutions/codechef/TOTR.cpp | eashwaranRaghu/Data-Structures-and-Algorithms | 3aad0f1da3d95b572fbb1950c770198bd042a80f | [
"MIT"
] | 1 | 2020-05-22T06:37:20.000Z | 2020-05-22T06:37:20.000Z | // Created on 26-06-2019 00:56:53 by necronomicon
#include <bits/stdc++.h>
using namespace std;
#define MP make_pair
#define PB push_back
#define ARR_MAX (int)1e5 //Max array length
#define INF (int)1e9 //10^9
#define EPS 1e-9 //10^-9
#define MOD 1000000007 //10^9+7
#define PI 3.1415926535897932384626433832795
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair<int, int> Pii;
typedef vector<int> Vi;
typedef vector<string> Vs;
typedef vector<Pii> VPii;
typedef vector<Vi> VVi;
typedef map<int,int> Mii;
typedef set<int> Si;
typedef multimap<int,int> MMii;
typedef multiset<int> MSi;
typedef unordered_map<int,int> UMii;
typedef unordered_set<int> USi;
typedef unordered_multimap<int,int> UMMii;
typedef unordered_multiset<int> UMSi;
typedef priority_queue<int> PQi;
typedef queue<int> Qi;
typedef deque<int> DQi;
int main () {
int t;
string s, line, line2;
getline(cin, line);
stringstream ss(line);
ss >> t >> s;
map <char, char> m;
for (int i = 0; i < s.size(); i++)
{
m[i + 'a'] = s[i];
m[i + 'a' - 32] = s[i] - 32;
}
while (t--){
getline(cin, line);
// cout << t << ':' << line << ':';
for (int i = 0; i < line.size() && line[i]!='\0'; i++)
{
if(line[i] == '_') line[i] = ' ';
else if(line[i] == '.' || line[i] == ',' || line[i] == '?' || line[i] == '!'){
continue;
}
else{
line[i] = m[line[i]];
}
}
cout << line << endl;
}
return EXIT_SUCCESS;
}
| 27.516129 | 91 | 0.5551 | [
"vector"
] |
23eb22b1cd32ab2af0643fdb2806e6e2ae3c1b23 | 723 | cc | C++ | Daily_Problem/2012/Middle/201214_Group_Anagrams/method2/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | 1 | 2020-02-07T12:25:56.000Z | 2020-02-07T12:25:56.000Z | Daily_Problem/2012/Middle/201214_Group_Anagrams/method2/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | null | null | null | Daily_Problem/2012/Middle/201214_Group_Anagrams/method2/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
using std::string;
using std::unordered_map;
using std::vector;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> sets;
for (auto str : strs) {
string ans = orderString(str);
sets[ans].push_back(str);
}
vector<vector<string>> ans;
for (auto it : sets) {
ans.push_back(it.second);
}
return ans;
}
private:
// 将其排序之后作为哈希表的键
unordered_map<char, int> s;
string orderString(string s) {
std::sort(s.begin(), s.end());
return s;
}
}; | 22.59375 | 64 | 0.580913 | [
"vector"
] |
671f1acf5c9da52115046435865df4c0a9fb687b | 2,382 | cpp | C++ | PA/Laborator/2020-2021/lab02 - Greedy/skel/cpp/task-3/main.cpp | mihai-constantin/ACS | 098c99d82dad8fb5d0e909da930c72f1185a99e2 | [
"Apache-2.0"
] | null | null | null | PA/Laborator/2020-2021/lab02 - Greedy/skel/cpp/task-3/main.cpp | mihai-constantin/ACS | 098c99d82dad8fb5d0e909da930c72f1185a99e2 | [
"Apache-2.0"
] | null | null | null | PA/Laborator/2020-2021/lab02 - Greedy/skel/cpp/task-3/main.cpp | mihai-constantin/ACS | 098c99d82dad8fb5d0e909da930c72f1185a99e2 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct Homework {
int deadline;
int score;
Homework(int _deadline, int _score) : deadline(_deadline), score(_score) {}
};
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
static bool cmp(Homework hw1, Homework hw2) {
if (hw1.deadline == hw2.deadline) {
return hw1.score < hw2.score;
}
return hw1.deadline < hw2.deadline;
}
private:
int n;
vector<Homework> hws;
void read_input() {
ifstream fin("in");
fin >> n;
for (int i = 0, deadline, score; i < n; i++) {
fin >> deadline >> score;
hws.push_back(Homework(deadline, score));
}
fin.close();
}
int get_result() {
/*
TODO: Aflati punctajul maxim pe care il puteti obtine planificand
optim temele.
*/
// sortare crescatoare dupa dl si crescatoare dupa punctaj
sort(hws.begin(), hws.end(), cmp);
int score = hws[hws.size() - 1].score;
hws[hws.size() - 1].score = -1;
for(int week = hws[hws.size() - 1].deadline - 1; week > 0; week--) {
// cout << "week " << week << ": ";
int current_score = 0;
int pos = -1;
for (int i = hws.size() - 2; i >= 0; i--) {
if (hws[i].deadline < week) {
break;
}
if (hws[i].score != -1 && current_score < hws[i].score) {
current_score = hws[i].score;
pos = i;
}
}
if (current_score != 0) {
score += current_score;
hws[pos].score = -1;
}
// cout << current_score << '\n';
}
// cout << "score: " << score << '\n';
return score;
}
void print_output(int result) {
ofstream fout("out");
fout << result;
fout.close();
}
};
// Please always keep this simple main function!
int main() {
// Allocate a Task object on heap in order to be able to
// declare huge static-allocated data structures inside the class.
Task *task = new Task();
task->solve();
delete task;
return 0;
}
| 24.8125 | 79 | 0.489505 | [
"object",
"vector"
] |
6721512f9f11abf5fd2d836ae83bbf83a37fd2d1 | 1,100 | cc | C++ | ui/base/linux/linux_desktop.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ui/base/linux/linux_desktop.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | ui/base/linux/linux_desktop.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/linux/linux_desktop.h"
#include <vector>
#include "base/environment.h"
#include "base/nix/xdg_util.h"
#include "base/strings/string_piece.h"
#include "base/values.h"
#include "ui/display/util/gpu_info_util.h"
namespace ui {
std::vector<base::Value> GetDesktopEnvironmentInfo() {
std::vector<base::Value> result;
auto env(base::Environment::Create());
std::string value;
if (env->GetVar(base::nix::kXdgCurrentDesktopEnvVar, &value)) {
result.push_back(
display::BuildGpuInfoEntry(base::nix::kXdgCurrentDesktopEnvVar, value));
}
if (env->GetVar(base::nix::kXdgSessionTypeEnvVar, &value)) {
result.push_back(
display::BuildGpuInfoEntry(base::nix::kXdgSessionTypeEnvVar, value));
}
constexpr char kGDMSession[] = "GDMSESSION";
if (env->GetVar(kGDMSession, &value))
result.push_back(display::BuildGpuInfoEntry(kGDMSession, value));
return result;
}
} // namespace ui
| 30.555556 | 80 | 0.723636 | [
"vector"
] |
6728b7fe356a38d765018d57e502392cee13bdd1 | 92,433 | cc | C++ | src/hugectr.cc | miguelusque/hugectr_backend | 277fb1acd78a8268f642437dd3cc49e485a8d20b | [
"BSD-3-Clause"
] | null | null | null | src/hugectr.cc | miguelusque/hugectr_backend | 277fb1acd78a8268f642437dd3cc49e485a8d20b | [
"BSD-3-Clause"
] | null | null | null | src/hugectr.cc | miguelusque/hugectr_backend | 277fb1acd78a8268f642437dd3cc49e485a8d20b | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <math.h>
#include <unistd.h>
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <thread>
#include <triton_helpers.hpp>
#include <vector>
#include "cuda_runtime_api.h"
#include "dirent.h"
#include "dlfcn.h"
#include "inference/embedding_interface.hpp"
#include "inference/hugectrmodel.hpp"
#include "inference/inference_utils.hpp"
#include "timer.hpp"
#include "triton/backend/backend_common.h"
namespace triton { namespace backend { namespace hugectr {
//
// HugeCTR Inference backend that demonstrates the TRITONBACKEND API for
// models that trained by HugeCTR(https://github.com/NVIDIA/HugeCTR).
// A general backend completes execution of the
// inference before returning from TRITONBACKED_ModelInstanceExecute.
// Memory type that HugeCTR model support for buffer
enum class MemoryType_t { GPU, CPU, PIN };
// HugeCTR Backend supports any model that trained by HugeCTR, which
// has exactly 3 input and exactly 1 output. The input and output should
// define the name as "DES","CATCOLUMN" and "ROWINDEX", datatype as FP32,
// UINT32 and INT32, the shape and datatype of the input and output must
// match. The backend responds with the output tensor contains the prediction
// result
//
#define GUARDED_RESPOND_IF_ERROR(RESPONSES, IDX, EXPR) \
do { \
if ((RESPONSES)[IDX] != nullptr) { \
TRITONSERVER_Error* err__ = (EXPR); \
if (err__ != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
(RESPONSES)[IDX], TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
err__), \
"failed to send error response"); \
(RESPONSES)[IDX] = nullptr; \
TRITONSERVER_ErrorDelete(err__); \
} \
} \
} while (false)
// An internal exception to carry the HugeCTR CUDA error code
#define CK_CUDA_THROW_(EXPR) \
do { \
const cudaError_t retval = (EXPR); \
if (retval != cudaSuccess) { \
throw std::runtime_error(hctr_str_concat( \
"Runtime error: ", cudaGetErrorString(retval), " ", __FILE__, ":", \
__LINE__, "\n")); \
} \
} while (0)
#define RESPOND_AND_RETURN_IF_ERROR(REQUEST, EXPR) \
do { \
TRITONSERVER_Error* rarie_err__ = (EXPR); \
if (rarie_err__ != nullptr) { \
TRITONBACKEND_Response* rarie_response__ = nullptr; \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseNew(&rarie_response__, REQUEST), \
"failed to create response"); \
if (rarie_response__ != nullptr) { \
LOG_IF_ERROR( \
TRITONBACKEND_ResponseSend( \
rarie_response__, TRITONSERVER_RESPONSE_COMPLETE_FINAL, \
rarie_err__), \
"failed to send error response"); \
} \
TRITONSERVER_ErrorDelete(rarie_err__); \
return; \
} \
} while (false)
// An internal abstraction for cuda memory allocation
class CudaAllocator {
public:
CudaAllocator(MemoryType_t type) : type_{type} {}
void* allocate(size_t size) const
{
void* ptr;
if (type_ == MemoryType_t::GPU) {
CK_CUDA_THROW_(cudaMalloc(&ptr, size));
} else {
CK_CUDA_THROW_(cudaMallocHost(&ptr, size));
}
return ptr;
}
void deallocate(void* ptr) const
{
if (type_ == MemoryType_t::GPU) {
CK_CUDA_THROW_(cudaFree(ptr));
} else {
CK_CUDA_THROW_(cudaFreeHost(ptr));
}
}
private:
MemoryType_t type_;
};
//
// HugeCTRBUffer
//
// Hugectr Buffer associated with a model instance that is using this backend.
// An object of this class is created and associated with each
// TRITONBACKEND_Instance for storing input data from client request
template <typename T>
class HugeCTRBuffer : public std::enable_shared_from_this<HugeCTRBuffer<T>> {
private:
std::vector<size_t> reserved_buffers_;
size_t total_num_elements_;
CudaAllocator allocator_;
void* ptr_ = nullptr;
size_t total_size_in_bytes_ = 0;
public:
static std::shared_ptr<HugeCTRBuffer> create(
MemoryType_t type = MemoryType_t::GPU)
{
return std::make_shared<HugeCTRBuffer>(type);
}
HugeCTRBuffer(MemoryType_t type)
: allocator_{type}, ptr_{nullptr}, total_size_in_bytes_{0}
{
}
~HugeCTRBuffer()
{
if (allocated()) {
allocator_.deallocate(ptr_);
}
}
bool allocated() const
{
return total_size_in_bytes_ != 0 && ptr_ != nullptr;
}
void allocate()
{
if (ptr_ != nullptr) {
std::cerr << "WrongInput: Memory has already been allocated.";
// TODO: Memory leak!
}
size_t offset = 0;
for (const size_t buffer : reserved_buffers_) {
size_t size = buffer;
if (size % 32 != 0) {
size += (32 - size % 32);
}
offset += size;
}
reserved_buffers_.clear();
total_size_in_bytes_ = offset;
if (total_size_in_bytes_ != 0) {
ptr_ = allocator_.allocate(total_size_in_bytes_);
}
}
size_t get_buffer_size() const { return total_size_in_bytes_; }
T* get_ptr() { return reinterpret_cast<T*>(ptr_); }
const T* get_ptr() const { return reinterpret_cast<const T*>(ptr_); }
void* get_raw_ptr() { return ptr_; }
const void* get_raw_ptr() const { return ptr_; }
static size_t get_num_elements_from_dimensions(
const std::vector<size_t>& dimensions)
{
size_t elements = 1;
for (const size_t dim : dimensions) {
elements *= dim;
}
return elements;
}
void reserve(const std::vector<size_t>& dimensions)
{
if (allocated()) {
std::cerr << "IllegalCall: Buffer is finalized.";
// TODO: Fix?!
}
const size_t num_elements = get_num_elements_from_dimensions(dimensions);
const size_t size_in_bytes = num_elements * sizeof(T);
reserved_buffers_.push_back(size_in_bytes);
total_num_elements_ += num_elements;
}
};
//
// HugeCTRBackend
//
// HugeCTRBackend associated with a Backend that is shared by all the models. An
// object of this class is created and associated with each
// TRITONBACKEND_Backend.
//
class HugeCTRBackend {
public:
static TRITONSERVER_Error* Create(
TRITONBACKEND_Backend* triton_backend_, HugeCTRBackend** backend,
std::string ps_json_config_file);
// Get the handle to the TRITONBACKEND model.
TRITONBACKEND_Backend* TritonBackend() { return triton_backend_; }
~HugeCTRBackend();
// HugeCTR unit type Parameter Server
HugeCTR::HugectrUtility<unsigned int>* HugeCTRParameterServerInt32()
{
return EmbeddingTable_int32;
}
// HugeCTR long long type Parameter Server
HugeCTR::HugectrUtility<long long>* HugeCTRParameterServerInt64()
{
return EmbeddingTable_int64;
}
HugeCTR::InferenceParams HugeCTRModelConfiguration(std::string modelname)
{
return inference_params_map.at(modelname);
}
std::map<std::string, HugeCTR::InferenceParams> HugeCTRModelConfigurationMap()
{
return inference_params_map;
}
// Initialize HugeCTR Embedding Table
TRITONSERVER_Error* HugeCTREmbedding_backend();
TRITONSERVER_Error* ParseParameterServer(const std::string& path);
uint64_t GetModelVersion(const std::string& model_name);
std::string ParameterServerJsonFile();
bool UpdateModelVersion(const std::string& model_name, uint64_t version);
private:
TRITONBACKEND_Backend* triton_backend_;
std::string ps_json_config_file_;
HugeCTR::HugectrUtility<unsigned int>* EmbeddingTable_int32;
HugeCTR::HugectrUtility<long long>* EmbeddingTable_int64;
std::vector<std::string> model_network_files;
std::map<std::string, HugeCTR::InferenceParams> inference_params_map;
std::map<std::string, uint64_t> model_version_map;
std::mutex version_map_mutex;
common::TritonJson::Value parameter_server_config;
bool support_int64_key_ = false;
HugeCTRBackend(
TRITONBACKEND_Backend* triton_backend_, std::string ps_json_config_file);
};
TRITONSERVER_Error*
HugeCTRBackend::Create(
TRITONBACKEND_Backend* triton_backend_, HugeCTRBackend** backend,
std::string ps_json_config_file)
{
*backend = new HugeCTRBackend(triton_backend_, ps_json_config_file);
return nullptr; // success
}
uint64_t
HugeCTRBackend::GetModelVersion(const std::string& model_name)
{
std::lock_guard<std::mutex> lock(version_map_mutex);
if (model_version_map.find(model_name) != model_version_map.end()) {
return model_version_map[model_name];
}
return 0;
}
bool
HugeCTRBackend::UpdateModelVersion(
const std::string& model_name, uint64_t version)
{
std::lock_guard<std::mutex> lock(version_map_mutex);
model_version_map[model_name] = version;
return true;
}
std::string
HugeCTRBackend::ParameterServerJsonFile()
{
return ps_json_config_file_;
}
HugeCTRBackend::HugeCTRBackend(
TRITONBACKEND_Backend* triton_backend, std::string ps_json_config_file)
: triton_backend_(triton_backend), ps_json_config_file_(ps_json_config_file)
{
// current much Model Backend initialization handled by TritonBackend_Backend
}
HugeCTRBackend::~HugeCTRBackend()
{
if (support_int64_key_) {
delete EmbeddingTable_int64;
} else {
delete EmbeddingTable_int32;
}
}
TRITONSERVER_Error*
HugeCTRBackend::ParseParameterServer(const std::string& path)
{
HCTR_TRITON_LOG(
INFO, "*****Parsing Parameter Server Configuration from ", path);
{
std::ifstream file_stream{path};
if (file_stream.is_open()) {
std::string filecontent{
std::istreambuf_iterator<char>{file_stream},
std::istreambuf_iterator<char>{}};
parameter_server_config.Parse(filecontent);
} else {
HCTR_TRITON_LOG(
WARN,
"Failed to open Parameter Server Configuration, please check whether "
"the file path is correct!");
}
}
common::TritonJson::Value json;
RETURN_IF_ERROR(TritonJsonHelper::parse(
support_int64_key_, parameter_server_config, "supportlonglong", true));
HCTR_TRITON_LOG(INFO, "Support 64-bit keys = ", support_int64_key_);
// Volatile database parameters.
HugeCTR::VolatileDatabaseParams volatile_db_params;
if (parameter_server_config.Find("volatile_db", &json)) {
auto& params = volatile_db_params;
const std::string log_prefix = "Volatile database -> ";
const char* key;
key = "type";
RETURN_IF_ERROR(TritonJsonHelper::parse(params.type, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "type = ", params.type);
// Backend specific.
key = "address";
RETURN_IF_ERROR(TritonJsonHelper::parse(params.address, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "address = ", params.address);
key = "user_name";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.user_name, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "user name = ", params.user_name);
key = "password";
RETURN_IF_ERROR(TritonJsonHelper::parse(params.password, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "password = <",
params.password.empty() ? "empty" : "specified", ">");
key = "algorithm";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.algorithm, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "algorithm = ", params.algorithm);
key = "num_partitions";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.num_partitions, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "number of partitions = ", params.num_partitions);
key = "max_get_batch_size";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.max_get_batch_size, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"max. batch size (GET) = ", params.max_get_batch_size);
key = "max_set_batch_size";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.max_set_batch_size, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"max. batch size (SET) = ", params.max_set_batch_size);
// Overflow handling related.
key = "refresh_time_after_fetch";
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.refresh_time_after_fetch, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"refresh time after fetch = ", params.refresh_time_after_fetch);
key = "overflow_margin";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.overflow_margin, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "overflow margin = ", params.overflow_margin);
key = "overflow_policy";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.overflow_policy, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "overflow policy = ", params.overflow_policy);
key = "overflow_resolution_target";
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.overflow_resolution_target, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"overflow resolution target = ", params.overflow_resolution_target);
// Caching behavior related.
key = "initial_cache_rate";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.initial_cache_rate, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "initial cache rate = ", params.initial_cache_rate);
key = "cache_missed_embeddings";
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.cache_missed_embeddings, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"cache missed embeddings = ", params.cache_missed_embeddings);
// Real-time update mechanism related.
key = "update_filters";
params.update_filters.clear();
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.update_filters, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "update filters = [",
hctr_str_join(", ", params.update_filters), "]");
}
// Persistent database parameters.
HugeCTR::PersistentDatabaseParams persistent_db_params;
if (parameter_server_config.Find("persistent_db", &json)) {
auto& params = persistent_db_params;
const std::string log_prefix = "Persistent database -> ";
const char* key;
key = "type";
RETURN_IF_ERROR(TritonJsonHelper::parse(params.type, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "type = ", params.type);
// Backend specific.
key = "path";
RETURN_IF_ERROR(TritonJsonHelper::parse(params.path, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "path = ", params.path);
key = "num_threads";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.num_threads, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "number of threads = ", params.num_threads);
key = "read_only";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.read_only, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "read-only = ", params.read_only);
key = "max_get_batch_size";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.max_get_batch_size, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"max. batch size (GET) = ", params.max_get_batch_size);
key = "max_set_batch_size";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.max_set_batch_size, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"max. batch size (SET) = ", params.max_set_batch_size);
// Real-time update mechanism related.
key = "update_filters";
params.update_filters.clear();
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.update_filters, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "update filters = [",
hctr_str_join(", ", params.update_filters), "]");
}
// Update source parameters.
HugeCTR::UpdateSourceParams update_source_params;
if (parameter_server_config.Find("update_source", &json)) {
auto& params = update_source_params;
const std::string log_prefix = "Update source -> ";
const char* key;
key = "type";
RETURN_IF_ERROR(TritonJsonHelper::parse(params.type, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "type = ", params.type);
// Backend specific.
key = "brokers";
RETURN_IF_ERROR(TritonJsonHelper::parse(params.brokers, json, key, false));
HCTR_TRITON_LOG(INFO, log_prefix, "brokers = ", params.brokers);
key = "poll_timeout_ms";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.poll_timeout_ms, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "poll timeout = ", params.poll_timeout_ms, " ms");
key = "max_receive_buffer_size";
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.max_receive_buffer_size, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix,
"max. receive buffer size = ", params.max_receive_buffer_size);
key = "max_batch_size";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.max_batch_size, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "max. batch size = ", params.max_batch_size);
key = "failure_backoff_ms";
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.failure_backoff_ms, json, key, false));
HCTR_TRITON_LOG(
INFO, log_prefix, "failure backoff = ", params.failure_backoff_ms,
" ms");
}
// Model configurations.
parameter_server_config.MemberAsArray("models", &json);
if (json.ArraySize() == 0) {
HCTR_TRITON_LOG(
WARN,
"No model configurations in JSON. Is the file formatted correctly?");
}
for (size_t model_index = 0; model_index < json.ArraySize(); model_index++) {
common::TritonJson::Value json_obj;
json.IndexAsObject(model_index, &json_obj);
// InferenceParams constructor order (non-default-filled arguments):
// [0] model_name -> std::string
std::string model_name;
RETURN_IF_ERROR(
TritonJsonHelper::parse(model_name, json_obj, "model", true));
HCTR_TRITON_LOG(INFO, "Model name = ", model_name);
const std::string log_prefix =
hctr_str_concat("Model '", model_name, "' -> ");
// [?] network_file -> std::string
std::string network_file;
RETURN_IF_ERROR(
TritonJsonHelper::parse(network_file, json_obj, "network_file", true));
HCTR_TRITON_LOG(INFO, log_prefix, "network file = ", network_file);
model_network_files.emplace_back(network_file);
// [1] max_batch_size -> size_t
size_t max_batch_size = 0;
RETURN_IF_ERROR(TritonJsonHelper::parse(
max_batch_size, json_obj, "max_batch_size", true));
HCTR_TRITON_LOG(INFO, log_prefix, "max. batch size = ", max_batch_size);
// [3] dense_model_file -> std::string
std::string dense_file;
RETURN_IF_ERROR(
TritonJsonHelper::parse(dense_file, json_obj, "dense_file", true));
HCTR_TRITON_LOG(INFO, log_prefix, "dense model file = ", dense_file);
// [4] sparse_model_files -> std::vector<std::string>
std::vector<std::string> sparse_files;
RETURN_IF_ERROR(
TritonJsonHelper::parse(sparse_files, json_obj, "sparse_files", true));
HCTR_TRITON_LOG(
INFO, log_prefix, "sparse model files = [",
hctr_str_join(", ", sparse_files), "]");
// [5] device_id -> int
const int device_id = 0;
// [6] use_gpu_embedding_cache -> bool
bool use_gpu_embedding_cache = true;
RETURN_IF_ERROR(TritonJsonHelper::parse(
use_gpu_embedding_cache, json_obj, "gpucache", true));
HCTR_TRITON_LOG(
INFO, log_prefix,
"use GPU embedding cache = ", use_gpu_embedding_cache);
// [2] hit_rate_threshold -> float
float hit_rate_threshold = 0.55;
RETURN_IF_ERROR(TritonJsonHelper::parse(
hit_rate_threshold, json_obj, "hit_rate_threshold",
use_gpu_embedding_cache));
HCTR_TRITON_LOG(
INFO, log_prefix, "hit rate threshold = ", hit_rate_threshold);
// [7] cache_size_percentage -> float
float cache_size_percentage = 0.55;
RETURN_IF_ERROR(TritonJsonHelper::parse(
cache_size_percentage, json_obj, "gpucacheper",
use_gpu_embedding_cache));
HCTR_TRITON_LOG(
INFO, log_prefix, "per model GPU cache = ", cache_size_percentage);
// [8] i64_input_key -> bool
const bool i64_input_key = support_int64_key_;
HugeCTR::InferenceParams params(
model_name, max_batch_size, hit_rate_threshold, dense_file,
sparse_files, device_id, use_gpu_embedding_cache, cache_size_percentage,
i64_input_key);
const char* key;
key = "num_of_worker_buffer_in_pool";
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.number_of_worker_buffers_in_pool, json_obj, key, true));
HCTR_TRITON_LOG(
INFO, log_prefix,
"num. pool worker buffers = ", params.number_of_worker_buffers_in_pool);
key = "num_of_refresher_buffer_in_pool";
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.number_of_refresh_buffers_in_pool, json_obj, key, true));
HCTR_TRITON_LOG(
INFO, log_prefix, "num. pool refresh buffers = ",
params.number_of_refresh_buffers_in_pool);
key = "cache_refresh_percentage_per_iteration";
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.cache_refresh_percentage_per_iteration, json_obj, key, true));
HCTR_TRITON_LOG(
INFO, log_prefix, "cache refresh rate per iteration = ",
params.cache_refresh_percentage_per_iteration);
key = "deployed_device_list";
params.deployed_devices.clear();
RETURN_IF_ERROR(
TritonJsonHelper::parse(params.deployed_devices, json_obj, key, true));
params.device_id = params.deployed_devices.back();
HCTR_TRITON_LOG(
INFO, log_prefix, "deployed device list = [",
hctr_str_join(", ", params.deployed_devices), "]");
key = "default_value_for_each_table";
params.default_value_for_each_table.clear();
RETURN_IF_ERROR(TritonJsonHelper::parse(
params.default_value_for_each_table, json_obj, key, true));
HCTR_TRITON_LOG(
INFO, log_prefix, "default value for each table = [",
hctr_str_join(", ", params.default_value_for_each_table), "]");
// TODO: Move to paramter server common parameters?
params.volatile_db = volatile_db_params;
params.persistent_db = persistent_db_params;
params.update_source = update_source_params;
// Done!
inference_params_map.emplace(model_name, params);
}
return nullptr;
}
// HugeCTR EmbeddingTable
TRITONSERVER_Error*
HugeCTRBackend::HugeCTREmbedding_backend()
{
HCTR_TRITON_LOG(
INFO, "*****The HugeCTR Backend Parameter Server is creating... *****");
HugeCTR::INFER_TYPE type = HugeCTR::INFER_TYPE::TRITON;
std::vector<HugeCTR::InferenceParams> model_vet;
for (const auto& s : HugeCTRModelConfigurationMap()) {
model_vet.push_back(s.second);
}
if (support_int64_key_) {
HCTR_TRITON_LOG(INFO, "***** Parameter Server(Int64) is creating... *****");
EmbeddingTable_int32 = nullptr;
EmbeddingTable_int64 =
HugeCTR::HugectrUtility<long long>::Create_Parameter_Server(
type, model_network_files, model_vet);
} else {
HCTR_TRITON_LOG(
INFO,
"***** The HugeCTR Backend Backend Parameter Server(Int32) is "
"creating... *****");
EmbeddingTable_int32 =
HugeCTR::HugectrUtility<unsigned int>::Create_Parameter_Server(
type, model_network_files, model_vet);
EmbeddingTable_int64 = nullptr;
}
HCTR_TRITON_LOG(
INFO,
"*****The HugeCTR Backend Backend created the Parameter Server "
"successfully! *****");
return nullptr;
}
//
// ModelState
//
// State associated with a model that is using this backend. An object
// of this class is created and associated with each
// TRITONBACKEND_Model.
//
class ModelState {
public:
static TRITONSERVER_Error* Create(
TRITONBACKEND_Model* triton_model, ModelState** state,
HugeCTR::HugectrUtility<unsigned int>* EmbeddingTable_int32,
HugeCTR::HugectrUtility<long long>* EmbeddingTable_int64,
HugeCTR::InferenceParams Model_Inference_Para, uint64_t model_ps_version);
~ModelState();
// Get the handle to the TRITONBACKEND model.
TRITONBACKEND_Model* TritonModel() { return triton_model_; }
// Get the HugeCTR model batch size.
int64_t BatchSize() const { return max_batch_size_; }
// Get the HugeCTR model slots size.
int64_t SlotNum() const { return slot_num_; }
// Get the HugeCTR model max nnz.
int64_t MaxNNZ() const { return max_nnz_; }
// Get the HugeCTR model dense size.
int64_t DeseNum() const { return dese_num_; }
// Get the HugeCTR model cat feature size.
int64_t CatNum() const { return cat_num_; }
// Get the HugeCTR model Embedding size.
int64_t EmbeddingSize() const { return embedding_size_; }
// Get Embedding Cache
std::shared_ptr<HugeCTR::embedding_interface> GetEmbeddingCache(
int64_t device_id)
{
if (embedding_cache_map.find(device_id) != embedding_cache_map.end()) {
return embedding_cache_map[device_id];
} else {
return nullptr;
}
}
// Get input data entry map
std::map<std::string, size_t> GetInputmap() { return input_map_; }
// Get the HugeCTR cache size percentage.
float CacheSizePer() const { return cache_size_per; }
// Get the HugeCTR label dimension.
int64_t LabelDim() const { return label_dim_; }
// Support GPU cache for embedding table.
bool GPUCache() const { return support_gpu_cache_; }
// Support mixed_precision for inference.
bool MixedPrecision() const { return use_mixed_precision_; }
// Support int64 embedding key
bool SupportLongEmbeddingKey() const { return support_int64_key_; }
// Get the current HugeCTR model original json config.
const std::string& HugeCTRJsonConfig() { return hugectr_config_; }
// Get the handle to the Hugectr_backend Configuration.
common::TritonJson::Value& ModelConfig() { return model_config_; }
// Get the name and version of the model.
const std::string& Name() const { return name_; }
uint64_t Version() const { return version_; }
TRITONSERVER_Error* SetPSModelVersion(uint64_t current_version);
// Validate that model configuration is supported by this backend.
TRITONSERVER_Error* ValidateModelConfig();
// Parse that model configuration is supported by this backend.
TRITONSERVER_Error* ParseModelConfig();
// Embedding cache asynchronous refresh
void EmbeddingCacheRefresh(const std::string& model_name, int device_id);
// Create Embedding_cache
TRITONSERVER_Error* Create_EmbeddingCache();
// Refresh embedding cache periodically
void Refresh_Embedding_Cache();
// HugeCTR unit PS
HugeCTR::HugectrUtility<unsigned int>* HugeCTRParameterServerInt32()
{
return EmbeddingTable_int32;
}
const HugeCTR::HugectrUtility<unsigned int>* HugeCTRParameterServerInt32()
const
{
return EmbeddingTable_int32;
}
// HugeCTR long long PS
HugeCTR::HugectrUtility<long long>* HugeCTRParameterServerInt64()
{
return EmbeddingTable_int64;
}
const HugeCTR::HugectrUtility<long long>* HugeCTRParameterServerInt64() const
{
return EmbeddingTable_int64;
}
// Model Inference Inference Parameter Configuration
HugeCTR::InferenceParams ModelInferencePara() { return Model_Inference_Para; }
private:
ModelState(
TRITONSERVER_Server* triton_server, TRITONBACKEND_Model* triton_model,
const char* name, const uint64_t version, uint64_t version_ps,
common::TritonJson::Value&& model_config,
HugeCTR::HugectrUtility<unsigned int>* EmbeddingTable_int32,
HugeCTR::HugectrUtility<long long>* EmbeddingTable_int64,
HugeCTR::InferenceParams Model_Inference_Para);
TRITONSERVER_Server* triton_server_;
TRITONBACKEND_Model* triton_model_;
const std::string name_;
const uint64_t version_;
uint64_t version_ps_;
int64_t max_batch_size_ = 64;
int64_t slot_num_ = 10;
int64_t dese_num_ = 50;
int64_t cat_num_ = 50;
int64_t embedding_size_ = 64;
int64_t max_nnz_ = 3;
int64_t label_dim_ = 1;
float cache_size_per = 0.5;
float hit_rate_threshold = 0.8;
float refresh_interval_ = 0.0f;
float refresh_delay_ = 0.0f;
std::string hugectr_config_;
common::TritonJson::Value model_config_;
std::vector<std::string> model_config_path;
std::vector<std::string> model_name;
std::vector<int64_t> gpu_shape;
// Multi-thread for embedding cache refresh when reload model
std::vector<std::thread> cache_refresh_threads;
bool support_int64_key_ = false;
bool support_gpu_cache_ = true;
bool use_mixed_precision_ = false;
HugeCTR::HugectrUtility<unsigned int>* EmbeddingTable_int32;
HugeCTR::HugectrUtility<long long>* EmbeddingTable_int64;
HugeCTR::InferenceParams Model_Inference_Para;
std::map<int64_t, std::shared_ptr<HugeCTR::embedding_interface>>
embedding_cache_map;
std::map<std::string, size_t> input_map_{
{"DES", 0}, {"CATCOLUMN", 1}, {"ROWINDEX", 2}};
Timer timer;
};
TRITONSERVER_Error*
ModelState::Create(
TRITONBACKEND_Model* triton_model, ModelState** state,
HugeCTR::HugectrUtility<unsigned int>* EmbeddingTable_int32,
HugeCTR::HugectrUtility<long long>* EmbeddingTable_int64,
HugeCTR::InferenceParams Model_Inference_Para, uint64_t model_ps_version)
{
TRITONSERVER_Message* config_message;
RETURN_IF_ERROR(TRITONBACKEND_ModelConfig(
triton_model, 1 /* config_version */, &config_message));
// We can get the model configuration as a json string from
// config_message, parse it with our favorite json parser to create
// DOM that we can access when we need to example the
// configuration. We use TritonJson, which is a wrapper that returns
// nice errors (currently the underlying implementation is
// rapidjson... but others could be added). You can use any json
// parser you prefer.
const char* buffer;
size_t byte_size;
RETURN_IF_ERROR(
TRITONSERVER_MessageSerializeToJson(config_message, &buffer, &byte_size));
common::TritonJson::Value model_config;
TRITONSERVER_Error* err = model_config.Parse(buffer, byte_size);
RETURN_IF_ERROR(TRITONSERVER_MessageDelete(config_message));
RETURN_IF_ERROR(err);
const char* model_name;
RETURN_IF_ERROR(TRITONBACKEND_ModelName(triton_model, &model_name));
uint64_t model_version;
RETURN_IF_ERROR(TRITONBACKEND_ModelVersion(triton_model, &model_version));
TRITONSERVER_Server* triton_server;
RETURN_IF_ERROR(TRITONBACKEND_ModelServer(triton_model, &triton_server));
*state = new ModelState(
triton_server, triton_model, model_name, model_version, model_ps_version,
std::move(model_config), EmbeddingTable_int32, EmbeddingTable_int64,
Model_Inference_Para);
return nullptr; // success
}
ModelState::ModelState(
TRITONSERVER_Server* triton_server, TRITONBACKEND_Model* triton_model,
const char* name, const uint64_t version, uint64_t model_ps_version,
common::TritonJson::Value&& model_config,
HugeCTR::HugectrUtility<unsigned int>* EmbeddingTable_int32,
HugeCTR::HugectrUtility<long long>* EmbeddingTable_int64,
HugeCTR::InferenceParams Model_Inference_Para)
: triton_server_(triton_server), triton_model_(triton_model), name_(name),
version_(version), version_ps_(model_ps_version),
model_config_(std::move(model_config)),
EmbeddingTable_int32(EmbeddingTable_int32),
EmbeddingTable_int64(EmbeddingTable_int64),
Model_Inference_Para(Model_Inference_Para)
{
// current much model initialization work handled by TritonBackend_Model
}
void
ModelState::EmbeddingCacheRefresh(const std::string& model_name, int device_id)
{
HCTR_TRITON_LOG(
INFO, "The model ", model_name,
" is refreshing the embedding cache asynchronously on device ", device_id,
".");
if (support_gpu_cache_) {
if (support_int64_key_) {
EmbeddingTable_int64->update_database_per_model(
hugectr_config_, Model_Inference_Para);
EmbeddingTable_int64->refresh_embedding_cache(model_name, device_id);
} else {
EmbeddingTable_int32->update_database_per_model(
hugectr_config_, Model_Inference_Para);
EmbeddingTable_int32->refresh_embedding_cache(model_name, device_id);
}
}
HCTR_TRITON_LOG(
INFO, "The model ", model_name,
" has refreshed the embedding cache asynchronously on device ", device_id,
".");
}
TRITONSERVER_Error*
ModelState::SetPSModelVersion(uint64_t current_version)
{
version_ps_ = current_version;
return nullptr;
}
TRITONSERVER_Error*
ModelState::ValidateModelConfig()
{
// We have the json DOM for the model configuration...
{
common::TritonJson::WriteBuffer tmp;
RETURN_IF_ERROR(model_config_.PrettyWrite(&tmp));
HCTR_TRITON_LOG(INFO, "Verifying model configuration: ", tmp.Contents());
}
// There must be 3 inputs.
{
common::TritonJson::Value inputs;
RETURN_IF_ERROR(model_config_.MemberAsArray("input", &inputs));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
inputs.ArraySize() == 3, INVALID_ARG, "expect 3 input, got ",
inputs.ArraySize());
for (size_t i = 0; i < 3; i++) {
common::TritonJson::Value input;
RETURN_IF_ERROR(inputs.IndexAsObject(i, &input));
// Input name.
std::string name;
RETURN_IF_ERROR(TritonJsonHelper::parse(name, input, "name", true));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
GetInputmap().count(name) > 0, INVALID_ARG,
"expected input name as DES,CATCOLUMN and ROWINDEX, but got ", name);
// Datatype.
std::string data_type;
RETURN_IF_ERROR(
TritonJsonHelper::parse(data_type, input, "data_type", true));
if (name == "DES") {
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
data_type == "TYPE_FP32", INVALID_ARG,
"expected DES input datatype as TYPE_FP32, got ", data_type);
} else if (name == "CATCOLUMN") {
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
data_type == "TYPE_UINT32" || data_type == "TYPE_INT64",
INVALID_ARG,
"expected CATCOLUMN input datatype as TYPE_UINT32 or TYPE_INT64, "
"got ",
data_type);
} else if (name == "ROWINDEX") {
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
data_type == "TYPE_INT32", INVALID_ARG,
"expected ROWINDEX input datatype as TYPE_FP32, got ", data_type);
}
// Input shape.
std::vector<int64_t> shape;
RETURN_IF_ERROR(backend::ParseShape(input, "dims", &shape));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
shape[0] == -1, INVALID_ARG, "expected input shape equal -1, got ",
backend::ShapeToString(shape));
}
}
// And there must be 1 output.
{
common::TritonJson::Value outputs;
RETURN_IF_ERROR(model_config_.MemberAsArray("output", &outputs));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
outputs.ArraySize() == 1, INVALID_ARG, "expect 1 output, got ",
outputs.ArraySize());
common::TritonJson::Value output;
RETURN_IF_ERROR(outputs.IndexAsObject(0, &output));
std::string data_type;
RETURN_IF_ERROR(
TritonJsonHelper::parse(data_type, output, "data_type", true));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
data_type == "TYPE_FP32", INVALID_ARG,
"expected output datatype as TYPE_FP32, got ", data_type);
// output must have -1 shape
std::vector<int64_t> shape;
RETURN_IF_ERROR(backend::ParseShape(output, "dims", &shape));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
shape[0] == -1, INVALID_ARG, "expected output shape equal -1, got ",
backend::ShapeToString(shape));
}
return nullptr; // success
}
TRITONSERVER_Error*
ModelState::ParseModelConfig()
{
common::TritonJson::WriteBuffer buffer;
RETURN_IF_ERROR(model_config_.PrettyWrite(&buffer));
HCTR_TRITON_LOG(INFO, "The model configuration: ", buffer.Contents());
// Get HugeCTR model configuration
common::TritonJson::Value instance_group;
RETURN_IF_ERROR(
model_config_.MemberAsArray("instance_group", &instance_group));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
instance_group.ArraySize() > 0, INVALID_ARG,
"expect at least one instance in instance group , got ",
instance_group.ArraySize());
for (size_t i = 0; i < instance_group.ArraySize(); i++) {
common::TritonJson::Value instance;
RETURN_IF_ERROR(instance_group.IndexAsObject(i, &instance));
std::string kind;
RETURN_IF_ERROR(instance.MemberAsString("kind", &kind));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
kind == "KIND_GPU", INVALID_ARG,
"expect GPU kind instance in instance group , got ", kind);
int64_t count;
RETURN_IF_ERROR(instance.MemberAsInt("count", &count));
RETURN_ERROR_IF_TRUE(
count > Model_Inference_Para.number_of_worker_buffers_in_pool,
TRITONSERVER_ERROR_INVALID_ARG,
std::string("expect the number of instance(in instance_group) less "
"than number_of_worker_buffers_in_pool that confifured in "
"Parameter Server json file , got ") +
std::to_string(count));
std::vector<int64_t> gpu_list;
RETURN_IF_ERROR(backend::ParseShape(instance, "gpus", &gpu_list));
for (auto id : gpu_list) {
gpu_shape.push_back(id);
}
}
// Parse HugeCTR model customized configuration.
common::TritonJson::Value parameters;
if (model_config_.Find("parameters", ¶meters)) {
common::TritonJson::Value value;
if (parameters.Find("slots", &value)) {
RETURN_IF_ERROR(
TritonJsonHelper::parse(slot_num_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "slots set = ", slot_num_);
}
if (parameters.Find("des_feature_num", &value)) {
RETURN_IF_ERROR(
TritonJsonHelper::parse(dese_num_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "desene number = ", dese_num_);
}
if (parameters.Find("cat_feature_num", &value)) {
RETURN_IF_ERROR(
TritonJsonHelper::parse(cat_num_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "cat_feature number = ", cat_num_);
if (cat_num_ <= 0) {
return HCTR_TRITON_ERROR(
INVALID_ARG, "expected at least one categorical feature, got ",
cat_num_);
}
}
if (parameters.Find("embedding_vector_size", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
embedding_size_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "embedding size = ", embedding_size_);
}
if (parameters.Find("max_nnz", &value)) {
RETURN_IF_ERROR(
TritonJsonHelper::parse(max_nnz_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "maxnnz = ", max_nnz_);
}
if (parameters.Find("refresh_interval", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
refresh_interval_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "refresh_interval = ", refresh_interval_);
}
if (parameters.Find("refresh_delay", &value)) {
RETURN_IF_ERROR(
TritonJsonHelper::parse(refresh_delay_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "refresh_delay = ", refresh_delay_);
}
if (parameters.Find("config", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
hugectr_config_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "HugeCTR model config path = ", hugectr_config_);
}
if (parameters.Find("sparse_files", &value)) {
std::string tmp;
RETURN_IF_ERROR(
TritonJsonHelper::parse(tmp, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "sparse_files = ", tmp);
Model_Inference_Para.sparse_model_files.clear();
hctr_str_split(tmp, ',', Model_Inference_Para.sparse_model_files);
}
if (parameters.Find("dense_file", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
Model_Inference_Para.dense_model_file, value, "string_value", true));
HCTR_TRITON_LOG(
INFO, "dense_file = ", Model_Inference_Para.dense_model_file);
}
if (parameters.Find("gpucache", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
support_gpu_cache_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "support gpu cache = ", support_gpu_cache_);
if (support_gpu_cache_ != Model_Inference_Para.use_gpu_embedding_cache) {
return HCTR_TRITON_ERROR(
INVALID_ARG, "Expected value for 'gpucache' = '",
support_gpu_cache_, "', ",
"which is inconsistent with parameter server JSON configuration "
"file.");
}
Model_Inference_Para.use_gpu_embedding_cache = support_gpu_cache_;
}
if (parameters.Find("mixed_precision", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
use_mixed_precision_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "support mixed_precision = ", use_mixed_precision_);
Model_Inference_Para.use_mixed_precision = use_mixed_precision_;
}
if (support_gpu_cache_ && parameters.Find("gpucacheper", &value)) {
RETURN_IF_ERROR(
TritonJsonHelper::parse(cache_size_per, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "gpu cache per = ", cache_size_per);
if (cache_size_per > Model_Inference_Para.cache_size_percentage) {
return HCTR_TRITON_ERROR(
INVALID_ARG,
"Expected value for 'gpucacheper' (GPU cache percentage) = '",
cache_size_per, "', ",
"which is greater than the value configured in the parameter "
"server JSON file ",
"(=", Model_Inference_Para.cache_size_percentage, ").");
}
Model_Inference_Para.cache_size_percentage = cache_size_per;
}
if (support_gpu_cache_ && parameters.Find("hit_rate_threshold", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
hit_rate_threshold, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "hit-rate threshold = ", hit_rate_threshold);
if (hit_rate_threshold > Model_Inference_Para.hit_rate_threshold) {
return HCTR_TRITON_ERROR(
INVALID_ARG, "Expected value for 'hit_rate_threshold' = '",
hit_rate_threshold, "', ",
"which is greater than the value configured in the parameter "
"server JSON file ",
"(=", Model_Inference_Para.hit_rate_threshold, ").");
}
Model_Inference_Para.hit_rate_threshold = hit_rate_threshold;
}
if (parameters.Find("label_dim", &value)) {
RETURN_IF_ERROR(
TritonJsonHelper::parse(label_dim_, value, "string_value", true));
HCTR_TRITON_LOG(INFO, "Label dim = ", label_dim_);
}
if (parameters.Find("embeddingkey_long_type", &value)) {
RETURN_IF_ERROR(TritonJsonHelper::parse(
support_int64_key_, value, "string_value", true));
HCTR_TRITON_LOG(
INFO, "support 64-bit embedding key = ", support_int64_key_);
Model_Inference_Para.i64_input_key = support_int64_key_;
}
}
model_config_.MemberAsInt("max_batch_size", &max_batch_size_);
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
static_cast<size_t>(max_batch_size_) ==
Model_Inference_Para.max_batchsize,
INVALID_ARG, "expected max_batch_size should equal to ",
Model_Inference_Para.max_batchsize,
" (configured in Parameter Server json file), got ", max_batch_size_);
HCTR_TRITON_LOG(
INFO, "Model_Inference_Para.max_batchsize: ",
Model_Inference_Para.max_batchsize);
Model_Inference_Para.max_batchsize = max_batch_size_;
HCTR_TRITON_LOG(
INFO, "max_batch_size in model config.pbtxt is ", max_batch_size_);
return nullptr;
}
void
ModelState::Refresh_Embedding_Cache()
{
// refresh embedding cache once after delay time
int64_t count = gpu_shape.size();
uint64_t exec_start_ns = 0;
SET_TIMESTAMP(exec_start_ns);
for (int i = 0; i < count; i++) {
if (support_gpu_cache_) {
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("The model ") + name_ +
std::string(" is periodically refreshing the embedding cache "
"asynchronously on device ") +
std::to_string(gpu_shape[i]))
.c_str());
if (support_int64_key_) {
EmbeddingTable_int64->refresh_embedding_cache(name_, gpu_shape[i]);
} else {
EmbeddingTable_int32->refresh_embedding_cache(name_, gpu_shape[i]);
}
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("The model ") + name_ +
std::string(
" has refreshed the embedding cache asynchronously on device ") +
std::to_string(gpu_shape[i]))
.c_str());
}
}
uint64_t exec_end_ns = 0;
SET_TIMESTAMP(exec_end_ns);
int64_t exe_time = (exec_end_ns - exec_start_ns) / 1000000;
LOG_MESSAGE(
TRITONSERVER_LOG_INFO,
(std::string("Refresh embedding table execution time is ") +
std::to_string(exe_time) + " ms")
.c_str());
}
TRITONSERVER_Error*
ModelState::Create_EmbeddingCache()
{
int64_t count = gpu_shape.size();
if (count > 0 && support_gpu_cache_) {
if (support_int64_key_ && EmbeddingTable_int64->GetEmbeddingCache(
name_, gpu_shape[0]) == nullptr) {
HCTR_TRITON_LOG(
INFO, "Parsing network file of ", name_,
", which will be used for online deployment. The network file path "
"is ",
hugectr_config_);
EmbeddingTable_int64->parse_networks_per_model(
hugectr_config_, Model_Inference_Para);
HCTR_TRITON_LOG(
INFO, "Update Database of Parameter Server for model ", name_);
EmbeddingTable_int64->update_database_per_model(
hugectr_config_, Model_Inference_Para);
HCTR_TRITON_LOG(INFO, "Create embedding cache for model ", name_);
EmbeddingTable_int64->create_embedding_cache_per_model(
hugectr_config_, Model_Inference_Para);
}
if (!support_int64_key_ && EmbeddingTable_int32->GetEmbeddingCache(
name_, gpu_shape[0]) == nullptr) {
EmbeddingTable_int32->parse_networks_per_model(
hugectr_config_, Model_Inference_Para);
EmbeddingTable_int32->update_database_per_model(
hugectr_config_, Model_Inference_Para);
EmbeddingTable_int32->create_embedding_cache_per_model(
hugectr_config_, Model_Inference_Para);
}
}
for (int i = 0; i < count; i++) {
std::vector<int>::iterator iter = find(
Model_Inference_Para.deployed_devices.begin(),
Model_Inference_Para.deployed_devices.end(), gpu_shape[i]);
HCTR_RETURN_TRITION_ERROR_IF_TRUE(
iter == Model_Inference_Para.deployed_devices.end(), INVALID_ARG,
"Please confirm that device ", gpu_shape[i],
" is added to 'deployed_device_list' in the ps configuration file");
if (embedding_cache_map.find(gpu_shape[i]) == embedding_cache_map.end()) {
HCTR_TRITON_LOG(
INFO, "******Creating Embedding Cache for model ", name_,
" in device ", gpu_shape[i]);
if (support_int64_key_) {
Model_Inference_Para.device_id = gpu_shape[i];
embedding_cache_map[gpu_shape[i]] =
EmbeddingTable_int64->GetEmbeddingCache(name_, gpu_shape[i]);
} else {
Model_Inference_Para.device_id = gpu_shape[i];
embedding_cache_map[gpu_shape[i]] =
EmbeddingTable_int32->GetEmbeddingCache(name_, gpu_shape[i]);
}
if (version_ps_ > 0 && version_ps_ != version_) {
timer.startonce(
0,
std::bind(
&ModelState::EmbeddingCacheRefresh, this, name_, gpu_shape[i]));
}
}
}
if (refresh_delay_ > 1e-6) {
// refresh embedding cache once after delay time
timer.startonce(
refresh_delay_, std::bind(&ModelState::Refresh_Embedding_Cache, this));
}
if (refresh_interval_ > 1e-6) {
// refresh embedding cache once based on period time
timer.start(
refresh_interval_,
std::bind(&ModelState::Refresh_Embedding_Cache, this));
}
HCTR_TRITON_LOG(
INFO, "******Creating Embedding Cache for model ", name_,
" successfully");
return nullptr;
}
ModelState::~ModelState()
{
if (support_gpu_cache_ && version_ps_ == version_) {
if (support_int64_key_) {
EmbeddingTable_int64->destory_embedding_cache_per_model(name_);
} else {
EmbeddingTable_int32->destory_embedding_cache_per_model(name_);
}
HCTR_TRITON_LOG(
INFO, "******Destorying Embedding Cache for model ", name_,
" successfully");
}
embedding_cache_map.clear();
for (auto& ec_refresh_thread : cache_refresh_threads) {
ec_refresh_thread.join();
}
timer.stop();
}
//
// ModelInstanceState
//
// State associated with a model instance. An object of this class is
// created and associated with each TRITONBACKEND_ModelInstance.
//
class ModelInstanceState {
public:
static TRITONSERVER_Error* Create(
ModelState* model_state,
TRITONBACKEND_ModelInstance* triton_model_instance,
ModelInstanceState** state, HugeCTR::InferenceParams instance_params);
~ModelInstanceState();
// Get the handle to the TRITONBACKEND model instance.
TRITONBACKEND_ModelInstance* TritonModelInstance()
{
return triton_model_instance_;
}
// Get the name, kind and device ID of the instance.
const std::string& Name() const { return name_; }
TRITONSERVER_InstanceGroupKind Kind() const { return kind_; }
int32_t DeviceId() const { return device_id_; }
// Get the state of the model that corresponds to this instance.
ModelState* StateForModel() const { return model_state_; }
// Get the prediction result that corresponds to this instance.
TRITONSERVER_Error* ProcessRequest(int64_t numofsamples);
// Create Embedding_cache
TRITONSERVER_Error* LoadHugeCTRModel();
std::shared_ptr<HugeCTRBuffer<float>> GetDeseBuffer()
{
return dense_value_buf;
}
std::shared_ptr<HugeCTRBuffer<unsigned int>> GetCatColBuffer_int32()
{
return cat_column_index_buf_int32;
}
std::shared_ptr<HugeCTRBuffer<long long>> GetCatColBuffer_int64()
{
return cat_column_index_buf_int64;
}
std::shared_ptr<HugeCTRBuffer<int>> GetRowBuffer() { return row_ptr_buf; }
std::shared_ptr<HugeCTRBuffer<float>> GetPredictBuffer()
{
return prediction_buf;
}
private:
ModelInstanceState(
ModelState* model_state,
TRITONBACKEND_ModelInstance* triton_model_instance, const char* name,
const TRITONSERVER_InstanceGroupKind kind, const int32_t device_id,
HugeCTR::InferenceParams instance_params);
ModelState* model_state_;
TRITONBACKEND_ModelInstance* triton_model_instance_;
const std::string name_;
const TRITONSERVER_InstanceGroupKind kind_;
const int32_t device_id_;
// HugeCTR Model buffer for input and output
// There buffers will be shared for all the requests
std::shared_ptr<HugeCTRBuffer<float>> dense_value_buf;
std::shared_ptr<HugeCTRBuffer<unsigned int>> cat_column_index_buf_int32;
std::shared_ptr<HugeCTRBuffer<long long>> cat_column_index_buf_int64;
std::shared_ptr<HugeCTRBuffer<int>> row_ptr_buf;
std::shared_ptr<HugeCTRBuffer<float>> prediction_buf;
std::shared_ptr<HugeCTR::embedding_interface> embedding_cache;
HugeCTR::InferenceParams instance_params_;
HugeCTR::HugeCTRModel* hugectrmodel_;
};
TRITONSERVER_Error*
ModelInstanceState::Create(
ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance,
ModelInstanceState** state, HugeCTR::InferenceParams instance_params)
{
const char* instance_name;
RETURN_IF_ERROR(
TRITONBACKEND_ModelInstanceName(triton_model_instance, &instance_name));
TRITONSERVER_InstanceGroupKind instance_kind;
RETURN_IF_ERROR(
TRITONBACKEND_ModelInstanceKind(triton_model_instance, &instance_kind));
int32_t device_id;
RETURN_IF_ERROR(
TRITONBACKEND_ModelInstanceDeviceId(triton_model_instance, &device_id));
int32_t instance_id;
RETURN_IF_ERROR(
TRITONBACKEND_ModelInstanceDeviceId(triton_model_instance, &instance_id));
*state = new ModelInstanceState(
model_state, triton_model_instance, instance_name, instance_kind,
device_id, instance_params);
return nullptr; // success
}
ModelInstanceState::ModelInstanceState(
ModelState* model_state, TRITONBACKEND_ModelInstance* triton_model_instance,
const char* name, const TRITONSERVER_InstanceGroupKind kind,
const int32_t device_id, HugeCTR::InferenceParams instance_params)
: model_state_(model_state), triton_model_instance_(triton_model_instance),
name_(model_state->Name()), kind_(kind), device_id_(device_id),
instance_params_(instance_params)
{
HCTR_TRITON_LOG(
INFO, "Triton Model Instance Initialization on device ", device_id);
cudaError_t cuerr = cudaSetDevice(device_id);
if (cuerr != cudaSuccess) {
std::cerr << "failed to set CUDA device to " << device_id << ": "
<< cudaGetErrorString(cuerr);
}
// Set current model instance device id as triton provided
instance_params_.device_id = device_id;
// Alloc the cuda memory
HCTR_TRITON_LOG(INFO, "Dense Feature buffer allocation: ");
dense_value_buf = HugeCTRBuffer<float>::create();
std::vector<size_t> dense_value_dims = {
static_cast<size_t>(model_state_->BatchSize() * model_state_->DeseNum())};
dense_value_buf->reserve(dense_value_dims);
dense_value_buf->allocate();
HCTR_TRITON_LOG(INFO, "Categorical Feature buffer allocation: ");
if (model_state_->SupportLongEmbeddingKey()) {
cat_column_index_buf_int64 =
HugeCTRBuffer<long long>::create(MemoryType_t::PIN);
std::vector<size_t> cat_column_index_dims = {static_cast<size_t>(
model_state_->BatchSize() * model_state_->CatNum())};
cat_column_index_buf_int64->reserve(cat_column_index_dims);
cat_column_index_buf_int64->allocate();
} else {
cat_column_index_buf_int32 =
HugeCTRBuffer<unsigned int>::create(MemoryType_t::PIN);
std::vector<size_t> cat_column_index_dims = {static_cast<size_t>(
model_state_->BatchSize() * model_state_->CatNum())};
cat_column_index_buf_int32->reserve(cat_column_index_dims);
cat_column_index_buf_int32->allocate();
}
HCTR_TRITON_LOG(INFO, "Categorical Row Index buffer allocation: ");
row_ptr_buf = HugeCTRBuffer<int>::create();
std::vector<size_t> row_ptrs_dims = {static_cast<size_t>(
model_state_->BatchSize() * model_state_->SlotNum() + 1)};
row_ptr_buf->reserve(row_ptrs_dims);
row_ptr_buf->allocate();
HCTR_TRITON_LOG(INFO, "Predict result buffer allocation: ");
prediction_buf = HugeCTRBuffer<float>::create();
std::vector<size_t> prediction_dims = {static_cast<size_t>(
model_state_->BatchSize() * model_state_->LabelDim())};
prediction_buf->reserve(prediction_dims);
prediction_buf->allocate();
}
ModelInstanceState::~ModelInstanceState()
{
// release all the buffers
embedding_cache.reset();
model_state_->GetEmbeddingCache(device_id_).reset();
delete hugectrmodel_;
}
TRITONSERVER_Error*
ModelInstanceState::LoadHugeCTRModel()
{
HugeCTR::INFER_TYPE type = HugeCTR::INFER_TYPE::TRITON;
HCTR_TRITON_LOG(
INFO, "The model origin json configuration file path is: ",
model_state_->HugeCTRJsonConfig());
embedding_cache = model_state_->GetEmbeddingCache(device_id_);
hugectrmodel_ = HugeCTR::HugeCTRModel::load_model(
type, model_state_->HugeCTRJsonConfig(), instance_params_,
embedding_cache);
HCTR_TRITON_LOG(INFO, "******Loading HugeCTR model successfully");
return nullptr;
}
TRITONSERVER_Error*
ModelInstanceState::ProcessRequest(int64_t numofsamples)
{
if (model_state_->SupportLongEmbeddingKey()) {
hugectrmodel_->predict(
dense_value_buf->get_ptr(), cat_column_index_buf_int64->get_raw_ptr(),
row_ptr_buf->get_ptr(), prediction_buf->get_ptr(), numofsamples);
} else {
hugectrmodel_->predict(
dense_value_buf->get_ptr(), cat_column_index_buf_int32->get_raw_ptr(),
row_ptr_buf->get_ptr(), prediction_buf->get_ptr(), numofsamples);
}
return nullptr;
}
/////////////
extern "C" {
// Implementing TRITONBACKEND_Initialize is optional. The backend
// should initialize any global state that is intended to be shared
// across all models and model instances that use the backend.
TRITONSERVER_Error*
TRITONBACKEND_Initialize(TRITONBACKEND_Backend* backend)
{
const char* name;
RETURN_IF_ERROR(TRITONBACKEND_BackendName(backend, &name));
HCTR_TRITON_LOG(INFO, "TRITONBACKEND_Initialize: ", name);
// We should check the backend API version that Triton supports
// vs. what this backend was compiled against.
uint32_t api_version_major, api_version_minor;
RETURN_IF_ERROR(
TRITONBACKEND_ApiVersion(&api_version_major, &api_version_minor));
HCTR_TRITON_LOG(
INFO, "Triton TRITONBACKEND API version: ", api_version_major, ".",
api_version_minor);
HCTR_TRITON_LOG(
INFO, "'", name,
"' TRITONBACKEND API version: ", TRITONBACKEND_API_VERSION_MAJOR, ".",
TRITONBACKEND_API_VERSION_MINOR);
if ((api_version_major != TRITONBACKEND_API_VERSION_MAJOR) ||
(api_version_minor < TRITONBACKEND_API_VERSION_MINOR)) {
return HCTR_TRITON_ERROR(
UNSUPPORTED,
"Triton backend API version does not support this backend");
}
// The backend configuration may contain information needed by the
// backend, such a command-line arguments. Hugectr backend requires
// that the model json configuration file path must be specified specify in
// the command-line.
TRITONSERVER_Message* backend_config_message;
RETURN_IF_ERROR(
TRITONBACKEND_BackendConfig(backend, &backend_config_message));
TRITONBACKEND_ArtifactType artifact_type;
const char* location;
RETURN_IF_ERROR(
TRITONBACKEND_BackendArtifacts(backend, &artifact_type, &location));
HCTR_TRITON_LOG(INFO, "The HugeCTR backend Repository location: ", location);
// Backend configuration message contains model configuration with json
// format example format:
// {"cmdline":{"model1":"/json_path1","model2":"/json_path2"}}
const char* buffer;
size_t byte_size;
RETURN_IF_ERROR(TRITONSERVER_MessageSerializeToJson(
backend_config_message, &buffer, &byte_size));
HCTR_TRITON_LOG(INFO, "The HugeCTR backend configuration: ", buffer);
// Parse the command-line argument to determine the type of embedding table
// Key
common::TritonJson::Value backend_config;
TRITONSERVER_Error* err = backend_config.Parse(buffer, byte_size);
RETURN_IF_ERROR(err);
common::TritonJson::Value cmdline;
;
std::vector<std::string> cmd_keys;
std::string ps_path;
if (backend_config.Find("cmdline", &cmdline)) {
RETURN_IF_ERROR(cmdline.Members(&cmd_keys));
for (const auto& param_key : cmd_keys) {
std::string value_string;
if (param_key == "ps") {
RETURN_IF_ERROR(cmdline.MemberAsString(param_key.c_str(), &ps_path));
}
}
}
// HugeCTR have a global backend state that we need create Parameter Server
// for all the models, which will be shared by all the models to update
// embedding cache
HugeCTRBackend* hugectr_backend;
RETURN_IF_ERROR(HugeCTRBackend::Create(backend, &hugectr_backend, ps_path));
RETURN_IF_ERROR(TRITONBACKEND_BackendSetState(
backend, reinterpret_cast<void*>(hugectr_backend)));
RETURN_IF_ERROR(hugectr_backend->ParseParameterServer(ps_path));
RETURN_IF_ERROR(hugectr_backend->HugeCTREmbedding_backend());
return nullptr; // success
}
// Implementing TRITONBACKEND_Finalize is optional unless state is set
// using TRITONBACKEND_BackendSetState. The backend must free this
// state and perform any other global cleanup.
TRITONSERVER_Error*
TRITONBACKEND_Finalize(TRITONBACKEND_Backend* backend)
{
void* vstate;
RETURN_IF_ERROR(TRITONBACKEND_BackendState(backend, &vstate));
HugeCTRBackend* state = reinterpret_cast<HugeCTRBackend*>(vstate);
HCTR_TRITON_LOG(INFO, "TRITONBACKEND_Backend Finalize: HugectrBackend");
delete state;
return nullptr; // success
}
// Implementing TRITONBACKEND_ModelInitialize is optional. The backend
// should initialize any state that is intended to be shared across
// all instances of the model.
TRITONSERVER_Error*
TRITONBACKEND_ModelInitialize(TRITONBACKEND_Model* model)
{
const char* name;
RETURN_IF_ERROR(TRITONBACKEND_ModelName(model, &name));
uint64_t version;
RETURN_IF_ERROR(TRITONBACKEND_ModelVersion(model, &version));
HCTR_TRITON_LOG(
INFO, "TRITONBACKEND_ModelInitialize: ", name, " (version ", version,
")");
// Can get location of the model artifacts. Normally we would need
// to check the artifact type to make sure it was something we can
// handle... but we are just going to log the location so we don't
// need the check. We would use the location if we wanted to load
// something from the model's repo.
TRITONBACKEND_ArtifactType artifact_type;
const char* location;
RETURN_IF_ERROR(
TRITONBACKEND_ModelRepository(model, &artifact_type, &location));
HCTR_TRITON_LOG(INFO, "Repository location: ", location);
// The model can access the backend as well... here we can access
// the backend global state.
TRITONBACKEND_Backend* backend;
RETURN_IF_ERROR(TRITONBACKEND_ModelBackend(model, &backend));
TRITONSERVER_Message* backend_config_message;
RETURN_IF_ERROR(
TRITONBACKEND_BackendConfig(backend, &backend_config_message));
const char* buffer;
size_t byte_size;
RETURN_IF_ERROR(TRITONSERVER_MessageSerializeToJson(
backend_config_message, &buffer, &byte_size));
HCTR_TRITON_LOG(INFO, "backend configuration in mode: ", buffer);
void* vbackendstate;
RETURN_IF_ERROR(TRITONBACKEND_BackendState(backend, &vbackendstate));
HugeCTRBackend* backend_state =
reinterpret_cast<HugeCTRBackend*>(vbackendstate);
// With each model we create a ModelState object and associate it
// with the TRITONBACKEND_Model.
ModelState* model_state;
uint64_t model_ps_version = backend_state->GetModelVersion(name);
uint64_t model_current_version;
RETURN_IF_ERROR(TRITONBACKEND_ModelVersion(model, &model_current_version));
if (backend_state->HugeCTRModelConfigurationMap().count(name) == 0) {
HCTR_TRITON_LOG(
INFO,
"Parsing the latest Parameter Server json config file for deploying "
"model ",
name, " online");
backend_state->ParseParameterServer(
backend_state->ParameterServerJsonFile());
}
if (backend_state->HugeCTRModelConfigurationMap().count(name) == 0) {
HCTR_TRITON_LOG(
WARN,
"Fail to parse the latest Parameter Server json config file for "
"deploying "
"model ",
name, " online");
return nullptr;
}
ModelState::Create(
model, &model_state, backend_state->HugeCTRParameterServerInt32(),
backend_state->HugeCTRParameterServerInt64(),
backend_state->HugeCTRModelConfiguration(name), model_ps_version);
RETURN_IF_ERROR(
TRITONBACKEND_ModelSetState(model, reinterpret_cast<void*>(model_state)));
backend_state->UpdateModelVersion(name, model_current_version);
// One of the primary things to do in ModelInitialize is to examine
// the model configuration to ensure that it is something that this
// backend can support. If not, returning an error from this
// function will prevent the model from loading.
RETURN_IF_ERROR(model_state->ValidateModelConfig());
// One of the primary things to do in ModelInitialize is to parsing
// the model configuration to ensure that it is something that this
// backend required. If not, returning an error from this
// function will prevent the model from loading.
RETURN_IF_ERROR(model_state->ParseModelConfig());
// One of the primary things to do in ModelInitialize is to initialize
// embedding cache to ensure that it is embedding vector that current model
// look_up. If not, returning an error from this function will prevent the
// model from loading.
RETURN_IF_ERROR(model_state->Create_EmbeddingCache());
return nullptr; // success
}
// Implementing TRITONBACKEND_ModelFinalize is optional unless state
// is set using TRITONBACKEND_ModelSetState. The backend must free
// this state and perform any other cleanup.
TRITONSERVER_Error*
TRITONBACKEND_ModelFinalize(TRITONBACKEND_Model* model)
{
const char* name;
RETURN_IF_ERROR(TRITONBACKEND_ModelName(model, &name));
TRITONBACKEND_Backend* backend;
RETURN_IF_ERROR(TRITONBACKEND_ModelBackend(model, &backend));
void* vbackendstate;
RETURN_IF_ERROR(TRITONBACKEND_BackendState(backend, &vbackendstate));
HugeCTRBackend* backend_state =
reinterpret_cast<HugeCTRBackend*>(vbackendstate);
uint64_t latest_model_ps_version = backend_state->GetModelVersion(name);
void* vstate;
RETURN_IF_ERROR(TRITONBACKEND_ModelState(model, &vstate));
ModelState* model_state = reinterpret_cast<ModelState*>(vstate);
model_state->SetPSModelVersion(latest_model_ps_version);
HCTR_TRITON_LOG(INFO, "TRITONBACKEND_ModelFinalize: delete model state");
delete model_state;
return nullptr; // success
}
// Implementing TRITONBACKEND_ModelInstanceInitialize is optional. The
// backend should initialize any state that is required for a model
// instance.
TRITONSERVER_Error*
TRITONBACKEND_ModelInstanceInitialize(TRITONBACKEND_ModelInstance* instance)
{
const char* name;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceName(instance, &name));
// The instance can access the corresponding model and backend as well... here
// we get the model and backend and from that get the model's state such that
// to dinstinguish whether current model is deployed on-line
TRITONBACKEND_Model* model;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceModel(instance, &model));
const char* modelname;
RETURN_IF_ERROR(TRITONBACKEND_ModelName(model, &modelname));
void* vmodelstate;
RETURN_IF_ERROR(TRITONBACKEND_ModelState(model, &vmodelstate));
ModelState* model_state = reinterpret_cast<ModelState*>(vmodelstate);
TRITONBACKEND_Backend* backend;
void* vbackendstate;
RETURN_IF_ERROR(TRITONBACKEND_ModelBackend(model, &backend));
RETURN_IF_ERROR(TRITONBACKEND_BackendState(backend, &vbackendstate));
HugeCTRBackend* backend_state =
reinterpret_cast<HugeCTRBackend*>(vbackendstate);
if (backend_state->HugeCTRModelConfigurationMap().count(modelname) == 0) {
HCTR_TRITON_LOG(
WARN, "Please make sure that the configuration of model ", modelname,
"has been added to the Parameter Server json configuration file!");
return nullptr;
}
int32_t device_id;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceDeviceId(instance, &device_id));
HCTR_TRITON_LOG(
INFO, "TRITONBACKEND_ModelInstanceInitialize: ", name, " (device ",
device_id, ")");
// With each instance we create a ModelInstanceState object and
// associate it with the TRITONBACKEND_ModelInstance.
ModelInstanceState* instance_state;
RETURN_IF_ERROR(ModelInstanceState::Create(
model_state, instance, &instance_state,
model_state->ModelInferencePara()));
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceSetState(
instance, reinterpret_cast<void*>(instance_state)));
HCTR_TRITON_LOG(INFO, "******Loading HugeCTR Model******");
RETURN_IF_ERROR(instance_state->LoadHugeCTRModel());
return nullptr; // success
}
// Implementing TRITONBACKEND_ModelInstanceFinalize is optional unless
// state is set using TRITONBACKEND_ModelInstanceSetState. The backend
// must free this state and perform any other cleanup.
TRITONSERVER_Error*
TRITONBACKEND_ModelInstanceFinalize(TRITONBACKEND_ModelInstance* instance)
{
void* vstate;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceState(instance, &vstate));
ModelInstanceState* instance_state =
reinterpret_cast<ModelInstanceState*>(vstate);
HCTR_TRITON_LOG(
INFO, "TRITONBACKEND_ModelInstanceFinalize: delete instance state");
delete instance_state;
return nullptr; // success
}
// Implementing TRITONBACKEND_ModelInstanceExecute is required.
TRITONSERVER_Error*
TRITONBACKEND_ModelInstanceExecute(
TRITONBACKEND_ModelInstance* instance, TRITONBACKEND_Request** requests,
const uint32_t request_count)
{
// Triton will not call this function simultaneously for the same
// 'instance'. But since this backend could be used by multiple
// instances from multiple models the implementation needs to handle
// multiple calls to this function at the same time (with different
// 'instance' objects). Suggested practice for this is to use only
// function-local and model-instance-specific state (obtained from
// 'instance'), which is what we do here.
ModelInstanceState* instance_state;
RETURN_IF_ERROR(TRITONBACKEND_ModelInstanceState(
instance, reinterpret_cast<void**>(&instance_state)));
ModelState* model_state = instance_state->StateForModel();
// This backend specifies BLOCKING execution policy. That means that
// we should not return from this function until execution is
// complete. Triton will automatically release 'instance' on return
// from this function so that it is again available to be used for
// another call to TRITONBACKEND_ModelInstanceExecute.
HCTR_TRITON_LOG(
INFO, "model ", model_state->Name(), ", instance ",
instance_state->Name(), ", executing ", request_count, " requests");
// 'responses' is initialized with the response objects below and
// if/when an error response is sent the corresponding entry in
// 'responses' is set to nullptr to indicate that that response has
// already been sent.
std::vector<TRITONBACKEND_Response*> responses;
responses.reserve(request_count);
// Create a single response object for each request. If something
// goes wrong when attempting to create the response objects just
// fail all of the requests by returning an error.
for (uint32_t r = 0; r < request_count; ++r) {
TRITONBACKEND_Response* response;
RETURN_IF_ERROR(TRITONBACKEND_ResponseNew(&response, requests[r]));
responses.push_back(response);
}
// HugeCTR model can't support concurrent prediction for all the requests,
// which means you would execute all the requests at the same time,
// So here we execute each request separately so there is no single range.
// As a result we just show the entire execution time as being the compute
// time as well.
uint64_t min_exec_start_ns = std::numeric_limits<uint64_t>::max();
uint64_t max_exec_end_ns = 0;
uint64_t total_batch_size = 0;
// After this point we take ownership of 'requests', which means
// that a response must be sent for every request. If something does
// go wrong in processing a particular request then we send an error
// response just for the specific request.
for (uint32_t r = 0; r < request_count; ++r) {
uint64_t exec_start_ns = 0;
TRITONBACKEND_Request* request = requests[r];
const char* request_id = "";
GUARDED_RESPOND_IF_ERROR(
responses, r, TRITONBACKEND_RequestId(request, &request_id));
uint64_t correlation_id = 0;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestCorrelationId(request, &correlation_id));
// Triton ensures that there is only a single input since that is
// what is specified in the model configuration, so normally there
// would be no reason to check it but we do here to demonstrate the
// API.
uint32_t input_count = 0;
GUARDED_RESPOND_IF_ERROR(
responses, r, TRITONBACKEND_RequestInputCount(request, &input_count));
uint32_t requested_output_count = 0;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestOutputCount(request, &requested_output_count));
// If an error response was sent for the above then display an
// error message and move on to next request.
if (responses[r] == nullptr) {
HCTR_TRITON_LOG(
ERROR, "request ", r,
": failed to read request input/output counts, error response sent");
continue;
}
HCTR_TRITON_LOG(
INFO, "request ", r, ": id = \"", request_id, "\"",
", correlation_id = ", correlation_id, ", input_count = ", input_count,
", requested_output_count = ", requested_output_count);
const char* input_name;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestInputName(request, 0 /* index */, &input_name));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
instance_state->StateForModel()->GetInputmap().count(input_name) > 0,
INVALID_ARG,
"expected input name as DES, CATCOLUMN and ROWINDEX in request, but "
"got ",
input_name);
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestInputName(request, 1 /* index */, &input_name));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
instance_state->StateForModel()->GetInputmap().count(input_name) > 0,
INVALID_ARG,
"expected input name as DES, CATCOLUMN and ROWINDEX in request, but "
"got ",
input_name);
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestInputName(request, 2 /* index */, &input_name));
HCTR_RETURN_TRITON_ERROR_IF_FALSE(
instance_state->StateForModel()->GetInputmap().count(input_name) > 0,
INVALID_ARG,
"expected input name as DES, CATCOLUMN and ROWINDEX in request, but "
"got ",
input_name);
const char des_input_name[] = "DES";
TRITONBACKEND_Input* des_input = nullptr;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestInput(request, des_input_name, &des_input));
const char catcol_input_name[] = "CATCOLUMN";
TRITONBACKEND_Input* catcol_input = nullptr;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestInput(request, catcol_input_name, &catcol_input));
const char row_input_name[] = "ROWINDEX";
TRITONBACKEND_Input* row_input = nullptr;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestInput(request, row_input_name, &row_input));
// We also validated that the model configuration specifies only a
// single output, but the request is not required to request any
// output at all so we only produce an output if requested.
const char* requested_output_name = nullptr;
if (requested_output_count > 0) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_RequestOutputName(
request, 0 /* index */, &requested_output_name));
}
// If an error response was sent while getting the input or
// requested output name then display an error message and move on
// to next request.
if (responses[r] == nullptr) {
HCTR_TRITON_LOG(
ERROR, "request ", r,
": failed to read input or requested output name, error response "
"sent");
continue;
}
TRITONSERVER_DataType des_datatype;
TRITONSERVER_DataType cat_datatype;
TRITONSERVER_DataType row_datatype;
const int64_t* input_shape;
uint32_t des_dims_count;
uint32_t cat_dims_count;
uint32_t row_dims_count;
uint64_t des_byte_size;
uint64_t cat_byte_size;
uint64_t row_byte_size;
uint32_t des_input_buffer_count;
uint32_t cat_input_buffer_count;
uint32_t rowindex_input_buffer_count;
int64_t num_of_samples = 0;
int64_t numofdes;
int64_t numofcat;
int64_t num_of_sample_des = 1;
int64_t num_of_sample_cat = 1;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_InputProperties(
catcol_input, nullptr /* input_name */, &cat_datatype, &input_shape,
&cat_dims_count, &cat_byte_size, &cat_input_buffer_count));
HCTR_TRITON_LOG(
INFO, "\tinput ", catcol_input_name,
": datatype = ", TRITONSERVER_DataTypeString(cat_datatype),
", shape = ", backend::ShapeToString(input_shape, cat_dims_count),
", byte_size = ", cat_byte_size,
", buffer_count = ", cat_input_buffer_count);
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_InputProperties(
row_input, nullptr /* input_name */, &row_datatype, &input_shape,
&row_dims_count, &row_byte_size, &rowindex_input_buffer_count));
HCTR_TRITON_LOG(
INFO, "\tinput ", row_input_name,
": datatype = ", TRITONSERVER_DataTypeString(row_datatype),
", shape = ", backend::ShapeToString(input_shape, row_dims_count),
", byte_size = ", row_byte_size,
", buffer_count = ", rowindex_input_buffer_count);
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_InputProperties(
des_input, nullptr /* input_name */, &des_datatype, &input_shape,
&des_dims_count, &des_byte_size, &des_input_buffer_count));
HCTR_TRITON_LOG(
INFO, "\tinput ", des_input_name,
": datatype = ", TRITONSERVER_DataTypeString(des_datatype),
", shape = ", backend::ShapeToString(input_shape, des_dims_count),
", byte_size = ", des_byte_size,
", buffer_count = ", des_input_buffer_count);
if (instance_state->StateForModel()->DeseNum() != 0 && des_byte_size == 0) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"The DES input in request is empty. The input input size should "
"be an integer multiple(the number of samples) of the "
"\"des_feature_num\" in config.pbtxt."));
}
if (responses[r] == nullptr) {
HCTR_TRITON_LOG(
ERROR, "request ", r,
": failed to read input properties, error response sent");
continue;
}
HCTR_TRITON_LOG(INFO, "\trequested_output ", requested_output_name);
// If the model doesn't support batching with two-dimension tensor then each
// request is necessarily batch-size 1. So the first dimension of the shape
// is the batch size=1.
if (des_dims_count > 0) {
total_batch_size += input_shape[0];
} else {
total_batch_size++;
}
// We only need to produce an output if it was requested.
if (requested_output_count > 0) {
// Hugectr model will handls all the inpput on device and predict the
// result. The output tensor copies the result from GPU to CPU.
//
// 1. Validate input tensor.
//
// 2. Initialize the output tensor.
//
// 3. Copy all input data -> Device Buffer.
//
// 4. Iterate over the input tensor buffers, pass to the HugeCTR predict
// and copy the
// result into the output buffer.
TRITONBACKEND_Response* response = responses[r];
// Step 1. Input should have correct size...
TRITONBACKEND_Output* output;
numofdes = des_byte_size / sizeof(float);
if (instance_state->StateForModel()->SupportLongEmbeddingKey()) {
numofcat = cat_byte_size / sizeof(long long);
} else {
numofcat = cat_byte_size / sizeof(unsigned int);
}
if (instance_state->StateForModel()->DeseNum() != 0 &&
numofdes % instance_state->StateForModel()->DeseNum() != 0) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"The DES input sample size in request is not match with "
"configuration. The input sample size to be an integer "
"multiple of the configuration."));
}
if (numofcat % instance_state->StateForModel()->CatNum() != 0) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"The CATCOLUMN input sample size in request is not match with "
"configuration. The input sample size to be an integer "
"multiple of the configuration."));
}
if (instance_state->StateForModel()->DeseNum() != 0) {
num_of_sample_des =
floor(numofdes / instance_state->StateForModel()->DeseNum());
}
num_of_sample_cat =
floor(numofcat / instance_state->StateForModel()->CatNum());
if (instance_state->StateForModel()->DeseNum() != 0 &&
num_of_sample_des != num_of_sample_cat) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"The input sample size in DES and CATCOLUMN is not match"));
}
num_of_samples = num_of_sample_cat;
if (num_of_samples > instance_state->StateForModel()->BatchSize()) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"The number of Input sample greater than max batch size"));
}
int64_t* out_putshape = &num_of_samples;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_ResponseOutput(
response, &output, requested_output_name, des_datatype,
out_putshape, 1));
if (responses[r] == nullptr) {
HCTR_TRITON_LOG(
ERROR, "request ", r,
": failed to create response output, error response sent");
continue;
}
// Step 2. Initialize the output tensor.
void* output_buffer;
TRITONSERVER_MemoryType output_memory_type = TRITONSERVER_MEMORY_GPU;
int64_t output_memory_type_id = 0;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_OutputBuffer(
output, &output_buffer, num_of_samples * sizeof(float),
&output_memory_type, &output_memory_type_id));
if (responses[r] == nullptr) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"failed to create output buffer in GPU memory"));
HCTR_TRITON_LOG(
ERROR, "request ", r,
": failed to create output buffer in CPU memory, error response "
"sent");
continue;
}
// Step 3. Copy all input data -> Device Buffer.
size_t output_buffer_offset = 0;
for (uint32_t b = 0; b < cat_input_buffer_count; ++b) {
const void* des_buffer = nullptr;
uint64_t buffer_byte_size = des_byte_size;
TRITONSERVER_MemoryType input_memory_type = TRITONSERVER_MEMORY_GPU;
int64_t input_memory_type_id = 0;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_InputBuffer(
des_input, b, &des_buffer, &buffer_byte_size,
&input_memory_type, &input_memory_type_id));
CK_CUDA_THROW_(cudaMemcpy(
instance_state->GetDeseBuffer()->get_raw_ptr(), des_buffer,
des_byte_size, cudaMemcpyHostToDevice));
const void* cat_buffer = nullptr;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_InputBuffer(
catcol_input, b, &cat_buffer, &cat_byte_size,
&input_memory_type, &input_memory_type_id));
if (instance_state->StateForModel()->SupportLongEmbeddingKey()) {
CK_CUDA_THROW_(cudaMemcpy(
instance_state->GetCatColBuffer_int64()->get_raw_ptr(),
cat_buffer, cat_byte_size, cudaMemcpyHostToHost));
} else {
CK_CUDA_THROW_(cudaMemcpy(
instance_state->GetCatColBuffer_int32()->get_raw_ptr(),
cat_buffer, cat_byte_size, cudaMemcpyHostToHost));
}
const void* row_buffer = nullptr;
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONBACKEND_InputBuffer(
row_input, b, &row_buffer, &row_byte_size, &input_memory_type,
&input_memory_type_id));
CK_CUDA_THROW_(cudaMemcpy(
instance_state->GetRowBuffer()->get_raw_ptr(), row_buffer,
row_byte_size, cudaMemcpyHostToDevice));
if (responses[r] == nullptr) {
GUARDED_RESPOND_IF_ERROR(
responses, r,
TRITONSERVER_ErrorNew(
TRITONSERVER_ERROR_UNSUPPORTED,
"failed to get input buffer in GPU memory"));
}
// Step 4. Perform prediction in device and copy result to cpu output
// buffer
HCTR_TRITON_LOG(
INFO, "*****Processing request on device***** ",
instance_state->DeviceId(), " for model ", instance_state->Name());
// Set Timestamp here to compute the prediction execution time for each
// request
SET_TIMESTAMP(exec_start_ns);
min_exec_start_ns = std::min(min_exec_start_ns, exec_start_ns);
// Model prediction
RETURN_IF_ERROR(instance_state->ProcessRequest(num_of_samples));
HCTR_TRITON_LOG(INFO, "******Processing request completed!******");
output_buffer_offset += buffer_byte_size;
CK_CUDA_THROW_(cudaMemcpy(
output_buffer, instance_state->GetPredictBuffer()->get_raw_ptr(),
num_of_samples * sizeof(float), cudaMemcpyDeviceToHost));
uint64_t exec_end_ns = 0;
SET_TIMESTAMP(exec_end_ns);
max_exec_end_ns = std::max(max_exec_end_ns, exec_end_ns);
// Get the prediction execution time (ms)
int64_t exe_time = (max_exec_end_ns - min_exec_start_ns) / 1000000;
HCTR_TRITON_LOG(INFO, "Prediction execution time is ", exe_time, " ms");
}
if (responses[r] == nullptr) {
HCTR_TRITON_LOG(
ERROR, "request ", r,
": failed to get input buffer in CPU memory, error response sent");
continue;
}
}
// Response parameters we attach some here. mak
// NumSample-> Number of samples in current request
// DeviceID-> Current model initialized on device ID
LOG_IF_ERROR(
TRITONBACKEND_ResponseSetIntParameter(
responses[r], "NumSample", num_of_samples),
"failed return Number of samples");
LOG_IF_ERROR(
TRITONBACKEND_ResponseSetIntParameter(
responses[r], "DeviceID", instance_state->DeviceId()),
"failed return device id");
// If we get to this point then there hasn't been any error and
// the response is complete and we can send it. This is the last
// (and only) response that we are sending for the request so we
// must mark it FINAL. If there is an error when sending all we
// can do is log it.
LOG_IF_ERROR(
TRITONBACKEND_ResponseSend(
responses[r], TRITONSERVER_RESPONSE_COMPLETE_FINAL,
nullptr /* success */),
"failed sending response");
uint64_t exec_end_ns = 0;
SET_TIMESTAMP(exec_end_ns);
max_exec_end_ns = std::max(max_exec_end_ns, exec_end_ns);
// Report statistics for the successful request. For an instance
// using the CPU we don't associate any device with the
// statistics, otherwise we associate the instance's device.
LOG_IF_ERROR(
TRITONBACKEND_ModelInstanceReportStatistics(
instance_state->TritonModelInstance(), request, true /* success */,
exec_start_ns, exec_start_ns, exec_end_ns, exec_end_ns),
"failed reporting request statistics");
}
// Done with requests...
// There are two types of statistics that we can report... the
// statistics for the entire batch of requests that we just executed
// and statistics for each individual request. Statistics for each
// individual request were reported above inside the loop as each
// request was processed (or for failed requests we report that
// failure below). Here we report statistics for the entire batch of
// requests.
LOG_IF_ERROR(
TRITONBACKEND_ModelInstanceReportBatchStatistics(
instance_state->TritonModelInstance(), total_batch_size,
min_exec_start_ns, min_exec_start_ns, max_exec_end_ns,
max_exec_end_ns),
"failed reporting batch request statistics");
// We could have released each request as soon as we sent the
// corresponding response. But for clarity we just release them all
// here. Note that is something goes wrong when releasing a request
// all we can do is log it... there is no response left to use to
// report an error.
for (uint32_t r = 0; r < request_count; ++r) {
TRITONBACKEND_Request* request = requests[r];
// Before releasing, record failed requests as those where
// responses[r] is nullptr. The timestamps are ignored in this
// case.
if (responses[r] == nullptr) {
LOG_IF_ERROR(
TRITONBACKEND_ModelInstanceReportStatistics(
instance_state->TritonModelInstance(), request,
false /* success */, 0, 0, 0, 0),
"failed reporting request statistics");
}
LOG_IF_ERROR(
TRITONBACKEND_RequestRelease(request, TRITONSERVER_REQUEST_RELEASE_ALL),
"failed releasing request");
}
return nullptr; // success
}
} // extern "C"
}}} // namespace triton::backend::hugectr
| 37.271371 | 80 | 0.689169 | [
"object",
"shape",
"vector",
"model"
] |
672a610f93d466178b0d570deaf39eb69ecddaa9 | 4,000 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/WpfGfx/common/shared/rgnutils.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 5,937 | 2018-12-04T16:32:50.000Z | 2022-03-31T09:48:37.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/common/shared/rgnutils.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 4,151 | 2018-12-04T16:38:19.000Z | 2022-03-31T18:41:14.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/common/shared/rgnutils.cpp | txlos/wpf | 4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1 | [
"MIT"
] | 1,084 | 2018-12-04T16:24:21.000Z | 2022-03-30T13:52:03.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//---------------------------------------------------------------------------------
//
//
// Module Name:
//
// rgnutils.cpp
//
//---------------------------------------------------------------------------------
#include "precomp.hpp"
MtDefine(MUnwrapRegionData, MILRawMemory, "MUnwrapRegionData");
//+--------------------------------------------------------------------------------
//
// Method:
// HrgnToRgnData
//
// Synposis:
// Extracts the region data from a region handle
//
// Arguments:
// hRgn - GDI region handle
//
// ppRgnData - Returned region data - callers must free this memory
// with WPFFree
// Returns:
// HRESULT indicating success or failure
//
//---------------------------------------------------------------------------------
HRESULT
HrgnToRgnData(
HRGN hrgn,
__deref_out RGNDATA **ppRgnData
)
{
// Get the region's data size, allocate a temporary buffer
HRESULT hr = S_OK;
UINT ccbRegionData;
RGNDATA *pRegionData = NULL;
IFCW32(ccbRegionData = GetRegionData(hrgn, 0, NULL));
pRegionData = WPFAllocType(
RGNDATA *,
ProcessHeap,
Mt(MUnwrapRegionData),
ccbRegionData
);
IFCOOM(pRegionData);
// Retrieve the region data
IFCW32(GetRegionData(hrgn, ccbRegionData, pRegionData));
*ppRgnData = pRegionData;
pRegionData = NULL;
Cleanup:
// Making sure that memory is recollected in case of error
if (pRegionData)
{
WPFFree(ProcessHeap, pRegionData);
}
RRETURN(hr);
}
//+--------------------------------------------------------------------------------
//
// Method:
// HrgnFromRects
//
// Synposis:
// Constructs region from the list of rectangles
//
// Arguments:
// pRects - ponter to the array of rects
//
// nCount - number of elements in pRects
//
// phrgn - Returned region
//
// Returns:
// HRESULT indicating success or failure
//
//---------------------------------------------------------------------------------
HRESULT
HrgnFromRects(
__in_ecount(nCount) const RECT *pRects,
UINT nCount,
__deref_out_ecount(1) HRGN *phrgn
)
{
HRESULT hr = S_OK;
HRGN hrgn = NULL;
UINT ccbRects = 0;
UINT ccbRegionData = 0;
RGNDATA *pRegionData = NULL;
RECT rcBound = {0};
// Calculate region data size and allocate buffer
IFC(UIntMult(nCount, sizeof(RECT), &ccbRects));
IFC(UIntAdd(ccbRects, sizeof(RGNDATA), &ccbRegionData));
pRegionData = WPFAllocType(
RGNDATA *,
ProcessHeap,
Mt(MUnwrapRegionData),
ccbRegionData
);
IFCOOM(pRegionData);
// Calculate bounding rect
if (nCount > 0)
{
rcBound = pRects[0];
for (UINT nRect = 1; nRect < nCount; nRect++)
{
if (pRects[nRect].left < rcBound.left) rcBound.left = pRects[nRect].left;
if (pRects[nRect].top < rcBound.top) rcBound.top = pRects[nRect].top;
if (pRects[nRect].right > rcBound.right) rcBound.right = pRects[nRect].right;
if (pRects[nRect].bottom > rcBound.bottom) rcBound.bottom = pRects[nRect].bottom;
}
}
// Poulate region data header
pRegionData->rdh.dwSize = sizeof(RGNDATAHEADER);
pRegionData->rdh.iType = RDH_RECTANGLES;
pRegionData->rdh.nCount = nCount;
pRegionData->rdh.nRgnSize = ccbRects;
pRegionData->rdh.rcBound = rcBound;
// Copy rectangles data
RtlCopyMemory(pRegionData->Buffer, pRects, ccbRects);
// Create region object
IFCW32(hrgn = ExtCreateRegion(NULL, ccbRegionData, pRegionData));
*phrgn = hrgn;
Cleanup:
if (pRegionData)
{
WPFFree(ProcessHeap, pRegionData);
}
RRETURN(hr);
}
| 24.84472 | 93 | 0.548 | [
"object"
] |
6734a1dca6c66b08da6ca074bd3dde98d9e5c3d3 | 1,262 | cpp | C++ | src/Texture.cpp | juliosueiras/astriod | 40b7d1b0ee4604bf85fa8795b4a5b65d032a9e55 | [
"MIT"
] | null | null | null | src/Texture.cpp | juliosueiras/astriod | 40b7d1b0ee4604bf85fa8795b4a5b65d032a9e55 | [
"MIT"
] | 7 | 2016-04-19T19:44:19.000Z | 2016-04-25T02:56:24.000Z | src/Texture.cpp | juliosueiras/asteroid | 40b7d1b0ee4604bf85fa8795b4a5b65d032a9e55 | [
"MIT"
] | null | null | null | #include <iostream>
#include <SDL_image.h>
#include "Texture.h"
Texture::Texture(SDL_Texture* tex, int width, int height)
: mSDLTex(tex)
, mWidth(width)
, mHeight(height)
{ }
Texture::~Texture()
{
if (mSDLTex) {
SDL_DestroyTexture(mSDLTex);
}
}
Texture* Texture::Load(const std::string& path, SDL_Renderer* renderer)
{
// load an image into an SDL_Surface (stored in RAM)
SDL_Surface* surf = IMG_Load(path.c_str());
if (!surf) {
std::cerr << "*** Failed to load image: " << IMG_GetError() << std::endl;
return NULL;
}
// create an SDL_Texture from the surface (stored in GPU DRAM)
SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf);
// free the surface, which is no longer needed
SDL_FreeSurface(surf);
if (tex) {
// query texture size
int width, height;
SDL_QueryTexture(tex, NULL, NULL, &width, &height);
// return a dynamically allocated Texture object
return new Texture(tex, width, height);
} else {
// texture creation failed
std::cerr << "*** Failed to create texture: " << SDL_GetError() << std::endl;
return NULL;
}
}
void Texture::Destroy(Texture* tex)
{
delete tex;
}
| 22.140351 | 85 | 0.616482 | [
"object"
] |
673d9d6d46449b8c7a514377e34b597f5eeab8de | 5,060 | hpp | C++ | third-party/casadi/casadi/solvers/linear_interpolant.hpp | dbdxnuliba/mit-biomimetics_Cheetah | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 8 | 2020-02-18T09:07:48.000Z | 2021-12-25T05:40:02.000Z | third-party/casadi/casadi/solvers/linear_interpolant.hpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | null | null | null | third-party/casadi/casadi/solvers/linear_interpolant.hpp | geekfeiw/Cheetah-Software | f3b0c0f6a3835d33b7f2f345f00640b3fc256388 | [
"MIT"
] | 13 | 2019-08-25T12:32:06.000Z | 2022-03-31T02:38:12.000Z | /*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* CasADi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef CASADI_LINEAR_INTERPOLANT_HPP
#define CASADI_LINEAR_INTERPOLANT_HPP
#include "casadi/core/interpolant_impl.hpp"
#include <casadi/solvers/casadi_interpolant_linear_export.h>
/** \defgroup plugin_Interpolant_linear
*/
/** \pluginsection{Interpolant,linear} */
/// \cond INTERNAL
namespace casadi {
/** \brief \pluginbrief{Interpolant,linear}
Implements a multilinear interpolant: For 1D, the interpolating polynomial
will be linear. For 2D, the interpolating polynomial will be bilinear, etc.
@copydoc Interpolant_doc
@copydoc plugin_Interpolant_linear
\author Joel Andersson
\date 2016
*/
class CASADI_INTERPOLANT_LINEAR_EXPORT LinearInterpolant : public Interpolant {
public:
// Constructor
LinearInterpolant(const std::string& name,
const std::vector<double>& grid,
const std::vector<casadi_int>& offset,
const std::vector<double>& values,
casadi_int m);
// Destructor
~LinearInterpolant() override;
// Get name of the plugin
const char* plugin_name() const override { return "linear";}
// Name of the class
std::string class_name() const override { return "LinearInterpolant";}
/** \brief Create a new Interpolant */
static Interpolant* creator(const std::string& name,
const std::vector<double>& grid,
const std::vector<casadi_int>& offset,
const std::vector<double>& values,
casadi_int m) {
return new LinearInterpolant(name, grid, offset, values, m);
}
// Initialize
void init(const Dict& opts) override;
/// Evaluate numerically
int eval(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const override;
///@{
/** \brief Full Jacobian */
bool has_jacobian() const override { return true;}
Function get_jacobian(const std::string& name,
const std::vector<std::string>& inames,
const std::vector<std::string>& onames,
const Dict& opts) const override;
///@}
/** \brief Is codegen supported? */
bool has_codegen() const override { return true;}
/** \brief Generate code for the body of the C function */
void codegen_body(CodeGenerator& g) const override;
/// A documentation string
static const std::string meta_doc;
///@{
/** \brief Options */
static Options options_;
const Options& get_options() const override { return options_;}
///@}
std::vector<casadi_int> lookup_mode_;
};
/** First order derivatives */
class CASADI_INTERPOLANT_LINEAR_EXPORT LinearInterpolantJac : public FunctionInternal {
public:
/// Constructor
LinearInterpolantJac(const std::string& name) : FunctionInternal(name) {}
/// Destructor
~LinearInterpolantJac() override {}
/** \brief Get type name */
std::string class_name() const override { return "LinearInterpolantJac";}
/** \brief Is codegen supported? */
bool has_codegen() const override { return true;}
/** \brief Generate code for the body of the C function */
void codegen_body(CodeGenerator& g) const override;
// Initialize
void init(const Dict& opts) override;
/// Evaluate numerically
int eval(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const override;
///@{
/** \brief Full Jacobian */
bool has_jacobian() const override { return true;}
Function get_jacobian(const std::string& name,
const std::vector<std::string>& inames,
const std::vector<std::string>& onames,
const Dict& opts) const override;
///@}
};
} // namespace casadi
/// \endcond
#endif // CASADI_LINEAR_INTERPOLANT_HPP
| 34.189189 | 100 | 0.631818 | [
"vector"
] |
674a8b096c76c82cd2b0d572a47b320744ea7381 | 4,611 | cpp | C++ | user/drivers/filesystem/src/fs/test/SectorTest.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | 4 | 2021-06-22T20:52:30.000Z | 2022-02-04T00:19:44.000Z | user/drivers/filesystem/src/fs/test/SectorTest.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | user/drivers/filesystem/src/fs/test/SectorTest.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | #include "SectorTest.h"
#include "Log.h"
#include "fs/Filesystem.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
/**
* Checks if we can attach to the given partition. We'll verify if the GUID is one that matches and
* if so create the filesystem object.
*/
bool SectorTestFs::TryStart(const PartitionTable::Guid &id, const PartitionTable::Partition &partition,
const std::shared_ptr<DriverSupport::disk::Disk> &disk, std::shared_ptr<Filesystem> &outFs,
int &outErr) {
// verify ID
if(id != kTypeId) return false;
// allocate FS
outErr = SectorTestFs::Alloc(partition.startLba, partition.size, disk, outFs);
return true;
}
/**
* Attempt to allocate the sector testing fs.
*/
int SectorTestFs::Alloc(const uint64_t start, const size_t length,
const std::shared_ptr<DriverSupport::disk::Disk> &disk,
std::shared_ptr<Filesystem> &out) {
std::shared_ptr<SectorTestFs> ptr(new SectorTestFs(start, length, disk));
if(!ptr->status) {
out = ptr;
}
return ptr->status;
}
/**
* Sets up the sector test fs.
*/
SectorTestFs::SectorTestFs(const uint64_t start, const size_t length,
const std::shared_ptr<DriverSupport::disk::Disk> &disk) : Filesystem(disk),
startLba(start), numSectors(length){
// start the test thread
this->worker = std::make_unique<std::thread>(&SectorTestFs::workerMain, this);
}
/**
* Shut down the worker boi. Setting the run flag to false is enough since it's sitting in an
* infinite loop doing IO, and it'll check that flag when the IO completes.
*/
SectorTestFs::~SectorTestFs() {
this->run = false;
this->worker->join();
}
/**
* Run loop for the driver tester.
*
* This will select random sectors to read from the disk (including random lengths) and verify that
* they were read correctly. This requires that the entire partition is filled with sequentially
* incrementing 4-byte integers in the native CPU byte order.
*/
void SectorTestFs::workerMain() {
int err;
// configurations
constexpr static const size_t kMaxSectors{16};
constexpr static const uint32_t kMaxSleepInterval{33}; // msec
constexpr static const size_t kPrintInterval{50};
// set up
std::vector<std::byte> data;
Success("%s starting", __PRETTY_FUNCTION__);
// enter run loop
size_t loops{0};
while(this->run) {
data.clear();
// generate a random sector and length pair
const uint64_t sector = arc4random_uniform(this->numSectors) + this->startLba;
const uint64_t sectorsLeft = this->numSectors - sector;
const auto numSectors = std::min(sectorsLeft,
static_cast<uint64_t>(arc4random_uniform(kMaxSectors)+1));
// perform the read
err = this->disk->Read(sector, numSectors, data);
//Trace("Read from %7lu (%2lu) returned %d", sector, numSectors, err);
if(err) {
Abort("Read from %7lu (%2lu sectors) failed: %d (round %lu)", sector, numSectors, err,
loops);
}
// validate it
const auto numWords = (numSectors * this->disk->getSectorSize()) / sizeof(uint32_t);
const uint32_t startVal = ((sector - this->startLba) * this->disk->getSectorSize()) / sizeof(uint32_t);
if(data.size() < (numWords * sizeof(uint32_t))) {
Abort("Insufficient data read: got %lu bytes, need %lu", data.size(),
(numWords * sizeof(uint32_t)));
}
const auto ptr = reinterpret_cast<const uint32_t *>(data.data());
for(size_t i = 0; i < numWords; i++) {
const uint32_t expected = startVal + i;
const auto actual = ptr[i];
if(expected != actual) {
uint32_t prev{0}, next{0};
if(i) {
prev = ptr[i-1];
}
if(i != (numWords - 1)) {
next = ptr[i+1];
}
Abort("Mismatch at word %lu ($%05x): read $%08x, expected $%08x "
"prev $%08x, next $%08x "
"(disk read from sector %lu, %lu sectors)", i, i*sizeof(uint32_t),
actual, expected, prev, next, sector, numSectors);
}
}
loops++;
if(!(loops % kPrintInterval)) {
Trace("%s loop %lu", __PRETTY_FUNCTION__, loops);
}
if(kMaxSleepInterval) {
ThreadUsleep(1000 * (arc4random_uniform(kMaxSleepInterval)+1));
}
}
// clean up
Success("%s exiting", __PRETTY_FUNCTION__);
}
| 32.935714 | 111 | 0.607027 | [
"object",
"vector"
] |
67544c34e911208660996d92aeb3c44f12f9478d | 16,288 | cpp | C++ | Source/AllProjects/CQLogicSrv/Shared/CQLogicSh_ElapsedTmFld.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CQLogicSrv/Shared/CQLogicSh_ElapsedTmFld.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CQLogicSrv/Shared/CQLogicSh_ElapsedTmFld.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQLogicSh_ElapsedTmFld.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 04/14/2013
//
// 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 a virtual field derivative that creates a boolean
// result from one or more source fields, by evaluting their values, and
// tracks how long that result has been true.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQLogicSh_.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
AdvRTTIDecls(TCQSLLDElapsedTm,TCQLSrvFldType);
// ---------------------------------------------------------------------------
// Local types and constants
// ---------------------------------------------------------------------------
namespace
{
namespace CQLogicSh_ElapsedTm
{
// -----------------------------------------------------------------------
// Our persistent format
// -----------------------------------------------------------------------
constexpr tCIDLib::TCard1 c1FmtVersion = 1;
}
}
// ---------------------------------------------------------------------------
// CLASS: TCQSLLDElapsedTm
// PREFIX: clsft
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TCQSLLDElapsedTm: Constructors and Destructor
// ---------------------------------------------------------------------------
//
// When we call the parent, indicate we are a normal field and want to be
// called to evaluate our value regularly, not just when our source fields
// change, since we have to count elapsed time.
//
TCQSLLDElapsedTm::TCQSLLDElapsedTm(const TString& strName) :
TCQLSrvFldType
(
strName
, tCQCKit::EFldTypes::Time
, tCQCKit::EFldAccess::Read
, kCIDLib::True
, kCIDLib::True
)
, m_bAutoReset(kCIDLib::True)
, m_bPrevState(kCIDLib::False)
, m_eLogOp(tCQCKit::ELogOps::AND)
, m_enctElapsed(0)
, m_enctLast(0)
{
}
TCQSLLDElapsedTm::TCQSLLDElapsedTm(const TCQSLLDElapsedTm& clsftSrc) :
TCQLSrvFldType(clsftSrc)
, m_bAutoReset(clsftSrc.m_bAutoReset)
, m_bPrevState(clsftSrc.m_bPrevState)
, m_eLogOp(clsftSrc.m_eLogOp)
, m_colExprList(clsftSrc.m_colExprList)
, m_enctElapsed(clsftSrc.m_enctElapsed)
, m_enctLast(clsftSrc.m_enctLast)
{
}
TCQSLLDElapsedTm::~TCQSLLDElapsedTm()
{
}
// ---------------------------------------------------------------------------
// TCQSLLDElapsedTm: Public oeprators
// ---------------------------------------------------------------------------
TCQSLLDElapsedTm&
TCQSLLDElapsedTm::operator=(const TCQSLLDElapsedTm& clsftSrc)
{
if (this != &clsftSrc)
{
TParent::operator=(clsftSrc);
m_bAutoReset = clsftSrc.m_bAutoReset;
m_bPrevState = clsftSrc.m_bPrevState;
m_eLogOp = clsftSrc.m_eLogOp;
m_colExprList = clsftSrc.m_colExprList;
m_enctElapsed = clsftSrc.m_enctElapsed;
m_enctLast = clsftSrc.m_enctLast;
}
return *this;
}
// ---------------------------------------------------------------------------
// TCQSLLDElapsedTm: Public, inherited methods
// ---------------------------------------------------------------------------
// We override in order to keep our expression list in sync with source fields
tCIDLib::TBoolean TCQSLLDElapsedTm::bAddField(const TString& strToAdd)
{
//
// Call our parent first. If he adds it, then we add an expression. We just set it
// to statement type for the initial value.
//
if (TParent::bAddField(strToAdd))
{
m_colExprList.objPlace
(
L"Time Test"
, tCQCKit::EExprTypes::Statement
, tCQCKit::EStatements::IsGThan
, TString(L"0")
, kCIDLib::False
);
return kCIDLib::True;
}
return kCIDLib::False;
}
// See if we are equal to the passed one
tCIDLib::TBoolean
TCQSLLDElapsedTm::bIsEqual(const TCQLSrvFldType& clsftRHS) const
{
if (!TParent::bIsEqual(clsftRHS))
return kCIDLib::False;
// Make sure it's of our type or beyond
CIDAssert
(
clsftRHS.bIsDescendantOf(clsThis())
, L"The RHS logic server field is not the same type as this field"
);
const TCQSLLDElapsedTm& clsftAct = static_cast<const TCQSLLDElapsedTm&>(clsftRHS);
// Compare the logical op
if (m_eLogOp != clsftAct.m_eLogOp)
return kCIDLib::False;
// That's ok, so compare the expressions. If not the same count, then not
const tCIDLib::TCard4 c4Count = m_colExprList.c4ElemCount();
if (c4Count != clsftAct.m_colExprList.c4ElemCount())
return kCIDLib::False;
// See if they are both the same auto/manual reset mode
if (m_bAutoReset != clsftAct.m_bAutoReset)
return kCIDLib::False;
// They are both the same size lists, so compare them
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
if (m_colExprList[c4Index] != clsftAct.m_colExprList[c4Index])
return kCIDLib::False;
}
return kCIDLib::True;
}
tCIDLib::TBoolean TCQSLLDElapsedTm::bIsValidSrcFld(const TCQCFldDef& flddToCheck) const
{
// We can do any type
return kCIDLib::True;
}
// We override in order to keep our expression list in sync with source fields
tCIDLib::TBoolean
TCQSLLDElapsedTm::bMoveField(const tCIDLib::TCard4 c4At
, const tCIDLib::TBoolean bUp)
{
//
// Call our parent first. If he moves it, then we move the same. WE don't
// have to verify the index, since he already proved it's ok.
//
if (TParent::bMoveField(c4At, bUp))
{
if (bUp)
m_colExprList.SwapItems(c4At, c4At - 1);
else
m_colExprList.SwapItems(c4At, c4At + 1);
return kCIDLib::True;
}
return kCIDLib::False;
}
tCIDLib::TBoolean
TCQSLLDElapsedTm::bValidate( TString& strErr
, tCIDLib::TCard4& c4SrcFldInd
, const TCQCFldCache& cfcData)
{
if (!TParent::bValidate(strErr, c4SrcFldInd, cfcData))
return kCIDLib::False;
// Validate all of the expressions
TString strField;
TString strMoniker;
const tCIDLib::TCard4 c4Count = m_colExprList.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
TCQCExpression& exprCur = m_colExprList[c4Index];
// Look up this source field
facCQCKit().bParseFldName(strSrcFldAt(c4Index), strMoniker, strField);
const TCQCFldDef& flddSrc = cfcData.flddFor
(
strMoniker, strField
);
if (!exprCur.bValidate(strErr, flddSrc.eType()))
{
c4SrcFldInd = c4Index;
return kCIDLib::False;
}
}
// No source field error so set it to max card
c4SrcFldInd = kCIDLib::c4MaxCard;
return kCIDLib::True;
}
tCIDLib::TVoid TCQSLLDElapsedTm::Initialize(TCQCFldCache& cfcInit)
{
// Call our parent first
TParent::Initialize(cfcInit);
m_bPrevState = kCIDLib::False;
m_enctElapsed = 0;
m_enctLast = TTime::enctNow();
}
// We override in order to keep our expression list in sync with source fields
tCIDLib::TVoid TCQSLLDElapsedTm::RemoveField(const tCIDLib::TCard4 c4At)
{
// Call our parent first. He'll validate the index
TParent::RemoveField(c4At);
m_colExprList.RemoveAt(c4At);
}
// ---------------------------------------------------------------------------
// TCQSLLDElapsedTm: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TCQSLLDElapsedTm::bAutoReset() const
{
return m_bAutoReset;
}
tCIDLib::TBoolean
TCQSLLDElapsedTm::bAutoReset(const tCIDLib::TBoolean bToSet)
{
m_bAutoReset = bToSet;
return m_bAutoReset;
}
// Set the negated flag on the indicated expression
tCIDLib::TBoolean
TCQSLLDElapsedTm::bNegatedAt(const tCIDLib::TCard4 c4At) const
{
return m_colExprList[c4At].bNegated();
}
// Get/set our logical operator
tCQCKit::ELogOps TCQSLLDElapsedTm::eLogOp() const
{
return m_eLogOp;
}
tCQCKit::ELogOps TCQSLLDElapsedTm::eLogOp(const tCQCKit::ELogOps eToSet)
{
m_eLogOp = eToSet;
return m_eLogOp;
}
// Provide access to our expressions for the client side driver
const TCQCExpression&
TCQSLLDElapsedTm::exprAt(const tCIDLib::TCard4 c4At) const
{
return m_colExprList[c4At];
}
TCQCExpression& TCQSLLDElapsedTm::exprAt(const tCIDLib::TCard4 c4At)
{
return m_colExprList[c4At];
}
//
// Reset our elapsed time. Also update the last stored time, so that if
// we are going to start counting again, that we start from this reset
// time.
//
tCIDLib::TVoid TCQSLLDElapsedTm::ResetTime()
{
m_enctElapsed = 0;
m_enctLast = TTime::enctNow();
}
tCIDLib::TVoid
TCQSLLDElapsedTm::SetExpressionAt(const tCIDLib::TCard4 c4At
, const TCQCExpression& exprToSet)
{
m_colExprList[c4At] = exprToSet;
}
// Set the negated flag on a given expression
tCIDLib::TVoid
TCQSLLDElapsedTm::SetNegatedAt( const tCIDLib::TCard4 c4At
, const tCIDLib::TBoolean bToSet)
{
m_colExprList[c4At].bNegated(bToSet);
}
// ---------------------------------------------------------------------------
// TCQSLLDElapsedTm: Hidden Construtors
// ---------------------------------------------------------------------------
//
// This is supported only for polymorphic streaming purposes. When we call
// the parent, indicate we are a normal field and want to be called to
// evaluate our value regularly, not just when our source fields change.
//
TCQSLLDElapsedTm::TCQSLLDElapsedTm() :
TCQLSrvFldType(kCIDLib::True, kCIDLib::True)
, m_bAutoReset(kCIDLib::True)
, m_bPrevState(kCIDLib::False)
, m_eLogOp(tCQCKit::ELogOps::AND)
, m_enctElapsed(0)
, m_enctLast(0)
{
}
// ---------------------------------------------------------------------------
// TCQSLLDElapsedTm: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TCQSLLDElapsedTm::StreamFrom(TBinInStream& strmToReadFrom)
{
// Our stuff should start with a start object marker
strmToReadFrom.CheckForStartMarker(CID_FILE, CID_LINE);
// Check the format version
tCIDLib::TCard1 c1FmtVersion;
strmToReadFrom >> c1FmtVersion;
if (!c1FmtVersion || (c1FmtVersion > CQLogicSh_ElapsedTm::c1FmtVersion))
{
facCIDLib().ThrowErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcGen_UnknownFmtVersion
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Format
, TCardinal(c1FmtVersion)
, clsThis()
);
}
// Do our parent's stuff
TParent::StreamFrom(strmToReadFrom);
// Stream our stuff
strmToReadFrom >> m_bAutoReset
>> m_colExprList
>> m_eLogOp;
// It should end with an end object marker
strmToReadFrom.CheckForEndMarker(CID_FILE, CID_LINE);
// Reset runtime stuff
m_bPrevState = kCIDLib::False;
m_enctLast = TTime::enctNow();
m_enctElapsed = 0;
}
tCIDLib::TVoid TCQSLLDElapsedTm::StreamTo(TBinOutStream& strmToWriteTo) const
{
strmToWriteTo << tCIDLib::EStreamMarkers::StartObject
<< CQLogicSh_ElapsedTm::c1FmtVersion;
// Do our parent's stuff
TParent::StreamTo(strmToWriteTo);
// Stream our stuff and the end marker
strmToWriteTo << m_bAutoReset
<< m_colExprList
<< m_eLogOp
<< tCIDLib::EStreamMarkers::EndObject;
}
// ---------------------------------------------------------------------------
// TCQSLLDElapsedTm: Protected, inherited methods
// ---------------------------------------------------------------------------
//
// We just run through each of our source fields and evaluate each one and
// build up the resulting status. Based on that we update the elapsed time
// and that's what we give back.
//
tCQLogicSh::EEvalRes
TCQSLLDElapsedTm::eBuildValue( const tCQLogicSh::TInfoList& colVals
, TCQCFldValue& fldvToFill
, const tCIDLib::TCard4
, const tCIDLib::TCard4 )
{
//
// We need to start with the correct initial value for the logical
// operator. For AND, we start with true and any false result will
// fail it, else we end up with the true. For the others we start with
// false. For OR any true result makes it go true, else we end up with
// false.
//
// For XOR we use it to remember if we've seen a previous success. If
// none of them comes out true, then we end up with the desired false.
// When we see a true we set it to true. If we see another true, we
// set it back to false and break out. Otherwise, we'll end up at the
// with the true result because only one was true.
//
tCIDLib::TBoolean bRes;
if (m_eLogOp == tCQCKit::ELogOps::AND)
bRes = kCIDLib::True;
else
bRes = kCIDLib::False;
const tCIDLib::TCard4 c4Count = m_colExprList.c4ElemCount();
CIDAssert
(
c4Count == colVals.c4ElemCount()
, L"Expr and src fld count are inconsistent"
);
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
// Evaluate the expr for this source field, passing it the field value
TCQCExpression& exprCur = m_colExprList[c4Index];
if (exprCur.bEvaluate(colVals[c4Index].fvCurrent(), 0))
{
if (m_eLogOp == tCQCKit::ELogOps::XOR)
{
// If we had any previous true, then we can take false now
if (bRes)
{
bRes = kCIDLib::False;
break;
}
// Remember we had a previous success
bRes = kCIDLib::True;
}
else if (m_eLogOp == tCQCKit::ELogOps::OR)
{
// If anything is true, then an OR will be true
bRes = kCIDLib::True;
break;
}
}
else
{
if (m_eLogOp == tCQCKit::ELogOps::AND)
{
// Any failure means an AND fails
bRes = kCIDLib::False;
break;
}
}
}
const tCIDLib::TEncodedTime enctNow = TTime::enctNow();
if (bRes)
{
if (m_bPrevState)
{
//
// We were already in true state, so just accumulate the
// time since last time.
//
m_enctElapsed += enctNow - m_enctLast;
}
else
{
//
// We are transitioning. If auto-reset, then reset it. Else,
// we just will pick up with the value we already have.
//
if (m_bAutoReset)
m_enctElapsed = 0;
}
}
else
{
//
// We've gone false, so reset if auto-reset. Else, we leave the
// current value there.
//
if (m_bAutoReset)
m_enctElapsed = 0;
}
// Reset the last time and store the new last state
m_bPrevState = bRes;
m_enctLast = enctNow;
// Store the result in the provided value
if (static_cast<TCQCTimeFldValue&>(fldvToFill).bSetValue(m_enctElapsed))
return tCQLogicSh::EEvalRes::NewValue;
return tCQLogicSh::EEvalRes::NoChange;
}
| 29.294964 | 87 | 0.555071 | [
"object"
] |
6759892ad8c85c4566e0354035db298944747def | 10,768 | cpp | C++ | src/particle_filter.cpp | mo7mmed77/Kidnapped_Vehicle_project | 7fd10e062e3e0734eed0672f0abbcd4d18af6a48 | [
"MIT"
] | null | null | null | src/particle_filter.cpp | mo7mmed77/Kidnapped_Vehicle_project | 7fd10e062e3e0734eed0672f0abbcd4d18af6a48 | [
"MIT"
] | null | null | null | src/particle_filter.cpp | mo7mmed77/Kidnapped_Vehicle_project | 7fd10e062e3e0734eed0672f0abbcd4d18af6a48 | [
"MIT"
] | null | null | null | /**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
using std::string;
using std::vector;
using std::normal_distribution;
using std::numeric_limits;
using std::uniform_int_distribution;
using std::uniform_real_distribution;
using std::ostream_iterator;
using std::stringstream;
std::default_random_engine gen;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
if(is_initialized){
return;
}
num_particles = 50; // TODO: Set the number of particles
// Set the Standard deviations of position and heading
double std_x = std[0];
double std_y = std[1];
double std_theta = std[2];
// set initial position and heading with normal distributions
normal_distribution<double> dist_x(x, std_x);
normal_distribution<double> dist_y(y, std_y);
normal_distribution<double> dist_theta(theta, std_theta);
//initialize all particiles
for (int i = 0; i < num_particles; ++i) {
Particle particle;
particle.x=dist_x(gen);
particle.y=dist_y(gen);
particle.theta=dist_theta(gen);
particle.weight=1;
particles.push_back(particle);
}
is_initialized=true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
// standard deviations
double std_x=std_pos[0];
double std_y=std_pos[1];
double std_theta=std_pos[2];
// for normal distribuation we have
normal_distribution<double> dist_x(0, std_x);
normal_distribution<double> dist_y(0, std_y);
normal_distribution<double> dist_theta(0, std_theta);
// update particles locations
for (int i = 0; i < num_particles; ++i) {
double theta = particles[i].theta;
// I added a small number to the yaw rate to avoid dividing by zero
particles[i].x += velocity / (yaw_rate+0.000001) * (sin(theta + yaw_rate * delta_t) - sin(theta)) + dist_x(gen);
particles[i].y += velocity / (yaw_rate+0.000001) * (cos(theta) - cos(theta + yaw_rate * delta_t)) +dist_y(gen);
particles[i].theta += yaw_rate * delta_t + dist_theta(gen);
}
}
void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted,
vector<LandmarkObs>& observations) {
/**
* TODO: Find the predicted measurement that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
//storing the number of predicitions and observations
unsigned int nPredictions = predicted.size();
unsigned int nObservations = observations.size();
for (unsigned int i=0;i<nObservations;i++){
// the min distance is init as a large number
double Dist_min=numeric_limits<double>::max();
int mapId=-1;
for (unsigned j=0; j<nPredictions;j++){
double xDist = observations[i].x - predicted[j].x;
double yDist = observations[i].y - predicted[j].y;
// find the total distance
double distance = sqrt(xDist * xDist + yDist * yDist);
if(distance <Dist_min){
Dist_min=distance;
mapId=predicted[j].id;
}
}
observations[i].id=mapId;
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
// Standard deviations of landmark positions
double stdLandmarkX = std_landmark[0];
double stdLandmarkY = std_landmark[1];
// for each particle we check closest landmarks and update weights
for (int i = 0; i < num_particles; i++) {
double x = particles[i].x;
double y = particles[i].y;
double theta = particles[i].theta;
// landmarks in the particles' sensor range
vector<LandmarkObs> inRangeLandmarks;
double sensor_range2 = sensor_range * sensor_range;
for (unsigned int j = 0; j < map_landmarks.landmark_list.size(); j++) {
float landmarkX = map_landmarks.landmark_list[j].x_f;
float landmarkY = map_landmarks.landmark_list[j].y_f;
int id = map_landmarks.landmark_list[j].id_i;
double dX = x - landmarkX;
double dY = y - landmarkY;
if ( dX*dX + dY*dY <= sensor_range2 ) {
inRangeLandmarks.push_back(LandmarkObs{ id, landmarkX, landmarkY });
}
// Observation coordinates transformation from particle coordinate to map coordinates
vector<LandmarkObs> Observations_in_map;
for (unsigned int j = 0; j < observations.size(); j++) {
double mappedX = cos(theta)*observations[j].x - sin(theta)*observations[j].y + x;
double mappedY = sin(theta)*observations[j].x + cos(theta)*observations[j].y + y;
//Recording the new transformed position
Observations_in_map.push_back(LandmarkObs{ observations[j].id, mappedX, mappedY });
}
// indext Update for the nearest landmark
dataAssociation(inRangeLandmarks, Observations_in_map);
// Weights reset
particles[i].weight = 1.0;
// Calculating weights for each mapped observation
for (unsigned int j = 0; j < Observations_in_map.size(); j++) {
double observationX = Observations_in_map[j].x;
double observationY = Observations_in_map[j].y;
// get x,y of the nearest landmark
int landmarkId = Observations_in_map[j].id;
double landmarkX, landmarkY;
unsigned int k = 0;
unsigned int nLandmarks = inRangeLandmarks.size();
bool found = false;
while (!found && k < nLandmarks) {
if (inRangeLandmarks[k].id == landmarkId) {
found = true;
landmarkX = inRangeLandmarks[k].x;
landmarkY = inRangeLandmarks[k].y;
}
k++;
}
// Calculating weight.
double dX = observationX - landmarkX;
double dY = observationY - landmarkY;
// Multivariate-Gaussian Probability
double weight = (1/(2*M_PI*stdLandmarkX*stdLandmarkY)) * exp(-(dX*dX/(2*stdLandmarkX*stdLandmarkX) + (dY*dY/(2*stdLandmarkY*stdLandmarkY))));
if (weight == 0) {
// avoid weight of zero
particles[i].weight *= 0.0001;
} else {
particles[i].weight *= weight;
}
}
}
}}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
// initial index is retrieved by random.
uniform_int_distribution<int> distInt(0, num_particles - 1);
int index = distInt(gen);
double beta = 0.0;
// Getting the weights max.
vector<double> weights;
double maxWeight = numeric_limits<double>::min();
for (int i = 0; i < num_particles; i++) {
weights.push_back(particles[i].weight);
if (particles[i].weight > maxWeight) {
maxWeight = particles[i].weight;
}
}
// Creating uniform real distributions
uniform_real_distribution<double> distDouble(0.0, maxWeight);
// Finding the Resampled Particles
vector<Particle> resampledParticles;
for (int i = 0; i < num_particles; i++) {
beta += distDouble(gen) * 2.0;
while (beta > weights[index]) {
beta -= weights[index];
index = (index + 1) % num_particles;
}
resampledParticles.push_back(particles[index]);
}
particles = resampledParticles;
}
void ParticleFilter::SetAssociations(Particle& particle,
const vector<int>& associations,
const vector<double>& sense_x,
const vector<double>& sense_y) {
// particle: the particle to which assign each listed association,
// and association's (x,y) world coordinates mapping
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
} | 33.234568 | 147 | 0.669484 | [
"vector",
"transform"
] |
675d7d84817da2aa4f19ad6e64212aa7f367576a | 6,999 | cpp | C++ | src/Vector.cpp | GiudGiud/OpenMOC | 83623ebe64b558d45fa021132f812d425774673f | [
"MIT"
] | null | null | null | src/Vector.cpp | GiudGiud/OpenMOC | 83623ebe64b558d45fa021132f812d425774673f | [
"MIT"
] | 1 | 2018-06-26T19:51:58.000Z | 2018-06-26T19:51:58.000Z | src/Vector.cpp | GiudGiud/OpenMOC | 83623ebe64b558d45fa021132f812d425774673f | [
"MIT"
] | null | null | null | #include "Vector.h"
/**
* @brief Constructor initializes Vector object as a floating point array
* and sets the vector dimensions.
* @detail The vector is ordered by cell (as opposed to by group) on the
* outside to be consistent with the Matrix object. Locks are used to
* make the vector object thread-safe against concurrent writes the
* same value. One lock locks out multiple rows of
* the vector at a time representing multiple groups in the same cell.
* @param num_x The number of cells in the x direction.
* @param num_y The number of cells in the y direction.
* @param num_groups The number of energy groups in each cell.
*/
Vector::Vector(int num_x, int num_y, int num_groups) {
setNumX(num_x);
setNumY(num_y);
setNumGroups(num_groups);
_num_rows = _num_x*_num_y*_num_groups;
/* Initialize array and set all to 0.0 */
_array = new FP_PRECISION[_num_rows];
setAll(0.0);
/* Allocate memory for OpenMP locks for each Vector cell */
_cell_locks = new omp_lock_t[_num_x*_num_y];
/* Loop over all Vector cells to initialize OpenMP locks */
#pragma omp parallel for schedule(guided)
for (int r=0; r < _num_x*_num_y; r++)
omp_init_lock(&_cell_locks[r]);
}
/**
* @brief Destructor deletes the arrays used to represent the vector.
*/
Vector::~Vector() {
if (_array != NULL)
delete [] _array;
if (_cell_locks != NULL)
delete [] _cell_locks;
}
/**
* @brief Increment a value in the vector.
* @detail This method takes a cell and group and floating
* point value. The cell and group are used to compute the
* row and column in the vector. If a value exists for the row,
* the value is incremented by val; otherwise, it is set to val.
* @param cell The cell location.
* @param group The group location.
* @param val The value used to increment the row location.
*/
void Vector::incrementValue(int cell, int group, FP_PRECISION val) {
if (cell >= _num_x*_num_y || cell < 0)
log_printf(ERROR, "Unable to increment Vector value for cell %d"
" which is not between 0 and %d", cell, _num_x*_num_y-1);
else if (group >= _num_groups || group < 0)
log_printf(ERROR, "Unable to increment Vector value for group %d"
" which is not between 0 and %d", group, _num_groups-1);
/* Atomically increment the Vector value from the
* temporary array using mutual exclusion locks */
omp_set_lock(&_cell_locks[cell]);
_array[cell*_num_groups + group] += val;
/* Release Vector cell mutual exclusion lock */
omp_unset_lock(&_cell_locks[cell]);
}
void Vector::setAll(FP_PRECISION val) {
std::fill_n(_array, _num_rows, val);
}
/**
* @brief Set a value in the vector.
* @detail This method takes a cell and group and floating
* point value. The cell and group are used to compute the
* row and column in the vector. The location of the corresponding
* row is set to val.
* @param cell The cell location.
* @param group The group location.
* @param val The value used to set the row location.
*/
void Vector::setValue(int cell, int group, FP_PRECISION val) {
if (cell >= _num_x*_num_y || cell < 0)
log_printf(ERROR, "Unable to set Vector value for cell %d"
" which is not between 0 and %d", cell, _num_x*_num_y-1);
else if (group >= _num_groups || group < 0)
log_printf(ERROR, "Unable to set Vector value for group %d"
" which is not between 0 and %d", group, _num_groups-1);
/* Atomically set the Vector value from the
* temporary array using mutual exclusion locks */
omp_set_lock(&_cell_locks[cell]);
_array[cell*_num_groups + group] = val;
/* Release Vector cell mutual exclusion lock */
omp_unset_lock(&_cell_locks[cell]);
}
/**
* @brief Clear all values in the vector.
*/
void Vector::clear() {
setAll(0.0);
}
/**
* @brief Scales the vector by a given value.
* @param val The value to scale the vector by.
*/
void Vector::scaleByValue(FP_PRECISION val) {
#pragma omp parallel for schedule(guided)
for (int i=0; i < _num_rows; i++)
_array[i] *= val;
}
/**
* @brief Print the vector object to the log file.
*/
void Vector::printString() {
std::stringstream string;
string << std::setprecision(6);
string << std::endl;
string << "Vector" << std::endl;
string << " Num rows: " << _num_rows << std::endl;
for (int row=0; row < _num_rows; row++)
string << " ( " << row << "): " << _array[row] << std::endl;
string << "End Vector" << std::endl;
log_printf(NORMAL, string.str().c_str());
}
/**
* @brief Copy the values from the current vector to an input vector.
* @param vector The vector to copy values to.
*/
void Vector::copyTo(Vector* vector) {
std::copy(_array, _array + _num_rows, vector->getArray());
}
/**
* @brief Get a value at location described by a given cell and
* group index.
* @param cell The cell location index.
* @param group The group location index.
*/
FP_PRECISION Vector::getValue(int cell, int group) {
return _array[cell*_num_groups + group];
}
/**
* @brief Get the array describing the vector.
* @return The array describing the vector.
*/
FP_PRECISION* Vector::getArray() {
return _array;
}
/**
* @brief Get the number of cells in the x dimension.
* @return The number of cells in the x dimension.
*/
int Vector::getNumX() {
return _num_x;
}
/**
* @brief Get the number of cells in the y dimension.
* @return The number of cells in the y dimension.
*/
int Vector::getNumY() {
return _num_y;
}
/**
* @brief Get the number of groups in each cell.
* @return The number of groups in each cell.
*/
int Vector::getNumGroups() {
return _num_groups;
}
/**
* @brief Get the number of rows in the vector.
* @return The number of rows in the vector.
*/
int Vector::getNumRows() {
return _num_rows;
}
/**
* @brief Get the sum of all the values in the vector.
* @return The sum of all the values in the vector.
*/
FP_PRECISION Vector::getSum() {
return pairwise_sum(_array, _num_rows);
}
/**
* @brief Set the number of cells in the x dimension.
* @param num_x The number of cells in the x dimension.
*/
void Vector::setNumX(int num_x) {
if (num_x < 1)
log_printf(ERROR, "Unable to set Vector num x to non-positive value %d",
num_x);
_num_x = num_x;
}
/**
* @brief Set the number of cells in the y dimension.
* @param num_y The number of cells in the y dimension.
*/
void Vector::setNumY(int num_y) {
if (num_y < 1)
log_printf(ERROR, "Unable to set Vector num y to non-positive value %d",
num_y);
_num_y = num_y;
}
/**
* @brief Set the number of groups in each cell.
* @param num_groups The number of groups in each cell.
*/
void Vector::setNumGroups(int num_groups) {
if (num_groups < 1)
log_printf(ERROR, "Unable to set Vector num groups to non-positive value"
" %d", num_groups);
_num_groups = num_groups;
}
| 26.018587 | 78 | 0.664809 | [
"object",
"vector"
] |
67658789608f223cb6fd77a82d3036df1bda31e4 | 566 | cpp | C++ | 20191214_1stAlgorithmTest/d.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | 20191214_1stAlgorithmTest/d.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | 20191214_1stAlgorithmTest/d.cpp | miyalab/AtCoder | a57c8a6195463a9a8edd1c3ddd36cc56f145c60d | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a(n+1,0);
bool flag = false;
// データ取得
for(int i=0;i<n;i++){
int buf;
cin >> buf;
a[buf]+=1;
// 重複検出
if(a[buf]==2){
cout << buf << " ";
flag = true;
}
}
// 重複あり
if(flag == true){
// データなし探索
for(int i=1;i<=n;i++){
if(a[i]==0) cout << i << endl;
}
}
// 重複なし
else{
cout << "Correct" << endl;
}
} | 14.894737 | 42 | 0.378092 | [
"vector"
] |
6767ca654ecb7a40b3b328efe7281f0f0ff68e1f | 2,095 | cc | C++ | src/main.cc | b4shfire/stegcrack | 0f6015c9a5cf16877dab544818d6a2cd6c36c7dd | [
"BSD-3-Clause"
] | 6 | 2021-02-16T09:03:30.000Z | 2021-09-05T16:09:53.000Z | src/main.cc | b4shfire/stegcrack | 0f6015c9a5cf16877dab544818d6a2cd6c36c7dd | [
"BSD-3-Clause"
] | null | null | null | src/main.cc | b4shfire/stegcrack | 0f6015c9a5cf16877dab544818d6a2cd6c36c7dd | [
"BSD-3-Clause"
] | 2 | 2021-10-02T18:22:47.000Z | 2021-10-05T00:59:48.000Z | // © 2021 Lorian Richmond
#include "ui.hh"
#include "utils.hh"
#include "ExtractedData.hh"
#include "file_handling.hh"
#include <math.h>
#include <fstream>
#include <iostream>
using namespace std;
void display_usage(string run_path){
cout << "Usage: " << run_path << " <filepath> <number of threads> (default: 4)" << endl;
}
int main(int argc, char** argv){
string filename;
int num_threads = 4;
switch (argc){
case 3:
num_threads = atoi(argv[2]);
case 2:
filename = argv[1];
break;
default:
display_usage(argv[0]);
return 1;
}
if (num_threads < 1 || num_threads > 100){
cout << "Number of threads must be between 1 and 100" << endl;
}
cout << "Opening file...";
FILE* p_file = fopen(filename.c_str(), "rb");
if (p_file == NULL){
cerr << endl << "Error: file could not be opened" << endl;
return 1;
}
cout << " done." << endl;
cout << "Reading file data...";
const vector<bool> bits = file_handling::auto_load(p_file);
cout << " done." << endl;
cout << "Brute-forcing seeds...";
const vector<uint32_t> valid_seeds = utils::find_valid_seeds(bits, num_threads);
cout << " done." << endl;
cout << "Attempting file extraction...";
const vector<ExtractedData> extracted_files = utils::extract_files(bits, valid_seeds);
cout << " done." << endl;
if (extracted_files.size() == 0){
cout << "\033[31m" << "No embedded files found" << "\033[0m" << endl;
}else{
// The probability of a non-stego file of this size generating valid metadata
// num seeds magic version payload_size enc_algo
double coincidence_probability = pow(2, 32) / pow(2, 24) / pow(2, 1) * (bits.size()/3-65) / pow(2, 32) * 22.0 / 32;
cout << "\033[32m" << extracted_files.size() << " embedded file" << (extracted_files.size() == 1 ? "" : "s") << " found" << "\033[0m" << endl;
cout << "(Confidence: " << (1-coincidence_probability) * 100 << "%)" << endl;
for (int i=0, s=(int)extracted_files.size(); i<s; i++){
ui::save_dialogue(extracted_files[i]);
}
}
return 0;
}
| 23.021978 | 144 | 0.606205 | [
"vector"
] |
6769b3dc95924af5cf160c61bf96fdf8d595aba2 | 18,010 | cpp | C++ | src/radiant/watchbsp.cpp | osen/openradiant | 47f0b65006e3e3325003f65cddbc7f1c78b5f138 | [
"BSD-3-Clause"
] | 11 | 2021-01-04T16:27:48.000Z | 2022-01-22T00:37:31.000Z | src/radiant/watchbsp.cpp | osen/openradiant | 47f0b65006e3e3325003f65cddbc7f1c78b5f138 | [
"BSD-3-Clause"
] | 6 | 2021-01-05T04:47:45.000Z | 2021-11-30T09:25:11.000Z | src/radiant/watchbsp.cpp | osen/openradiant | 47f0b65006e3e3325003f65cddbc7f1c78b5f138 | [
"BSD-3-Clause"
] | 1 | 2021-04-01T20:57:22.000Z | 2021-04-01T20:57:22.000Z | /*
Copyright (c) 2001, Loki software, inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Loki software 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 REGENTS 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.
*/
//-----------------------------------------------------------------------------
//
// DESCRIPTION:
// monitoring window for running BSP processes (and possibly various other stuff)
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#endif
#include "qe3.h"
#include "watchbsp.h"
#include "feedback.h"
#if defined( __linux__ ) || defined( __FreeBSD__ ) || defined( __APPLE__ ) || defined ( USE_POSIX )
#include <sys/time.h>
#define SOCKET_ERROR -1
#endif
#ifdef __APPLE__
#include <unistd.h>
#endif
#include <assert.h>
#include <glib/gi18n.h>
// Static functions for the SAX callbacks -------------------------------------------------------
// utility for saxStartElement below
static void abortStream( message_info_t *data ){
g_pParentWnd->GetWatchBSP()->Reset();
// tell there has been an error
if ( g_pParentWnd->GetWatchBSP()->HasBSPPlugin() ) {
g_BSPFrontendTable.m_pfnEndListen( 2 );
}
// yeah this doesn't look good.. but it's needed so that everything will be ignored until the stream goes out
data->ignore_depth = -1;
data->recurse++;
}
#include "stream_version.h"
static void saxStartElement( message_info_t *data, const xmlChar *name, const xmlChar **attrs ){
if ( data->ignore_depth == 0 ) {
if ( data->bGeometry ) {
// we have a handler
data->pGeometry->saxStartElement( data, name, attrs );
}
else
{
if ( strcmp( (char *)name, "q3map_feedback" ) == 0 ) {
// check the correct version
// old q3map don't send a version attribute
// the ones we support .. send Q3MAP_STREAM_VERSION
if ( !attrs[0] || !attrs[1] || ( strcmp( (char*)attrs[0],"version" ) != 0 ) ) {
Sys_FPrintf( SYS_ERR, "No stream version given in the feedback stream, this is an old q3map version.\n"
"Please turn off monitored compiling if you still wish to use this q3map executable\n" );
abortStream( data );
return;
}
else if ( strcmp( (char*)attrs[1],Q3MAP_STREAM_VERSION ) != 0 ) {
Sys_FPrintf( SYS_ERR,
"This version of Radiant reads version %s debug streams, I got an incoming connection with version %s\n"
"Please make sure your versions of Radiant and q3map are matching.\n", Q3MAP_STREAM_VERSION, (char*)attrs[1] );
abortStream( data );
return;
}
}
// we don't treat locally
else if ( strcmp( (char *)name, "message" ) == 0 ) {
data->msg_level = atoi( (char *)attrs[1] );
}
else if ( strcmp( (char *)name, "polyline" ) == 0 ) {
// polyline has a particular status .. right now we only use it for leakfile ..
data->bGeometry = true;
data->pGeometry = &g_pointfile;
data->pGeometry->saxStartElement( data, name, attrs );
}
else if ( strcmp( (char *)name, "select" ) == 0 ) {
CSelectMsg *pSelect = new CSelectMsg();
data->bGeometry = true;
data->pGeometry = pSelect;
data->pGeometry->saxStartElement( data, name, attrs );
}
else if ( strcmp( (char *)name, "pointmsg" ) == 0 ) {
CPointMsg *pPoint = new CPointMsg();
data->bGeometry = true;
data->pGeometry = pPoint;
data->pGeometry->saxStartElement( data, name, attrs );
}
else if ( strcmp( (char *)name, "windingmsg" ) == 0 ) {
CWindingMsg *pWinding = new CWindingMsg();
data->bGeometry = true;
data->pGeometry = pWinding;
data->pGeometry->saxStartElement( data, name, attrs );
}
else
{
Sys_FPrintf( SYS_WRN, "WARNING: ignoring unrecognized node in XML stream (%s)\n", name );
// we don't recognize this node, jump over it
// (NOTE: the ignore mechanism is a bit screwed, only works when starting an ignore at the highest level)
data->ignore_depth = data->recurse;
}
}
}
data->recurse++;
}
static void saxEndElement( message_info_t *data, const xmlChar *name ) {
data->recurse--;
// we are out of an ignored chunk
if ( data->recurse == data->ignore_depth ) {
data->ignore_depth = 0;
return;
}
if ( data->bGeometry ) {
data->pGeometry->saxEndElement( data, name );
// we add the object to the debug window
if ( !data->bGeometry ) {
g_DbgDlg.Push( data->pGeometry );
}
}
if ( data->recurse == data->stop_depth ) {
#ifdef _DEBUG
Sys_FPrintf( SYS_ERR, "ERROR: Received error msg .. shutting down..\n" );
#endif
// tell there has been an error
if ( g_pParentWnd->GetWatchBSP()->HasBSPPlugin() ) {
g_BSPFrontendTable.m_pfnEndListen( 2 );
}
return;
}
}
static void saxCharacters( message_info_t *data, const xmlChar *ch, int len ){
if ( data->bGeometry ) {
data->pGeometry->saxCharacters( data, ch, len );
}
else
{
if ( data->ignore_depth != 0 ) {
return;
}
// output the message using the level
char buf[1024];
memcpy( buf, ch, len );
buf[len] = '\0';
Sys_FPrintf( data->msg_level, "%s", buf );
// if this message has error level flag, we mark the depth to stop the compilation when we get out
// we don't set the msg level if we don't stop on leak
if ( data->msg_level == 3 ) {
data->stop_depth = data->recurse - 1;
}
}
}
static void saxComment( void *ctx, const xmlChar *msg ){
Sys_Printf( "XML comment: %s\n", msg );
}
static void saxWarning( void *ctx, const char *msg, ... ){
char saxMsgBuffer[4096];
va_list args;
va_start( args, msg );
vsprintf( saxMsgBuffer, msg, args );
va_end( args );
Sys_FPrintf( SYS_WRN, "XML warning: %s\n", saxMsgBuffer );
}
static void saxError( void *ctx, const char *msg, ... ){
char saxMsgBuffer[4096];
va_list args;
va_start( args, msg );
vsprintf( saxMsgBuffer, msg, args );
va_end( args );
Sys_FPrintf( SYS_ERR, "XML error: %s\n", saxMsgBuffer );
}
static void saxFatal( void *ctx, const char *msg, ... ){
char buffer[4096];
va_list args;
va_start( args, msg );
vsprintf( buffer, msg, args );
va_end( args );
Sys_FPrintf( SYS_ERR, "XML fatal error: %s\n", buffer );
}
static xmlSAXHandler saxParser = {
0, /* internalSubset */
0, /* isStandalone */
0, /* hasInternalSubset */
0, /* hasExternalSubset */
0, /* resolveEntity */
0, /* getEntity */
0, /* entityDecl */
0, /* notationDecl */
0, /* attributeDecl */
0, /* elementDecl */
0, /* unparsedEntityDecl */
0, /* setDocumentLocator */
0, /* startDocument */
0, /* endDocument */
(startElementSAXFunc)saxStartElement, /* startElement */
(endElementSAXFunc)saxEndElement, /* endElement */
0, /* reference */
(charactersSAXFunc)saxCharacters, /* characters */
0, /* ignorableWhitespace */
0, /* processingInstruction */
(commentSAXFunc)saxComment, /* comment */
(warningSAXFunc)saxWarning, /* warning */
(errorSAXFunc)saxError, /* error */
(fatalErrorSAXFunc)saxFatal, /* fatalError */
};
// ------------------------------------------------------------------------------------------------
CWatchBSP::~CWatchBSP(){
Reset();
if ( m_pCmd ) {
g_ptr_array_free( m_pCmd, true );
m_pCmd = NULL;
}
if ( m_sBSPName ) {
g_free( m_sBSPName );
m_sBSPName = NULL;
}
Net_Shutdown();
}
void CWatchBSP::RunQuake() {
// build the command line
Str cmd;
cmd = g_pGameDescription->mExecutablesPath.GetBuffer();
// this is game dependant
if ( !strcmp( ValueForKey( g_qeglobals.d_project_entity, "gamemode" ),"mp" ) ) {
// MP
cmd += g_pGameDescription->mMultiplayerEngine.GetBuffer();
}
else
{
// SP
cmd += g_pGameDescription->mEngine.GetBuffer();
}
#ifdef _WIN32
// NOTE: we are using unix pathnames and CreateProcess doesn't like / in the program path
// FIXME: This isn't true anymore, doesn't it?
FindReplace( cmd, "/", "\\" );
#endif
Str cmdline;
if ( g_pGameDescription->idTech2 ) {
cmdline = "+exec radiant.cfg +map ";
cmdline += m_sBSPName;
}
else
// NOTE: idTech3 specific - there used to be some logic depending on engine breed here
{
cmdline = "+set sv_pure 0 ";
// TTimo: a check for vm_* but that's all fine
//cmdline = "+set sv_pure 0 +set vm_ui 0 +set vm_cgame 0 +set vm_game 0 ";
if ( *ValueForKey( g_qeglobals.d_project_entity, "gamename" ) != '\0' ) {
cmdline += "+set fs_game ";
cmdline += ValueForKey( g_qeglobals.d_project_entity, "gamename" );
cmdline += " ";
}
//!\todo Read the start-map args from a config file.
if ( g_pGameDescription->mGameFile == "wolf.game" ) {
if ( !strcmp( ValueForKey( g_qeglobals.d_project_entity, "gamemode" ),"mp" ) ) {
// MP
cmdline += "+devmap ";
cmdline += m_sBSPName;
}
else
{
// SP
cmdline += "+set nextmap \"spdevmap ";
cmdline += m_sBSPName;
cmdline += "\"";
}
}
else
{
cmdline += "+devmap ";
cmdline += m_sBSPName;
}
}
Sys_Printf( "%s %s\n", cmd.GetBuffer(), cmdline.GetBuffer() );
// execute now
if ( !Q_Exec( cmd.GetBuffer(), (char *)cmdline.GetBuffer(), g_pGameDescription->mEnginePath.GetBuffer(), false ) ) {
CString msg;
msg = "Failed to execute the following command: ";
msg += cmd; msg += cmdline;
Sys_Printf( msg );
gtk_MessageBox( g_pParentWnd->m_pWidget, msg, _( "BSP monitoring" ), MB_OK | MB_ICONERROR );
}
}
void CWatchBSP::Reset(){
if ( m_pInSocket ) {
Net_Disconnect( m_pInSocket );
m_pInSocket = NULL;
}
if ( m_pListenSocket ) {
Net_Disconnect( m_pListenSocket );
m_pListenSocket = NULL;
}
if ( m_xmlInputBuffer ) {
xmlFreeParserInputBuffer( m_xmlInputBuffer );
m_xmlInputBuffer = NULL;
}
if ( m_xmlParserCtxt ) {
xmlFreeParserCtxt( m_xmlParserCtxt );
m_xmlParserCtxt = NULL;
}
m_eState = EIdle;
}
bool CWatchBSP::SetupListening(){
#ifdef _DEBUG
if ( m_pListenSocket ) {
Sys_FPrintf( SYS_ERR, "ERROR: m_pListenSocket != NULL in CWatchBSP::SetupListening\n" );
return false;
}
#endif
Sys_Printf( "Setting up\n" );
if ( !Net_Setup() ) {
return false;
}
m_pListenSocket = Net_ListenSocket( 39000 );
if ( m_pListenSocket == NULL ) {
return false;
}
Sys_Printf( "Listening...\n" );
return true;
}
void CWatchBSP::DoEBeginStep() {
if ( !SetupListening() ) {
CString msg;
msg = _( "Failed to get a listening socket on port 39000.\nTry running with BSP monitoring disabled if you can't fix this.\n" );
Sys_Printf( msg );
gtk_MessageBox( g_pParentWnd->m_pWidget, msg, _( "BSP monitoring" ), MB_OK | MB_ICONERROR );
Reset();
return;
}
// re-initialise the debug window
if ( m_iCurrentStep == 0 ) {
g_DbgDlg.Init();
}
// set the timer for timeouts and step cancellation
g_timer_reset( m_pTimer );
g_timer_start( m_pTimer );
if ( !m_bBSPPlugin ) {
Sys_Printf( "=== running BSP command ===\n%s\n", g_ptr_array_index( m_pCmd, m_iCurrentStep ) );
if ( !Q_Exec( NULL, (char *) g_ptr_array_index( m_pCmd, m_iCurrentStep ), NULL, true ) ) {
CString msg;
msg = _( "Failed to execute the following command: " );
msg += (char *) g_ptr_array_index( m_pCmd, m_iCurrentStep );
msg += _( "\nCheck that the file exists and that you don't run out of system resources.\n" );
Sys_Printf( msg );
gtk_MessageBox( g_pParentWnd->m_pWidget, msg, _( "BSP monitoring" ), MB_OK | MB_ICONERROR );
Reset();
return;
}
}
m_eState = EBeginStep;
}
void CWatchBSP::RoutineProcessing(){
// used for select()
#ifdef _WIN32
TIMEVAL tout = { 0, 0 };
#endif
#if defined( __linux__ ) || defined( __FreeBSD__ ) || defined( __APPLE__ ) || defined ( USE_POSIX )
timeval tout;
tout.tv_sec = 0;
tout.tv_usec = 0;
#endif
switch ( m_eState )
{
case EBeginStep:
// timeout: if we don't get an incoming connection fast enough, go back to idle
if ( g_timer_elapsed( m_pTimer, NULL ) > g_PrefsDlg.m_iTimeout ) {
gtk_MessageBox( g_pParentWnd->m_pWidget, _( "The connection timed out, assuming the BSP process failed\nMake sure you are using a networked version of Q3Map?\nOtherwise you need to disable BSP Monitoring in prefs." ), _( "BSP process monitoring" ), MB_OK );
Reset();
if ( m_bBSPPlugin ) {
// status == 1 : didn't get the connection
g_BSPFrontendTable.m_pfnEndListen( 1 );
}
break;
}
#ifdef _DEBUG
// some debug checks
if ( !m_pListenSocket ) {
Sys_FPrintf( SYS_ERR, "ERROR: m_pListenSocket == NULL in CWatchBSP::RoutineProcessing EBeginStep state\n" );
Reset();
break;
}
#endif
// we are not connected yet, accept any incoming connection
m_pInSocket = Net_Accept( m_pListenSocket );
if ( m_pInSocket ) {
Sys_Printf( "Connected.\n" );
// prepare the message info struct for diving in
memset( &m_message_info, 0, sizeof( message_info_s ) );
// a dumb flag to make sure we init the push parser context when first getting a msg
m_eState = EWatching;
}
break;
case EWatching:
#ifdef _DEBUG
// some debug checks
if ( !m_pInSocket ) {
Sys_FPrintf( SYS_ERR, "ERROR: m_pInSocket == NULL in CWatchBSP::RoutineProcessing EWatching state\n" );
Reset();
break;
}
#endif
// select() will identify if the socket needs an update
// if the socket is identified that means there's either a message or the connection has been closed/reset/terminated
fd_set readfds;
int ret;
FD_ZERO( &readfds );
FD_SET( ( (unsigned int)m_pInSocket->socket ), &readfds );
// from select man page:
// n is the highest-numbered descriptor in any of the three sets, plus 1
// (no use on windows)
ret = select( m_pInSocket->socket + 1, &readfds, NULL, NULL, &tout );
if ( ret == SOCKET_ERROR ) {
Sys_FPrintf( SYS_WRN, "WARNING: SOCKET_ERROR in CWatchBSP::RoutineProcessing\n" );
Sys_Printf( "Terminating the connection.\n" );
Reset();
break;
}
if ( ret == 1 ) {
// the socket has been identified, there's something (message or disconnection)
// see if there's anything in input
ret = Net_Receive( m_pInSocket, &msg );
if ( ret > 0 ) {
// unsigned int size = msg.size; //++timo just a check
g_strlcpy( m_xmlBuf, NMSG_ReadString( &msg ), sizeof( m_xmlBuf) );
if ( m_xmlParserCtxt == NULL ) {
m_xmlParserCtxt = xmlCreatePushParserCtxt( &saxParser, &m_message_info, m_xmlBuf, strlen( m_xmlBuf ), NULL );
if ( m_xmlParserCtxt == NULL ) {
Sys_FPrintf( SYS_ERR, "Failed to create the XML parser (incoming stream began with: %s)\n", m_xmlBuf );
Reset();
break;
}
}
else
{
xmlParseChunk( m_xmlParserCtxt, m_xmlBuf, strlen( m_xmlBuf ), 0 );
}
}
else
{
// error or connection closed/reset
// NOTE: if we get an error down the XML stream we don't reach here
Net_Disconnect( m_pInSocket );
m_pInSocket = NULL;
Sys_Printf( "Connection closed.\n" );
if ( m_bBSPPlugin ) {
// let the BSP plugin know that the job is done
g_BSPFrontendTable.m_pfnEndListen( 0 );
}
Reset();
// move to next step or finish
m_iCurrentStep++;
if ( m_iCurrentStep < m_pCmd->len ) {
DoEBeginStep();
break;
}
// launch the engine .. OMG
if ( g_PrefsDlg.m_bRunQuake ) {
// do we enter sleep mode before?
if ( g_PrefsDlg.m_bDoSleep ) {
Sys_Printf( "Going into sleep mode..\n" );
g_pParentWnd->OnSleep();
}
Sys_Printf( "Running engine...\n" );
RunQuake();
}
}
}
break;
default:
break;
}
}
void CWatchBSP::DoMonitoringLoop( GPtrArray *pCmd, char *sBSPName ){
guint i;
if ( m_eState != EIdle ) {
Sys_Printf( "WatchBSP got a monitoring request while not idling...\n" );
// prompt the user, should we cancel the current process and go ahead?
if ( gtk_MessageBox( g_pParentWnd->m_pWidget, _( "I am already monitoring a BSP process.\nDo you want me to override and start a new compilation?" ),
_( "BSP process monitoring" ), MB_YESNO ) == IDNO ) {
return;
}
}
Reset();
if ( m_pCmd ) {
g_ptr_array_free( m_pCmd, true );
m_pCmd = NULL;
}
if ( m_sBSPName ) {
g_free( m_sBSPName );
m_sBSPName = NULL;
}
// glib 2.30
// m_pCmd = g_ptr_array_new_full( pCmd->len, g_free );
m_pCmd = g_ptr_array_sized_new( pCmd->len );
g_ptr_array_set_free_func( m_pCmd, g_free );
for ( i = 0; i < pCmd->len; i++ ) {
g_ptr_array_add( m_pCmd, g_strdup( (char *) pCmd->pdata[i] ) );
}
m_iCurrentStep = 0;
m_sBSPName = g_strdup(sBSPName);
DoEBeginStep();
}
void CWatchBSP::ExternalListen(){
m_bBSPPlugin = true;
DoEBeginStep();
}
// the part of the watchbsp interface we export to plugins
// NOTE: in the long run, the whole watchbsp.cpp interface needs to go out and be handled at the BSP plugin level
// for now we provide something really basic and limited, the essential is to have something that works fine and fast (for 1.1 final)
void WINAPI QERApp_Listen(){
// open the listening socket
g_pParentWnd->GetWatchBSP()->ExternalListen();
}
| 29.966722 | 260 | 0.660355 | [
"object"
] |
676f7b148d19e8ec0ab44b29e2c308037f6854a6 | 6,289 | cc | C++ | mindspore/ccsrc/plugin/device/ascend/optimizer/ir_fission/adam_weight_decay_fission.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/ccsrc/plugin/device/ascend/optimizer/ir_fission/adam_weight_decay_fission.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/plugin/device/ascend/optimizer/ir_fission/adam_weight_decay_fission.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2022 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "plugin/device/ascend/optimizer/ir_fission/adam_weight_decay_fission.h"
#include <memory>
#include <vector>
#include <string>
#include "include/common/utils/anfalgo.h"
#include "mindspore/core/ops/core_ops.h"
namespace mindspore {
namespace opt {
namespace {
// AdamWeightDecay's inputs: param, m, v, lr, beta1, beta2, eps, weight_decay, gradient
constexpr size_t kIdxParam = 1;
constexpr size_t kIdxM = 2;
constexpr size_t kIdxV = 3;
constexpr size_t kIdxLr = 4;
constexpr size_t kIdxBeta1 = 5;
constexpr size_t kIdxBeta2 = 6;
constexpr size_t kIdxEps = 7;
constexpr size_t kIdxWeightDecay = 8;
constexpr size_t kIdxGradient = 9;
constexpr size_t kAamWeightDecayInputNum = 9;
AnfNodePtr CreateNodeBase(const FuncGraphPtr &graph, const std::vector<AnfNodePtr> &new_node_inputs,
const AnfNodePtr &node) {
auto new_node = graph->NewCNode(new_node_inputs);
MS_EXCEPTION_IF_NULL(new_node);
new_node->set_kernel_info(std::make_shared<device::KernelInfo>());
new_node->set_scope(node->scope());
new_node->set_abstract(node->abstract());
auto types = {common::AnfAlgo::GetOutputInferDataType(node, 0)};
auto shapes = {common::AnfAlgo::GetOutputInferShape(node, 0)};
common::AnfAlgo::SetOutputInferTypeAndShape(types, shapes, new_node.get());
return new_node;
}
AnfNodePtr CreateNodeOfBinaryOp(const FuncGraphPtr &graph, const string &op_name, const AnfNodePtr &node1,
const AnfNodePtr &node2) {
std::vector<AnfNodePtr> new_node_inputs = {NewValueNode(std::make_shared<Primitive>(op_name)), node1, node2};
return CreateNodeBase(graph, new_node_inputs, node2);
}
AnfNodePtr CreateNodeOfUnaryOp(const FuncGraphPtr &graph, const string &op_name, const AnfNodePtr &node) {
std::vector<AnfNodePtr> new_node_inputs = {NewValueNode(std::make_shared<Primitive>(op_name)), node};
return CreateNodeBase(graph, new_node_inputs, node);
}
ValueNodePtr CreateValueNode(const FuncGraphPtr &graph, double value) {
auto tensor = std::make_shared<tensor::Tensor>(value);
auto kernel_graph = graph->cast<KernelGraphPtr>();
ValueNodePtr value_node = kernel_graph->NewValueNode(tensor->ToAbstract(), tensor);
kernel_graph->AddValueNodeToGraph(value_node);
return value_node;
}
} // namespace
const BaseRef AdamWeightDecayFission::DefinePattern() const {
VarPtr Xs = std::make_shared<SeqVar>();
return VectorRef({prim::kPrimAdamWeightDecay, Xs});
}
const AnfNodePtr AdamWeightDecayFission::Process(const FuncGraphPtr &graph, const AnfNodePtr &node,
const EquivPtr &) const {
MS_EXCEPTION_IF_NULL(graph);
MS_EXCEPTION_IF_NULL(node);
auto adam_weight_decay_cnode = node->cast<CNodePtr>();
MS_EXCEPTION_IF_NULL(adam_weight_decay_cnode);
CheckCNodeInputSize(adam_weight_decay_cnode, kAamWeightDecayInputNum);
const auto ori_inputs = adam_weight_decay_cnode->inputs();
// create beta1 * m
auto mul_1 = CreateNodeOfBinaryOp(graph, kMulOpName, ori_inputs[kIdxBeta1], ori_inputs[kIdxM]);
// create 1-beta1
auto num_one = CreateValueNode(graph, 1.0);
auto sub_1 = CreateNodeOfBinaryOp(graph, kSubOpName, num_one, ori_inputs[kIdxBeta1]);
// create (1-beta1) * gradient
auto mul_2 = CreateNodeOfBinaryOp(graph, kMulOpName, sub_1, ori_inputs[kIdxGradient]);
// create next_m = beta1 * m + (1 - beat1) * gradient
auto add_1 = CreateNodeOfBinaryOp(graph, kTensorAddOpName, mul_1, mul_2);
// create beta2 * v
auto mul_3 = CreateNodeOfBinaryOp(graph, kMulOpName, ori_inputs[kIdxBeta2], ori_inputs[kIdxV]);
// create gradient^2
auto square = CreateNodeOfUnaryOp(graph, kSquareOpName, ori_inputs[kIdxGradient]);
// create 1-beta2
auto sub_2 = CreateNodeOfBinaryOp(graph, kSubOpName, num_one, ori_inputs[kIdxBeta2]);
// create (1-beta2) * gradient^2
auto mul_4 = CreateNodeOfBinaryOp(graph, kMulOpName, sub_2, square);
// create next_v = beta2 * v + (1 - beta2) * gradient^2
auto add_2 = CreateNodeOfBinaryOp(graph, kTensorAddOpName, mul_3, mul_4);
// create sqrt(next_v)
auto sqrt = CreateNodeOfUnaryOp(graph, kSqrtOpName, add_2);
// create eps + sqrt(next_v)
auto add_3 = CreateNodeOfBinaryOp(graph, kTensorAddOpName, ori_inputs[kIdxEps], sqrt);
// create update = next_m / (eps + sqrt(next_v))
auto real_div = CreateNodeOfBinaryOp(graph, kRealDivOpName, add_1, add_3);
// create weight_decay * param
auto mul_5 = CreateNodeOfBinaryOp(graph, kMulOpName, ori_inputs[kIdxWeightDecay], ori_inputs[kIdxParam]);
// create update <== weight_decay * param + update
auto add_4 = CreateNodeOfBinaryOp(graph, kTensorAddOpName, mul_5, real_div);
// create update_with_lr = lr * update
auto mul_6 = CreateNodeOfBinaryOp(graph, kMulOpName, ori_inputs[kIdxLr], add_4);
// create param - update_with_lr
auto sub_3 = CreateNodeOfBinaryOp(graph, kSubOpName, ori_inputs[kIdxParam], mul_6);
// create param = param - update_with_lr
auto assign_1 = CreateNodeOfBinaryOp(graph, prim::kPrimAssign->name(), ori_inputs[kIdxParam], sub_3);
// create m = next_m
auto assign_2 = CreateNodeOfBinaryOp(graph, prim::kPrimAssign->name(), ori_inputs[kIdxM], add_1);
// create v = next_v
auto assign_3 = CreateNodeOfBinaryOp(graph, prim::kPrimAssign->name(), ori_inputs[kIdxV], add_2);
std::vector<AnfNodePtr> make_tuple_inputs = {NewValueNode(prim::kPrimMakeTuple), assign_1, assign_2, assign_3};
auto make_tuple = graph->NewCNode(make_tuple_inputs);
MS_EXCEPTION_IF_NULL(make_tuple);
return make_tuple;
}
} // namespace opt
} // namespace mindspore
| 45.572464 | 114 | 0.730482 | [
"vector"
] |
6770379fe108f46c45d0990da37adf82b3257739 | 1,795 | cpp | C++ | src/abnf/Terminal_StringValue.cpp | medooze/sdp- | 4bf23de4cf6ade65fedb68a8c8a5baf4bd6a3e6d | [
"MIT"
] | 32 | 2018-01-01T17:01:19.000Z | 2022-02-25T10:30:47.000Z | src/abnf/Terminal_StringValue.cpp | medooze/sdp- | 4bf23de4cf6ade65fedb68a8c8a5baf4bd6a3e6d | [
"MIT"
] | 4 | 2018-01-08T16:13:05.000Z | 2021-01-25T11:47:44.000Z | src/abnf/Terminal_StringValue.cpp | medooze/sdp- | 4bf23de4cf6ade65fedb68a8c8a5baf4bd6a3e6d | [
"MIT"
] | 13 | 2018-09-30T05:59:24.000Z | 2022-02-24T08:58:36.000Z | /* -----------------------------------------------------------------------------
* Terminal_StringValue.cpp
* -----------------------------------------------------------------------------
*
* Producer : com.parse2.aparse.Parser 2.5
* Produced : Mon Jan 08 13:30:55 CET 2018
*
* -----------------------------------------------------------------------------
*/
#include <string>
using std::string;
#include <vector>
using std::vector;
#include "Terminal_StringValue.hpp"
#include "Visitor.hpp"
#include "ParserContext.hpp"
using namespace abnf;
Terminal_StringValue::Terminal_StringValue(
const string& spelling,
const vector<Rule*>& rules) : Rule(spelling, rules)
{
}
Rule* Terminal_StringValue::clone(void) const
{
return new Terminal_StringValue(this->spelling, this->rules);
}
void* Terminal_StringValue::accept(Visitor& visitor)
{
return visitor.visit(this);
}
Terminal_StringValue* Terminal_StringValue::parse(
ParserContext& context,
const string& pattern)
{
context.push("StringValue", pattern);
bool parsed = false;
Terminal_StringValue* stringValue = NULL;
try
{
if (context.index + pattern.length() <= context.text.length())
{
string value = context.text.substr(context.index, pattern.length());
parsed = value.compare(pattern) == 0;
if (parsed)
{
context.index += pattern.length();
stringValue = new Terminal_StringValue(value, vector<Rule*>());
}
}
}
catch (...) {}
context.pop("StringValue", parsed);
return stringValue;
}
/* -----------------------------------------------------------------------------
* eof
* -----------------------------------------------------------------------------
*/
| 23.933333 | 81 | 0.499721 | [
"vector"
] |
67753145aafef144df2e46d74806d2d0a1ef3421 | 637 | hpp | C++ | include/ce2/asset/texture3.hpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | include/ce2/asset/texture3.hpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | include/ce2/asset/texture3.hpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "chokoengine.hpp"
CE_BEGIN_NAMESPACE
class _Texture3 : public _Asset { CE_OBJECT_COMMON
protected: //allow rendertarget access
_Texture3(std::nullptr_t);
GLuint _pointer;
uint _width, _height, _depth;
byte _channels;
GLenum _format;
public:
_Texture3(uint w, uint h, uint d, GLenum fmt);
virtual ~_Texture3(); //allow render targets etc to override
CE_GET_MEMBER(width);
CE_GET_MEMBER(height);
CE_GET_MEMBER(depth);
CE_GET_MEMBER(channels);
CE_GET_MEMBER(format);
bool loaded() const;
virtual void Bind() const;
virtual void Unbind() const;
};
CE_END_NAMESPACE | 19.30303 | 64 | 0.723705 | [
"render"
] |
677b5ec6d30fe894b3cf266450b402166c55bdb0 | 27,573 | cpp | C++ | src/ContactPlanning.cpp | ShihaoWang/Online-Contact-Planning-for-Fall-Mitigation | ef63e67e92e369edbff9854f681e1c2329f2a6d3 | [
"MIT"
] | null | null | null | src/ContactPlanning.cpp | ShihaoWang/Online-Contact-Planning-for-Fall-Mitigation | ef63e67e92e369edbff9854f681e1c2329f2a6d3 | [
"MIT"
] | null | null | null | src/ContactPlanning.cpp | ShihaoWang/Online-Contact-Planning-for-Fall-Mitigation | ef63e67e92e369edbff9854f681e1c2329f2a6d3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <sstream>
#include "CommonHeader.h"
#include "NonlinearOptimizerInfo.h"
#include <ctime>
#include <algorithm>
#include <random>
#include <queue>
#include <math.h>
static bool ContactPairCMP(const pair<Vector3, double> & a, const pair<Vector3, double> & b)
{
return (a.second > b.second);
}
static double NewContactsEval(const std::vector<Vector3> & FixedContacts, const std::vector<Vector3> & NewContacts, const Vector3 & COMPos, const Vector3 & COMVel)
{
// This function is used to evaluate the robot current NewContact according to our objective.
std::vector<Vector3> ActContacts;
ActContacts.reserve(FixedContacts.size() + NewContacts.size());
for (int i = 0; i < FixedContacts.size(); i++)
{
ActContacts.push_back(FixedContacts[i]);
}
for (int i = 0; i < NewContacts.size(); i++)
{
ActContacts.push_back(NewContacts[i]);
}
std::vector<PIPInfo> PIPTotal = PIPGenerator(ActContacts, COMPos, COMVel);
int CPPIPIndex;
double CPObjective = CapturePointGenerator(PIPTotal, CPPIPIndex);
return CPObjective;
}
static std::vector<Vector3> OptimalContactFinder(const std::vector<Vector3> & SupportContact, const std::vector<Vector3> & FixedContacts, const Vector3 & COMPos, const Vector3 & COMVel, const double & RefFailureMetric)
{
// This function is used to estimate robot's cost based on the point contact addition for failure metric evaluation.
std::vector<Vector3> OptimalContact;
OptimalContact.reserve(SupportContact.size());
std::vector<double> ContactFailureMetric(SupportContact.size());
double Tol = 1e-5;
const int ActContactNo = FixedContacts.size() + 1;
for (int i = 0; i < SupportContact.size(); i++)
{
std::vector<Vector3> ActContacts;
ActContacts.reserve(ActContactNo);
for (int j = 0; j < ActContactNo-1; j++)
{
ActContacts.push_back(FixedContacts[j]);
}
ActContacts.push_back(SupportContact[i]);
std::vector<PIPInfo> PIPTotal = PIPGenerator(ActContacts, COMPos, COMVel);
int CPPIPIndex;
double CPObjective = CapturePointGenerator(PIPTotal, CPPIPIndex);
ContactFailureMetric[i] = CPObjective;
if(CPObjective<RefFailureMetric)
{
// This indicates that the curent contact is at least a better contact.
if(CPObjective<Tol)
{
// This means that current contact is OptimalContact
OptimalContact.push_back(SupportContact[i]);
}
}
}
switch (OptimalContact.size())
{
case 0:
{
// This indicates the OptimalContact does not have any element.
// Then the idea is to get the lowest cost from failure metric as the optimal contact.
int OptiIndex = std::distance(ContactFailureMetric.begin(), std::min_element(ContactFailureMetric.begin(), ContactFailureMetric.end()));
OptimalContact.push_back(SupportContact[OptiIndex]);
}
break;
default:
break;
}
return OptimalContact;
}
static std::vector<Vector3> SupportContactFinder(const Vector3 & COMPos, const PIPInfo & PIPObj, const std::vector<Vector3> & ContactFreeContact, SignedDistanceFieldInfo & SDFInfo)
{
// This function is used to get supportive contact and should be only called after ContactFreePoint function.
// The introduced rotational momentum should be in the counter direction.
// The rotation axis is the only thing needed here!
Vector3 EdgeA = PIPObj.EdgeA;
Vector3 EdgeB = PIPObj.EdgeB;
Vector3 EdgeDir = EdgeB - EdgeA;
std::vector<Vector3> SupportContact;
SupportContact.reserve(ContactFreeContact.size());
for (int i = 0; i < ContactFreeContact.size(); i++)
{
Vector3 ContactFreePoint = ContactFreeContact[i];
Vector3 PointNormDir = SDFInfo.SignedDistanceNormal(ContactFreePoint);
Vector3 rPos2COMPos = ContactFreePoint - COMPos;
Vector3 InducedMomentum = cross(rPos2COMPos, PointNormDir);
double ProjMomentumVal = InducedMomentum.x * EdgeDir.x + InducedMomentum.y * EdgeDir.y + InducedMomentum.z * EdgeDir.z;
if(ProjMomentumVal<=0)
{
SupportContact.push_back(ContactFreePoint);
}
}
return SupportContact;
}
static std::vector<std::pair<Vector3, double>> ContactFreeInfoFn(const Robot & SimRobot, const std::vector<LinkInfo> & RobotLinkInfo, const std::vector<ContactStatusInfo> & RobotContactInfo, ReachabilityMap & RMObject)
{
// This function is used to generate pairs of ContactFreeInfo
std::vector<std::pair<Vector3, double>> ContactFreeInfo;
for (int i = 0; i < RobotContactInfo.size(); i++)
{
switch (RobotContactInfo[i].LocalContactStatus[0])
{
case 1:
{
Vector3 LinkiPjPos;
SimRobot.GetWorldPosition(RobotLinkInfo[i].AvgLocalContact, RobotLinkInfo[i].LinkIndex, LinkiPjPos);
double Radius = RMObject.EndEffectorCollisionRadius[i];
auto ContactFreeInfo_i = std::make_pair (LinkiPjPos, Radius);
ContactFreeInfo.push_back(ContactFreeInfo_i);
}
break;
}
}
return ContactFreeInfo;
}
static AllContactStatusInfo SwingLimbIndices(Robot & SimRobot, const std::vector<ContactStatusInfo> & RobotContactInfo)
{
// This function is used to generate Swing Limb Indices and its associated contact status info.
// First part is for contact modification.
// Second part is for contact addition.
// This part should be rewritten to allow more general case.
Vector3 COMPos(0.0, 0.0, 0.0), COMVel(0.0, 0.0, 0.0);
CentroidalState(SimRobot, COMPos, COMVel);
AllContactStatusInfo AllContactStatusObj;
int LegActNo = RobotContactInfo[0].LocalContactStatus[0] + RobotContactInfo[1].LocalContactStatus[0];
int AllActNo = LegActNo + RobotContactInfo[2].LocalContactStatus[0] + RobotContactInfo[3].LocalContactStatus[0];
// Contact Modification
switch (AllActNo)
{
case 0:
{
std::cerr<<"No Active Contact!"<<endl;
exit(1);
}
break;
case 1:
// No contact modification
break;
default:
{
// Algorithms for contact modification
switch (LegActNo)
{
case 0:
{
std::cerr<<"No Active Foot Contact!"<<endl;
exit(1);
}
break;
case 1:
{
// In this case, the contact modification can only be conducted for hand contact if there exists.
switch (RobotContactInfo[2].LocalContactStatus[0])
{
case 1:
{
std::vector<ContactStatusInfo> RobotContactInfoModi = RobotContactInfo;
RobotContactInfoModi[2].StatusSwitch(0);
AllContactStatusObj.ContactStatusAppender(RobotContactInfoModi, 2, 0);
}
break;
default:
break;
}
switch (RobotContactInfo[3].LocalContactStatus[0])
{
case 1:
{
std::vector<ContactStatusInfo> RobotContactInfoModi = RobotContactInfo;
RobotContactInfoModi[3].StatusSwitch(0);
AllContactStatusObj.ContactStatusAppender(RobotContactInfoModi, 3, 0);
}
break;
default:
break;
}
}
break;
default:
{
// More general case where two feet contact is shown while hands may be involved.
for (int i = 0; i < 4; i++)
{
switch (RobotContactInfo[i].LocalContactStatus[0])
{
case 1:
{
std::vector<ContactStatusInfo> RobotContactInfoModi = RobotContactInfo;
RobotContactInfoModi[i].StatusSwitch(0);
AllContactStatusObj.ContactStatusAppender(RobotContactInfoModi, i, 0);
}
break;
default:
break;
}
}
}
break;
}
}
break;
}
// Contact Addition
for (int i = 0; i < RobotContactInfo.size(); i++)
{
switch (RobotContactInfo[i].LocalContactStatus[0])
{
case 0:
{
std::vector<ContactStatusInfo> RobotContactInfoTemp = RobotContactInfo;
AllContactStatusObj.ContactStatusAppender(RobotContactInfoTemp, i, 1);
}
break;
}
}
return AllContactStatusObj;
}
static std::vector<Vector3> OptimalContactSearcher(const Robot & SimRobot, const PIPInfo & PIPObj, const Vector3 & PredictedCOMPos, ReachabilityMap & RMObject, const std::vector<LinkInfo> & RobotLinkInfo, const std::vector<ContactStatusInfo> & FixedRobotContactInfo, const int & SwingLimbIndex, const double & RefFailureMetric, DataRecorderInfo & DataRecorderObj)
{
std::vector<Vector3> OptimalContact;
// Get all the fixed contact positions.
std::vector<Vector3> FixedContactPos;
for (int i = 0; i < RobotLinkInfo.size(); i++)
{
for (int j = 0; j < RobotLinkInfo[i].LocalContacts.size(); j++)
{
switch (FixedRobotContactInfo[i].LocalContactStatus[j])
{
case 1:
{
// This means that current contact is active and we should keep its location and Jacobian.
Vector3 LinkiPjPos;
SimRobot.GetWorldPosition(RobotLinkInfo[i].LocalContacts[j], RobotLinkInfo[i].LinkIndex, LinkiPjPos);
FixedContactPos.push_back(LinkiPjPos);
}
break;
default:
break;
}
}
}
std::vector<std::pair<Vector3, double>> ContactFreeInfo = ContactFreeInfoFn(SimRobot, RobotLinkInfo, FixedRobotContactInfo, RMObject);
Vector3 COMPos(0.0, 0.0, 0.0), COMVel(0.0, 0.0, 0.0);
CentroidalState(SimRobot, COMPos, COMVel);
/*
Data point filtering
*/
// 0. Reachable with respect to the pivotal joint
std::vector<Vector3> ActiveReachableContact = RMObject.ReachablePointsFinder(SimRobot, SwingLimbIndex, NonlinearOptimizerInfo::SDFInfo);
switch (ActiveReachableContact.size()){
case 0:return OptimalContact;
break;
default:
break;
}
// Vector3Writer(ActiveReachableContact, "ActiveReachableContact");
// 1. Self-collision from other end effectors
std::vector<Vector3> ContactFreeContact = RMObject.ContactFreePointsFinder(RMObject.EndEffectorCollisionRadius[SwingLimbIndex], ActiveReachableContact, ContactFreeInfo);
switch (ContactFreeContact.size()){
case 0:return OptimalContact;
break;
default:
break;
}
// Vector3Writer(ContactFreeContact, "ContactFreeContact");
// 2. Supportive
std::vector<Vector3> SupportContact = SupportContactFinder(COMPos, PIPObj, ContactFreeContact, NonlinearOptimizerInfo::SDFInfo);
switch (SupportContact.size()){
case 0:return OptimalContact;
break;
default:
break;
}
// Vector3Writer(SupportContact, "SupportContact");
// 3. Optimal Contact
OptimalContact = OptimalContactFinder(SupportContact, FixedContactPos, COMPos, COMVel, RefFailureMetric);
switch (OptimalContact.size())
{
case 0:
{
return OptimalContact;
}
break;
default:
break;
}
// Vector3Writer(OptimalContact, "OptimalContact");
const int CutOffNo = 10;
// 4. Selected Optimal Contact
/* Method 1: highest distance to edge*/
// Select the contact point such that COM projection has the highest distance to edge.
std::vector<Vector3> SPVertices;
for (int i = 0; i < RobotLinkInfo.size(); i++)
{
int LinkiPNo = RobotLinkInfo[i].LocalContacts.size();
for (int j = 0; j < LinkiPNo; j++)
{
switch (FixedRobotContactInfo[i].LocalContactStatus[j])
{
case 0:
break;
case 1:
{
Vector3 LinkiPjPos;
SimRobot.GetWorldPosition(RobotLinkInfo[i].LocalContacts[j], RobotLinkInfo[i].LinkIndex, LinkiPjPos);
LinkiPjPos.z = 0.0;
SPVertices.push_back(LinkiPjPos);
}
break;
default:
break;
}
}
}
Vector3 COM_Pos = PredictedCOMPos;
std::vector<std::pair<Vector3, double>> ContactPairVec;
ContactPairVec.reserve(OptimalContact.size());
// Here a little modification will be made to ensure a more accurate computation of contact points.
std::vector<Vector3> SwingLimbVertices;
SwingLimbVertices.reserve(RobotLinkInfo[SwingLimbIndex].LocalContacts.size());
for (int i = 0; i < RobotLinkInfo[SwingLimbIndex].LocalContacts.size(); i++)
{
Vector3 LinkiPjPos;
SimRobot.GetWorldPosition(RobotLinkInfo[SwingLimbIndex].LocalContacts[i], RobotLinkInfo[SwingLimbIndex].LinkIndex, LinkiPjPos);
SwingLimbVertices.push_back(LinkiPjPos);
}
Vector3 SwingLimbAvg;
SimRobot.GetWorldPosition(RobotLinkInfo[SwingLimbIndex].AvgLocalContact, RobotLinkInfo[SwingLimbIndex].LinkIndex, SwingLimbAvg);
int FacetFlag = 0;
for (int i = 0; i < OptimalContact.size(); i++)
{
std::vector<Vector3> NewSPVertices = SPVertices;
Vector3 ShiftVec = OptimalContact[i] - SwingLimbAvg;
for (int j = 0; j < SwingLimbVertices.size(); j++)
{
NewSPVertices.push_back(SwingLimbVertices[j] + ShiftVec);
}
FacetInfo SPObj = FlatContactHullGeneration(NewSPVertices, FacetFlag); // This is the support polygon
COM_Pos.z = 0.0;
double COMDist = SPObj.ProjPoint2EdgeDist(COM_Pos);
std::pair<Vector3, double> ContactPair_i = std::make_pair(OptimalContact[i], COMDist) ;
ContactPairVec.push_back(ContactPair_i);
}
/* Method 2: Random Selection */
// std::vector<int> OptimalContactIndices(OptimalContact.size());
// for (int i = 0; i < OptimalContact.size(); i++)
// {
// OptimalContactIndices[i] = i;
// }
//
// unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
// std::default_random_engine e(seed);
// std::shuffle(std::begin(OptimalContactIndices), std::end(OptimalContactIndices), e);
// std::vector<Vector3> ReducedOptimalContact;
// if(OptimalContactIndices.size()>CutOffNo)
// {
// for (int i = 0; i < CutOffNo; i++)
// {
// ReducedOptimalContact.push_back(OptimalContact[OptimalContactIndices[i]]);
// }
// }
// else
// {
// ReducedOptimalContact = OptimalContact;
// }
// /* Method 3: Momentum Projection */
// std::vector<std::pair<Vector3, double>> ContactPairVec;
// ContactPairVec.reserve(OptimalContact.size());
// Vector3 RotAxis = PIPObj.x_unit;
// Vector3 RefPoint = PIPObj.Intersection;
// for (int i = 0; i < OptimalContact.size(); i++)
// {
// Vector3 ContactForceNorm = NonlinearOptimizerInfo::SDFInfo.SignedDistanceNormal(OptimalContact[i]);
// Vector3 SupportMomentum = cross(ContactForceNorm, OptimalContact[i] - RefPoint);
// double SupportMomentumProj = RotAxis.dot(SupportMomentum);
// std::pair<Vector3, double> ContactPair_i = std::make_pair(OptimalContact[i], SupportMomentumProj) ;
// ContactPairVec.push_back(ContactPair_i);
// }
// /* Method 4: Centroidal Direction */
// std::vector<std::pair<Vector3, double>> ContactPairVec;
// ContactPairVec.reserve(OptimalContact.size());
// for (int i = 0; i < OptimalContact.size(); i++)
// {
// double SupportMomentumProj = COMVel.dot(OptimalContact[i] - COM_Pos);
// std::pair<Vector3, double> ContactPair_i = std::make_pair(OptimalContact[i], SupportMomentumProj) ;
// ContactPairVec.push_back(ContactPair_i);
// }
sort(ContactPairVec.begin(), ContactPairVec.end(), ContactPairCMP);
std::vector<Vector3> ReducedOptimalContact;
if(ContactPairVec.size()>CutOffNo)
{
for (int i = 0; i < CutOffNo; i++)
{
ReducedOptimalContact.push_back(ContactPairVec[i].first);
}
}
else
{
for (int i = 0; i < ContactPairVec.size(); i++)
{
ReducedOptimalContact.push_back(ContactPairVec[i].first);
}
}
// In The End we give all these values
DataRecorderObj.ActiveReachableContact = ActiveReachableContact;
DataRecorderObj.ContactFreeContact = ContactFreeContact;
DataRecorderObj.SupportContact = SupportContact;
DataRecorderObj.OptimalContact = OptimalContact;
DataRecorderObj.ReducedOptimalContact = ReducedOptimalContact;
// Vector3Writer(ReducedOptimalContact, "ReducedOptimalContact");
return ReducedOptimalContact;
}
static double MinimumTimeEstimation(Robot & SimRobot, std::vector<int> & SwingLimbChain, const Config & qInit, const Config & qGoal)
{
std::vector<double> ExecutationTime(SwingLimbChain.size());
for (int i = 0; i < SwingLimbChain.size(); i++)
{
double ConfigDiff = qGoal[SwingLimbChain[i]] - qInit[SwingLimbChain[i]];
ExecutationTime[i] = abs(ConfigDiff/SimRobot.velMax(SwingLimbChain[i]));
}
return *std::max_element(ExecutationTime.begin(), ExecutationTime.end());
}
static ControlReferenceInfo ControlReferenceGenerationInner(const Robot & SimRobot, const PIPInfo & PIPObj, const Vector3 & PredictedCOMPos, ReachabilityMap & RMObject, SelfLinkGeoInfo & SelfLinkGeoObj, const std::vector<LinkInfo> & RobotLinkInfo, const std::vector<ContactStatusInfo> & FixedRobotContactInfo, const int & SwingLimbIndex, const int & Type, const double & RefFailureMetric, DataRecorderInfo & DataRecorderObj)
{
ControlReferenceInfo ControlReferenceObj;
Vector3 ContactInit; // This is the position of the reference contact for robot's active end effector.
SimRobot.GetWorldPosition(RobotLinkInfo[SwingLimbIndex].AvgLocalContact, RobotLinkInfo[SwingLimbIndex].LinkIndex, ContactInit);
Vector3 COMPos(0.0, 0.0, 0.0), COMVel(0.0, 0.0, 0.0);
CentroidalState(SimRobot, COMPos, COMVel);
std::vector<Vector3> OptimalContact = OptimalContactSearcher(SimRobot, PIPObj, PredictedCOMPos, RMObject, RobotLinkInfo, FixedRobotContactInfo, SwingLimbIndex, RefFailureMetric, DataRecorderObj);
switch (OptimalContact.size())
{
case 0:
{
return ControlReferenceObj;
}
break;
default:
{
// Now too early to assume that FailureFlag is true.
bool FeasiFlag;
std::vector<SplineLib::cSpline3> SplineObj;
int OptimalContactIndex = 0;
while(OptimalContactIndex<OptimalContact.size())
{
Robot SimRobotInner = SimRobot;
Vector3 ContactGoal = OptimalContact[OptimalContactIndex];
Vector3 ContactGoalGrad = NonlinearOptimizerInfo::SDFInfo.SignedDistanceNormal(ContactGoal);
SplineObj = TransientTrajGene(SimRobotInner, SwingLimbIndex, SelfLinkGeoObj, RobotLinkInfo, ContactInit, ContactGoal, RMObject, DataRecorderObj, FeasiFlag);
if(FeasiFlag)
{
EndPathInfo EndPathObj(SplineObj, SwingLimbIndex);
InvertedPendulumInfo InvertedPendulumObj(PIPObj.theta, PIPObj.thetadot, COMPos, COMVel);
/*
1. At each sampled waypoints along the end effector trajectory, an end effector position is evaluated from path.
2. Based on robot's current configuration, an IK problem is solved to get robot's swing limb configuration.
3. A time-optimal executation duration is computed.
4. Based on that time, robot's whole-body configuration is updated with inverted pendulum model.
5. The whole algorithm terminates when robot's self-collision has been triggered or no feasible IK solution can be found.
*/
const int sNumber = 5; // 6 sampled points will be extracted from EndPathObj.
int sIndex = 1;
double sDiff = 1.0/(1.0 * sNumber - 1.0);
double sVal = 0.0;
Config CurrentConfig = SimRobotInner.q;
CurrentConfig = YPRShifter(CurrentConfig);
double CurrentTime = 0.0;
Vector3 CurrentContactPos = ContactInit;
std::vector<double> TimeTraj;
std::vector<Config> ConfigTraj;
std::vector<Vector3> EndEffectorTraj;
TimeTraj.reserve(sNumber);
ConfigTraj.reserve(sNumber);
EndEffectorTraj.reserve(sNumber);
TimeTraj.push_back(CurrentTime);
ConfigTraj.push_back(CurrentConfig);
EndEffectorTraj.push_back(CurrentContactPos);
bool OptFlag = true;
while((sIndex<sNumber)&&(OptFlag == true))
{
sVal = 1.0 * sIndex * sDiff;
EndPathObj.s2Pos(sVal, CurrentContactPos);
bool LastFlag;
switch (sIndex)
{
case 4: LastFlag = true;
break;
default: LastFlag = false;
break;
}
std::vector<double> OptConfig = TransientOptFn(SimRobotInner, SwingLimbIndex, SelfLinkGeoObj, CurrentContactPos, RMObject, OptFlag, LastFlag);;
if(OptFlag)
{
// Minimum Time Estimation.
double CurrentTime_i = MinimumTimeEstimation(SimRobotInner, RMObject.EndEffectorLink2Pivotal[SwingLimbIndex], CurrentConfig, Config(OptConfig));
CurrentTime+=CurrentTime_i;
TimeTraj.push_back(CurrentTime);
ConfigTraj.push_back(Config(OptConfig));
EndEffectorTraj.push_back(CurrentContactPos);
// Then we should update the robot's CurrentConfig based on CurrentTime_i.
Config UpdatedConfig = WholeBodyDynamicsIntegrator(SimRobotInner, OptConfig, PIPObj, InvertedPendulumObj, CurrentTime_i, sIndex);
SimRobotInner.UpdateConfig(UpdatedConfig);
CurrentConfig = UpdatedConfig;
}
else
{
break;
}
sIndex++;
}
// Here the inner optimiztion loop has been finished!
if(OptFlag)
{
ControlReferenceObj.TrajectoryUpdate(TimeTraj, ConfigTraj, EndEffectorTraj, ContactGoal, ContactGoalGrad, EndPathObj.TotalLength, Type);
std::vector<ContactStatusInfo> GoalContactInfo = FixedRobotContactInfo;
for(int i = 0; i<FixedRobotContactInfo[SwingLimbIndex].LocalContactStatus.size(); i++)
{
GoalContactInfo[SwingLimbIndex].LocalContactStatus[i] = 1;
}
ControlReferenceObj.InitContactInfo = FixedRobotContactInfo;
ControlReferenceObj.GoalContactInfo = GoalContactInfo;
DataRecorderObj.OptConfigs = ConfigTraj;
return ControlReferenceObj;
}
}
OptimalContactIndex++;
}
}
break;
}
return ControlReferenceObj;
}
ControlReferenceInfo ControlReferenceGeneration(Robot & SimRobot, const Vector3 & COMPos, const Vector3 & COMVel, const double & RefFailureMetric, const std::vector<ContactStatusInfo> & RobotContactInfo, ReachabilityMap & RMObject, SelfLinkGeoInfo & SelfLinkGeoObj, const double & TimeStep, double & PlanTime, const string & SpecificPath, const int & PlanningSteps, const double & DistTol, const int & ContactStatusOptionRef, int & PreviousContactStatusIndex, const double & CurTime)
{
// The whole planning algorithm should be written here.
// The high-level idea is to plan individual end effector's configuration trajectory.
AllContactStatusInfo AllContactStatusObj = SwingLimbIndices(SimRobot, RobotContactInfo);
std::clock_t start_time = std::clock(); // get current time
int ContactStatusOption = 0;
int LimbSuccessNo = 0;
std::vector<ControlReferenceInfo> RobotTrajVec;
ControlReferenceInfo RobotTraj;
std::vector<double> ExeTimeVec;
std::vector<int> ContactStatusOptionVec;
std::vector<double> EndPathLengthVec;
for(ContactStatusOption = 0; ContactStatusOption< AllContactStatusObj.ContactStatusInfoVec.size(); ContactStatusOption++){
if(ContactStatusOptionRef!=-1){
if(ContactStatusOption!=ContactStatusOptionRef){
continue;
}
}
std::vector<ContactStatusInfo> RobotContactInfo = AllContactStatusObj.ContactStatusInfoVec[ContactStatusOption];
int SwingLimbIndex = AllContactStatusObj.SwingLimbIndices[ContactStatusOption];
std::vector<Vector3> ActContactPos = ContactPositionFinder(SimRobot, NonlinearOptimizerInfo::RobotLinkInfo, RobotContactInfo); // From ContactInfoActive
DataRecorderInfo DataRecorderObj;
// Here TipOverPIP needs to be computed given RobotContactInfo!
Vector3 PredictedCOMPos;
PIPInfo TipOverPIP = TipOverPIPGene(ActContactPos, COMPos, COMVel, PredictedCOMPos);
RobotTraj = ControlReferenceGenerationInner(SimRobot, TipOverPIP, PredictedCOMPos, RMObject, SelfLinkGeoObj, NonlinearOptimizerInfo::RobotLinkInfo, RobotContactInfo, SwingLimbIndex, AllContactStatusObj.ContactTypeVec[ContactStatusOption], RefFailureMetric, DataRecorderObj);
RobotTraj.SwingLimbIndex = SwingLimbIndex;
RobotTraj.ContactStatusOptionIndex = ContactStatusOption;
double duration_time = (std::clock() - start_time)/(double)CLOCKS_PER_SEC;
std::printf("Planning takes: %f ms\n", 1000.0 * duration_time);
start_time = std::clock(); // get current time
RobotTraj.PlanningTime = 1000.0 * duration_time; // The unit is ms.
PlanTime+= 1000.0 * duration_time;
if(RobotTraj.ControlReferenceFlag)
{
DataRecorderObj.PlanningNo = PlanningSteps;
DataRecorderObj.LimbNo = LimbSuccessNo;
DataRecorderObj.DataRecorder(SpecificPath);
for (int i = 0; i < DataRecorderObj.OptConfigs.size(); i++)
{
const string OptConfigFile = std::to_string(PlanningSteps) + "_" + std::to_string(LimbSuccessNo) + "_" + "OptConfig" + std::to_string(i) + ".config";
RobotConfigWriter(DataRecorderObj.OptConfigs[i], SpecificPath, OptConfigFile);
}
LimbSuccessNo++;
RobotTrajVec.push_back(RobotTraj);
ExeTimeVec.push_back(RobotTraj.PlanStateTraj.EndTime());
ContactStatusOptionVec.push_back(ContactStatusOption);
EndPathLengthVec.push_back(RobotTraj.PathLength);
}
}
// Based on the value of the impulse, let's select the one with the lowest impulse.
switch (RobotTrajVec.size())
{
case 0:
{
std::printf("Planning fails to find a feasible solution! \n");
// Planning fails to find a feasible solution!
return RobotTraj;
}
break;
default:
{
PlanningInfoFileAppender(PlanningSteps, RobotTrajVec.size()-1, SpecificPath, CurTime);
int RobotTrajIndex = EndEffectorSelector(ExeTimeVec, EndPathLengthVec, ContactStatusOptionVec, PreviousContactStatusIndex);
std::printf("Planning successfully finds a feasible solution! \nRobot Limb Index: %d\n", NonlinearOptimizerInfo::RobotLinkInfo[RobotTrajVec[RobotTrajIndex].SwingLimbIndex].LinkIndex);
RobotTraj = RobotTrajVec[RobotTrajIndex];
if(PreviousContactStatusIndex!=RobotTraj.ContactStatusOptionIndex) PreviousContactStatusIndex = RobotTraj.ContactStatusOptionIndex;
}
break;
}
return RobotTraj;
}
double PresumeContactMinDis(Robot & SimRobot, const std::vector<ContactStatusInfo> & RobotContactInfo)
{
// This function calculates the maximum distance of minimum end effectors.
double Dis = 0.0;
double ContactDist;
std::vector<double> ContactDisVec;
for (int i = 0; i < RobotContactInfo.size(); i++)
{
switch (RobotContactInfo[i].LocalContactStatus[0])
{
case 1:
{
ContactDist = 100000.0;
for(int j = 0; j < NonlinearOptimizerInfo::RobotLinkInfo[i].LocalContacts.size(); j++)
{
Vector3 ContactPos;
SimRobot.GetWorldPosition(NonlinearOptimizerInfo::RobotLinkInfo[i].LocalContacts[j], RobotContactInfo[i].LinkIndex, ContactPos);
double RefPosDist = NonlinearOptimizerInfo::SDFInfo.SignedDistance(ContactPos);
if(ContactDist>RefPosDist)
{
ContactDist = RefPosDist;
}
}
}
break;
default:
ContactDist = 0.0;
break;
}
ContactDisVec.push_back(ContactDist);
}
return *max_element(ContactDisVec.begin(), ContactDisVec.end());
}
| 39.446352 | 483 | 0.687049 | [
"vector",
"model"
] |
677bfe12aeec846ec7ee84396501d3f2095fc4a1 | 791 | cpp | C++ | zigzag-conversion.cpp | c650/leetcode | 3042d2d144575f3b2a43a2da95b33973b849a9d1 | [
"MIT"
] | 1 | 2020-06-21T17:31:04.000Z | 2020-06-21T17:31:04.000Z | zigzag-conversion.cpp | c650/leetcode | 3042d2d144575f3b2a43a2da95b33973b849a9d1 | [
"MIT"
] | null | null | null | zigzag-conversion.cpp | c650/leetcode | 3042d2d144575f3b2a43a2da95b33973b849a9d1 | [
"MIT"
] | 2 | 2020-07-17T16:01:10.000Z | 2020-10-31T05:40:28.000Z | class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) {
return s;
}
std::vector<std::string> ret(numRows);
const int n = s.length();
bool down = true;
for (int i = 0, tr = 0; i < n; ++i) {
ret[tr].push_back(s[i]);
if (down && tr == numRows - 1) {
down = false;
--tr;
} else if (!down && tr == 0) {
down = true;
++tr;
} else {
tr += down ? 1 : -1;
}
}
std::stringstream ss;
for (auto& e : ret) {
ss << e;
}
return ss.str();
}
};
| 22.6 | 46 | 0.323641 | [
"vector"
] |
678e13af077bd85147d8724592b66c262446e2b5 | 1,138 | cpp | C++ | test/either/match.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | test/either/match.cpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | test/either/match.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/catch/begin.hpp>
#include <fcppt/catch/end.hpp>
#include <fcppt/either/match.hpp>
#include <fcppt/either/object.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <string>
#include <fcppt/config/external_end.hpp>
FCPPT_CATCH_BEGIN
TEST_CASE("either::match", "[either]")
{
using either_int = fcppt::either::object<std::string, int>;
auto const success_function(
[](int const _value) { return std::string("success: ") + std::to_string(_value); });
auto const failure_function(
[](std::string const &_value) { return std::string("failure: ") + _value; });
CHECK(
fcppt::either::match(either_int(std::string("test")), failure_function, success_function) ==
std::string("failure: test"));
CHECK(
fcppt::either::match(either_int(42), failure_function, success_function) ==
std::string("success: 42"));
}
FCPPT_CATCH_END
| 30.756757 | 98 | 0.689807 | [
"object"
] |
096b05a9af8729f2011a30243d1c06fbb13e8eae | 23,340 | cpp | C++ | matchmaking/match_searcher.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | cstrike15_src/matchmaking/match_searcher.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | cstrike15_src/matchmaking/match_searcher.cpp | bahadiraraz/Counter-Strike-Global-Offensive | 9a0534100cb98ffa1cf0c32e138f0e7971e910d3 | [
"MIT"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | //===== Copyright � 1996-2009, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
//===========================================================================//
#include "mm_framework.h"
#include "vstdlib/random.h"
#include "fmtstr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
static ConVar mm_session_search_num_results( "mm_session_search_num_results", "10", FCVAR_DEVELOPMENTONLY );
static ConVar mm_session_search_distance( "mm_session_search_distance", "1", FCVAR_DEVELOPMENTONLY );
ConVar mm_session_search_qos_timeout( "mm_session_search_qos_timeout", "15.0", FCVAR_RELEASE );
// static ConVar mm_session_search_ping_limit( "mm_session_search_ping_limit", "200", FCVAR_RELEASE ); -- removed, using mm_dedicated_search_maxping instead
static ConVar mm_session_search_ping_buckets( "mm_session_search_ping_buckets", "4", FCVAR_RELEASE );
CMatchSearcher::CMatchSearcher( KeyValues *pSettings ) :
m_pSettings( pSettings ), // takes ownership
m_autodelete_pSettings( m_pSettings ),
m_pSessionSearchTree( NULL ),
m_autodelete_pSessionSearchTree( m_pSessionSearchTree ),
m_pSearchPass( NULL ),
m_eState( STATE_INIT )
{
#ifdef _X360
ZeroMemory( &m_xOverlapped, sizeof( m_xOverlapped ) );
m_pQosResults = NULL;
m_pCancelOverlappedJob = NULL;
#endif
DevMsg( "Created CMatchSearcher:\n" );
KeyValuesDumpAsDevMsg( m_pSettings, 1 );
InitializeSettings();
}
CMatchSearcher::~CMatchSearcher()
{
DevMsg( "Destroying CMatchSearcher:\n" );
KeyValuesDumpAsDevMsg( m_pSettings, 1 );
// Free all retrieved game details
CUtlVector< SearchResult_t > *arrResults[] = { &m_arrSearchResults, &m_arrSearchResultsAggregate };
for ( int ia = 0; ia < ARRAYSIZE( arrResults ); ++ ia )
{
for ( int k = 0; k < arrResults[ia]->Count(); ++ k )
{
SearchResult_t &sr = arrResults[ia]->Element( k );
if ( sr.m_pGameDetails )
{
sr.m_pGameDetails->deleteThis();
sr.m_pGameDetails = NULL;
}
}
}
}
void CMatchSearcher::InitializeSettings()
{
// Initialize only the settings required to connect...
if ( KeyValues *kv = m_pSettings->FindKey( "system", true ) )
{
KeyValuesAddDefaultString( kv, "network", "LIVE" );
KeyValuesAddDefaultString( kv, "access", "public" );
}
if ( KeyValues *pMembers = m_pSettings->FindKey( "members", true ) )
{
int numMachines = pMembers->GetInt( "numMachines", -1 );
if ( numMachines == -1 )
{
numMachines = 1;
pMembers->SetInt( "numMachines", numMachines );
}
int numPlayers = pMembers->GetInt( "numPlayers", -1 );
if ( numPlayers == -1 )
{
numPlayers = 1;
#ifdef _GAMECONSOLE
numPlayers = XBX_GetNumGameUsers();
#endif
pMembers->SetInt( "numPlayers", numPlayers );
}
pMembers->SetInt( "numSlots", numPlayers );
KeyValues *pMachine = pMembers->FindKey( "machine0");
if ( !pMachine )
{
pMachine = pMembers->CreateNewKey();
pMachine->SetName( "machine0" );
XUID machineid = g_pPlayerManager->GetLocalPlayer( XBX_GetPrimaryUserId() )->GetXUID();
pMachine->SetUint64( "id", machineid );
pMachine->SetUint64( "flags", MatchSession_GetMachineFlags() );
pMachine->SetInt( "numPlayers", numPlayers );
pMachine->SetUint64( "dlcmask", g_pMatchFramework->GetMatchSystem()->GetDlcManager()->GetDataInfo()->GetUint64( "@info/installed" ) );
pMachine->SetString( "tuver", MatchSession_GetTuInstalledString() );
pMachine->SetInt( "ping", 0 );
for ( int k = 0; k < numPlayers; ++ k )
{
if ( KeyValues *pPlayer = pMachine->FindKey( CFmtStr( "player%d", k ), true ) )
{
int iController = 0;
#ifdef _GAMECONSOLE
iController = XBX_GetUserId( k );
#endif
IPlayerLocal *player = g_pPlayerManager->GetLocalPlayer( iController );
pPlayer->SetUint64( "xuid", player->GetXUID() );
pPlayer->SetString( "name", player->GetName() );
}
}
}
}
DevMsg( "CMatchSearcher::InitializeGameSettings adjusted settings:\n" );
KeyValuesDumpAsDevMsg( m_pSettings, 1 );
}
KeyValues * CMatchSearcher::GetSearchSettings()
{
return m_pSettings;
}
void CMatchSearcher::Destroy()
{
// Stop the search
if ( m_eState == STATE_SEARCHING )
{
#ifdef _X360
m_pCancelOverlappedJob = ThreadExecute( MMX360_CancelOverlapped, &m_xOverlapped ); // UpdateDormantOperations will clean the rest
MMX360_RegisterDormant( this );
return;
#endif
}
#ifdef _X360
if ( m_eState == STATE_CHECK_QOS )
{
g_pMatchExtensions->GetIXOnline()->XNetQosRelease( m_pQosResults );
m_pQosResults = NULL;
}
#endif
#if !defined( NO_STEAM )
while ( m_arrOutstandingAsyncOperation.Count() > 0 )
{
IMatchAsyncOperation *pAsyncOperation = m_arrOutstandingAsyncOperation.Tail();
m_arrOutstandingAsyncOperation.RemoveMultipleFromTail( 1 );
if ( pAsyncOperation )
pAsyncOperation->Release();
}
#endif
delete this;
}
void CMatchSearcher::OnSearchEvent( KeyValues *pNotify )
{
g_pMatchEventsSubscription->BroadcastEvent( pNotify );
}
#ifdef _X360
bool CMatchSearcher::UpdateDormantOperation()
{
if ( !m_pCancelOverlappedJob->IsFinished() )
return true; // keep running dormant
m_pCancelOverlappedJob->Release();
m_pCancelOverlappedJob = NULL;
delete this;
return false; // destroyed object, remove from dormant list
}
#endif
void CMatchSearcher::Update()
{
switch ( m_eState )
{
case STATE_INIT:
m_eState = STATE_SEARCHING;
// Session is searching
OnSearchEvent( new KeyValues(
"OnMatchSessionUpdate",
"state", "progress",
"progress", "searching"
) );
// Kick off the search
StartSearch();
break;
case STATE_SEARCHING:
// Waiting for session search to complete
#ifdef _X360
if ( XHasOverlappedIoCompleted( &m_xOverlapped ) )
Live_OnSessionSearchCompleted();
#endif
break;
#ifdef _X360
case STATE_CHECK_QOS:
// Keep checking for results or until the wait time expires
if ( Plat_FloatTime() > m_flQosTimeout ||
!m_pQosResults->cxnqosPending )
Live_OnQosCheckCompleted();
break;
#endif
#if !defined (NO_STEAM)
case STATE_WAITING_LOBBY_DATA_AND_PING:
{
bool bWaitLonger = ( ( Plat_MSTime() - m_uiQosTimeoutStartMS ) < ( mm_session_search_qos_timeout.GetFloat() * 1000.f ) );
if ( bWaitLonger )
{
bool bHasPendingLobbyData = false;
for ( int j = 0; j < m_arrSearchResults.Count(); ++ j )
{
SearchResult_t &sr = m_arrSearchResults[j];
if ( !sr.m_numPlayers )
{ // didn't even receive lobby data from Steam yet
bHasPendingLobbyData = true;
}
else if ( sr.m_svAdr.GetIPHostByteOrder() && ( sr.m_svPing <= 0 ) )
{ // received valid IP for lobby, still pinging
bHasPendingLobbyData = true;
}
}
if ( !bHasPendingLobbyData )
bWaitLonger = false;
}
if ( !bWaitLonger )
{
m_CallbackOnLobbyDataReceived.Unregister();
// Go ahead and start joining the results
AggregateSearchPassResults();
OnSearchPassDone( m_pSearchPass );
}
}
break;
#endif
}
}
#if !defined (NO_STEAM)
void CMatchSearcher::Steam_OnLobbyDataReceived( LobbyDataUpdate_t *pLobbyDataUpdate )
{
int iResultIndex = 0;
for ( ; iResultIndex < m_arrSearchResults.Count(); ++ iResultIndex )
{
if ( m_arrSearchResults[ iResultIndex ].m_uiLobbyId == pLobbyDataUpdate->m_ulSteamIDLobby )
break;
}
if ( !m_arrSearchResults.IsValidIndex( iResultIndex ) )
return;
SearchResult_t *pRes = &m_arrSearchResults[ iResultIndex ];
if ( !pLobbyDataUpdate->m_bSuccess )
{
DevMsg( "[MM] Could not get lobby data for lobby %llu (%llx)\n",
pRes->m_uiLobbyId, pRes->m_uiLobbyId );
pRes->m_numPlayers = -1; // set numPlayers to negative number to indicate a failure here
}
else
{
// Get num players
const char *numPlayers = steamapicontext->SteamMatchmaking()->GetLobbyData(
pRes->m_uiLobbyId, "members:numPlayers" );
if ( !numPlayers )
{
DevMsg( "[MM] Unable to get num players for lobby (%llx)\n",
pRes->m_uiLobbyId );
pRes->m_numPlayers = -1; // set numPlayers to negative number to indicate a failure here
}
else
{
pRes->m_numPlayers = V_atoi( numPlayers );
if ( !pRes->m_numPlayers )
pRes->m_numPlayers = -1; // set numPlayers to negative number to indicate a failure here
}
// Get the address of the server
const char* pServerAdr = steamapicontext->SteamMatchmaking()->GetLobbyData(
pRes->m_uiLobbyId, "server:adronline" );
if ( !pServerAdr )
{
// DevMsg( "[MM] Unable to get server address from lobby (%llx)\n",
// pRes->m_uiLobbyId );
}
else
{
pRes->m_svAdr.SetFromString( pServerAdr );
DevMsg ( "[MM] Lobby %d: id %llu (%llx), num Players %d, sv ip %s, pinging dist %d\n",
iResultIndex, pRes->m_uiLobbyId, pRes->m_uiLobbyId, pRes->m_numPlayers,
pRes->m_svAdr.ToString(), pRes->m_svPing );
// Ping server
IMatchAsyncOperation *pAsyncOperationPing = NULL;
g_pMatchExtensions->GetINetSupport()->ServerPing( pRes->m_svAdr, this, &pAsyncOperationPing );
m_arrOutstandingAsyncOperation.AddToTail( pAsyncOperationPing );
pRes->m_pAsyncOperationPingWeakRef = pAsyncOperationPing;
}
}
}
// Callback for server reservation check
void CMatchSearcher::OnOperationFinished( IMatchAsyncOperation *pOperation )
{
if ( !pOperation )
return;
if ( m_eState != STATE_WAITING_LOBBY_DATA_AND_PING )
return;
for ( int i = 0; i < m_arrSearchResults.Count(); ++ i )
{
if ( m_arrSearchResults[i].m_pAsyncOperationPingWeakRef != pOperation )
continue;
int result = pOperation->GetResult();
bool failed = ( pOperation->GetState() == AOS_FAILED );
SearchResult_t *pRes = &m_arrSearchResults[i];
pRes->m_svPing = ( failed ? -1 : ( result ? result : -1 ) );
if ( pRes->m_svPing < 0 )
{
DevMsg( "[MM] Failed pinging server %s for lobby#%d %llu (%llx)\n",
pRes->m_svAdr.ToString(), i, pRes->m_uiLobbyId, pRes->m_uiLobbyId );
}
else
{
DevMsg( "[MM] Successfully pinged server %s for lobby#%d %llu (%llx) = %d ms\n",
pRes->m_svAdr.ToString(), i, pRes->m_uiLobbyId, pRes->m_uiLobbyId, pRes->m_svPing );
}
m_arrSearchResults[i].m_pAsyncOperationPingWeakRef = NULL;
}
}
#endif
void CMatchSearcher::OnSearchDone()
{
m_eState = STATE_DONE;
}
void CMatchSearcher::AggregateSearchPassResults()
{
#ifndef NO_STEAM
extern ConVar mm_dedicated_search_maxping;
int nPingLimitMax = mm_dedicated_search_maxping.GetInt();
if ( nPingLimitMax <= 0 )
nPingLimitMax = 5000;
for ( int k = 0; k < mm_session_search_ping_buckets.GetInt(); ++ k )
{
int iPingLow = ( nPingLimitMax * k ) / mm_session_search_ping_buckets.GetInt();
int iPingHigh = ( nPingLimitMax * ( k + 1 ) ) / mm_session_search_ping_buckets.GetInt();
for ( int iResult = 0; iResult < m_arrSearchResults.Count(); ++ iResult )
{
SearchResult_t *pRes = &m_arrSearchResults[iResult];
if ( ( pRes->m_svPing > iPingLow ) && ( pRes->m_svPing <= iPingHigh ) )
{
m_arrSearchResultsAggregate.AddToTail( *pRes );
DevMsg ( "[MM] Search aggregated result%d / %d: id %llu (%llx), num Players %d, sv ip %s, dist %d\n",
m_arrSearchResultsAggregate.Count(), iResult, pRes->m_uiLobbyId, pRes->m_uiLobbyId, pRes->m_numPlayers,
pRes->m_svAdr.ToString(), pRes->m_svPing );
}
}
}
DevMsg ( "[MM] Search aggregated %d results\n", m_arrSearchResultsAggregate.Count() );
#endif
m_arrSearchResults.Purge();
}
void CMatchSearcher::OnSearchPassDone( KeyValues *pSearchPass )
{
// If we have enough results, then call it done
if ( m_arrSearchResultsAggregate.Count() >= mm_session_search_num_results.GetInt() )
{
OnSearchDone();
return;
}
// Evaluate if there is a nextpass condition
char const *szNextPassKeyName = "nextpass";
if ( KeyValues *pConditions = pSearchPass->FindKey( "nextpass?" ) )
{
// Inspect conditions and select which next pass will happen
}
if ( KeyValues *pNextPass = pSearchPass->FindKey( szNextPassKeyName ) )
{
StartSearchPass( pNextPass );
}
else
{
OnSearchDone();
}
}
#ifdef _X360
void CMatchSearcher::Live_OnSessionSearchCompleted()
{
DevMsg( "Received %d search results from Xbox LIVE.\n", GetXSearchResult()->dwSearchResults );
for( unsigned int i = 0; i < GetXSearchResult()->dwSearchResults; ++ i )
{
XSESSION_SEARCHRESULT const &xsr = GetXSearchResult()->pResults[i];
SearchResult_t sr = { xsr.info, NULL };
m_arrSearchResults.AddToTail( sr );
DevMsg( 2, "Result #%02d: %llx\n", i + 1, ( const uint64& ) xsr.info.sessionID );
}
if ( !m_arrSearchResults.Count() )
{
OnSearchPassDone( m_pSearchPass );
}
else
{
DevMsg( "Checking QOS with %d search results.\n", m_arrSearchResults.Count() );
Live_CheckSearchResultsQos();
}
}
void CMatchSearcher::Live_CheckSearchResultsQos()
{
m_eState = STATE_CHECK_QOS;
int nResults = m_arrSearchResults.Count();
CUtlVector< const void * > memQosData;
memQosData.SetCount( 3 * nResults );
const void ** bufQosData[3];
for ( int k = 0; k < ARRAYSIZE( bufQosData ); ++ k )
bufQosData[k] = &memQosData[ k * nResults ];
for ( int k = 0; k < m_arrSearchResults.Count(); ++ k )
{
SearchResult_t const &sr = m_arrSearchResults[k];
bufQosData[0][k] = &sr.m_info.hostAddress;
bufQosData[1][k] = &sr.m_info.sessionID;
bufQosData[2][k] = &sr.m_info.keyExchangeKey;
}
//
// Note: XNetQosLookup requires only 2 successful probes to be received from the host.
// This is much less than the recommended 8 probes because on a 10% data loss profile
// it is impossible to find the host when requiring 8 probes to be received.
m_flQosTimeout = Plat_FloatTime() + mm_session_search_qos_timeout.GetFloat();
int res = g_pMatchExtensions->GetIXOnline()->XNetQosLookup(
nResults,
reinterpret_cast< XNADDR const ** >( bufQosData[0] ),
reinterpret_cast< XNKID const ** >( bufQosData[1] ),
reinterpret_cast< XNKEY const ** >( bufQosData[2] ),
0, // number of security gateways to probe
NULL, // gateway ip addresses
NULL, // gateway service ids
2, // number of probes
0, // upstream bandwith to use (0 = default)
0, // flags - not supported
NULL, // signal event
&m_pQosResults );// results
if ( res != 0 )
{
DevWarning( "OnlineSearch::Live_CheckSearchResultsQos - XNetQosLookup failed (code = 0x%08X)!\n", res );
m_arrSearchResults.Purge();
OnSearchPassDone( m_pSearchPass );
}
}
void CMatchSearcher::Live_OnQosCheckCompleted()
{
for ( uint k = m_pQosResults->cxnqos; k --> 0; )
{
XNQOSINFO &xqi = m_pQosResults->axnqosinfo[k];
BYTE uNeedFlags = XNET_XNQOSINFO_TARGET_CONTACTED | XNET_XNQOSINFO_DATA_RECEIVED;
if ( ( ( xqi.bFlags & uNeedFlags ) != uNeedFlags) ||
( xqi.bFlags & XNET_XNQOSINFO_TARGET_DISABLED ) )
{
m_arrSearchResults.Remove( k );
continue;
}
extern ConVar mm_dedicated_search_maxping;
if ( mm_dedicated_search_maxping.GetInt() > 0 &&
xqi.wRttMedInMsecs > mm_dedicated_search_maxping.GetInt() )
{
m_arrSearchResults.Remove( k );
continue;
}
if ( xqi.cbData && xqi.pbData )
{
MM_GameDetails_QOS_t gd = { xqi.pbData, xqi.cbData, xqi.wRttMedInMsecs };
Assert( !m_arrSearchResults[k].m_pGameDetails );
m_arrSearchResults[k].m_pGameDetails = g_pMatchFramework->GetMatchNetworkMsgController()->UnpackGameDetailsFromQOS( &gd );
}
}
g_pMatchExtensions->GetIXOnline()->XNetQosRelease( m_pQosResults );
m_pQosResults = NULL;
// Go ahead and start joining the results
DevMsg( "Qos completed with %d search results.\n", m_arrSearchResults.Count() );
AggregateSearchPassResults();
OnSearchPassDone( m_pSearchPass );
}
#elif !defined( NO_STEAM )
void CMatchSearcher::Steam_OnLobbyMatchListReceived( LobbyMatchList_t *pLobbyMatchList, bool bError )
{
Msg( "[MM] Received %d search results.\n", bError ? 0 : pLobbyMatchList->m_nLobbiesMatching );
m_CallbackOnLobbyDataReceived.Register( this, &CMatchSearcher::Steam_OnLobbyDataReceived );
// Walk through search results and request lobby data
for ( int iLobby = 0; iLobby < (int) ( bError ? 0 : pLobbyMatchList->m_nLobbiesMatching ); ++ iLobby )
{
uint64 uiLobbyId = steamapicontext->SteamMatchmaking()->GetLobbyByIndex( iLobby ).ConvertToUint64();
SearchResult_t sr = { uiLobbyId };
sr.m_pGameDetails = NULL;
sr.m_svAdr.SetFromString( "0.0.0.0" );
sr.m_svPing = 0;
sr.m_numPlayers = 0;
sr.m_pAsyncOperationPingWeakRef = NULL;
m_arrSearchResults.AddToTail( sr );
steamapicontext->SteamMatchmaking()->RequestLobbyData( sr.m_uiLobbyId );
}
m_eState = STATE_WAITING_LOBBY_DATA_AND_PING; // Waiting for lobby data
m_uiQosPingLastMS = m_uiQosTimeoutStartMS = Plat_MSTime();
}
KeyValues * CMatchSearcher::SearchResult_t::GetGameDetails() const
{
if ( !m_pGameDetails )
{
m_pGameDetails = g_pMatchFramework->GetMatchNetworkMsgController()->UnpackGameDetailsFromSteamLobby( m_uiLobbyId );
}
return m_pGameDetails;
}
#endif
void CMatchSearcher::StartSearch()
{
Assert( !m_pSessionSearchTree );
m_pSessionSearchTree = g_pMMF->GetMatchTitleGameSettingsMgr()->DefineSessionSearchKeys( m_pSettings );
m_autodelete_pSessionSearchTree.Assign( m_pSessionSearchTree );
Assert( m_pSessionSearchTree );
if ( !m_pSessionSearchTree )
{
DevWarning( "OnlineSearch::StartSearch failed to build filter list!\n" );
OnSearchDone();
}
else
{
StartSearchPass( m_pSessionSearchTree );
}
}
void CMatchSearcher::StartSearchPass( KeyValues *pSearchPass )
{
KeyValues *pSearchParams = pSearchPass;
m_pSearchPass = pSearchPass;
// Make sure we have fresh buffer for search results
m_arrSearchResults.Purge();
m_eState = STATE_SEARCHING;
DevMsg( "OnlineSearch::StartSearchPass:\n" );
KeyValuesDumpAsDevMsg( pSearchParams, 1 );
#ifdef _X360
DWORD dwSearchRule = pSearchParams->GetInt( "rule" );
m_arrContexts.RemoveAll();
if ( KeyValues *pContexts = pSearchParams->FindKey( "Contexts" ) )
{
for ( KeyValues *val = pContexts->GetFirstValue(); val; val = val->GetNextValue() )
{
XUSER_CONTEXT ctx = { 0 };
ctx.dwContextId = atoi( val->GetName() );
if ( val->GetDataType() == KeyValues::TYPE_INT )
{
ctx.dwValue = val->GetInt();
m_arrContexts.AddToTail( ctx );
}
}
}
m_arrProperties.RemoveAll();
if ( KeyValues *pContexts = pSearchParams->FindKey( "Properties" ) )
{
for ( KeyValues *val = pContexts->GetFirstValue(); val; val = val->GetNextValue() )
{
XUSER_PROPERTY prop = { 0 };
prop.dwPropertyId = atoi( val->GetName() );
if ( val->GetDataType() == KeyValues::TYPE_INT )
{
prop.value.type = XUSER_DATA_TYPE_INT32;
prop.value.nData = val->GetInt();
m_arrProperties.AddToTail( prop );
}
}
}
DWORD ret = ERROR_SUCCESS;
DWORD numBytes = 0;
DWORD dwNumSlotsRequired = pSearchParams->GetInt( "numPlayers" );
//
// Issue the asynchrounous session search request
//
ret = g_pMatchExtensions->GetIXOnline()->XSessionSearchEx(
dwSearchRule, XBX_GetPrimaryUserId(), mm_session_search_num_results.GetInt(),
dwNumSlotsRequired,
m_arrProperties.Count(), m_arrContexts.Count(),
m_arrProperties.Base(), m_arrContexts.Base(),
&numBytes, NULL, NULL
);
// Log the search request to read X360 queries easier
DevMsg( "XSessionSearchEx by rule %d for slots %d\n", dwSearchRule, dwNumSlotsRequired );
for ( int k = 0; k < m_arrContexts.Count(); ++ k )
DevMsg( " CTX %u/0x%08X = 0x%X/%u\n", m_arrContexts[k].dwContextId, m_arrContexts[k].dwContextId, m_arrContexts[k].dwValue, m_arrContexts[k].dwValue );
for ( int k = 0; k < m_arrProperties.Count(); ++ k )
DevMsg( " PRP %u/0x%08X = 0x%X/%u\n", m_arrProperties[k].dwPropertyId, m_arrProperties[k].dwPropertyId, m_arrProperties[k].value.nData, m_arrProperties[k].value.nData );
DevMsg( "will use %u bytes buffer.\n", numBytes );
if ( ERROR_INSUFFICIENT_BUFFER == ret && numBytes > 0 )
{
m_bufSearchResultHeader.EnsureCapacity( numBytes );
ZeroMemory( GetXSearchResult(), numBytes );
ZeroMemory( &m_xOverlapped, sizeof( m_xOverlapped ) );
DevMsg( "Searching...\n" );
ret = g_pMatchExtensions->GetIXOnline()->XSessionSearchEx(
dwSearchRule, XBX_GetPrimaryUserId(), mm_session_search_num_results.GetInt(),
dwNumSlotsRequired,
m_arrProperties.Count(), m_arrContexts.Count(),
m_arrProperties.Base(), m_arrContexts.Base(),
&numBytes, GetXSearchResult(), &m_xOverlapped
);
if ( ret == ERROR_IO_PENDING )
return;
}
// Otherwise search failed
DevWarning( "XSessionSearchEx failed (code = 0x%08X)\n", ret );
ZeroMemory( &m_xOverlapped, sizeof( m_xOverlapped ) );
OnSearchPassDone( m_pSearchPass );
#elif !defined( NO_STEAM )
ISteamMatchmaking *mm = steamapicontext->SteamMatchmaking();
// Configure filters
DWORD dwNumSlotsRequired = pSearchParams->GetInt( "numPlayers" );
mm->AddRequestLobbyListFilterSlotsAvailable( dwNumSlotsRequired );
// Set filters
char const * arrKeys[] = { "Filter<", "Filter<=", "Filter=", "Filter<>", "Filter>=", "Filter>" };
ELobbyComparison nValueCmp[] = { k_ELobbyComparisonLessThan, k_ELobbyComparisonEqualToOrLessThan, k_ELobbyComparisonEqual, k_ELobbyComparisonNotEqual, k_ELobbyComparisonEqualToOrGreaterThan, k_ELobbyComparisonGreaterThan };
for ( int k = 0; k < ARRAYSIZE( arrKeys ); ++ k )
{
if ( KeyValues *kv = pSearchParams->FindKey( arrKeys[k] ) )
{
for ( KeyValues *val = kv->GetFirstValue(); val; val = val->GetNextValue() )
{
if ( val->GetDataType() == KeyValues::TYPE_STRING )
{
mm->AddRequestLobbyListStringFilter( val->GetName(), val->GetString(), nValueCmp[k] );
}
else if ( val->GetDataType() == KeyValues::TYPE_INT )
{
mm->AddRequestLobbyListNumericalFilter( val->GetName(), val->GetInt(), nValueCmp[k] );
}
}
}
}
// Set ordering near values
if ( KeyValues *kv = pSearchParams->FindKey( "Near" ) )
{
for ( KeyValues *val = kv->GetFirstValue(); val; val = val->GetNextValue() )
{
if ( val->GetDataType() == KeyValues::TYPE_INT )
{
mm->AddRequestLobbyListNearValueFilter( val->GetName(), val->GetInt() );
}
else
{
// TODO: need to set near value filter for strings
}
}
}
ELobbyDistanceFilter eFilter = k_ELobbyDistanceFilterDefault;
switch ( mm_session_search_distance.GetInt() )
{
case k_ELobbyDistanceFilterClose:
case k_ELobbyDistanceFilterDefault:
case k_ELobbyDistanceFilterFar:
case k_ELobbyDistanceFilterWorldwide:
eFilter = ( ELobbyDistanceFilter ) mm_session_search_distance.GetInt();
break;
}
// Set distance filter to Near
mm->AddRequestLobbyListDistanceFilter( eFilter );
// Set dependent lobby
if ( uint64 uiDependentLobbyId = pSearchParams->GetUint64( "DependentLobby", 0ull ) )
{
mm->AddRequestLobbyListCompatibleMembersFilter( uiDependentLobbyId );
}
// RequestLobbyList - will get called back at Steam_OnLobbyMatchListReceived
DevMsg( "Searching...\n" );
SteamAPICall_t hCall = mm->RequestLobbyList();
m_CallbackOnLobbyMatchListReceived.Set( hCall, this, &CMatchSearcher::Steam_OnLobbyMatchListReceived );
#endif
}
//
// Results retrieval overrides
//
bool CMatchSearcher::IsSearchFinished() const
{
return m_eState == STATE_DONE;
}
int CMatchSearcher::GetNumSearchResults() const
{
return IsSearchFinished() ? m_arrSearchResultsAggregate.Count() : 0;
}
CMatchSearcher::SearchResult_t const & CMatchSearcher::GetSearchResult( int idx ) const
{
if ( !IsSearchFinished() || !m_arrSearchResultsAggregate.IsValidIndex( idx ) )
{
Assert( false );
static SearchResult_t s_empty;
return s_empty;
}
else
{
return m_arrSearchResultsAggregate[ idx ];
}
}
| 29.358491 | 224 | 0.705955 | [
"object"
] |
097c3e51a17e5771430f9cd5ab9127f90121d5ee | 2,648 | cpp | C++ | tp3-codage-de-hamming/src/main.cpp | SinanDaroukh/code-theory | cb6b69c19c74c6f18ea16b24c5249bf247de1747 | [
"MIT"
] | null | null | null | tp3-codage-de-hamming/src/main.cpp | SinanDaroukh/code-theory | cb6b69c19c74c6f18ea16b24c5249bf247de1747 | [
"MIT"
] | null | null | null | tp3-codage-de-hamming/src/main.cpp | SinanDaroukh/code-theory | cb6b69c19c74c6f18ea16b24c5249bf247de1747 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <bitset>
#include <vector>
/**
* Hamming (7,4)
**/
#define N 4
#define HAMMING_7 7
/**
* Debug macros
**/
#define DEBUG_RF true // Debug Information: Read File
#define DEBUG_HE true // Debug Information: Hamming Encoding
using namespace std;
/**
* vector<bitset<N> > readFile(string filename)
* Read a file in binary and create a vector of bitset wih a width of 4 for each bitset
* Return a vector bitset
**/
vector<bitset<N> > readFile(string filename)
{
vector<bitset<N> > content;
ifstream reader;
char buffer;
reader.open(filename.c_str(), ios::binary|ios::in);
if(DEBUG_RF)
cout << "Read : \t";
if(reader != NULL && reader.is_open())
{
while(!reader.eof())
{
reader.read(&buffer, 1);
bitset<N> bsBufferLSB(buffer);
bitset<N> bsBufferMSB(buffer>>4);
content.push_back(bsBufferMSB);
content.push_back(bsBufferLSB);
if(DEBUG_RF)
{
cout << " |" << bsBufferMSB.to_string();
cout << " |" << bsBufferLSB.to_string();
}
}
}
if(DEBUG_RF)
cout << endl;
reader.close();
return content;
}
/**
* vector<bitset<HAMMING_7> > HammingEncoding(vector<bitset<N> > bitsetVector)
* Convert a vector of bitset<4> into a hamming vector of bitset<7>
**/
vector<bitset<HAMMING_7> > HammingEncoding(vector<bitset<N> > bitsetVector)
{
vector<bitset<HAMMING_7> > encodedBitset;
if(DEBUG_HE)
std::cout << "Encode : \t";
for(vector<bitset<N> >::iterator i = bitsetVector.begin(); i != bitsetVector.end();++i)
{
// Code to modify (sample)
bitset<N> inBuffer = *i;
bitset<HAMMING_7> outBuffer;
outBuffer[0] = inBuffer[0];
outBuffer[1] = inBuffer[1];
outBuffer[2] = inBuffer[2];
outBuffer[3] = inBuffer[3];
outBuffer[4] = 0;
outBuffer[5] = 0;
outBuffer[6] = 0;
if(DEBUG_HE)
cout << " | " << outBuffer.to_string();
encodedBitset.push_back(outBuffer);
}
if(DEBUG_HE)
cout << endl;
return encodedBitset;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Main //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
vector< bitset<N> > input_data;
vector< bitset<HAMMING_7> > encode_data;
// Read data to encode
input_data = readFile("test.txt");
// Encode by Hamming (7,4) coding
encode_data = HammingEncoding(input_data);
// Inject error
// TODO
// Decode
// TODO
}
| 21.184 | 116 | 0.55929 | [
"vector"
] |
097e400721433f4513beb067ed76f571056b21ea | 56,164 | cpp | C++ | Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Client/ZWaveUSB3C_Window.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Client/ZWaveUSB3C_Window.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/Drivers/ZWave/ZWaveUSB3/Client/ZWaveUSB3C_Window.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: ZWaveUSB3C_Window.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 03/05/2018
//
// 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 main window of the ZWave USB3 client driver
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "ZWaveUSB3C_.hpp"
// ---------------------------------------------------------------------------
// Magic macro
// ---------------------------------------------------------------------------
RTTIDecls(TZWaveUSB3CWnd,TCQCDriverClient)
// ---------------------------------------------------------------------------
// CLASS: TZW3UnitAttrWnd
// PREFIX: wnd
//
// We just need a simple derivative of the attribute editor, so that we can provide some
// custom visual editing. The main driver window implements the IPE interface and sets
// himself on us, so he can provide validation and storing new values.
// ---------------------------------------------------------------------------
class TZW3UnitAttrWnd : public TAttrEditWnd
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TZW3UnitAttrWnd();
TZW3UnitAttrWnd(const TZW3UnitAttrWnd&) = delete;
~TZW3UnitAttrWnd();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TZW3UnitAttrWnd& operator=(const TZW3UnitAttrWnd&) = delete;
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid SetEditInfo
(
TZWaveUSB3CWnd* const pwndDriver
);
protected :
// -------------------------------------------------------------------
// Protected, virtual methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bVisEdit
(
TAttrData& adatEdit
, const TArea& areaCellScr
, const tCIDLib::TCard8 c8UserId
) override;
tCIDLib::TVoid CellClicked
(
const tCIDLib::TCard4 c4Row
, const tCIDLib::TCard4 c4Column
, const tCIDLib::TBoolean bLeftButton
) override;
private :
// -------------------------------------------------------------------
// Private data members
//
// m_pwndDriver
// We are given a pointer to the driver window which we need in order to
// get to the unit and device index stuff, and we also disallow editing
// if the server side driver is doing a scan.
// -------------------------------------------------------------------
TZWaveUSB3CWnd* m_pwndDriver;
// -------------------------------------------------------------------
// Magic macros
// -------------------------------------------------------------------
RTTIDefs(TZW3UnitAttrWnd, TAttrEditWnd);
};
AdvRTTIDecls(TZW3UnitAttrWnd, TAttrEditWnd);
// ---------------------------------------------------------------------------
// TZW3UnitAttrWnd: Constructors and Destructor
// ---------------------------------------------------------------------------
TZW3UnitAttrWnd::TZW3UnitAttrWnd() :
m_pwndDriver(nullptr)
{
}
TZW3UnitAttrWnd::~TZW3UnitAttrWnd()
{
}
// ---------------------------------------------------------------------------
// TZW3UnitAttrWnd: Public, non-virtual methods
// ---------------------------------------------------------------------------
//
// The main driver window gives us a pointer to himself. He also implements the IPE
// interface for the attribute editor, and set him as our IPE handler.
//
tCIDLib::TVoid TZW3UnitAttrWnd::SetEditInfo(TZWaveUSB3CWnd* const pwndDriver)
{
m_pwndDriver = pwndDriver;
SetIPEHandler(pwndDriver);
}
// ---------------------------------------------------------------------------
// TZW3UnitAttrWnd: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TZW3UnitAttrWnd::bVisEdit( TAttrData& adatEdit
, const TArea& areaCellScr
, const tCIDLib::TCard8 c8UserId)
{
// Let the base class check it first
if (TAttrEditWnd::bVisEdit(adatEdit, areaCellScr, c8UserId))
return kCIDLib::True;
return kCIDLib::False;
}
tCIDLib::TVoid
TZW3UnitAttrWnd::CellClicked(const tCIDLib::TCard4 c4Row
, const tCIDLib::TCard4 c4Column
, const tCIDLib::TBoolean bLeftButton)
{
//
// If the driver is busy, we prevent editing. Else we just let it go on to
// the underlying class.
//
if (bLeftButton && !m_pwndDriver->bCanEdit())
{
TErrBox msgbBusy
(
L"The driver is either not in a state that allows editing, or there are "
L"changes pending on the server side that need to be downloaded first."
);
msgbBusy.ShowIt(*this);
return;
}
TParent::CellClicked(c4Row, c4Column, bLeftButton);
}
// ---------------------------------------------------------------------------
// CLASS: TZWaveUSB3CWnd
// PREFIX: wnd
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TZWaveUSB3CWnd: Constructors and Destructor
// ---------------------------------------------------------------------------
TZWaveUSB3CWnd::TZWaveUSB3CWnd( const TCQCDriverObjCfg& cqcdcThis
, const TCQCUserCtx& cuctxToUse) :
TCQCDriverClient(cqcdcThis, L"TZWaveUSB3CWnd", tCQCKit::EActLevels::Low, cuctxToUse)
, m_bDelayNewCfg(kCIDLib::False)
, m_bGotConfig(kCIDLib::False)
, m_bInNetworkCur(kCIDLib::False)
, m_bInNetworkNew(kCIDLib::False)
, m_menuOpts(L"Options")
, m_pwndAttrs(nullptr)
, m_pwndDrvState(nullptr)
, m_pwndInNetwork(nullptr)
, m_pwndList(nullptr)
, m_pwndOptions(nullptr)
, m_pwndUnitInst(nullptr)
{
// We have to set these upon reconnnect as well so we split this off
InitStateData();
}
TZWaveUSB3CWnd::~TZWaveUSB3CWnd()
{
}
// ---------------------------------------------------------------------------
// TZWaveUSB3CWnd: Public, inherited methods
// ---------------------------------------------------------------------------
// If our edit info is different from our original info, then we've changed something
tCIDLib::TBoolean TZWaveUSB3CWnd::bChanges() const
{
// If we haven't gotten our config even once yet, say none
if (!m_bGotConfig)
return kCIDLib::False;
// Otherwise compare our working config to the previously gotten/saved
return m_dcfgEdit != m_dcfgOrg;
}
tCIDLib::TBoolean
TZWaveUSB3CWnd::bIPEValidate(const TString& strSrc
, TAttrData& adatVal
, const TString& strNewVal
, TString& strErrMsg
, tCIDLib::TCard8& c8UserId) const
{
//
// Get the unit (the user id is the unit id), and make sure that it's state
// is still good. If it went south while we were editing, then something is
// wrong.
//
const TZWUnitInfo* punitiTar = m_dcfgEdit.punitiFindById(tCIDLib::TCard1(c8UserId));
if (!punitiTar || (punitiTar->eState() < tZWaveUSB3Sh::EUnitStates::GetInitVals))
{
strErrMsg = L"The driver configuration has changed while you were editing, in "
L"such a way that this change cannot be stored.";
return kCIDLib::False;
}
//
// Call the base mixin class to do basic validation. If that fails, then
// no need to look further.
//
if (!MIPEIntf::bIPEValidate(strSrc, adatVal, strNewVal, strErrMsg, c8UserId))
return kCIDLib::False;
if (adatVal.strId() == kZWaveUSB3Sh::strUAttr_Name)
{
// Make sure it's not a dup and it's a legal base field name
const TZWUnitInfo* punitiDup = m_dcfgEdit.punitiFindByName(strNewVal);
if (punitiDup)
{
strErrMsg = L"This name is already in use by another unit";
return kCIDLib::False;
}
if (!facCQCKit().bIsValidBaseFldName(strNewVal))
{
strErrMsg = L"The name must start with a character and be only characters, "
L"digits, underscrore or hyphen";
return kCIDLib::False;
}
}
return kCIDLib::True;
}
tCIDLib::TBoolean TZWaveUSB3CWnd::bSaveChanges(TString& strErrMsg)
{
// If we never managed to get any, then do nothing
if (!m_bGotConfig)
return kCIDLib::True;
// Do validation on our edit config. If that fails, give up
if (!m_dcfgEdit.bValidate(strErrMsg))
return kCIDLib::False;
// If we are not connected to our server side driver, nothing we can do
if(eConnState() == tCQCGKit::EConnStates::SrvOffline)
{
strErrMsg = L"The server side driver cannot be contacted, so the changes cannot be saved";
return kCIDLib::False;
}
// Let's try to send our current edit config to the driver
tCIDLib::TBoolean bRet = kCIDLib::True;
try
{
// Flatten the current edit config out to the transfer object
m_zwdxdGUI.Reset();
m_zwdxdGUI.m_strCmd = kZWaveUSB3Sh::strSendData_SetConfig;
{
TBinMBufOutStream strmTar(&m_zwdxdGUI.m_mbufData);
strmTar << m_dcfgEdit << kCIDLib::FlushIt;
m_zwdxdGUI.m_c4BufSz = strmTar.c4CurSize();
}
if (bSendGUICmd(orbcServer()))
{
// It worked, so copy to the original now
m_dcfgOrg = m_dcfgEdit;
}
else
{
strErrMsg = m_zwdxdGUI.m_strMsg;
bRet = kCIDLib::False;
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
strErrMsg = errToCatch.strErrText();
bRet = kCIDLib::False;
}
return bRet;
}
//
// If an edited value validates OK, this is called and we store the data back to the
// unit.
//
tCIDLib::TVoid
TZWaveUSB3CWnd::IPEValChanged( const tCIDCtrls::TWndId widSrc
, const TString& strSrc
, const TAttrData& adatNew
, const TAttrData& adatOld
, const tCIDLib::TCard8 c8UserId)
{
//
// Get the unit (the user id is the unit id), and make sure that it's state
// is still good. If it went south while we were editing, then something is
// wrong.
//
TZWUnitInfo* punitiTar = m_dcfgEdit.punitiFindById(tCIDLib::TCard1(c8UserId));
if (!punitiTar || (punitiTar->eState() < tZWaveUSB3Sh::EUnitStates::GetInitVals))
{
TErrBox msgbErr
(
L"The driver configuration has changed while you were editing, in "
L"such a way that this change cannot be stored."
);
msgbErr.ShowIt(*this);
return;
}
//
// Some of these we generate ourself so we have to handle them ourself. The
// others just become option values on the unit, so we take the key and the
// formatted text of the value and set it as an option value.
//
if (adatNew.strId() == kZWaveUSB3Sh::strUAttr_Name)
{
// Update the unit and for this initial change the main list
punitiTar->strName(adatNew.strValue());
tCIDLib::TCard4 c4ListInd = m_pwndList->c4IdToIndex(tCIDLib::TCard4(c8UserId));
m_pwndList->SetColText
(
c4ListInd, tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Name), adatNew.strValue()
);
}
else
{
// The attribute id is the option key
TString strNewVal;
adatNew.FormatToText(strNewVal);
punitiTar->SetOption(adatNew.strId(), strNewVal);
}
}
// ---------------------------------------------------------------------------
// TZWaveUSB3CWnd: Public, non-virtual methods
// ---------------------------------------------------------------------------
//
// This is for the attribute editor window, so he can prevent edits while the driver
// is doing things that we know is about to invalidate any change that would be made.
// So if he is doing a replication scan or he has configuration changes.
//
tCIDLib::TBoolean TZWaveUSB3CWnd::bCanEdit() const
{
// Use the 'new' versions so that we have the most recent info
TLocker lockrSync(pmtxSync());
return
(
(m_c4CfgSerNumNew == m_c4CfgSerNumCur)
&& (m_eDrvStateNew >= tZWaveUSB3Sh::EDrvStates::Ready)
);
}
//
// A helper to send a msg to the server and get the response back. Other things
// besides this window need to do this. Dialog boxes need to definitely. The caller
// provides us with some temp values to use, to avoid constant creation and
// destruction of the resources required.
//
tCIDLib::TBoolean
TZWaveUSB3CWnd::bSendSrvMsg(const TWindow& wndOwner
, TZWDriverXData& zwdxdComm
, THeapBuf& mbufTmp)
{
tCIDLib::TCard4 c4Cnt;
{
TBinMBufOutStream strmTar(&mbufTmp);
strmTar << zwdxdComm << kCIDLib::FlushIt;
c4Cnt = strmTar.c4CurSize();
}
try
{
// We currently don't use the data name
TString strDataName;
const tCIDLib::TBoolean bRes = orbcServer()->bSendData
(
strMoniker()
, kZWaveUSB3Sh::strSendData_Type
, strDataName
, c4Cnt
, mbufTmp
, sectUser()
);
if (!bRes)
{
// We didn't get anything back, fake an error back into the exchange object
zwdxdComm.StatusReset(kCIDLib::False, L"The driver didn't understand the msg");
return kCIDLib::False;
}
// STream in the response
TBinMBufInStream strmSrc(&mbufTmp, c4Cnt);
strmSrc >> zwdxdComm;
}
catch(TError& errToCatch)
{
if (facZWaveUSB3C().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
zwdxdComm.StatusReset(kCIDLib::False, errToCatch.strErrText());
return kCIDLib::False;
}
catch(...)
{
TString strMsg = TString::strConcat(L"A system exception occured sending command: ", zwdxdComm.m_strCmd);
TErrBox msgbErr(strMsg);
msgbErr.ShowIt(*this);
zwdxdComm.StatusReset(kCIDLib::False, strMsg);
return kCIDLib::False;
}
// Return the status reply of the driver
return zwdxdComm.m_bStatus;
}
// ---------------------------------------------------------------------------
// TZWaveUSB3CWnd: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TZWaveUSB3CWnd::bCreated()
{
TParent::bCreated();
// Get the dialog description we'll use to create the main controls
TDlgDesc dlgdMain;
facZWaveUSB3C().bCreateDlgDesc(kZWaveUSB3C::ridIntf_Main, dlgdMain);
// Find the attribute editor and replace the class with our own
dlgdMain.SetCppType(kZWaveUSB3C::ridMain_Attrs, L"TZW3UnitAttrWnd");
// And now create the controls
tCIDCtrls::TWndId widInitFocus;
CreateDlgItems(dlgdMain, widInitFocus);
//
// Now do an initial auto-size to fit our client area. This will cause the
// the pane window to be resized, and it in turn will resize the panes, which
// will resize their contents.
//
AutoAdjustChildren(dlgdMain.areaPos(), areaClient());
// It won't be shown but set our window text so it'll get picked up by any popups
strWndText(facZWaveUSB3C().strMsg(kZWU3CMsgs::midMain_Title));
// Get typed pointers to the widgets we want to interact with a lot
CastChildWnd(*this, kZWaveUSB3C::ridMain_Attrs, m_pwndAttrs);
CastChildWnd(*this, kZWaveUSB3C::ridMain_DrvState, m_pwndDrvState);
CastChildWnd(*this, kZWaveUSB3C::ridMain_InNetwork, m_pwndInNetwork);
CastChildWnd(*this, kZWaveUSB3C::ridMain_UnitList, m_pwndList);
CastChildWnd(*this, kZWaveUSB3C::ridMain_Options, m_pwndOptions);
CastChildWnd(*this, kZWaveUSB3C::ridMain_UnitInstruct, m_pwndUnitInst);
//
// Tell the attribute editor about us. We couldn't do it until now because it's
// create via dialog description. He will also set us up as the in place editor
// for himself.
//
m_pwndAttrs->SetEditInfo(this);
// Register our event handlers
m_pwndOptions->pnothRegisterHandler(this, &TZWaveUSB3CWnd::eClickHandler);
m_pwndList->pnothRegisterHandler(this, &TZWaveUSB3CWnd::eLBHandler);
m_pwndAttrs->pnothRegisterHandler(this, &TZWaveUSB3CWnd::eAttrEditHandler);
// Set up the column titles
tCIDLib::TStrList colCols(tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Count));
tCIDLib::ForEachE<tZWaveUSB3C::EListCols>
(
[&colCols](const tZWaveUSB3C::EListCols eCol)
{
colCols.objAdd(tZWaveUSB3C::strAltXlatEListCols(eCol));
}
);
m_pwndList->SetColumns(colCols);
// Set up the column widths to reasonable defaults per column
TFontMetrics fmtrDef;
{
TGraphWndDev gdevTmp(*this);
gdevTmp.QueryFontMetrics(fmtrDef);
}
tCIDLib::ForEachE<tZWaveUSB3C::EListCols>
(
[&colCols, this, &fmtrDef](const tZWaveUSB3C::EListCols eCol)
{
tCIDLib::TCard4 c4Width = 0;
tCIDLib::EHJustify eHJustify = tCIDLib::EHJustify::Left;
switch(eCol)
{
case tZWaveUSB3C::EListCols::Menu :
c4Width = 4;
eHJustify = tCIDLib::EHJustify::Center;
break;
case tZWaveUSB3C::EListCols::Id :
c4Width = 6;
eHJustify = tCIDLib::EHJustify::Right;
break;
case tZWaveUSB3C::EListCols::Name :
c4Width = 32;
break;
case tZWaveUSB3C::EListCols::State:
c4Width = 12;
break;
case tZWaveUSB3C::EListCols::Listener :
c4Width = 10;
break;
case tZWaveUSB3C::EListCols::Make :
case tZWaveUSB3C::EListCols::Model :
c4Width = 16;
break;
default :
// Shoudln't happen, but just so we see it if it does
c4Width = 8;
break;
};
if (c4Width)
{
m_pwndList->SetColOpts
(
tCIDLib::c4EnumOrd(eCol)
, c4Width * fmtrDef.c4AverageWidth()
, eHJustify
, 2 * fmtrDef.c4AverageWidth()
);
}
}
);
//
// Set our in network text to match the default value of our current value
// flag so that it will be correct if we happen to be in that state when we
// start up (hence it would not be updated by our polling.)
//
m_pwndInNetwork->strWndText(facCQCKit().strBoolYesNo(m_bInNetworkCur));
// Pre-create our options popup
m_menuOpts.Create(facZWaveUSB3C(), kZWaveUSB3C::ridMenu_Options);
//
// Check the off trace level since that's what we set as our default initial
// value. If the server is the same, we won't ever update, so we need to get
// this initial value set.
//
m_menuOpts.SetItemCheck(kZWaveUSB3C::ridMenu_Opt_Trace_Off, kCIDLib::True);
// Make sure the got config flag is false initially upon creation
m_bGotConfig = kCIDLib::False;
return kCIDLib::True;
}
//
// This is for getting 'once on connect' type data from the server side driver. It
// is called from the background thread. We reset our state data, and force a call
// to our own poll method, since it does what we need.
//
tCIDLib::TBoolean TZWaveUSB3CWnd::bGetConnectData(tCQCKit::TCQCSrvProxy& orbcTarget)
{
TLocker lockrSync(pmtxSync());
// Initialize our per-connection state data
InitStateData();
// Do a poll and return whether we succeeded. If so, Connected() will be called
return bDoPoll(orbcTarget);
}
//
// This is called from the background polling thread, to give us a chance to ask
// the server for the latest data.
//
// We first ask for basic data, which let's us keep our status displays up to date.
// And, if this indicates there is new configuration, we download that. We just
// leave the data for the GUI thread to pick up.
//
// We have to gather all the data into locals first, then lock, then store.
//
tCIDLib::TBoolean TZWaveUSB3CWnd::bDoPoll(tCQCKit::TCQCSrvProxy& orbcTarget)
{
const tCIDLib::TCard4 c4PrevSerialNum = m_c4CfgSerNumNew;
tCIDLib::TBoolean bInNetwork;
tCIDLib::TCard4 c4CfgSerNum;
tZWaveUSB3Sh::EDrvStates eDrvState;
tCQCKit::EVerboseLvls eTraceLevel;
try
{
// As an initial test, get the general status info
m_zwdxdPoll.Reset();
m_zwdxdPoll.m_strCmd = kZWaveUSB3Sh::strSendData_QueryStatusInfo;
if (!bSendPollCmd(orbcTarget))
return kCIDLib::False;
//
// It worked so stream the values out.
{
TBinMBufInStream strmSrc(&m_zwdxdPoll.m_mbufData, m_zwdxdPoll.m_c4BufSz);
strmSrc >> c4CfgSerNum
>> bInNetwork
>> eDrvState
>> eTraceLevel;
}
//
// If not locked out, and the config serial number changed, we need to get
// the config.
//
if ((c4CfgSerNum != c4PrevSerialNum) && !m_bDelayNewCfg)
{
m_zwdxdPoll.Reset();
m_zwdxdPoll.m_strCmd = kZWaveUSB3Sh::strSendData_QueryConfig;
if (!bSendPollCmd(orbcTarget))
return kCIDLib::False;
TBinMBufInStream strmSrc(&m_zwdxdPoll.m_mbufData, m_zwdxdPoll.m_c4BufSz);
strmSrc >> m_dcfgTmp;
}
// OK, let's lock and store the new data
TLocker lockrSync(pmtxSync());
m_bInNetworkNew = bInNetwork;
m_eDrvStateNew = eDrvState;
m_eTraceLevelNew = eTraceLevel;
// If not locked out, update the config stuff
if (!m_bDelayNewCfg)
{
m_c4CfgSerNumNew = c4CfgSerNum;
if (c4CfgSerNum != c4PrevSerialNum)
m_dcfgNew = m_dcfgTmp;
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
return kCIDLib::False;
}
return kCIDLib::True;
}
tCIDLib::TVoid TZWaveUSB3CWnd::Connected()
{
//
// Do an initial update of our data. Indicate this is the initial update after
// connection. That makes him take the new config as is. He locks so we don't
// have to do that.
//
UpdateData(kCIDLib::True);
//
// Do an initial load of the unit list. We are just dealing with our own GUI
// thread data here, so don't need to lock.
//
LoadUnits();
}
tCIDLib::TVoid TZWaveUSB3CWnd::DoCleanup()
{
}
tCIDLib::TVoid TZWaveUSB3CWnd::LostConnection()
{
// Clear the unit list
m_pwndList->RemoveAll();
}
//
// This is called if our poll callback indicates it left new data. In our case it
// always does and we just check for changes ourself and update what needs to be.
//
tCIDLib::TVoid TZWaveUSB3CWnd::UpdateDisplayData()
{
//
// We have a helper for this since we also need to do a variation of it from
// the initial connect. Pick up any new data left for us by the poll thread
// and update display as required. Indicate this is not the initial update.
// He locks while updating.
//
UpdateData(kCIDLib::False);
}
// ---------------------------------------------------------------------------
// TZWaveUSB3CWnd: Private, non-virtual methods
// ---------------------------------------------------------------------------
// When the user selects the new unit approval option, this is called
tCIDLib::TVoid TZWaveUSB3CWnd::ApproveNewUnits()
{
// If there are outstanding changes, warn that they will be lost
if (m_dcfgEdit != m_dcfgOrg)
{
const tCIDLib::TCard4 c4Choice = facCIDWUtils().c4TriChoiceDlg
(
*this
, L"Lose Changes?"
, facZWaveUSB3Sh().strMsg(kZWU3CMsgs::midQ_CouldLoseChanges)
, L"Save First"
, L"Just Approve"
, L"Cancel"
);
if (c4Choice == 3)
return;
if (c4Choice == 1)
{
TString strErr;
if (!bSaveChanges(strErr))
{
TErrBox msgbErr(L"Save Failed", strErr);
msgbErr.ShowIt(*this);
return;
}
// Wait for a little bit for the server to settle
TThread::Sleep(2000);
}
}
// We can do it, so send the command to the server
m_zwdxdGUI.Reset();
m_zwdxdGUI.m_strCmd = kZWaveUSB3Sh::strSendData_ApproveNewUnits;
if (bSendGUICmd(orbcServer()))
{
TOkBox msgbDone(facZWaveUSB3C().strMsg(kZWU3CMsgs::midStatus_UnitsApproved));
msgbDone.ShowIt(*this);
}
else
{
TErrBox msgbErr(m_zwdxdGUI.m_strMsg);
msgbErr.ShowIt(*this);
}
//
// Just in case, get back in sync with the server now. We just call our own
// poll method, who will do what is required.
//
bDoPoll(orbcServer());
}
//
// A helper to handle sending commands and getting the reply. We just call the
// public one that lets everyone get access to this functionality, providing the
// values it needs. WE have one for the GUI and one for the poll thread, since
// we don't want to have to lock while sending msgs, and therefore they need to
// use different members.
//
tCIDLib::TBoolean TZWaveUSB3CWnd::bSendGUICmd(tCQCKit::TCQCSrvProxy& orbcTarget)
{
if (!bSendSrvMsg(*this, m_zwdxdGUI, m_mbufGUI))
{
TErrBox msgbErr(m_zwdxdGUI.m_strMsg);
msgbErr.ShowIt(*this);
}
return m_zwdxdGUI.m_bStatus;
}
// This one cannot do the error box since this is background stuff
tCIDLib::TBoolean TZWaveUSB3CWnd::bSendPollCmd(tCQCKit::TCQCSrvProxy& orbcTarget)
{
if (!bSendSrvMsg(*this, m_zwdxdPoll, m_mbufPoll))
return kCIDLib::False;
// We got something back so return the status
return m_zwdxdPoll.m_bStatus;
}
//
// This is called to load a specific unit up into the list, or to update it if it is
// already there. We set the unit id as the row id, so that we can easily get from
// id to raw regardless of sort. The caller sends us a temp list of of strings to use
// to load up the column values, so it must be one string per column we have.
//
tCIDLib::TCard4
TZWaveUSB3CWnd::c4LoadUnitToList(const TZWUnitInfo& unitiCur, tCIDLib::TStrList& colCols)
{
// Set up the new values
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Menu)] = L"v";
if (unitiCur.strMake().bIsEmpty() || unitiCur.strModel().bIsEmpty())
{
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Make)] = TString::strEmpty();
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Model)] = TString::strEmpty();
}
else
{
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Make)] = unitiCur.strMake();
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Model)] = unitiCur.strModel();
}
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Listener)] = facCQCKit().strBoolYesNo(unitiCur.bAlwaysOn());
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Id)].SetFormatted(unitiCur.c1Id());
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::State)] = tZWaveUSB3Sh::strAltXlatEUnitStates(unitiCur.eState());
colCols[tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Name)] = unitiCur.strName();
// Either add or update
tCIDLib::TCard4 c4ListInd = m_pwndList->c4IdToIndex(unitiCur.c1Id(), kCIDLib::False);
if (c4ListInd == kCIDLib::c4MaxCard)
m_pwndList->c4AddItem(colCols, unitiCur.c1Id());
else
m_pwndList->UpdateRowAt(colCols, c4ListInd, unitiCur.c1Id(), kCIDLib::True);
return c4ListInd;
}
//
// Called when the user selects the disable option for a unit. We just send the
// command. If it actually happens, we'll see it as a change coming back and will
// update the unit's state display accordingly.
//
tCIDLib::TVoid
TZWaveUSB3CWnd::DisableUnit(TZWUnitInfo& unitiTar, const tCIDLib::TCard4 c4ListInd)
{
m_zwdxdGUI.Reset();
m_zwdxdGUI.m_strCmd = kZWaveUSB3Sh::strSendData_DisableUnit;
m_zwdxdGUI.m_c1UnitId = unitiTar.c1Id();
if (bSendGUICmd(orbcServer()))
{
TOkBox msgbDone(facZWaveUSB3C().strMsg(kZWU3CMsgs::midWarn_DisableDone));
msgbDone.ShowIt(*this);
//
// Go ahead and update our local display on the assumption is going to happen
// anyway given that we didn't get an error. This will make it happen faster.
//
unitiTar.eState(tZWaveUSB3Sh::EUnitStates::Disabled);
m_pwndList->SetColText
(
c4ListInd
, tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::State)
, tZWaveUSB3Sh::strAltXlatEUnitStates(unitiTar.eState())
);
}
}
//
// When the user selects to start an include/exclude operation from the options menu.
// We tell the server side driver to start that process.
//
// We block the poll thread from storing configuration during this process because
// we need to force a full update of config after this is done and it would sneak
// in and see the change before we could deal with it otherwise. If we end up failing
// the process, the normal poll will subsequently catch up if any changes happened
// while we were doing this.
//
tCIDLib::TVoid TZWaveUSB3CWnd::DoIncEx()
{
// If they have any changes, tell them to save that first
if (m_dcfgEdit != m_dcfgOrg)
{
TYesNoBox msgbWarn(facZWaveUSB3C().strMsg(kZWU3CMsgs::midQ_RepWithChanges));
if (!msgbWarn.bShowIt(*this))
return;
}
TBoolJanitor janInc(&m_bDelayNewCfg, kCIDLib::True);
TZWUSB3IncludeDlg dlgInclude;
const tCIDLib::TBoolean bRes = dlgInclude.bRunDlg(*this);
// We need to query config now
m_zwdxdGUI.Reset();
m_zwdxdGUI.m_strCmd = kZWaveUSB3Sh::strSendData_QueryConfig;
if (bSendGUICmd(orbcServer()))
{
TBinMBufInStream strmSrc(&m_zwdxdGUI.m_mbufData, m_zwdxdGUI.m_c4BufSz);
strmSrc >> m_dcfgNew;
//
// Update the new serial number so that UpdateData() will see new info.
// We can update this becasue we have the poll thread locked out from
// updating config info. Otherwise he'd just ovewrite this.
//
m_c4CfgSerNumNew = m_dcfgNew.c4CalcSNHash();
//
// Do an initial mode data update. That will make him just take the new
// config as is, not try to integrate with existing stuff.
//
UpdateData(kCIDLib::True);
}
else
{
//
// Tell the user there was an error. Once we clear the include dialog
// flag, the polling will pick up any changes that might have occurred
// while we were in the dialog and update normally.
//
TErrBox msgbErr(m_zwdxdGUI.m_strMsg);
msgbErr.ShowIt(*this);
}
}
//
// When the user drops down the per-unit menu and makes a selection, this is called.
// We get the unit id and the list index.
//
tCIDLib::TVoid
TZWaveUSB3CWnd::DoUnitOpt(const tCIDLib::TCard1 c1Id, const tCIDLib::TCard4 c4ListInd)
{
//
// Lock out new config being downloaded during this since it would invalidate our
// target unit object. It's an issue because there are non-blocking operations
// here that will allow the poll method to start happening again.
//
TBoolJanitor janInc(&m_bDelayNewCfg, kCIDLib::True);
// Get the unit so we can update the menu based on the unit
TZWUnitInfo& unitiTar = m_dcfgEdit.unitiFindById(c1Id);
// Create a popup menu
TPopupMenu menuOpts(L"UnitMenu");
menuOpts.Create(facZWaveUSB3C(), kZWaveUSB3C::ridMenu_UnitOpts);
// If the selected unit doesn't support associations disable those options
if (!unitiTar.bSupportsClass(tZWaveUSB3Sh::ECClasses::Association))
{
menuOpts.SetItemEnable(kZWaveUSB3C::ridMenu_UnitOpt_AssocToDrv, kCIDLib::False);
menuOpts.SetItemEnable(kZWaveUSB3C::ridMenu_UnitOpt_MngAssoc, kCIDLib::False);
}
// If it doesn't support configuration, disable the configuration related ones
if (!unitiTar.bSupportsClass(tZWaveUSB3Sh::ECClasses::Config))
{
menuOpts.SetItemEnable(kZWaveUSB3C::ridMenu_UnitOpt_MngCfgParam, kCIDLib::False);
}
//
// If neither association nor configuration, then clearly auto-config is useless.
// Or if the unit doesn't yet have device info, since we can't have any auto-cfg
// data until then.
//
if ((!unitiTar.bSupportsClass(tZWaveUSB3Sh::ECClasses::Association)
&& !unitiTar.bSupportsClass(tZWaveUSB3Sh::ECClasses::Config))
|| !unitiTar.bHasDevInfo())
{
menuOpts.SetItemEnable(kZWaveUSB3C::ridMenu_UnitOpt_AutoConfig, kCIDLib::False);
}
// Set the enable/disable item to the opposite of whatever it is now
if (unitiTar.eState() == tZWaveUSB3Sh::EUnitStates::Disabled)
menuOpts.SetItemText(kZWaveUSB3C::ridMenu_UnitOpt_Disable, L"Enable");
else
menuOpts.SetItemText(kZWaveUSB3C::ridMenu_UnitOpt_Disable, L"Disable");
//
// If the unit already has device info, then disable setting of the unit type.
// If it doesn't have it, then disable show notes.
//
if (unitiTar.bHasDevInfo())
menuOpts.SetItemEnable(kZWaveUSB3C::ridMenu_UnitOpt_SetType, kCIDLib::False);
else
menuOpts.SetItemEnable(kZWaveUSB3C::ridMenu_UnitOpt_ShowNotes, kCIDLib::False);
// Get the area of the cell and convert to screen coordinates
TArea areaCell;
m_pwndList->QueryColArea
(
c4ListInd, tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Menu), areaCell
);
m_pwndList->ToScreenCoordinates(areaCell, areaCell);
// Pop it up at the bottom left of the cell, top aligned
const tCIDLib::TCard4 c4SelInd = menuOpts.c4Process
(
*this, areaCell.pntLL(), tCIDLib::EVJustify::Top, tCIDLib::EHJustify::Left
);
switch(c4SelInd)
{
case 0 :
// No selection
break;
case kZWaveUSB3C::ridMenu_UnitOpt_AssocToDrv :
{
TZWUSB3AssocToDrvDlg dlgAssoc;
dlgAssoc.RunDlg(*this, unitiTar);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_AutoConfig :
{
TZWUSB3AutoCfgDlg dlgAutoCfg;
dlgAutoCfg.RunDlg(*this, unitiTar);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_Disable :
{
//
// Ask the server to enable or disable the node. If he does we'll see
// that as a change coming back to us.
//
DisableUnit(unitiTar, c4ListInd);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_GenReport:
{
TZWUSB3GenReportDlg dlgReport;
dlgReport.RunDlg(*this, unitiTar);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_MngAssoc :
{
TZWUSB3AssocDlg dlgAssoc;
dlgAssoc.RunDlg(*this, m_dcfgEdit, unitiTar);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_MngCfgParam :
{
TZWUSB3CfgParamDlg dlgCfgParam;
dlgCfgParam.RunDlg(*this, unitiTar);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_ShowInfo :
{
//
// Pass this guy to a simple dialog that dipslays the info and allows
// the user to save it to a text file.
//
TZWUSB3UnitInfoDlg dlgInfo;
dlgInfo.RunDlg(*this, unitiTar);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_ShowNotes :
{
TString strNotes;
if (facZWaveUSB3Sh().bQueryModelNotes(unitiTar.c8ManIds(), strNotes))
{
TString strTitle = TString::strConcat(L"Notes for unit: ", unitiTar.strName());
TOkBox msgbNotes(strTitle, strNotes);
msgbNotes.ShowIt(*this);
}
else
{
TOkBox msgbNone(L"This unit doesn't have any associated notes");
msgbNone.ShowIt(*this);
}
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_Rescan :
{
TZWUSB3ResetUnitDlg dlgReset;
dlgReset.RunDlg(*this, unitiTar);
break;
}
case kZWaveUSB3C::ridMenu_UnitOpt_SetType :
{
SetUnitType(unitiTar, c4ListInd);
break;
}
default :
break;
};
}
//
// For our attribute editor, if the user does visual editing, we don't get any IPE
// calls since that is not related to in place editing. Instead we get notified this
// way. We will validate any that need validating in our bVisEdit() override in our
// attribute editor derived class above. But we need this to store the value.
//
tCIDCtrls::EEvResponses TZWaveUSB3CWnd::eAttrEditHandler(TAttrEditInfo& wnotInfo)
{
//
// The unit id is the user data. Just look it up and pass it the new attribute
// data.
//
tCIDLib::TCard1 c1Id = tCIDLib::TCard1(wnotInfo.c8UserId());
TZWUnitInfo& unitiLoad = m_dcfgEdit.unitiFindById(c1Id);
unitiLoad.StoreUnitAttr(wnotInfo.adatNew());
return tCIDCtrls::EEvResponses::Handled;
}
// Handle clicks from our buttons
tCIDCtrls::EEvResponses TZWaveUSB3CWnd::eClickHandler(TButtClickInfo& wnotEvent)
{
// If we are not connected, then do nothing
if (eConnState() != tCQCGKit::EConnStates::Connected)
return tCIDCtrls::EEvResponses::Handled;
if (wnotEvent.widSource() == kZWaveUSB3C::ridMain_Options)
{
//
// Search the current config. If no units are in wait for approval, disable
// the approve new units options, else enable it.
//
m_menuOpts.SetItemEnable
(
kZWaveUSB3C::ridMenu_Opt_ApproveNew, m_dcfgEdit.bUnitsToApprove()
);
//
// Get the options button area and translate to screen coordinates, so that
// we can pop it up relative to where the button is.
//
TArea areaButt = m_pwndOptions->areaWnd();
ToScreenCoordinates(areaButt, areaButt);
const tCIDLib::TCard4 c4SelId = m_menuOpts.c4Process
(
*this, areaButt.pntUR(), tCIDLib::EVJustify::Bottom, tCIDLib::EHJustify::Right
);
switch(c4SelId)
{
case 0 :
// No selection was made
break;
case kZWaveUSB3C::ridMenu_Opt_ApproveNew :
ApproveNewUnits();
break;
case kZWaveUSB3C::ridMenu_Opt_Trace_Off :
case kZWaveUSB3C::ridMenu_Opt_Trace_Low :
case kZWaveUSB3C::ridMenu_Opt_Trace_Medium :
case kZWaveUSB3C::ridMenu_Opt_Trace_High :
case kZWaveUSB3C::ridMenu_Opt_Trace_Flush :
case kZWaveUSB3C::ridMenu_Opt_Trace_Reset :
SetTraceOption(c4SelId);
break;
case kZWaveUSB3C::ridMenu_Opt_IncEx :
DoIncEx();
break;
case kZWaveUSB3C::ridMenu_Opt_SaveCfg :
SaveCfgToFile();
break;
default :
TErrBox msgbErr(L"Unknown option");
msgbErr.ShowIt(*this);
break;
};
}
return tCIDCtrls::EEvResponses::Handled;
}
// Handle events from our main list window
tCIDCtrls::EEvResponses TZWaveUSB3CWnd::eLBHandler(TListChangeInfo& wnotEvent)
{
if (wnotEvent.widSource() == kZWaveUSB3C::ridMain_UnitList)
{
if (wnotEvent.eEvent() == tCIDCtrls::EListEvents::Cleared)
{
// Clear the attribute window and the status description text
m_pwndAttrs->RemoveAll();
m_pwndUnitInst->ClearText();
}
else if (wnotEvent.eEvent() == tCIDCtrls::EListEvents::SelChanged)
{
//
// Load up the attributes for this guy. It also displays some helper
// text for the newly selected unit, based on its state.
//
LoadUnitAttrs(tCIDLib::TCard1(wnotEvent.c4Id()));
}
else if (wnotEvent.eEvent() == tCIDCtrls::EListEvents::ColClicked)
{
//
// We handle this in order to provide a little drop down menu for
// the units, so that the user can invoke some operations on them.
//
// So, if they click that cell, we position a menu just below the
// menu cell.
//
if (wnotEvent.c4ColIndex() == tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Menu))
DoUnitOpt(tCIDLib::TCard1(wnotEvent.c4Id()), wnotEvent.c4Index());
}
}
return tCIDCtrls::EEvResponses::Handled;
}
//
// Called from the ctor and upon (re)establishing a connection, to get our polling
// oriented flags set up.
//
tCIDLib::TVoid TZWaveUSB3CWnd::InitStateData()
{
m_bDelayNewCfg = kCIDLib::False;
m_bInNetworkCur = kCIDLib::False;
m_bInNetworkNew = kCIDLib::False;
m_c4CfgSerNumCur = 0;
m_c4CfgSerNumNew = 0;
m_eDrvStateCur = tZWaveUSB3Sh::EDrvStates::Startup;
m_eDrvStateNew = tZWaveUSB3Sh::EDrvStates::Startup;
m_eTraceLevelCur = tCQCKit::EVerboseLvls::Off;
m_eTraceLevelNew = tCQCKit::EVerboseLvls::Off;
}
//
// This will load up the attribute editor window with the editable attributes of
// the passed unit.
//
tCIDLib::TVoid TZWaveUSB3CWnd::LoadUnitAttrs(const tCIDLib::TCard1 c1Id)
{
m_pwndAttrs->RemoveAll();
try
{
TZWUnitInfo& unitiLoad = m_dcfgEdit.unitiFindById(c1Id);
//
// Based on the unit state, we display some helper text in a static text
// control under the list.
//
m_pwndUnitInst->strWndText
(
tZWaveUSB3Sh::strXlatEUnitStates(unitiLoad.eState())
);
// See if this guy has device info. If not, nothing more to do.
if (!unitiLoad.bHasDevInfo())
return;
//
// Let it try to create its unit object. Even if it already has one, we let
// let it create a new one, in case something has changed that would affect
// which one it would create, or the options it would present us. Tell it
// this is being done on the client side.
//
// This will give him a chance to parse out any extra info from the device
// info file, which might affect options.
//
unitiLoad.MakeUnitObject(kCIDLib::True);
// If by some chance he failed to create one, we can't do anything
if (!unitiLoad.bHasUnitObject())
{
TErrBox msgbErr(L"The unit failed to create a unit handler object");
msgbErr.ShowIt(*this);
return;
}
//
// And now ask him for his editable attributes. Some of these are option
// values provided by the unit handler and CC impls. Some are just direct
// edits of members of the unit info object.
//
tCIDMData::TAttrList colAttrs;
unitiLoad.QueryUnitAttrs(colAttrs);
//
// And now we can load them to the attribute editor. So that we can get
// back to this unit when we get IPE callbacks, we need to pass along the
// unit id.
//
m_pwndAttrs->LoadValues(colAttrs, unitiLoad.c1Id());
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
// Does the grunt work to load up the unit list
tCIDLib::TVoid TZWaveUSB3CWnd::LoadUnits()
{
// Prevent painting while we do this to avoid blinkies
TWndPaintJanitor janPaint(m_pwndList);
// Remove existing units
m_pwndList->RemoveAll();
// If our config indicates we are in network, load the info
if (m_dcfgEdit.bInNetwork())
{
tCIDLib::TStrList colCols(tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Count));
colCols.AddXCopies(TString::strEmpty(), tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Count));
const tZWaveUSB3Sh::TUnitInfoList& colLoad = m_dcfgEdit.colUnits();
const tCIDLib::TCard4 c4Count = colLoad.c4ElemCount();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
c4LoadUnitToList(colLoad[c4Index], colCols);
}
// If the list is not empty, select the first one
if (m_pwndList->c4ItemCount())
m_pwndList->SelectByIndex(0);
}
//
// Called when the user selects Save Config from the manu option menu. We let him choose
// a target file and write out our config to that.
//
tCIDLib::TVoid TZWaveUSB3CWnd::SaveCfgToFile()
{
// Let the user select an output file
tCIDLib::TBoolean bRes = kCIDLib::False;
TString strSelected;
{
tCIDLib::TKVPList colFileTypes(1);
colFileTypes.objAdd(TKeyValuePair(L"CQC Z-Wave Cfg Dump", L"*.CQCZWCfg"));
bRes = facCIDCtrls().bSaveFileDlg
(
*this
, facZWaveUSB3C().strMsg(kZWU3CMsgs::midMsg_SelectTargetFl)
, TString::strEmpty()
, TString::strEmpty()
, strSelected
, colFileTypes
, tCIDCtrls::EFSaveOpts::FilesOnly
);
}
// If they made a selection, then let's do it
if (bRes)
{
try
{
TBinFileOutStream strmOut
(
strSelected
, tCIDLib::ECreateActs::CreateAlways
, tCIDLib::EFilePerms::Default
, tCIDLib::EFileFlags::SequentialScan
);
strmOut << m_dcfgNew << kCIDLib::FlushIt;
}
catch(TError& errToCatch)
{
TExceptDlg dlgErr
(
*this
, L"An error occurred while saving the configuration file"
, errToCatch
);
}
}
}
// Called when the user select one of the trace file related menu options
tCIDLib::TVoid TZWaveUSB3CWnd::SetTraceOption(const tCIDLib::TCard4 c4SelId)
{
tCIDLib::TBoolean bSetCheck = kCIDLib::False;
tCIDLib::TCard4 c4TraceOpt = kCIDLib::c4MaxCard;
tCIDLib::TCard4 c4MenuId = 0;
switch(c4SelId)
{
case kZWaveUSB3C::ridMenu_Opt_Trace_Off :
bSetCheck = kCIDLib::True;
c4TraceOpt = 0;
break;
case kZWaveUSB3C::ridMenu_Opt_Trace_Low :
bSetCheck = kCIDLib::True;
c4TraceOpt = 1;
break;
case kZWaveUSB3C::ridMenu_Opt_Trace_Medium :
bSetCheck = kCIDLib::True;
c4TraceOpt = 2;
break;
case kZWaveUSB3C::ridMenu_Opt_Trace_High :
bSetCheck = kCIDLib::True;
c4TraceOpt = 3;
break;
case kZWaveUSB3C::ridMenu_Opt_Trace_Flush :
c4TraceOpt = 5;
break;
case kZWaveUSB3C::ridMenu_Opt_Trace_Reset :
c4TraceOpt = 6;
break;
default :
break;
};
if (c4TraceOpt == kCIDLib::c4MaxCard)
{
TErrBox msgbErr(L"Invalid trace menu option received");
msgbErr.ShowIt(*this);
return;
}
m_zwdxdGUI.Reset();
m_zwdxdGUI.m_strCmd = kZWaveUSB3Sh::strSendData_SetTrace;
m_zwdxdGUI.m_c4Val1 = c4TraceOpt;
if (bSendGUICmd(orbcServer()))
{
if (bSetCheck)
m_menuOpts.SetItemCheck(c4SelId, kCIDLib::True);
}
}
tCIDLib::TVoid
TZWaveUSB3CWnd::SetUnitType(TZWUnitInfo& unitiTar, const tCIDLib::TCard4 c4ListInd)
{
//
// Pass in any existing manids value. It'll try to select that one if it is
// present.
//
tCIDLib::TCard8 c8ManIds = unitiTar.c8ManIds();
const tCIDLib::TCard8 c8OrgIds = c8ManIds;
// Let them select. If no selection just return
TZWUSB3SelUTypeDlg dlgSel;
if (!dlgSel.bRunDlg(*this, c8ManIds, unitiTar.strName()))
return;
// OK, let's let this unit update himself with the selected device info
TString strErr;
if (unitiTar.bForceManIds(c8ManIds, strErr))
{
//
// Update the list row for this guy, and reselect it, forcing an event to
// be sent so that the attribute editor will update.
//
tCIDLib::TStrList colCols;
colCols.AddXCopies
(
TString::strEmpty(), tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Count)
);
c4LoadUnitToList(unitiTar, colCols);
m_pwndList->SelectByIndex(c4ListInd, kCIDLib::True);
//
// If the man id is a generic one, make sure they know they have to do any
// associations and configuration parameters. Else just let them know they
// have to save before the change will take effect.
//
TString strMsg
(
L"The type has been set, but will not take effect until you save changes."
);
if (facZWaveUSB3Sh().bIsGenericManId(c8ManIds))
{
strMsg.Append
(
L"\n\nAlso note that, for generic handlers, you must set up any configuration "
L"parameters and associations required. The driver has no idea what is "
L"appropriate."
);
}
TOkBox msgbDone(strMsg);
msgbDone.ShowIt(*this);
}
else
{
TErrBox msgbErr(strErr);
msgbErr.ShowIt(*this);
}
}
//
// Update our data. This is called from the GUI thread. We see if the poll thread has
// gotten any new info. If so we update as needed.
//
// WE HAVE A special case of the initial one, where we just want to take what is in
// new as is. This is when we first get config from the driver, or after a replication
// completes.
//
// We have to lock during this since we are accessing the 'new' versions of the data
// members. We make those our working values, so we need to lock out the poll thread
// during this or race conditions galore.
//
tCIDLib::TVoid TZWaveUSB3CWnd::UpdateData(const tCIDLib::TBoolean bInitial)
{
TLocker lockrSync(pmtxSync());
//
// If any states have changed update our displays of them. We need to lock while
// doing this to insure consistency since the poll thread will be updating them.
//
if (m_bInNetworkNew != m_bInNetworkCur)
{
m_bInNetworkCur = m_bInNetworkNew;
m_pwndInNetwork->strWndText(facCQCKit().strBoolYesNo(m_bInNetworkCur));
// If we aren't in the network anymore, then clear the unit list
if (!m_bInNetworkCur)
m_pwndList->RemoveAll();
}
if(m_eDrvStateNew != m_eDrvStateCur)
{
m_eDrvStateCur = m_eDrvStateNew;
m_pwndDrvState->strWndText(tZWaveUSB3Sh::strLoadEDrvStates(m_eDrvStateCur));
}
// Update the menu if the trace level changes
if (m_eTraceLevelCur != m_eTraceLevelNew)
{
m_eTraceLevelCur = m_eTraceLevelNew;
tCIDLib::TResId ridNew = 0;
if (m_eTraceLevelCur == tCQCKit::EVerboseLvls::Off)
ridNew = kZWaveUSB3C::ridMenu_Opt_Trace_Off;
else if (m_eTraceLevelCur == tCQCKit::EVerboseLvls::Low)
ridNew = kZWaveUSB3C::ridMenu_Opt_Trace_Low;
else if (m_eTraceLevelCur == tCQCKit::EVerboseLvls::Medium)
ridNew = kZWaveUSB3C::ridMenu_Opt_Trace_Medium;
else if (m_eTraceLevelCur == tCQCKit::EVerboseLvls::High)
ridNew = kZWaveUSB3C::ridMenu_Opt_Trace_High;
// Check new one and uncheck any previous
if (ridNew)
m_menuOpts.SetItemCheck(ridNew, kCIDLib::True, kCIDLib::True);
}
//
// If we see the configuration change here, then it was not caused by us, it
// was by the driver. The only thing that can be is that we have updated the
// state of a unit or it woke up and we were able to get info about it. Anything
// else can only change because we forced a replication and in that case the
// new config is explicitly requested and stored up front.
//
if(m_c4CfgSerNumNew != m_c4CfgSerNumCur)
{
m_c4CfgSerNumCur = m_c4CfgSerNumNew;
tCIDLib::TBoolean bCurChanged = kCIDLib::False;
tCIDLib::TCard4 c4ListSelInd = kCIDLib::c4MaxCard;
if (bInitial)
{
// Remember we have at least gotten valid config once
m_bGotConfig = kCIDLib::True;
// Copy new stuff to edit, then load units
m_dcfgEdit = m_dcfgNew;
LoadUnits();
}
else
{
//
// Not an initial load, so we start with current edits, and we will
// weave in any changes.
//
const tCIDLib::TCard4 c4Count = m_dcfgEdit.c4UnitCount();
c4ListSelInd = m_pwndList->c4CurItem();
tCIDLib::TStrList colCols;
colCols.AddXCopies
(
TString::strEmpty(), tCIDLib::c4EnumOrd(tZWaveUSB3C::EListCols::Count)
);
const tZWaveUSB3Sh::TUnitInfoList& colSrc = m_dcfgNew.colUnits();
for(tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++)
{
tCIDLib::TCard4 c4At;
if (m_dcfgEdit.bUpdateUnit(colSrc[c4Index], c4At))
{
m_dcfgEdit.bUpdateUnit(colSrc[c4Index], c4At);
const tCIDLib::TCard4 c4CurListInd = c4LoadUnitToList
(
m_dcfgEdit.unitiAt(c4At), colCols
);
if (c4ListSelInd == c4CurListInd)
bCurChanged = kCIDLib::True;
}
}
}
// Make new edit content the new baseline
m_dcfgOrg = m_dcfgEdit;
//
// If there weren't any before, select one if we can. Else force a re-selection
// on the current item if we changed it, so that the attribute editor will
// update.
//
if ((c4ListSelInd == kCIDLib::c4MaxCard) && m_pwndList->c4ItemCount())
m_pwndList->SelectByIndex(0);
else if (bCurChanged)
m_pwndList->SelectByIndex(c4ListSelInd, kCIDLib::True);
}
}
| 33.213483 | 120 | 0.58801 | [
"object",
"model"
] |
0980796bee10745fda88ddad8861e78bc0546b2f | 4,693 | cpp | C++ | source/examples/ex09_stream.cpp | 3a2l/OpenGL-Examples | a7284a0fc596898188f53671dac36ae60da62408 | [
"MIT"
] | 24 | 2020-11-01T17:14:59.000Z | 2022-03-24T11:48:05.000Z | source/examples/ex09_stream.cpp | 3a2l/OpenGL-Examples | a7284a0fc596898188f53671dac36ae60da62408 | [
"MIT"
] | 1 | 2020-11-06T15:44:37.000Z | 2020-11-07T20:47:01.000Z | source/examples/ex09_stream.cpp | 3a2l/OpenGL-Examples | a7284a0fc596898188f53671dac36ae60da62408 | [
"MIT"
] | 4 | 2020-11-02T14:34:49.000Z | 2021-12-22T09:58:06.000Z | #include <application.hpp>
#include <shader.hpp>
#include <imgui-utils/utils.hpp>
#include <vector>
struct Vertex {
glm::vec3 position;
glm::vec<4, glm::uint8, glm::defaultp> color;
};
class ElementsApplication : public our::Application {
our::ShaderProgram program;
GLuint vertex_array = 0, vertex_buffer = 0, element_buffer = 0;
std::vector<Vertex> vertices = {
{{-0.5, -0.5, 0.0},{255, 0, 0, 255}},
{{0.5, -0.5, 0.0},{0, 255, 0, 255}},
{{0.0, 0.5, 0.0},{0, 0, 255, 255}}
};
std::vector<uint16_t> elements = { 0, 1, 2 };
GLenum primitive_mode = GL_TRIANGLES, polygon_mode = GL_FILL;
bool use_elements = true;
our::WindowConfiguration getWindowConfiguration() override {
return { "Stream", {1280, 720}, false };
}
void onInitialize() override {
program.create();
program.attach("assets/shaders/ex06_multiple_attributes/multiple_attributes.vert", GL_VERTEX_SHADER);
program.attach("assets/shaders/ex04_varyings/varying_color.frag", GL_FRAGMENT_SHADER);
program.link();
glGenVertexArrays(1, &vertex_array);
glBindVertexArray(vertex_array);
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(Vertex), vertices.data(), GL_STREAM_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(Vertex), (void*)offsetof(Vertex, position));
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, true, sizeof(Vertex), (void*)offsetof(Vertex, color));
glEnableVertexAttribArray(1);
glGenBuffers(1, &element_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, elements.size()*sizeof(uint16_t), elements.data(), GL_STREAM_DRAW);
glBindVertexArray(0);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
void onDraw(double deltaTime) override {
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(Vertex), vertices.data(), GL_STREAM_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, elements.size()*sizeof(uint16_t), elements.data(), GL_STREAM_DRAW);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);
glBindVertexArray(vertex_array);
glPolygonMode(GL_FRONT_AND_BACK, polygon_mode);
if(use_elements)
glDrawElements(primitive_mode, elements.size(), GL_UNSIGNED_SHORT, (void*)0);
else
glDrawArrays(primitive_mode, 0, vertices.size());
glBindVertexArray(0);
if(keyboard.justPressed(GLFW_KEY_ESCAPE)) glfwSetWindowShouldClose(window, true);
}
void onDestroy() override {
program.destroy();
glDeleteVertexArrays(1, &vertex_array);
glDeleteBuffers(1, &vertex_buffer);;
glDeleteBuffers(1, &element_buffer);
}
void onImmediateGui(ImGuiIO &io) override {
ImGui::Begin("Controls");
our::OptionMapCombo("Primitive Type", primitive_mode, our::gl_enum_options::primitives);
our::OptionMapCombo("Polygon Mode", polygon_mode, our::gl_enum_options::polygon_modes);
ImGui::Checkbox("Use Elements", &use_elements);
ImGui::End();
ImGui::Begin("Vertices");
our::ReorderableList(std::begin(vertices), std::end(vertices),
[](size_t index, Vertex& vertex){
ImGui::Text("Vertex %zu", index);
ImGui::DragFloat3("Position", glm::value_ptr(vertex.position), 0.01, -2, 2);
our::ColorEdit4U8("Color", glm::value_ptr(vertex.color));
},
[&](size_t index){ vertices.insert(std::begin(vertices) + index, Vertex()); },
[&](size_t index){ vertices.erase(std::begin(vertices) + index); });
ImGui::End();
ImGui::Begin("Elements");
int max_element = (int)vertices.size() - 1;
float speed = 1.0f / (float)(max_element + 1);
our::ReorderableList(std::begin(elements), std::end(elements),
[&](size_t index, uint16_t & element){
std::string str_id = std::to_string(index);
int element_i32 = element;
ImGui::DragInt(str_id.c_str(), &element_i32, speed, 0, max_element);
element = element_i32;
},
[&](size_t index){ elements.insert(std::begin(elements) + index, 0); },
[&](size_t index){ elements.erase(std::begin(elements) + index); });
ImGui::End();
}
};
int main(int argc, char** argv) {
return ElementsApplication().run();
}
| 37.246032 | 113 | 0.644151 | [
"vector"
] |
099157da165bf0dace51a615af808b37eaece6e4 | 8,406 | cpp | C++ | bc/type.cpp | HansKristian-Work/DXIL2SPIRV | ea9ac33ae88c9efb0f864d473eb22c3c04d166a5 | [
"MIT"
] | 5 | 2019-11-07T13:14:56.000Z | 2019-12-09T20:01:47.000Z | bc/type.cpp | HansKristian-Work/DXIL2SPIRV | ea9ac33ae88c9efb0f864d473eb22c3c04d166a5 | [
"MIT"
] | null | null | null | bc/type.cpp | HansKristian-Work/DXIL2SPIRV | ea9ac33ae88c9efb0f864d473eb22c3c04d166a5 | [
"MIT"
] | null | null | null | /* Copyright (c) 2019-2022 Hans-Kristian Arntzen for Valve Corporation
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "type.hpp"
#include "cast.hpp"
#include "context.hpp"
#include <assert.h>
namespace LLVMBC
{
PointerType::PointerType(Type *type, uint32_t addr_space)
: Type(type->getContext(), TypeID::PointerTyID)
, contained_type(type)
{
address_space = addr_space;
}
PointerType *PointerType::get(Type *pointee, unsigned addr_space)
{
auto &context = pointee->getContext();
auto &cache = context.get_type_cache();
for (auto *type : cache)
{
if (type->getTypeID() == TypeID::PointerTyID)
{
auto *pointer_type = cast<PointerType>(type);
if (pointer_type->getAddressSpace() == addr_space && pointer_type->getElementType() == pointee)
return pointer_type;
}
}
auto *type = context.construct<PointerType>(pointee, addr_space);
cache.push_back(type);
return type;
}
unsigned Type::getAddressSpace() const
{
return address_space;
}
Type *PointerType::getElementType() const
{
return contained_type;
}
ArrayType::ArrayType(Type *type, uint64_t elements_)
: Type(type->getContext(), TypeID::ArrayTyID)
, contained_type(type)
, elements(elements_)
{
}
ArrayType *ArrayType::get(Type *element, uint64_t size)
{
auto &context = element->getContext();
auto &cache = context.get_type_cache();
for (auto *type : cache)
{
if (type->getTypeID() == TypeID::ArrayTyID)
{
auto *array_type = cast<ArrayType>(type);
if (array_type->getArrayNumElements() == size && array_type->getArrayElementType() == element)
return array_type;
}
}
auto *type = context.construct<ArrayType>(element, size);
cache.push_back(type);
return type;
}
VectorType::VectorType(LLVMBC::LLVMContext &context, unsigned vector_size_, LLVMBC::Type *type)
: Type(context, TypeID::VectorTyID)
, element_type(type)
, vector_size(vector_size_)
{
}
unsigned VectorType::getVectorSize() const
{
return vector_size;
}
Type *VectorType::getElementType() const
{
return element_type;
}
VectorType *VectorType::get(unsigned vector_size, Type *element)
{
auto &context = element->getContext();
auto &cache = context.get_type_cache();
for (auto *type : cache)
{
if (type->getTypeID() == TypeID::VectorTyID)
{
auto *vector_type = cast<VectorType>(type);
if (vector_type->getVectorSize() == vector_size && vector_type->getElementType() == element)
return vector_type;
}
}
auto *type = context.construct<VectorType>(context, vector_size, element);
cache.push_back(type);
return type;
}
uint64_t Type::getArrayNumElements() const
{
assert(type_id == TypeID::ArrayTyID);
return cast<ArrayType>(this)->elements;
}
unsigned Type::getVectorNumElements() const
{
assert(type_id == TypeID::VectorTyID);
return cast<VectorType>(this)->getVectorSize();
}
Type *Type::getArrayElementType() const
{
assert(type_id == TypeID::ArrayTyID);
return cast<ArrayType>(this)->contained_type;
}
Type *Type::getStructElementType(unsigned index) const
{
assert(type_id == TypeID::StructTyID);
return cast<StructType>(this)->getElementType(index);
}
unsigned Type::getStructNumElements() const
{
assert(type_id == TypeID::StructTyID);
return cast<StructType>(this)->getNumElements();
}
unsigned Type::getIntegerBitWidth() const
{
assert(type_id == TypeID::IntegerTyID);
return cast<IntegerType>(this)->getBitWidth();
}
Type *Type::getPointerElementType() const
{
assert(type_id == TypeID::PointerTyID);
return cast<PointerType>(this)->getElementType();
}
StructType::StructType(LLVMContext &context, Vector<Type *> member_types_)
: Type(context, TypeID::StructTyID)
, member_types(std::move(member_types_))
{
}
unsigned StructType::getNumElements() const
{
return member_types.size();
}
Type *StructType::getElementType(unsigned N) const
{
assert(N < member_types.size());
return member_types[N];
}
StructType *StructType::get(LLVMContext &context, Vector<Type *> member_types)
{
auto &cache = context.get_type_cache();
for (auto *type : cache)
{
if (type->getTypeID() == TypeID::StructTyID)
{
auto *struct_type = cast<StructType>(type);
if (struct_type->getNumElements() == member_types.size())
{
bool equal = true;
unsigned count = member_types.size();
for (unsigned i = 0; i < count; i++)
{
if (member_types[i] != struct_type->getElementType(i))
{
equal = false;
break;
}
}
if (equal)
return struct_type;
}
}
}
auto *type = context.construct<StructType>(context, std::move(member_types));
cache.push_back(type);
return type;
}
FunctionType::FunctionType(LLVMContext &context, Type *return_type_, Vector<Type *> argument_types_)
: Type(context, TypeID::FunctionTyID)
, return_type(return_type_)
, argument_types(std::move(argument_types_))
{
}
unsigned FunctionType::getNumParams() const
{
return unsigned(argument_types.size());
}
Type *FunctionType::getParamType(unsigned index) const
{
assert(index < argument_types.size());
return argument_types[index];
}
Type *FunctionType::getReturnType() const
{
return return_type;
}
IntegerType::IntegerType(LLVMContext &context, uint32_t width_)
: Type(context, TypeID::IntegerTyID)
, width(width_)
{
}
uint32_t IntegerType::getBitWidth() const
{
return width;
}
Type::Type(LLVMContext &context_, TypeID type_id_)
: context(context_)
, type_id(type_id_)
{
}
Type::TypeID Type::getTypeID() const
{
return type_id;
}
Type *Type::getIntTy(LLVMContext &context, uint32_t width)
{
auto &cache = context.get_type_cache();
for (auto *type : cache)
if (type->getTypeID() == TypeID::IntegerTyID && cast<IntegerType>(type)->getBitWidth() == width)
return type;
auto *type = context.construct<IntegerType>(context, width);
cache.push_back(type);
return type;
}
Type *Type::getTy(LLVMContext &context, TypeID id)
{
auto &cache = context.get_type_cache();
for (auto *type : cache)
if (type->getTypeID() == id)
return type;
auto *type = context.construct<Type>(context, id);
cache.push_back(type);
return type;
}
Type *Type::getVoidTy(LLVMContext &context)
{
return getTy(context, TypeID::VoidTyID);
}
Type *Type::getHalfTy(LLVMContext &context)
{
return getTy(context, TypeID::HalfTyID);
}
Type *Type::getFloatTy(LLVMContext &context)
{
return getTy(context, TypeID::FloatTyID);
}
Type *Type::getDoubleTy(LLVMContext &context)
{
return getTy(context, TypeID::DoubleTyID);
}
Type *Type::getLabelTy(LLVMContext &context)
{
return getTy(context, TypeID::LabelTyID);
}
Type *Type::getMetadataTy(LLVMContext &context)
{
return getTy(context, TypeID::MetadataTyID);
}
Type *Type::getInt1Ty(LLVMContext &context)
{
return getIntTy(context, 1);
}
Type *Type::getInt8Ty(LLVMContext &context)
{
return getIntTy(context, 8);
}
Type *Type::getInt16Ty(LLVMContext &context)
{
return getIntTy(context, 16);
}
Type *Type::getInt32Ty(LLVMContext &context)
{
return getIntTy(context, 32);
}
Type *Type::getInt64Ty(LLVMContext &context)
{
return getIntTy(context, 64);
}
bool Type::isIntegerTy() const
{
return type_id == TypeID::IntegerTyID;
}
bool Type::isFloatingPointTy() const
{
return type_id == TypeID::HalfTyID || type_id == TypeID::FloatTyID || type_id == TypeID::DoubleTyID;
}
LLVMContext &Type::getContext()
{
return context;
}
} // namespace LLVMBC
| 23.35 | 101 | 0.719367 | [
"vector"
] |
09a3842c15a7d14f5a23446a57f96ac0b7fd5d2d | 796 | cpp | C++ | examples/main.cpp | mauzil/IntelHexParser | 94af820f29f02fcc70a539180480760543669a8f | [
"MIT"
] | 2 | 2018-05-16T04:44:08.000Z | 2021-04-28T11:49:32.000Z | examples/main.cpp | mauzil/IntelHexParser | 94af820f29f02fcc70a539180480760543669a8f | [
"MIT"
] | 1 | 2019-11-26T14:45:13.000Z | 2019-11-26T14:45:13.000Z | examples/main.cpp | mauzil/IntelHexParser | 94af820f29f02fcc70a539180480760543669a8f | [
"MIT"
] | 6 | 2016-01-07T17:00:23.000Z | 2020-10-03T07:02:10.000Z | #include "../include/IntelHexFile.h"
#include <iostream>
#include <assert.h>
using namespace std;
void usage(string name);
#define PAGE_SIZE 255
int main(int argc, char* argv[])
{
if(argc < 2)
{
usage(argv[0]);
return 1;
}
/*
* Parse file
*/
IntelHexFile file(argv[1]);
cout << "File: " << file << endl;
/*
* Get the program
*/
Program program = file.getProgram();
cout << "Program: " << program << endl;
/*
* Get the program in a vector of pages
*/
vector<ProgramPage> programPages = program.getPages(PAGE_SIZE);
for(vector<ProgramPage>::iterator it = programPages.begin(); it != programPages.end(); ++it)
{
ProgramPage page = (*it);
cout << "Page: " << page << endl;
}
return 0;
}
void usage(string name)
{
cout << name << ": [*.hex]" << endl;
}
| 15.92 | 93 | 0.611809 | [
"vector"
] |
09a7d9fae1fac7c62e79863b0784d03e0947fce0 | 8,029 | cpp | C++ | Anomaly Engine/src/Anomaly/Rendering/Primatives/Shader.cpp | Smkautltl/Anomaly-Engine | 02dc713c611e1fb91674fb8bc93445e488e77b20 | [
"Apache-2.0"
] | null | null | null | Anomaly Engine/src/Anomaly/Rendering/Primatives/Shader.cpp | Smkautltl/Anomaly-Engine | 02dc713c611e1fb91674fb8bc93445e488e77b20 | [
"Apache-2.0"
] | null | null | null | Anomaly Engine/src/Anomaly/Rendering/Primatives/Shader.cpp | Smkautltl/Anomaly-Engine | 02dc713c611e1fb91674fb8bc93445e488e77b20 | [
"Apache-2.0"
] | null | null | null | #include "aepch.h"
#include "Shader.h"
#include <Anomaly/Rendering/stb_image.h>
#include <glad/glad.h>
namespace Anomaly
{
Shader::Shader(const char* VertexSrcFileName, const char* FragmentSrcFileName, const char* geometryPath)
{
ReadInShaders(VertexSrcFileName, FragmentSrcFileName, geometryPath);
// Create an empty vertex shader handle
GLchar* source = const_cast<GLchar*>(VertexSrc.c_str());
GLint isCompiled = 0;
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
{
glShaderSource(vertexShader, 1, &source, nullptr);
// Compile the vertex shader
glCompileShader(vertexShader);
CheckComplied(vertexShader, "VERTEX");
}
// Create an empty fragment shader handle
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
{
// Send the fragment shader source code to GL
source = const_cast<GLchar*>(FragmentSrc.c_str());
glShaderSource(fragmentShader, 1, &source, 0);
// Compile the fragment shader
glCompileShader(fragmentShader);
CheckComplied(vertexShader, "FRAGMENT");
}
// Create an empty geometry shader handle
GLuint GeomShader = glCreateShader(GL_GEOMETRY_SHADER);
{
// Send the Geom shader source code to GL
if(geometryPath != nullptr)
{
source = const_cast<GLchar*>(GeomSrc.c_str());
glShaderSource(GeomShader, 1, &source, 0);
// Compile the fragment shader
glCompileShader(GeomShader);
CheckComplied(vertexShader, "GEOMETRY");
}
}
// Vertex, fragment and geom shaders are successfully compiled.
// Now time to link them together into a program.
// Get a program object.
m_RendererID = glCreateProgram();
// Attach our shaders to our program
glAttachShader(m_RendererID, vertexShader);
glAttachShader(m_RendererID, fragmentShader);
if(geometryPath != nullptr)
glAttachShader(m_RendererID, GeomShader);
// Link our program
glLinkProgram(m_RendererID);
CheckComplied(m_RendererID, "PROGRAM");
// Always detach shaders after a successful link.
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
if(geometryPath != nullptr)
glDeleteShader(GeomShader);
}
Shader::~Shader()
{
glDeleteProgram(m_RendererID);
}
void Shader::Bind() const
{
glUseProgram(m_RendererID);
}
void Shader::UnBind() const
{
glUseProgram(0);
}
void Shader::ReadInShaders(const char* VertexSrcFileName, const char* FragmentSrcFileName, const char* geometrySrcFileName)
{
//Vertex Shader
{
std::string AppPathVert = __argv[0];
AppPathVert.replace(AppPathVert.end() - 11, AppPathVert.end(), "Content\\Shaders\\" + std::string(VertexSrcFileName));
vPath = AppPathVert.c_str();
std::ifstream VertexShaderFile;
VertexShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
VertexShaderFile.open(vPath);
std::stringstream ShaderStreamVert;
ShaderStreamVert << VertexShaderFile.rdbuf();
VertexSrc = ShaderStreamVert.str();
VertexShaderFile.close();
}
catch (std::ifstream::failure e)
{
AE_CORE_ERROR("Vertex Shader File failed to read!: {0}", e.what());
}
}
//Fragment Shader
{
std::string AppPathFrag = __argv[0];
AppPathFrag.replace(AppPathFrag.end() - 11, AppPathFrag.end(), "Content\\Shaders\\" + std::string(FragmentSrcFileName));
fPath = AppPathFrag.c_str();
std::stringstream ShaderStreamFrag;
std::ifstream FragmentShaderFile;
FragmentShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
FragmentShaderFile.open(fPath);
ShaderStreamFrag << FragmentShaderFile.rdbuf();
FragmentSrc = ShaderStreamFrag.str();
FragmentShaderFile.close();
}
catch (std::ifstream::failure e)
{
AE_CORE_ERROR("Fragment Shader File failed to read!: {0}", e.what());
}
}
//Geom Shader
{
if(geometrySrcFileName != nullptr)
{
std::string AppPathGeom = __argv[0];
AppPathGeom.replace(AppPathGeom.end() - 11, AppPathGeom.end(), "Content\\Shaders\\" + std::string(geometrySrcFileName));
gPath = AppPathGeom.c_str();
std::stringstream ShaderStreamGeom;
std::ifstream GeomShaderFile;
GeomShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
GeomShaderFile.open(gPath);
ShaderStreamGeom << GeomShaderFile.rdbuf();
GeomSrc = ShaderStreamGeom.str();
GeomShaderFile.close();
}
catch (std::ifstream::failure e)
{
AE_CORE_ERROR("Geometry Shader File failed to read!: {0}", e.what());
}
}
}
}
void Shader::CheckComplied(unsigned shader, std::string type)
{
GLint Completed;
GLchar infoLog[1024];
if(type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &Completed);
if(!Completed)
{
std::string path;
if(type == "VERTEX")
{
path = vPath;
}
else if(type == "FRAGMENT")
{
path = fPath;
}
else if(type == "GEOMETRY")
{
path = gPath;
}
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
AE_CORE_ERROR("Shader failed to COMPILE of Type:{0} \n LOG:{1} \nPATH: {2}", type, infoLog, path);
}
}
else
{
glGetProgramiv(shader, GL_LINK_STATUS, &Completed);
if(!Completed)
{
std::string path;
if(type == "VERTEX")
{
path = vPath;
}
else if(type == "FRAGMENT")
{
path = fPath;
}
else if(type == "GEOMETRY")
{
path = gPath;
}
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
AE_CORE_ERROR("Shader failed to LINK of Type:{0} \n LOG:{1} \nPATH: {2}", type, infoLog, path);
}
}
}
void Shader::GenerateTextures(const std::vector<char*> SrcFileName)
{
for (auto i = 0; i < SrcFileName.size(); i++)
{
//Generates and binds 1st texture
std::string AppPath = __argv[0];
AppPath.replace(AppPath.end() - 11, AppPath.end(), "Content\\Textures\\" + std::string(SrcFileName[i]));
const char* tPath = AppPath.c_str();
m_textures.push_back(0);
glGenTextures(0 + i, &m_textures[i]);
glBindTexture(GL_TEXTURE_2D, m_textures[i]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int width, height, nrchannels;
stbi_set_flip_vertically_on_load(true);
unsigned char *data = stbi_load(tPath, &width, &height, &nrchannels, 0);
if(data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
AE_CORE_ERROR("Texture failed to load!");
}
stbi_image_free(data);
}
}
void Shader::BindTexture(unsigned int id)
{
glBindTexture(GL_TEXTURE_2D, id);
}
void Shader::BindAllTextures()
{
for (auto texture : m_textures)
{
glBindTexture(GL_TEXTURE_2D, texture);
}
}
void Shader::SetActiveTexture(int num)
{
glActiveTexture(GL_TEXTURE0 + num);
}
void Shader::SetUniformMatrix4(const std::string& name, const glm::mat4& matrix) const
{
GLint location = glGetUniformLocation(m_RendererID, name.c_str());
glUniformMatrix4fv(location, 1, GL_FALSE ,glm::value_ptr(matrix));
}
void Shader::SetUniformBool(const std::string& name, bool value) const
{
GLint location = glGetUniformLocation(m_RendererID, name.c_str());
glUniform1i(location, value);
}
void Shader::SetUniformInt(const std::string& name, int value) const
{
GLint location = glGetUniformLocation(m_RendererID, name.c_str());
glUniform1i(location, value);
}
void Shader::SetUniformFloat(const std::string& name, float value) const
{
GLint location = glGetUniformLocation(m_RendererID, name.c_str());
glUniform1f(location, value);
}
void Shader::SetUniformVec3(const std::string& name, glm::vec3 value) const
{
GLint location = glGetUniformLocation(m_RendererID, name.c_str());
glUniform3f(location, value.r, value.g, value.b);
}
}
| 27.216949 | 124 | 0.686511 | [
"geometry",
"object",
"vector"
] |
09b693ce6357f74e788df5487ee903f96ed08459 | 147,209 | cpp | C++ | codec/h264_enc/src/umc_h264_deblocking.cpp | viticm/ipp-media | 1d942e8b04ce1e4e02787e2f451b2091061e1b4d | [
"MIT"
] | 1 | 2022-03-02T20:23:13.000Z | 2022-03-02T20:23:13.000Z | codec/h264_enc/src/umc_h264_deblocking.cpp | viticm/ipp-media | 1d942e8b04ce1e4e02787e2f451b2091061e1b4d | [
"MIT"
] | null | null | null | codec/h264_enc/src/umc_h264_deblocking.cpp | viticm/ipp-media | 1d942e8b04ce1e4e02787e2f451b2091061e1b4d | [
"MIT"
] | null | null | null | /*
//
// INTEL CORPORATION PROPRIETARY INFORMATION
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Intel Corporation and may not be copied
// or disclosed except in accordance with the terms of that agreement.
// Copyright (c) 2003-2012 Intel Corporation. All Rights Reserved.
//
//
*/
#include "umc_config.h"
#ifdef UMC_ENABLE_H264_VIDEO_ENCODER
#include "umc_h264_video_encoder.h"
#include "umc_h264_deblocking.h"
#include "umc_h264_deblocking_tools.h"
#include "vm_types.h"
#include "vm_debug.h"
#include "umc_h264_to_ipp.h"
#include "umc_h264_bme.h"
// alpha table
Ipp8u ENCODER_ALPHA_TABLE_8u[52] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
4, 4, 5, 6, 7, 8, 9, 10,
12, 13, 15, 17, 20, 22, 25, 28,
32, 36, 40, 45, 50, 56, 63, 71,
80, 90, 101,113,127,144,162,182,
203,226,255,255
};
// beta table
Ipp8u ENCODER_BETA_TABLE_8u[52] =
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 3, 3, 3, 3, 4,
4, 4, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12,
13, 13, 14, 14, 15, 15, 16, 16,
17, 17, 18, 18
};
// clipping table
Ipp8u ENCODER_CLIP_TAB_8u[52][5] =
{
{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},{ 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0},{ 0, 0, 0, 1, 1},{ 0, 0, 0, 1, 1},{ 0, 0, 0, 1, 1},{ 0, 0, 0, 1, 1},{ 0, 0, 1, 1, 1},{ 0, 0, 1, 1, 1},{ 0, 1, 1, 1, 1},
{ 0, 1, 1, 1, 1},{ 0, 1, 1, 1, 1},{ 0, 1, 1, 1, 1},{ 0, 1, 1, 2, 2},{ 0, 1, 1, 2, 2},{ 0, 1, 1, 2, 2},{ 0, 1, 1, 2, 2},{ 0, 1, 2, 3, 3},
{ 0, 1, 2, 3, 3},{ 0, 2, 2, 3, 3},{ 0, 2, 2, 4, 4},{ 0, 2, 3, 4, 4},{ 0, 2, 3, 4, 4},{ 0, 3, 3, 5, 5},{ 0, 3, 4, 6, 6},{ 0, 3, 4, 6, 6},
{ 0, 4, 5, 7, 7},{ 0, 4, 5, 8, 8},{ 0, 4, 6, 9, 9},{ 0, 5, 7,10,10},{ 0, 6, 8,11,11},{ 0, 6, 8,13,13},{ 0, 7,10,14,14},{ 0, 8,11,16,16},
{ 0, 9,12,18,18},{ 0,10,13,20,20},{ 0,11,15,23,23},{ 0,13,17,25,25}
};
// chroma scaling QP table
Ipp8u ENCODER_QP_SCALE_CR[52] =
{
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 29, 30,
31, 32, 32, 33, 34, 34, 35, 35,
36, 36, 37, 37, 37, 38, 38, 38,
39, 39, 39, 39
};
// masks for external blocks pair "coded bits"
Ipp32u ENCODER_EXTERNAL_BLOCK_MASK[NUMBER_OF_DIRECTION][2][4] =
{
// block mask for vertical deblocking
{
{2 << 0, 2 << 2, 2 << 8, 2 << 10},
{2 << 5, 2 << 7, 2 << 13,2 << 15}
},
// block mask for horizontal deblocking
{
{2 << 0, 2 << 1, 2 << 4, 2 << 5},
{2 << 10,2 << 11,2 << 14,2 << 15}
}
};
#define DECL(prev, cur) (2 << (prev) | 2 << (cur))
// masks for internal blocks pair "coded bits"
Ipp32u ENCODER_INTERNAL_BLOCKS_MASK[NUMBER_OF_DIRECTION][12] =
{
// blocks pair-mask for vertical deblocking
{
DECL(0, 1), DECL(2, 3), DECL(8, 9), DECL(10, 11),
DECL(1, 4), DECL(3, 6), DECL(9, 12), DECL(11, 14),
DECL(4, 5), DECL(6, 7), DECL(12, 13),DECL(14, 15)
},
// blocks pair-mask for horizontal deblocking
{
DECL(0, 2), DECL(1, 3), DECL(4, 6), DECL(5, 7),
DECL(2, 8), DECL(3, 9), DECL(6, 12), DECL(7, 13),
DECL(8, 10), DECL(9, 11), DECL(12, 14),DECL(13, 15)
}
};
#undef DECL
//////////////
// implement array of IPP optimized luma deblocking functions
#if defined(_WIN32_WCE) && defined(_M_IX86) && defined(__stdcall)
#define _IPP_STDCALL_CDECL
#undef __stdcall
#endif // defined(_WIN32_WCE) && defined(_M_IX86) && defined(__stdcall)
IppStatus FilterDeblockingLuma_VerEdge(
Ipp8u *pSrcDst,
Ipp32s srcDstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS)
{
return(ippiFilterDeblockingLuma_VerEdge_H264_8u_C1IR(pSrcDst, srcDstStep, pAlpha, pBeta, pThresholds, pBS));
}
IppStatus FilterDeblockingLuma_HorEdge(
Ipp8u *pSrcDst,
Ipp32s srcDstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS)
{
return(ippiFilterDeblockingLuma_HorEdge_H264_8u_C1IR(pSrcDst, srcDstStep, pAlpha, pBeta, pThresholds, pBS));
}
IppStatus (*(EncoderIppLumaDeblocking_8u[])) (Ipp8u *, Ipp32s, Ipp8u *, Ipp8u *, Ipp8u *, Ipp8u *) =
{
&(FilterDeblockingLuma_VerEdge),
&(FilterDeblockingLuma_HorEdge)
};
inline IppStatus encoderIppLumaDeblocking(
Ipp32s dir,
Ipp8u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBetha,
Ipp8u* pThresholds,
Ipp8u* pBs,
Ipp32s)
{
return(EncoderIppLumaDeblocking_8u[dir](pSrcDst, srcdstStep, pAlpha, pBetha, pThresholds, pBs));
}
IppStatus FilterDeblockingChroma_VerEdge(
Ipp8u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS)
{
return ippiFilterDeblockingChroma_VerEdge_H264_8u_C1IR(pSrcDst, srcdstStep, pAlpha, pBeta, pThresholds, pBS);
}
IppStatus FilterDeblockingChroma_HorEdge(
Ipp8u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS)
{
return ippiFilterDeblockingChroma_HorEdge_H264_8u_C1IR(pSrcDst, srcdstStep, pAlpha, pBeta, pThresholds, pBS);
}
IppStatus FilterDeblockingChroma422_VerEdge(
Ipp8u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS)
{
CONVERT_TO_8U(2, 8);
return ippiFilterDeblockingChroma422VerEdge_H264_8u_C1IR(&info);
}
IppStatus FilterDeblockingChroma422_HorEdge(
Ipp8u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS)
{
CONVERT_TO_8U(2, 16);
return ippiFilterDeblockingChroma422HorEdge_H264_8u_C1IR(&info);
}
// implement array of IPP optimized chroma deblocking functions
IppStatus (*(EncoderIppChromaDeblocking_8u[])) (Ipp8u *, Ipp32s, Ipp8u *, Ipp8u *, Ipp8u *, Ipp8u *) =
{
&(FilterDeblockingChroma_VerEdge),
&(FilterDeblockingChroma_HorEdge),
&(FilterDeblockingChroma422_VerEdge),
&(FilterDeblockingChroma422_HorEdge)
};
inline IppStatus encoderIppChromaDeblocking(
Ipp32s dir,
Ipp8u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBetha,
Ipp8u* pThresholds,
Ipp8u* pBs,
Ipp32s)
{
return(EncoderIppChromaDeblocking_8u[dir](pSrcDst, srcdstStep, pAlpha, pBetha, pThresholds, pBs));
}
IppStatus FilterDeblockingLuma_VerEdge(
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS,
Ipp32s bit_depth)
{
CONVERT_TO_16U(2, 16);
return ippiFilterDeblockingLumaVerEdge_H264_16u_C1IR(&info);
}
IppStatus FilterDeblockingLuma_HorEdge(
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS,
Ipp32s bit_depth)
{
CONVERT_TO_16U(2, 16);
return ippiFilterDeblockingLumaHorEdge_H264_16u_C1IR(&info);
}
IppStatus (*(EncoderIppLumaDeblocking_16s[])) (Ipp16u *, Ipp32s, Ipp8u *, Ipp8u *, Ipp8u *, Ipp8u *, Ipp32s bitdepth) =
{
&(FilterDeblockingLuma_VerEdge),
&(FilterDeblockingLuma_HorEdge)
};
inline IppStatus encoderIppLumaDeblocking(
Ipp32s dir,
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBetha,
Ipp8u* pThresholds,
Ipp8u* pBs,
Ipp32s bitdepth)
{
return(EncoderIppLumaDeblocking_16s[dir](pSrcDst, srcdstStep, pAlpha, pBetha, pThresholds, pBs, bitdepth));
}
IppStatus FilterDeblockingChroma_VerEdge(
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS,
Ipp32s bit_depth)
{
CONVERT_TO_16U(2, 8);
return ippiFilterDeblockingChromaVerEdge_H264_16u_C1IR(&info);
}
IppStatus FilterDeblockingChroma_HorEdge(
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS,
Ipp32s bit_depth)
{
CONVERT_TO_16U(2, 8);
return ippiFilterDeblockingChromaHorEdge_H264_16u_C1IR(&info);
}
IppStatus FilterDeblockingChroma422_VerEdge(
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS,
Ipp32s bit_depth)
{
CONVERT_TO_16U(2, 16);
return ippiFilterDeblockingChroma422VerEdge_H264_16u_C1IR(&info);
}
IppStatus FilterDeblockingChroma422_HorEdge(
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBeta,
Ipp8u* pThresholds,
Ipp8u* pBS,
Ipp32s bit_depth)
{
CONVERT_TO_16U(2, 16);
return ippiFilterDeblockingChroma422HorEdge_H264_16u_C1IR(&info);//return DeblockChroma422_hor_16u(&info);
}
IppStatus (*(EncoderIppChromaDeblocking_16s[])) (Ipp16u *, Ipp32s, Ipp8u *, Ipp8u *, Ipp8u *, Ipp8u *, Ipp32s bitdepth) =
{
&(FilterDeblockingChroma_VerEdge),
&(FilterDeblockingChroma_HorEdge),
&(FilterDeblockingChroma422_VerEdge),
&(FilterDeblockingChroma422_HorEdge)
};
inline IppStatus encoderIppChromaDeblocking(
Ipp32s dir,
Ipp16u* pSrcDst,
Ipp32s srcdstStep,
Ipp8u* pAlpha,
Ipp8u* pBetha,
Ipp8u* pThresholds,
Ipp8u* pBs,
Ipp32s bitdepth)
{
return(EncoderIppChromaDeblocking_16s[dir](pSrcDst, srcdstStep, pAlpha, pBetha, pThresholds, pBs, bitdepth));
}
#if defined(_IPP_STDCALL_CDECL)
#undef _IPP_STDCALL_CDECL
#define __stdcall __cdecl
#endif // defined(_IPP_STDCALL_CDECL)
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_ResetDeblockingVariables(void* state, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
PIXTYPE *pY, *pU, *pV;
Ipp32u offset;
Ipp32s MBYAdjust = 0;
Ipp32u mbXOffset, mbYOffset;
Ipp32s pic_pitchPixels = core_enc->m_pCurrentFrame->m_pitchPixels;
Ipp32u MBAddr = pParams->nMBAddr;
Ipp32u nCurrMB_X, nCurrMB_Y;
H264Slice<COEFFSTYPE, PIXTYPE> *curr_slice;
if(core_enc->m_MaxSliceSize)
curr_slice = &core_enc->m_Slices[0];
else
curr_slice = &core_enc->m_Slices[core_enc->m_pCurrentFrame->m_mbinfo.mbs[MBAddr].slice_id];
// load planes
pY = core_enc->m_pReconstructFrame->m_pYPlane;
pU = core_enc->m_pReconstructFrame->m_pUPlane;
pV = core_enc->m_pReconstructFrame->m_pVPlane;
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
if(core_enc->m_pCurrentFrame->m_bottom_field_flag[core_enc->m_field_index])
{
pY += pic_pitchPixels;
pU += pic_pitchPixels;
pV += pic_pitchPixels;
}
if (core_enc->m_field_index)
MBYAdjust = core_enc->m_HeightInMBs;
pic_pitchPixels *= 2;
}
// prepare macroblock variables
nCurrMB_X = (MBAddr % core_enc->m_WidthInMBs);
nCurrMB_Y = (MBAddr / core_enc->m_WidthInMBs)- MBYAdjust;
Ipp32s chromaShiftX;
Ipp32s chromaShiftY;
switch(core_enc->m_PicParamSet.chroma_format_idc) {
case 0: //MONOCHROME
chromaShiftX = chromaShiftY = 0;
break;
case 2: //422
chromaShiftX = 3;
chromaShiftY = 4;
break;
case 3: //444
chromaShiftX = chromaShiftY = 4;
break;
case 1: //420
default:
chromaShiftX = chromaShiftY = 3;
}
mbXOffset = nCurrMB_X * 16;
mbYOffset = nCurrMB_Y * 16;
Ipp32s chromaXOffset = nCurrMB_X<<chromaShiftX;
Ipp32s chromaYOffset = nCurrMB_Y<<chromaShiftY;
// calc plane's offsets
offset = mbXOffset + (mbYOffset * pic_pitchPixels);
pY += offset;
pU += chromaXOffset + chromaYOffset * pic_pitchPixels;
pV += chromaXOffset + chromaYOffset * pic_pitchPixels;
// set external edge variables
pParams->ExternalEdgeFlag[VERTICAL_DEBLOCKING] = (nCurrMB_X != 0);
pParams->ExternalEdgeFlag[HORIZONTAL_DEBLOCKING] = (nCurrMB_Y != 0);
if (DEBLOCK_FILTER_ON_NO_SLICE_EDGES == curr_slice->m_disable_deblocking_filter_idc)
{
// don't filter at slice boundaries
if (nCurrMB_X)
{
if (core_enc->m_pCurrentFrame->m_mbinfo.mbs[MBAddr].slice_id !=
core_enc->m_pCurrentFrame->m_mbinfo.mbs[MBAddr - 1].slice_id)
pParams->ExternalEdgeFlag[VERTICAL_DEBLOCKING] = 0;
}
if (nCurrMB_Y)
{
if (core_enc->m_pCurrentFrame->m_mbinfo.mbs[MBAddr].slice_id !=
core_enc->m_pCurrentFrame->m_mbinfo.mbs[MBAddr - core_enc->m_WidthInMBs].slice_id)
pParams->ExternalEdgeFlag[HORIZONTAL_DEBLOCKING] = 0;
}
}
// reset external edges strength
SetEdgeStrength(pParams->Strength[VERTICAL_DEBLOCKING], 0);
SetEdgeStrength(pParams->Strength[HORIZONTAL_DEBLOCKING], 0);
// set neighbour addreses
pParams->nNeighbour[VERTICAL_DEBLOCKING] = MBAddr - 1;
pParams->nNeighbour[HORIZONTAL_DEBLOCKING] = MBAddr - core_enc->m_WidthInMBs;
// set deblocking flag(s)
pParams->DeblockingFlag[VERTICAL_DEBLOCKING] = 0;
pParams->DeblockingFlag[HORIZONTAL_DEBLOCKING] = 0;
// save variables
pParams->pY = pY;
pParams->pU = pU;
pParams->pV = pV;
pParams->pitchPixels = pic_pitchPixels;
pParams->nMaxMVector = (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec) ? (2) : (4);
pParams->MBFieldCoded = (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec);
// set slice's variables
pParams->nAlphaC0Offset = curr_slice->m_slice_alpha_c0_offset;
pParams->nBetaOffset = curr_slice->m_slice_beta_offset;
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_DeblockMacroblockISlice(void* state, Ipp32u MBAddr)
{
__align(16)
DeblockingParameters<PIXTYPE> params;
// prepare deblocking parameters
params.nMBAddr = MBAddr;
H264CoreEncoder_ResetDeblockingVariables<COEFFSTYPE, PIXTYPE>(state, ¶ms);
H264CoreEncoder_PrepareDeblockingParametersISlice(state, ¶ms);
// perform deblocking
//!!!Chroma must be called first because luma clears strength for 8x8 transform.
H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, ¶ms);
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_DeblockMacroblockPSlice(void* state, Ipp32u MBAddr)
{
__align(16)
DeblockingParameters<PIXTYPE> params;
// prepare deblocking parameters
params.nMBAddr = MBAddr;
H264CoreEncoder_ResetDeblockingVariables<COEFFSTYPE, PIXTYPE>(state, ¶ms);
H264CoreEncoder_PrepareDeblockingParametersPSlice<COEFFSTYPE, PIXTYPE>(state, ¶ms);
// perform deblocking
//!!!Chroma must be called first because luma clears strength for 8x8 transform.
H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, ¶ms);
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_DeblockMacroblockBSlice(void* state, Ipp32u MBAddr)
{
__align(16)
DeblockingParameters<PIXTYPE> params;
// prepare deblocking parameters
params.nMBAddr = MBAddr;
H264CoreEncoder_ResetDeblockingVariables<COEFFSTYPE, PIXTYPE>(state, ¶ms);
H264CoreEncoder_PrepareDeblockingParametersBSlice<COEFFSTYPE, PIXTYPE>(state, ¶ms);
// perform deblocking
//!!!Chroma must be called first because luma clears strength for 8x8 transform.
H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, ¶ms);
H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, ¶ms);
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_DeblockSlice(void* state, H264Slice<COEFFSTYPE, PIXTYPE> *curr_slice, Ipp32u uFirstMB, Ipp32u unumMBs)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
H264CoreEncoder_DeblockingFunction pDeblocking = NULL;
// no filtering edges of this slice
if (DEBLOCK_FILTER_OFF == curr_slice->m_disable_deblocking_filter_idc)
return;
// MBAFF case
if (core_enc->m_SliceHeader.MbaffFrameFlag)
{
// select optimized deblocking function
switch (curr_slice->m_slice_type)
{
case INTRASLICE:
pDeblocking = &H264CoreEncoder_DeblockMacroblockISliceMBAFF<COEFFSTYPE, PIXTYPE>;
break;
case PREDSLICE:
pDeblocking = &H264CoreEncoder_DeblockMacroblockPSliceMBAFF<COEFFSTYPE, PIXTYPE>;
break;
case BPREDSLICE:
pDeblocking = &H264CoreEncoder_DeblockMacroblockBSliceMBAFF<COEFFSTYPE, PIXTYPE>;
break;
default:
pDeblocking = NULL;
break;
}
}
// non-MBAFF case
else
{
// select optimized deblocking function
switch (curr_slice->m_slice_type)
{
case INTRASLICE:
pDeblocking = &H264CoreEncoder_DeblockMacroblockISlice<COEFFSTYPE, PIXTYPE>;
break;
case PREDSLICE:
pDeblocking = &H264CoreEncoder_DeblockMacroblockPSlice<COEFFSTYPE, PIXTYPE>;
break;
case BPREDSLICE:
pDeblocking = &H264CoreEncoder_DeblockMacroblockBSlice<COEFFSTYPE, PIXTYPE>;
break;
default:
pDeblocking = NULL;
break;
}
}
if (NULL == pDeblocking)
return;
// perform deblocking process on every macroblock
Ipp32u i;
for (i = uFirstMB; i < uFirstMB + unumMBs; i++)
(*pDeblocking)(state, i);
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_DeblockLuma(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
PIXTYPE *pY = pParams->pY;
Ipp32s pic_pitchPixels = pParams->pitchPixels;
Ipp32s MBAddr = pParams->nMBAddr;
Ipp8u Clipping[16];
Ipp8u Alpha[2];
Ipp8u Beta[2];
Ipp32s AlphaC0Offset = pParams->nAlphaC0Offset;
Ipp32s BetaOffset = pParams->nBetaOffset;
Ipp32s pmq_QP = core_enc->m_mbinfo.mbs[MBAddr].QP;
//
// luma deblocking
//
if (pParams->DeblockingFlag[dir])
{
Ipp8u *pClipTab;
Ipp32s QP;
Ipp32s index;
Ipp8u *pStrength = pParams->Strength[dir];
//
// correct strengths for high profile
//
if (pGetMB8x8TSFlag(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr))
{
SetEdgeStrength(pStrength + 4, 0); // 16 bits????
SetEdgeStrength(pStrength + 12, 0);
}
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32s pmp_QP;
// get neighbour block QP
pmp_QP = core_enc->m_mbinfo.mbs[pParams->nNeighbour[dir]].QP;
// luma variables
QP = (pmp_QP + pmq_QP + 1) >> 1 ;
// external edge variables
index = IClip(0, 51, QP + BetaOffset);
Beta[0] = getEncoderBethaTable(index);
index = IClip(0, 51, QP + AlphaC0Offset);
Alpha[0] = getEncoderAlphaTable(index);
pClipTab = getEncoderClipTab(index);
// create clipping values
Clipping[0] = pClipTab[pStrength[0]];
Clipping[1] = pClipTab[pStrength[1]];
Clipping[2] = pClipTab[pStrength[2]];
Clipping[3] = pClipTab[pStrength[3]];
}
// internal edge variables
QP = pmq_QP;
index = IClip(0, 51, QP + BetaOffset);
Beta[1] = getEncoderBethaTable(index);
index = IClip(0, 51, QP + AlphaC0Offset);
Alpha[1] = getEncoderAlphaTable(index);
pClipTab = getEncoderClipTab(index);
// create clipping values
{
Ipp32u edge;
for (edge = 1;edge < 4;edge += 1)
{
if (*((Ipp32u *) (pStrength + edge * 4)))
{
// create clipping values
Clipping[edge * 4 + 0] = pClipTab[pStrength[edge * 4 + 0]];
Clipping[edge * 4 + 1] = pClipTab[pStrength[edge * 4 + 1]];
Clipping[edge * 4 + 2] = pClipTab[pStrength[edge * 4 + 2]];
Clipping[edge * 4 + 3] = pClipTab[pStrength[edge * 4 + 3]];
}
}
}
// perform deblocking
encoderIppLumaDeblocking(
dir,
pY,
pic_pitchPixels,
Alpha,
Beta,
Clipping,
pStrength,
core_enc->m_PicParamSet.bit_depth_luma);
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_DeblockChroma(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
// do no deblocking of 4:0:0 format
if (core_enc->m_PicParamSet.chroma_format_idc)
{
PIXTYPE *pU = pParams->pU;
PIXTYPE *pV = pParams->pV;
Ipp32s pic_pitchPixels = pParams->pitchPixels;
Ipp32s MBAddr = pParams->nMBAddr;
Ipp8u Clipping[16];
Ipp8u Alpha[2];
Ipp8u Beta[2];
Ipp32s AlphaC0Offset = pParams->nAlphaC0Offset;
Ipp32s BetaOffset = pParams->nBetaOffset;
Ipp32s pmq_QP = core_enc->m_mbinfo.mbs[MBAddr].QP;
//
// chroma deblocking
//
if (pParams->DeblockingFlag[dir])
{
Ipp8u *pClipTab;
Ipp32s QP;
Ipp32s index;
Ipp8u *pStrength = pParams->Strength[dir];
Ipp32s nPlane;
for (nPlane = 0; nPlane < 2; nPlane += 1)
{
if ((0 == nPlane) || (core_enc->m_PicParamSet.chroma_qp_index_offset != core_enc->m_PicParamSet.second_chroma_qp_index_offset))
{
Ipp32s chroma_qp_offset = (0 == nPlane) ? (core_enc->m_PicParamSet.chroma_qp_index_offset) : (core_enc->m_PicParamSet.second_chroma_qp_index_offset);
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32s pmp_QP;
// get left block QP
pmp_QP = core_enc->m_mbinfo.mbs[pParams->nNeighbour[dir]].QP;
// external edge variables averaging???
//QP = ENCODER_QP_SCALE_CR[getChromaQP(pmp_QP, chroma_qp_offset, core_enc->m_SeqParamSet.bit_depth_chroma)];
QP = ENCODER_QP_SCALE_CR[IClip(0, 51, pmq_QP + chroma_qp_offset)];
index = IClip(0, 51, QP + BetaOffset);
Beta[0] = getEncoderBethaTable(index);
index = IClip(0, 51, QP + AlphaC0Offset);
Alpha[0] = getEncoderAlphaTable(index);
pClipTab = getEncoderClipTab(index);
// create clipping values
Clipping[0] = pClipTab[pStrength[0]];
Clipping[1] = pClipTab[pStrength[1]];
Clipping[2] = pClipTab[pStrength[2]];
Clipping[3] = pClipTab[pStrength[3]];
}
// internal edge variables
QP = ENCODER_QP_SCALE_CR[IClip(0, 51, pmq_QP + chroma_qp_offset)];
//QP = ENCODER_QP_SCALE_CR[getChromaQP(pmq_QP, chroma_qp_offset, core_enc->m_SeqParamSet.bit_depth_chroma)];
index = IClip(0, 51, QP + BetaOffset);
Beta[1] = getEncoderBethaTable(index);
index = IClip(0, 51, QP + AlphaC0Offset);
Alpha[1] = getEncoderAlphaTable(index);
pClipTab = getEncoderClipTab(index);
// create clipping values
if (core_enc->m_PicParamSet.chroma_format_idc == 2 && HORIZONTAL_DEBLOCKING == dir)
{
// create clipping values
Clipping[4] = (Ipp8u) (pClipTab[pStrength[4]]);
Clipping[5] = (Ipp8u) (pClipTab[pStrength[5]]);
Clipping[6] = (Ipp8u) (pClipTab[pStrength[6]]);
Clipping[7] = (Ipp8u) (pClipTab[pStrength[7]]);
Clipping[8] = (Ipp8u) (pClipTab[pStrength[8]]);
Clipping[9] = (Ipp8u) (pClipTab[pStrength[9]]);
Clipping[10] = (Ipp8u) (pClipTab[pStrength[10]]);
Clipping[11] = (Ipp8u) (pClipTab[pStrength[11]]);
Clipping[12] = (Ipp8u) (pClipTab[pStrength[12]]);
Clipping[13] = (Ipp8u) (pClipTab[pStrength[13]]);
Clipping[14] = (Ipp8u) (pClipTab[pStrength[14]]);
Clipping[15] = (Ipp8u) (pClipTab[pStrength[15]]);
}
else
{
// create clipping values
Clipping[4] = (Ipp8u) (pClipTab[pStrength[8]]);
Clipping[5] = (Ipp8u) (pClipTab[pStrength[9]]);
Clipping[6] = (Ipp8u) (pClipTab[pStrength[10]]);
Clipping[7] = (Ipp8u) (pClipTab[pStrength[11]]);
}
}
// perform deblocking chroma component
encoderIppChromaDeblocking(
dir + (core_enc->m_PicParamSet.chroma_format_idc & 0x2),
(0 == nPlane) ? (pU) : (pV),
pic_pitchPixels,
Alpha,
Beta,
Clipping,
pStrength,
core_enc->m_SeqParamSet.bit_depth_chroma);
}
}
}
}
template<typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersISlice(
void*,
DeblockingParameters<PIXTYPE> *pParams)
{
// set deblocking flag(s)
pParams->DeblockingFlag[VERTICAL_DEBLOCKING] = 1;
pParams->DeblockingFlag[HORIZONTAL_DEBLOCKING] = 1;
// calculate strengths
if (pParams->ExternalEdgeFlag[VERTICAL_DEBLOCKING])
{
// deblocking with strong deblocking of external edge
SetEdgeStrength(pParams->Strength[VERTICAL_DEBLOCKING] + 0, 4);
}
SetEdgeStrength(pParams->Strength[VERTICAL_DEBLOCKING] + 4, 3);
SetEdgeStrength(pParams->Strength[VERTICAL_DEBLOCKING] + 8, 3);
SetEdgeStrength(pParams->Strength[VERTICAL_DEBLOCKING] + 12, 3);
if (pParams->ExternalEdgeFlag[HORIZONTAL_DEBLOCKING])
{
if (pParams->MBFieldCoded)
{
// deblocking field macroblock with external edge
SetEdgeStrength(pParams->Strength[HORIZONTAL_DEBLOCKING] + 0, 3);
}
else
{
// deblocking with strong deblocking of external edge
SetEdgeStrength(pParams->Strength[HORIZONTAL_DEBLOCKING] + 0, 4);
}
}
SetEdgeStrength(pParams->Strength[HORIZONTAL_DEBLOCKING] + 4, 3);
SetEdgeStrength(pParams->Strength[HORIZONTAL_DEBLOCKING] + 8, 3);
SetEdgeStrength(pParams->Strength[HORIZONTAL_DEBLOCKING] + 12, 3);
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersPSlice16(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
//fc Ipp32u cbp_luma = (core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma;
Ipp32u cbp_luma = ((core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma & 0xffff) << 1;
Ipp8u *pStrength = pParams->Strength[dir];
Ipp32u *pDeblockingFlag = &(pParams->DeblockingFlag[dir]);
//
// external edge
//
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32u nNeighbour;
// select neighbour addres
nNeighbour = pParams->nNeighbour[dir];
// when neighbour macroblock isn't intra
if (!IS_INTRA_MBTYPE((core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->mbtype))
{
Ipp32u idx;
Ipp32s iRefQ;
H264MotionVector *pVectorQ;
// load reference index & motion vector for current block
{
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQ = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQ = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQ = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQ = -1;
}
pVectorQ = core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors;
}
// select neighbour
//fc H264MacroblockLocalInfo *pNeighbour = core_enc->m_mbinfo.mbs + nNeighbour;
Ipp32u cbp_luma_nb = ((core_enc->m_mbinfo.mbs + nNeighbour)->cbp_luma & 0xffff) << 1;
// cicle on blocks
for (idx = 0;idx < 4;idx += 1)
{
Ipp32u blkQ, blkP;
blkQ = ENCODER_EXTERNAL_BLOCK_MASK[dir][CURRENT_BLOCK][idx];
blkP = ENCODER_EXTERNAL_BLOCK_MASK[dir][NEIGHBOUR_BLOCK][idx];
// when one of couple of blocks has coeffs
if ((cbp_luma & blkQ) ||
//fc (pNeighbour->cbp_luma & blkP))
(cbp_luma_nb & blkP))
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nNeighbourBlock;
Ipp32s iRefP;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
nNeighbourBlock = idx * 4 + 3;
else
nNeighbourBlock = idx + 12;
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefP = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefP = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefP = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefP = -1;
}
VM_ASSERT((iRefP != -1) || (iRefQ != -1));
// when reference indexes are equal
if (iRefQ == iRefP)
{
H264MotionVector *pVectorP;
pVectorP = core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQ->mvx - pVectorP->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQ->mvy - pVectorP->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
else
pStrength[idx] = 0;
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// external edge required in strong filtering
else
{
if ((HORIZONTAL_DEBLOCKING == dir) &&
(pParams->MBFieldCoded))
SetEdgeStrength(pStrength + 0, 3);
else
SetEdgeStrength(pStrength + 0, 4);
*pDeblockingFlag = 1;
}
}
//
// internal edge(s)
//
{
Ipp32u idx;
// reset all strengths
SetEdgeStrength(pStrength + 4, 0);
SetEdgeStrength(pStrength + 8, 0);
SetEdgeStrength(pStrength + 12, 0);
// set deblocking flag
if (cbp_luma & 0x1fffe)
*pDeblockingFlag = 1;
// cicle of edge(s)
// we do all edges in one cicle
for (idx = 4;idx < 16;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
pStrength[idx] = 2;
}
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersPSlice(void* state, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
Ipp32u mbtype = (core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->mbtype;
// when this macroblock is intra coded
if (IS_INTRA_MBTYPE(mbtype))
{
H264CoreEncoder_PrepareDeblockingParametersISlice(state, pParams);
return;
}
// try simplest function to prepare deblocking parameters
switch (mbtype)
{
// when macroblock has type inter 16 on 16
case MBTYPE_INTER:
case MBTYPE_FORWARD:
case MBTYPE_BACKWARD:
case MBTYPE_BIDIR:
H264CoreEncoder_PrepareDeblockingParametersPSlice16<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersPSlice16<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, pParams);
break;
/*
// when macroblock has type inter 16 on 8
case MBTYPE_INTER_16x8:
H264CoreEncoder_PrepareDeblockingParametersPSlice8x16(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersPSlice16x8(state, HORIZONTAL_DEBLOCKING, pParams);
return;
// when macroblock has type inter 8 on 16
case MBTYPE_INTER_8x16:
H264CoreEncoder_PrepareDeblockingParametersPSlice16x8(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersPSlice8x16(state, HORIZONTAL_DEBLOCKING, pParams);
return;
*/
default:
H264CoreEncoder_PrepareDeblockingParametersPSlice4<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersPSlice4<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, pParams);
break;
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersPSlice4(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
//fc Ipp32u cbp_luma = (core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma;
Ipp32u cbp_luma = ((core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma & 0xffff) << 1;
Ipp8u *pStrength = pParams->Strength[dir];
Ipp32u *pDeblockingFlag = &(pParams->DeblockingFlag[dir]);
//
// external edge
//
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32u nNeighbour;
// select neighbour addres
nNeighbour = pParams->nNeighbour[dir];
// when neighbour macroblock isn't intra
if (!IS_INTRA_MBTYPE((core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->mbtype))
{
Ipp32u idx;
// select neighbour
//fc H264MacroblockLocalInfo *pNeighbour = core_enc->m_mbinfo.mbs + nNeighbour;
Ipp32u cbp_luma_nb = ((core_enc->m_mbinfo.mbs + nNeighbour)->cbp_luma & 0xffff) << 1;
// cicle on blocks
for (idx = 0;idx < 4;idx += 1)
{
Ipp32u blkQ, blkP;
blkQ = ENCODER_EXTERNAL_BLOCK_MASK[dir][CURRENT_BLOCK][idx];
blkP = ENCODER_EXTERNAL_BLOCK_MASK[dir][NEIGHBOUR_BLOCK][idx];
// when one of couple of blocks has coeffs
if ((cbp_luma & blkQ) ||
//fc (pNeighbour->cbp_luma & blkP))
(cbp_luma_nb & blkP))
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nBlock, nNeighbourBlock;
Ipp32s iRefQ, iRefP;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
{
nBlock = idx * 4;
nNeighbourBlock = idx * 4 + 3;
}
else
{
nBlock = idx;
nNeighbourBlock = idx + 12;
}
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQ = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQ = -1;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefP = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefP = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQ = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQ = -1;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefP = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefP = -1;
}
VM_ASSERT((iRefP != -1) || (iRefQ != -1));
// when reference indexes are equal
if (iRefQ == iRefP)
{
H264MotionVector *pVectorQ, *pVectorP;
pVectorQ = core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nBlock;
pVectorP = core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQ->mvx - pVectorP->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQ->mvy - pVectorP->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
else
pStrength[idx] = 0;
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// external edge required in strong filtering
else
{
if ((HORIZONTAL_DEBLOCKING == dir) &&
(pParams->MBFieldCoded))
SetEdgeStrength(pStrength + 0, 3);
else
SetEdgeStrength(pStrength + 0, 4);
*pDeblockingFlag = 1;
}
}
//
// internal edge(s)
//
{
Ipp32u idx;
// cicle of edge(s)
// we do all edges in one cicle
for (idx = 4;idx < 16;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nBlock, nNeighbourBlock;
Ipp32s iRefQ, iRefP;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
{
nBlock = (idx & 3) * 4 + (idx >> 2);
nNeighbourBlock = nBlock - 1;
}
else
{
nBlock = idx;
nNeighbourBlock = idx - 4;
}
VM_ASSERT(-1 == core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nBlock]);
VM_ASSERT(-1 == core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nNeighbourBlock]);
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
// select reference field for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
iRefQ = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
// select reference field for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nNeighbourBlock];
iRefP = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
iRefQ = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nNeighbourBlock];
iRefP = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
VM_ASSERT((iRefP != -1) || (iRefQ != -1));
// when reference indexes are equal
if (iRefQ == iRefP)
{
H264MotionVector *pVectorQ, *pVectorP;
pVectorQ = core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nBlock;
pVectorP = core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQ->mvx - pVectorP->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQ->mvy - pVectorP->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
else
pStrength[idx] = 0;
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersBSlice16(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
//fc Ipp32u cbp_luma = (core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma;
Ipp32u cbp_luma = ((core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma & 0xffff) << 1;
Ipp8u *pStrength = pParams->Strength[dir];
Ipp32u *pDeblockingFlag = &(pParams->DeblockingFlag[dir]);
//
// external edge
//
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32u nNeighbour;
// select neighbour addres
nNeighbour = pParams->nNeighbour[dir];
// when neighbour macroblock isn't intra
if (!IS_INTRA_MBTYPE((core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->mbtype))
{
Ipp32u idx;
Ipp32s iRefQFrw, iRefQBck;
const H264MotionVector *pVectorQFrw, *pVectorQBck;
// load reference indexes for current block
{
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQBck = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQBck = -1;
}
// select current block motion vectors
pVectorQFrw = (iRefQFrw < 0)? &null_mv : core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors;
pVectorQBck = (iRefQBck < 0)? &null_mv : core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors;
}
// select neighbour
//fc H264MacroblockLocalInfo *pNeighbour = core_enc->m_mbinfo.mbs + nNeighbour;
Ipp32u cbp_luma_nb = ((core_enc->m_mbinfo.mbs + nNeighbour)->cbp_luma & 0xffff) << 1;
// cicle on blocks
for (idx = 0;idx < 4;idx += 1)
{
Ipp32u blkQ, blkP;
blkQ = ENCODER_EXTERNAL_BLOCK_MASK[dir][CURRENT_BLOCK][idx];
blkP = ENCODER_EXTERNAL_BLOCK_MASK[dir][NEIGHBOUR_BLOCK][idx];
// when one of couple of blocks has coeffs
if ((cbp_luma & blkQ) ||
//fc (pNeighbour->cbp_luma & blkP))
(cbp_luma_nb & blkP))
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nNeighbourBlock;
Ipp32s iRefPFrw, iRefPBck;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
nNeighbourBlock = idx * 4 + 3;
else
nNeighbourBlock = idx + 12;
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPBck = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPBck = -1;
}
// when reference indexes are equal
if (((iRefQFrw == iRefPFrw) && (iRefQBck == iRefPBck)) ||
((iRefQFrw == iRefPBck) && (iRefQBck == iRefPFrw)))
{
// set initial value of strength
pStrength[idx] = 0;
// when forward and backward reference pictures of previous block are different
if (iRefPFrw != iRefPBck)
{
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select previous block motion vectors
if (iRefQFrw == iRefPFrw)
{
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
}
else
{
pVectorPFrw = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
}
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
// when forward and backward reference pictures of previous block are equal
else
{
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select previous block motion vectors
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
if ((4 <= abs(pVectorQFrw->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPBck->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPFrw->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// external edge required in strong filtering
else
{
if ((HORIZONTAL_DEBLOCKING == dir) &&
(pParams->MBFieldCoded))
SetEdgeStrength(pStrength + 0, 3);
else
SetEdgeStrength(pStrength + 0, 4);
*pDeblockingFlag = 1;
}
}
//
// internal edge(s)
//
{
Ipp32u idx;
// reset all strengths
SetEdgeStrength(pStrength + 4, 0);
SetEdgeStrength(pStrength + 8, 0);
SetEdgeStrength(pStrength + 12, 0);
// set deblocking flag
if (cbp_luma & 0x1fffe)
*pDeblockingFlag = 1;
// cicle of edge(s)
// we do all edges in one cicle
for (idx = 4;idx < 16;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
pStrength[idx] = 2;
}
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersBSlice16x8(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
//fc Ipp32u cbp_luma = (core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma;
Ipp32u cbp_luma = ((core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma & 0xffff) << 1;
Ipp8u *pStrength = pParams->Strength[dir];
Ipp32u *pDeblockingFlag = &(pParams->DeblockingFlag[dir]);
Ipp32s iRefQFrw, iRefQBck;
const H264MotionVector *pVectorQFrw, *pVectorQBck;
//
// external edge
//
// load reference indexes & motion vector for first half of current block
{
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQBck = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[0];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQBck = -1;
}
// select current block motion vectors
pVectorQFrw = (iRefQFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors;
pVectorQBck = (iRefQBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors;
}
// prepare deblocking parameter for external edge
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32u nNeighbour;
// select neighbour addres
nNeighbour = pParams->nNeighbour[dir];
// when neighbour macroblock isn't intra
if (!IS_INTRA_MBTYPE((core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->mbtype))
{
Ipp32u idx;
// select neighbour
//fc H264MacroblockLocalInfo *pNeighbour = core_enc->m_mbinfo.mbs + nNeighbour;
Ipp32u cbp_luma_nb = ((core_enc->m_mbinfo.mbs + nNeighbour)->cbp_luma & 0xffff) << 1;
// cicle on blocks
for (idx = 0;idx < 4;idx += 1)
{
Ipp32u blkQ, blkP;
blkQ = ENCODER_EXTERNAL_BLOCK_MASK[dir][CURRENT_BLOCK][idx];
blkP = ENCODER_EXTERNAL_BLOCK_MASK[dir][NEIGHBOUR_BLOCK][idx];
// when one of couple of blocks has coeffs
if ((cbp_luma & blkQ) ||
//fc (pNeighbour->cbp_luma & blkP))
(cbp_luma_nb & blkP))
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nNeighbourBlock;
Ipp32s iRefPFrw, iRefPBck;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
nNeighbourBlock = idx * 4 + 3;
else
nNeighbourBlock = idx + 12;
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPBck = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPBck = -1;
}
// when reference indexes are equal
if (((iRefQFrw == iRefPFrw) && (iRefQBck == iRefPBck)) ||
((iRefQFrw == iRefPBck) && (iRefQBck == iRefPFrw)))
{
// set initial value of strength
pStrength[idx] = 0;
// when forward and backward reference pictures of previous block are different
if (iRefPFrw != iRefPBck)
{
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select previous block motion vectors
if (iRefQFrw == iRefPFrw)
{
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
}
else
{
pVectorPFrw = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
}
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
// when forward and backward reference pictures of previous block are equal
else
{
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select previous block motion vectors
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
if ((4 <= abs(pVectorQFrw->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPBck->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPFrw->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// external edge required in strong filtering
else
{
if ((HORIZONTAL_DEBLOCKING == dir) &&
(pParams->MBFieldCoded))
SetEdgeStrength(pStrength + 0, 3);
else
SetEdgeStrength(pStrength + 0, 4);
*pDeblockingFlag = 1;
}
}
//
// internal edge(s)
//
{
Ipp32u idx;
// cicle of edge(s)
for (idx = 4;idx < 8;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// we haven't to compare motion vectors - they are equal
else
pStrength[idx] = 0;
}
// load reference indexes & motion vector for second half of current block
{
Ipp32s iRefQFrw2, iRefQBck2;
Ipp32u nStrength;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// load reference indexes for current block
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[15];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQFrw2 = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQFrw2 = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[15];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQBck2 = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQBck2 = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[15];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQFrw2 = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQFrw2 = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[15];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQBck2 = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQBck2 = -1;
}
// when reference indexes are equal
if (((iRefQFrw == iRefQFrw2) && (iRefQBck == iRefQBck2)) ||
((iRefQFrw == iRefQBck2) && (iRefQBck == iRefQFrw2)))
{
// set initial value of strength
nStrength = 0;
// when forward and backward reference pictures of previous block are different
if (iRefQFrw2 != iRefQBck2)
{
const H264MotionVector *pVectorQFrw2, *pVectorQBck2;
// select previous block motion vectors
if (iRefQFrw == iRefQFrw2)
{
pVectorQFrw2 = (iRefQFrw2 < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + 15;
pVectorQBck2 = (iRefQBck2 < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + 15;
}
else
{
pVectorQFrw2 = (iRefQBck2 < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + 15;
pVectorQBck2 = (iRefQFrw2 < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + 15;
}
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorQFrw2->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorQFrw2->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorQBck2->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorQBck2->mvy)))
{
nStrength = 1;
*pDeblockingFlag = 1;
}
}
// when forward and backward reference pictures of previous block are equal
else
{
const H264MotionVector *pVectorQFrw2, *pVectorQBck2;
// select block second motion vectors
pVectorQFrw2 = (iRefQFrw2 < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + 15;
pVectorQBck2 = (iRefQBck2 < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + 15;
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorQFrw2->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorQFrw2->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorQBck2->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorQBck2->mvy)))
{
if ((4 <= abs(pVectorQFrw->mvx - pVectorQBck2->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorQBck2->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorQFrw2->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorQFrw2->mvy)))
{
nStrength = 1;
*pDeblockingFlag = 1;
}
}
}
}
// when reference indexes are different
else
{
nStrength = 1;
*pDeblockingFlag = 1;
}
// cicle of edge(s)
for (idx = 8;idx < 12;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// we have compared motion vectors
else
pStrength[idx] = (Ipp8u) nStrength;
}
}
// cicle of edge(s)
for (idx = 12;idx < 16;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// we haven't to compare motion vectors - they are equal
else
pStrength[idx] = 0;
}
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersBSlice8x16(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
//fc Ipp32u cbp_luma = (core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma;
Ipp32u cbp_luma = ((core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma & 0xffff) << 1;
Ipp8u *pStrength = pParams->Strength[dir];
Ipp32u *pDeblockingFlag = &(pParams->DeblockingFlag[dir]);
//
// external edge
//
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32u nNeighbour;
// select neighbour addres
nNeighbour = pParams->nNeighbour[dir];
// when neighbour macroblock isn't intra
if (!IS_INTRA_MBTYPE((core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->mbtype))
{
Ipp32u idx;
Ipp32s iRefQFrw[2], iRefQBck[2];
const H264MotionVector *(pVectorQFrw[2]), *(pVectorQBck[2]);
// in following calculations we avoided multiplication on 15
// by using formulae a * 15 = a * 16 - a
// load reference indexes for current block
for (idx = 0;idx < 2;idx += 1)
{
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[idx * 16 - idx];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQFrw[idx] = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQFrw[idx] = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[idx * 16 - idx];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQBck[idx] = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQBck[idx] = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[idx * 16 - idx];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQFrw[idx] = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQFrw[idx] = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[idx * 16 - idx];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQBck[idx] = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQBck[idx] = -1;
}
// select current block motion vectors
pVectorQFrw[idx] = (iRefQFrw[idx] < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + (idx * 16 - idx);
pVectorQBck[idx] = (iRefQBck[idx] < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + (idx * 16 - idx);
}
// select neighbour
//fc H264MacroblockLocalInfo *pNeighbour = core_enc->m_mbinfo.mbs + nNeighbour;
Ipp32u cbp_luma_nb = ((core_enc->m_mbinfo.mbs + nNeighbour)->cbp_luma & 0xffff) << 1;
// cicle on blocks
for (idx = 0;idx < 4;idx += 1)
{
Ipp32u blkQ, blkP;
blkQ = ENCODER_EXTERNAL_BLOCK_MASK[dir][CURRENT_BLOCK][idx];
blkP = ENCODER_EXTERNAL_BLOCK_MASK[dir][NEIGHBOUR_BLOCK][idx];
// when one of couple of blocks has coeffs
if ((cbp_luma & blkQ) ||
//fc (pNeighbour->cbp_luma & blkP))
(cbp_luma_nb & blkP))
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nNeighbourBlock;
Ipp32s iRefPFrw, iRefPBck;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
nNeighbourBlock = idx * 4 + 3;
else
nNeighbourBlock = idx + 12;
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPBck = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPBck = -1;
}
// when reference indexes are equal
if (((iRefQFrw[idx / 2] == iRefPFrw) && (iRefQBck[idx / 2] == iRefPBck)) ||
((iRefQFrw[idx / 2] == iRefPBck) && (iRefQBck[idx / 2] == iRefPFrw)))
{
// set initial value of strength
pStrength[idx] = 0;
// when forward and backward reference pictures of previous block are different
if (iRefPFrw != iRefPBck)
{
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select previous block motion vectors
if (iRefQFrw[idx / 2] == iRefPFrw)
{
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
}
else
{
pVectorPFrw = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
}
// compare motion vectors
if ((4 <= abs(pVectorQFrw[idx / 2]->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw[idx / 2]->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck[idx / 2]->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck[idx / 2]->mvy - pVectorPBck->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
// when forward and backward reference pictures of previous block are equal
else
{
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select previous block motion vectors
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQFrw[idx / 2]->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw[idx / 2]->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck[idx / 2]->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck[idx / 2]->mvy - pVectorPBck->mvy)))
{
if ((4 <= abs(pVectorQFrw[idx / 2]->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw[idx / 2]->mvy - pVectorPBck->mvy)) ||
(4 <= abs(pVectorQBck[idx / 2]->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck[idx / 2]->mvy - pVectorPFrw->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// external edge required in strong filtering
else
{
if ((HORIZONTAL_DEBLOCKING == dir) &&
(pParams->MBFieldCoded))
SetEdgeStrength(pStrength + 0, 3);
else
SetEdgeStrength(pStrength + 0, 4);
*pDeblockingFlag = 1;
}
}
//
// internal edge(s)
//
{
Ipp32u idx;
// reset all strengths
SetEdgeStrength(pStrength + 4, 0);
SetEdgeStrength(pStrength + 8, 0);
SetEdgeStrength(pStrength + 12, 0);
// set deblocking flag
if (cbp_luma & 0x1fffe)
*pDeblockingFlag = 1;
// cicle of edge(s)
// we do all edges in one cicle
for (idx = 4;idx < 16;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
pStrength[idx] = 2;
}
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersBSlice(void* state, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
Ipp32u mbtype = (core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->mbtype;
// when this macroblock is intra coded
if (IS_INTRA_MBTYPE(mbtype))
{
H264CoreEncoder_PrepareDeblockingParametersISlice(state, pParams);
return;
}
// try simplest function to prepare deblocking parameters
switch (mbtype)
{
// when macroblock has type inter 16 on 16
case MBTYPE_INTER:
case MBTYPE_FORWARD:
case MBTYPE_BACKWARD:
case MBTYPE_BIDIR:
H264CoreEncoder_PrepareDeblockingParametersBSlice16<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersBSlice16<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, pParams);
break;
// when macroblock has type inter 16 on 8
case MBTYPE_INTER_16x8:
case MBTYPE_FWD_FWD_16x8:
case MBTYPE_BWD_BWD_16x8:
case MBTYPE_FWD_BWD_16x8:
case MBTYPE_BWD_FWD_16x8:
case MBTYPE_BIDIR_FWD_16x8:
case MBTYPE_BIDIR_BWD_16x8:
case MBTYPE_FWD_BIDIR_16x8:
case MBTYPE_BWD_BIDIR_16x8:
case MBTYPE_BIDIR_BIDIR_16x8:
H264CoreEncoder_PrepareDeblockingParametersBSlice8x16<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersBSlice16x8<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, pParams);
return;
// when macroblock has type inter 8 on 16
case MBTYPE_INTER_8x16:
case MBTYPE_FWD_FWD_8x16:
case MBTYPE_BWD_BWD_8x16:
case MBTYPE_FWD_BWD_8x16:
case MBTYPE_BWD_FWD_8x16:
case MBTYPE_BIDIR_FWD_8x16:
case MBTYPE_BIDIR_BWD_8x16:
case MBTYPE_FWD_BIDIR_8x16:
case MBTYPE_BWD_BIDIR_8x16:
case MBTYPE_BIDIR_BIDIR_8x16:
H264CoreEncoder_PrepareDeblockingParametersBSlice16x8<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersBSlice8x16<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, pParams);
return;
default:
H264CoreEncoder_PrepareDeblockingParametersBSlice4<COEFFSTYPE, PIXTYPE>(state, VERTICAL_DEBLOCKING, pParams);
H264CoreEncoder_PrepareDeblockingParametersBSlice4<COEFFSTYPE, PIXTYPE>(state, HORIZONTAL_DEBLOCKING, pParams);
break;
}
}
template<typename COEFFSTYPE, typename PIXTYPE>
void H264CoreEncoder_PrepareDeblockingParametersBSlice4(void* state, Ipp32u dir, DeblockingParameters<PIXTYPE> *pParams)
{
H264CoreEncoder<COEFFSTYPE, PIXTYPE>* core_enc = (H264CoreEncoder<COEFFSTYPE, PIXTYPE>*)state;
Ipp32u MBAddr = pParams->nMBAddr;
//fc Ipp32u cbp_luma = (core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma;
Ipp32u cbp_luma = ((core_enc->m_mbinfo.mbs + MBAddr)->cbp_luma & 0xffff) << 1;
Ipp8u *pStrength = pParams->Strength[dir];
Ipp32u *pDeblockingFlag = &(pParams->DeblockingFlag[dir]);
//
// external edge
//
if (pParams->ExternalEdgeFlag[dir])
{
Ipp32u nNeighbour;
// select neighbour addres
nNeighbour = pParams->nNeighbour[dir];
// when neighbour macroblock isn't intra
if (!IS_INTRA_MBTYPE((core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->mbtype))
{
Ipp32u idx;
// select neighbour
//fc H264MacroblockLocalInfo *pNeighbour = core_enc->m_mbinfo.mbs + nNeighbour;
Ipp32u cbp_luma_nb = ((core_enc->m_mbinfo.mbs + nNeighbour)->cbp_luma & 0xffff) << 1;
// cicle on blocks
for (idx = 0;idx < 4;idx += 1)
{
Ipp32u blkQ, blkP;
blkQ = ENCODER_EXTERNAL_BLOCK_MASK[dir][CURRENT_BLOCK][idx];
blkP = ENCODER_EXTERNAL_BLOCK_MASK[dir][NEIGHBOUR_BLOCK][idx];
// when one of couple of blocks has coeffs
if ((cbp_luma & blkQ) ||
//fc (pNeighbour->cbp_luma & blkP))
(cbp_luma_nb & blkP))
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nBlock, nNeighbourBlock;
Ipp32s iRefQFrw, iRefPFrw, iRefQBck, iRefPBck;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
{
nBlock = idx * 4;
nNeighbourBlock = nBlock + 3;
}
else
{
nBlock = idx;
nNeighbourBlock = idx + 12;
}
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefQBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefQBck = -1;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
else
iRefPBck = -1;
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select reference index for current block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefQBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefQBck = -1;
// select reference index for previous block
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPFrw = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPFrw = -1;
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][nNeighbour].RefIdxs[nNeighbourBlock];
if (0 <= index)
{
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + nNeighbour)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
iRefPBck = H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
else
iRefPBck = -1;
}
// when reference indexes are equal
if (((iRefQFrw == iRefPFrw) && (iRefQBck == iRefPBck)) ||
((iRefQFrw == iRefPBck) && (iRefQBck == iRefPFrw)))
{
// set initial value of strength
pStrength[idx] = 0;
// when forward and backward reference pictures of previous block are different
if (iRefPFrw != iRefPBck)
{
const H264MotionVector *pVectorQFrw, *pVectorQBck;
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select current block motion vectors
pVectorQFrw = (iRefQFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nBlock;
pVectorQBck = (iRefQBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + nBlock;
// select previous block motion vectors
if (iRefQFrw == iRefPFrw)
{
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
}
else
{
pVectorPFrw = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
}
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
// when forward and backward reference pictures of previous block are equal
else
{
const H264MotionVector *pVectorQFrw, *pVectorQBck;
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select current block motion vectors
pVectorQFrw = (iRefQFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nBlock;
pVectorQBck = (iRefQBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + nBlock;
// select previous block motion vectors
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][nNeighbour].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][nNeighbour].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
if ((4 <= abs(pVectorQFrw->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPBck->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPFrw->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// external edge required in strong filtering
else
{
if ((HORIZONTAL_DEBLOCKING == dir) &&
(pParams->MBFieldCoded))
SetEdgeStrength(pStrength + 0, 3);
else
SetEdgeStrength(pStrength + 0, 4);
*pDeblockingFlag = 1;
}
}
//
// internal edge(s)
//
{
Ipp32u idx;
// cicle of edge(s)
// we do all edges in one cicle
for (idx = 4;idx < 16;idx += 1)
{
Ipp32u blkQ;
blkQ = ENCODER_INTERNAL_BLOCKS_MASK[dir][idx - 4];
if (cbp_luma & blkQ)
{
pStrength[idx] = 2;
*pDeblockingFlag = 1;
}
// compare motion vectors & reference indexes
else
{
Ipp32u nBlock, nNeighbourBlock;
Ipp32s iRefQFrw, iRefQBck, iRefPFrw, iRefPBck;
Ipp32s nVectorDiffLimit = pParams->nMaxMVector;
// calc block and neighbour block number
if (VERTICAL_DEBLOCKING == dir)
{
nBlock = (idx & 3) * 4 + (idx >> 2);
nNeighbourBlock = nBlock - 1;
}
else
{
nBlock = idx;
nNeighbourBlock = idx - 4;
}
// field coded image
if (FRM_STRUCTURE > core_enc->m_pCurrentFrame->m_PictureStructureForDec)
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
Ipp8s *pFields;
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_Prediction;
// select forward reference index for blocks
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
iRefQFrw = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nNeighbourBlock];
iRefPFrw = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select reference fields number array
pFields = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_Prediction;
// select backward reference index for blocks
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nBlock];
iRefQBck = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nNeighbourBlock];
iRefPBck = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
H264EncoderFrame_GetNumberByParity(
pRefPicList[index],
pFields[index]));
}
// frame coded image
else
{
H264EncoderFrame<PIXTYPE> **pRefPicList;
Ipp32s index;
// select forward reference pictures list
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
0,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select forward reference index for block(s)
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nBlock];
iRefQFrw = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[0][MBAddr].RefIdxs[nNeighbourBlock];
iRefPFrw = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
// select backward reference pictures list
pRefPicList = H264EncoderFrame_GetRefPicList(
core_enc->m_pCurrentFrame,
(core_enc->m_pCurrentFrame->m_mbinfo.mbs + MBAddr)->slice_id,
1,
core_enc->m_MaxSliceSize)->m_RefPicList;
// select backward reference index for block(s)
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nBlock];
iRefQBck = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
index = core_enc->m_pCurrentFrame->m_mbinfo.RefIdxs[1][MBAddr].RefIdxs[nNeighbourBlock];
iRefPBck = (index < 0) ?
(-1) :
H264EncoderFrame_DeblockPicID(
pRefPicList[index],
0);
}
// when reference indexes are equal
if (((iRefQFrw == iRefPFrw) && (iRefQBck == iRefPBck)) ||
((iRefQFrw == iRefPBck) && (iRefQBck == iRefPFrw)))
{
// set initial value of strength
pStrength[idx] = 0;
// when forward and backward reference pictures of previous block are different
if (iRefPFrw != iRefPBck)
{
const H264MotionVector *pVectorQFrw, *pVectorQBck;
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select current block motion vectors
pVectorQFrw = (iRefQFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nBlock;
pVectorQBck = (iRefQBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + nBlock;
// select previous block motion vectors
if (iRefQFrw == iRefPFrw)
{
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + nNeighbourBlock;
}
else
{
pVectorPFrw = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nNeighbourBlock;
}
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
// when forward and backward reference pictures of previous block are equal
else
{
const H264MotionVector *pVectorQFrw, *pVectorQBck;
const H264MotionVector *pVectorPFrw, *pVectorPBck;
// select current block motion vectors
pVectorQFrw = (iRefQFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nBlock;
pVectorQBck = (iRefQBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + nBlock;
// select previous block motion vectors
pVectorPFrw = (iRefPFrw < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[0][MBAddr].MotionVectors + nNeighbourBlock;
pVectorPBck = (iRefPBck < 0)? &null_mv: core_enc->m_pCurrentFrame->m_mbinfo.MV[1][MBAddr].MotionVectors + nNeighbourBlock;
// compare motion vectors
if ((4 <= abs(pVectorQFrw->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPFrw->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPBck->mvy)))
{
if ((4 <= abs(pVectorQFrw->mvx - pVectorPBck->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQFrw->mvy - pVectorPBck->mvy)) ||
(4 <= abs(pVectorQBck->mvx - pVectorPFrw->mvx)) ||
(nVectorDiffLimit <= abs(pVectorQBck->mvy - pVectorPFrw->mvy)))
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
// when reference indexes are different
else
{
pStrength[idx] = 1;
*pDeblockingFlag = 1;
}
}
}
}
}
// forced instantiation
#ifdef BITDEPTH_9_12
#define COEFFSTYPE Ipp32s
#define PIXTYPE Ipp16u
template void H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_DeblockSlice<COEFFSTYPE, PIXTYPE>(void*, H264Slice<COEFFSTYPE, PIXTYPE>*, Ipp32u, Ipp32u);
template void H264CoreEncoder_PrepareDeblockingParametersPSlice<COEFFSTYPE, PIXTYPE>(void*, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_PrepareDeblockingParametersBSlice<COEFFSTYPE, PIXTYPE>(void*, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_PrepareDeblockingParametersPSlice4<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_PrepareDeblockingParametersBSlice4<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
#undef COEFFSTYPE
#undef PIXTYPE
#endif
#define COEFFSTYPE Ipp16s
#define PIXTYPE Ipp8u
template void H264CoreEncoder_DeblockLuma<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_DeblockChroma<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_DeblockSlice<COEFFSTYPE, PIXTYPE>(void*, H264Slice<COEFFSTYPE, PIXTYPE>*, Ipp32u, Ipp32u);
template void H264CoreEncoder_PrepareDeblockingParametersPSlice<COEFFSTYPE, PIXTYPE>(void*, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_PrepareDeblockingParametersBSlice<COEFFSTYPE, PIXTYPE>(void*, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_PrepareDeblockingParametersPSlice4<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
template void H264CoreEncoder_PrepareDeblockingParametersBSlice4<COEFFSTYPE, PIXTYPE>(void*, Ipp32u, DeblockingParameters<PIXTYPE>*);
#endif //UMC_ENABLE_H264_VIDEO_ENCODER
| 43.245887 | 169 | 0.492035 | [
"vector",
"transform"
] |
09bc9b0a7df81c622acf764c2e0494381c9bdc21 | 10,605 | cpp | C++ | src/third_party/wiredtiger/test/cppsuite/tests/run.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/cppsuite/tests/run.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/third_party/wiredtiger/test/cppsuite/tests/run.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /*-
* Public Domain 2014-present MongoDB, Inc.
* Public Domain 2008-2014 WiredTiger, Inc.
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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.
*/
#include <fstream>
#include <iostream>
#include <string>
#include "test_harness/util/logger.h"
#include "test_harness/test.h"
#include "burst_inserts.cpp"
#include "hs_cleanup.cpp"
#include "operations_test.cpp"
#include "search_near_01.cpp"
#include "search_near_02.cpp"
#include "search_near_03.cpp"
#include "test_template.cpp"
/* Declarations to avoid the error raised by -Werror=missing-prototypes. */
const std::string parse_configuration_from_file(const std::string &filename);
void print_help();
int64_t run_test(
const std::string &test_name, const std::string &config, const std::string &wt_open_config);
const std::string
parse_configuration_from_file(const std::string &filename)
{
std::string cfg, line, error;
std::ifstream cFile(filename);
if (cFile.is_open()) {
while (getline(cFile, line)) {
/* Whitespaces are only for readability, they can be removed safely. */
line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end());
if (line[0] == '#' || line.empty())
continue;
cfg += line;
}
} else {
error = "Couldn't open " + filename + " file for reading.";
testutil_die(EINVAL, error.c_str());
}
return (cfg);
}
void
print_help()
{
std::cout << "NAME" << std::endl;
std::cout << "\trun" << std::endl;
std::cout << std::endl;
std::cout << "SYNOPSIS" << std::endl;
std::cout << "\trun [OPTIONS]" << std::endl;
std::cout << "\trun -C [WIREDTIGER_OPEN_CONFIGURATION]" << std::endl;
std::cout << "\trun -c [TEST_FRAMEWORK_CONFIGURATION]" << std::endl;
std::cout << "\trun -f [FILE]" << std::endl;
std::cout << "\trun -l [TRACE_LEVEL]" << std::endl;
std::cout << "\trun -t [TEST_NAME]" << std::endl;
std::cout << std::endl;
std::cout << "DESCRIPTION" << std::endl;
std::cout << "\trun executes the test framework." << std::endl;
std::cout << "\tIf no test is indicated, all tests are executed." << std::endl;
std::cout
<< "\tIf no configuration is indicated, the default configuration for each test will be used."
<< std::endl;
std::cout
<< "\tIf a configuration is indicated, the given configuration will be used either for "
"all tests or the test indicated."
<< std::endl;
std::cout << std::endl;
std::cout << "OPTIONS" << std::endl;
std::cout << "\t-h Output a usage message and exit." << std::endl;
std::cout << "\t-C Additional wiredtiger open configuration." << std::endl;
std::cout << "\t-c Test framework configuration. Cannot be used with -f." << std::endl;
std::cout << "\t-f File that contains the configuration. Cannot be used with -C." << std::endl;
std::cout << "\t-l Trace level from 0 to 3. "
"1 is the default level, all warnings and errors are logged."
<< std::endl;
std::cout << "\t-t Test name to be executed." << std::endl;
}
/*
* Run a specific test.
* - test_name: specifies which test to run.
* - config: defines the configuration used for the test.
*/
int64_t
run_test(const std::string &test_name, const std::string &config, const std::string &wt_open_config)
{
int error_code = 0;
test_harness::logger::log_msg(LOG_TRACE, "Configuration\t:" + config);
if (test_name == "hs_cleanup")
hs_cleanup(test_harness::test_args{config, test_name, wt_open_config}).run();
else if (test_name == "burst_inserts")
burst_inserts(test_harness::test_args{config, test_name, wt_open_config}).run();
else if (test_name == "operations_test")
operations_test(test_harness::test_args{config, test_name, wt_open_config}).run();
else if (test_name == "search_near_01")
search_near_01(test_harness::test_args{config, test_name, wt_open_config}).run();
else if (test_name == "search_near_02")
search_near_02(test_harness::test_args{config, test_name, wt_open_config}).run();
else if (test_name == "search_near_03")
search_near_03(test_harness::test_args{config, test_name, wt_open_config}).run();
else if (test_name == "test_template")
test_template(test_harness::test_args{config, test_name, wt_open_config}).run();
else {
test_harness::logger::log_msg(LOG_ERROR, "Test not found: " + test_name);
error_code = -1;
}
if (error_code == 0)
test_harness::logger::log_msg(LOG_INFO, "Test " + test_name + " done.");
return (error_code);
}
static std::string
get_default_config_path(const std::string &test_name)
{
return ("configs/" + test_name + "_default.txt");
}
int
main(int argc, char *argv[])
{
std::string cfg, config_filename, current_cfg, current_test_name, test_name, wt_open_config;
int64_t error_code = 0;
const std::vector<std::string> all_tests = {"burst_inserts", "hs_cleanup", "operations_test",
"search_near_01", "search_near_02", "search_near_03", "test_template"};
/* Set the program name for error messages. */
(void)testutil_set_progname(argv);
/* Parse args
* -C : Additional wiredtiger_open configuration.
* -c : Test framework configuration. Cannot be used with -f. If no specific test is specified
* to be run, the same configuration will be used for all existing tests.
* -f : Filename that contains the configuration. Cannot be used with -C. If no specific test
* is specified to be run, the same configuration will be used for all existing tests.
* -l : Trace level.
* -t : Test to run. All tests are run if not specified.
*/
for (size_t i = 1; (i < argc) && (error_code == 0); ++i) {
if (std::string(argv[i]) == "-h") {
print_help();
return 0;
} else if (std::string(argv[i]) == "-C") {
if ((i + 1) < argc) {
wt_open_config = argv[++i];
/* Add a comma to the front if the user didn't supply one. */
if (wt_open_config[0] != ',')
wt_open_config.insert(0, 1, ',');
} else
error_code = -1;
} else if (std::string(argv[i]) == "-c") {
if (!config_filename.empty()) {
test_harness::logger::log_msg(LOG_ERROR, "Option -C cannot be used with -f");
error_code = -1;
} else if ((i + 1) < argc)
cfg = argv[++i];
else
error_code = -1;
} else if (std::string(argv[i]) == "-f") {
if (!cfg.empty()) {
test_harness::logger::log_msg(LOG_ERROR, "Option -f cannot be used with -C");
error_code = -1;
} else if ((i + 1) < argc)
config_filename = argv[++i];
else
error_code = -1;
} else if (std::string(argv[i]) == "-t") {
if ((i + 1) < argc)
test_name = argv[++i];
else
error_code = -1;
} else if (std::string(argv[i]) == "-l") {
if ((i + 1) < argc)
test_harness::logger::trace_level = std::stoi(argv[++i]);
else
error_code = -1;
} else
error_code = -1;
}
if (error_code == 0) {
test_harness::logger::log_msg(
LOG_INFO, "Trace level: " + std::to_string(test_harness::logger::trace_level));
if (test_name.empty()) {
/* Run all tests. */
test_harness::logger::log_msg(LOG_INFO, "Running all tests.");
for (auto const &it : all_tests) {
current_test_name = it;
/* Configuration parsing. */
if (!config_filename.empty())
current_cfg = parse_configuration_from_file(config_filename);
else if (cfg.empty())
current_cfg =
parse_configuration_from_file(get_default_config_path(current_test_name));
else
current_cfg = cfg;
error_code = run_test(current_test_name, current_cfg, wt_open_config);
if (error_code != 0)
break;
}
} else {
current_test_name = test_name;
/* Check the test exists. */
if (std::find(all_tests.begin(), all_tests.end(), current_test_name) ==
all_tests.end()) {
test_harness::logger::log_msg(
LOG_ERROR, "The test " + current_test_name + " was not found.");
error_code = -1;
} else {
/* Configuration parsing. */
if (!config_filename.empty())
cfg = parse_configuration_from_file(config_filename);
else if (cfg.empty())
cfg = parse_configuration_from_file(get_default_config_path(current_test_name));
error_code = run_test(current_test_name, cfg, wt_open_config);
}
}
if (error_code != 0)
test_harness::logger::log_msg(LOG_ERROR, "Test " + current_test_name + " failed.");
} else
test_harness::logger::log_msg(LOG_ERROR,
"Invalid command line arguments supplied. Try "
"'./run -h' for help.");
return (error_code);
}
| 40.477099 | 100 | 0.60264 | [
"vector"
] |
09c17accc39b83310a22aa11a1ee3635e0021bf9 | 2,216 | hpp | C++ | Core/include/Function.hpp | bzcheeseman/Hobbit | a2427a3db8a9194883aa6e33bde65f6e7966b049 | [
"Apache-2.0"
] | 1 | 2018-04-22T01:01:00.000Z | 2018-04-22T01:01:00.000Z | Core/include/Function.hpp | bzcheeseman/Hobbit | a2427a3db8a9194883aa6e33bde65f6e7966b049 | [
"Apache-2.0"
] | 1 | 2018-04-04T16:43:17.000Z | 2018-04-13T01:39:57.000Z | Core/include/Function.hpp | bzcheeseman/Hobbit | a2427a3db8a9194883aa6e33bde65f6e7966b049 | [
"Apache-2.0"
] | 1 | 2019-11-06T15:01:13.000Z | 2019-11-06T15:01:13.000Z | //
// Created by Aman LaChapelle on 3/17/18.
//
// Hobbit
// Copyright (c) 2018 Aman LaChapelle
// Full license at Hobbit/LICENSE.txt
//
/*
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.
*/
#ifndef HOBBIT_FUNCTION_HPP
#define HOBBIT_FUNCTION_HPP
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
class LLVMContext;
class Type;
class Function;
class Value;
class Argument;
}
namespace Hobbit {
class Module;
class Tensor;
namespace core {
class Symbol;
class OpNode;
}
enum OpCode {
ALLOCA = 0,
SDOT = 1,
};
class Function {
public:
static std::unique_ptr<Function> Create(Module *m, const std::string &name);
void AddSymbol(void *sym_addr, core::Symbol *arg);
core::Symbol *GetSymbol(void *sym_addr);
void MarkSymbolAsArg(void *sym_addr);
Tensor *AddOpNode(std::initializer_list<void *> sym_addrs,
const OpCode &opcode);
llvm::LLVMContext *GetContext();
const std::string &GetName();
std::vector<Tensor *>
GetSignatureArgs(std::initializer_list<void *> output_addrs);
void Emit(llvm::Function *func);
void AddBlock(const std::string &name);
void AddToBlock(const std::string &name, llvm::Value *v);
private:
// std::unique_ptr<Tensor> CreateVariable(void *addr);
// std::unique_ptr<Tensor> CreateConstant(void *addr);
std::string name_;
Module *module_;
// everything in this function comes from these
std::map<void *, core::Symbol *> symbol_table_;
std::vector<core::OpNode *> op_table_;
std::map<std::string, std::vector<llvm::Value *>> function_blocks_;
};
}
#endif // HOBBIT_FUNCTION_HPP
| 24.086957 | 80 | 0.682762 | [
"vector"
] |
09cde8900b44c2b57a27adfa4b30c7506f61bea7 | 12,140 | hpp | C++ | cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_ppp_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_ppp_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_ppp_oper.hpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z | #ifndef _CISCO_IOS_XE_PPP_OPER_
#define _CISCO_IOS_XE_PPP_OPER_
#include <memory>
#include <vector>
#include <string>
#include <ydk/types.hpp>
#include <ydk/errors.hpp>
namespace cisco_ios_xe {
namespace Cisco_IOS_XE_ppp_oper {
class PppData : public ydk::Entity
{
public:
PppData();
~PppData();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::shared_ptr<ydk::Entity> clone_ptr() const override;
ydk::augment_capabilities_function get_augment_capabilities_function() const override;
std::string get_bundle_yang_models_location() const override;
std::string get_bundle_name() const override;
std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override;
class PppInterface; //type: PppData::PppInterface
class PppStatistics; //type: PppData::PppStatistics
class Pppoe; //type: PppData::Pppoe
ydk::YList ppp_interface;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_ppp_oper::PppData::PppStatistics> ppp_statistics; // presence node
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_ppp_oper::PppData::Pppoe> pppoe; // presence node
}; // PppData
class PppData::PppInterface : public ydk::Entity
{
public:
PppInterface();
~PppInterface();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf phy_ifname; //type: string
class PppVa; //type: PppData::PppInterface::PppVa
ydk::YList ppp_va;
}; // PppData::PppInterface
class PppData::PppInterface::PppVa : public ydk::Entity
{
public:
PppVa();
~PppVa();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf va_ifname; //type: string
ydk::YLeaf vrf_name; //type: string
ydk::YLeaf interface_ip; //type: string
ydk::YLeaf gateway_ip; //type: string
ydk::YLeaf primary_dns_ip; //type: string
ydk::YLeaf secondary_dns_ip; //type: string
ydk::YLeaf mtu; //type: uint32
ydk::YLeaf auth_type; //type: PppIosAuthType
}; // PppData::PppInterface::PppVa
class PppData::PppStatistics : public ydk::Entity
{
public:
PppStatistics();
~PppStatistics();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf ppp_lcp_pkts; //type: uint32
ydk::YLeaf ppp_ipcp_pkts; //type: uint32
ydk::YLeaf ppp_ccp_pkts; //type: uint32
}; // PppData::PppStatistics
class PppData::Pppoe : public ydk::Entity
{
public:
Pppoe();
~Pppoe();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf role; //type: PppoeOperationalRole
class PppoeSessionList; //type: PppData::Pppoe::PppoeSessionList
class PppoeStatistics; //type: PppData::Pppoe::PppoeStatistics
ydk::YList pppoe_session_list;
std::shared_ptr<cisco_ios_xe::Cisco_IOS_XE_ppp_oper::PppData::Pppoe::PppoeStatistics> pppoe_statistics; // presence node
}; // PppData::Pppoe
class PppData::Pppoe::PppoeSessionList : public ydk::Entity
{
public:
PppoeSessionList();
~PppoeSessionList();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf ifname; //type: string
class Session; //type: PppData::Pppoe::PppoeSessionList::Session
ydk::YList session;
}; // PppData::Pppoe::PppoeSessionList
class PppData::Pppoe::PppoeSessionList::Session : public ydk::Entity
{
public:
Session();
~Session();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
ydk::YLeaf session_id; //type: uint16
ydk::YLeaf lmac; //type: string
ydk::YLeaf rmac; //type: string
ydk::YLeaf va_ifname; //type: string
ydk::YLeaf vrf_name; //type: string
ydk::YLeaf dot1q_qinq_outer_vlan; //type: uint16
ydk::YLeaf dot1q_qinq_inner_vlan; //type: uint16
ydk::YLeaf service_name; //type: string
ydk::YLeaf in_packet; //type: uint32
ydk::YLeaf out_packet; //type: uint32
ydk::YLeaf in_bytes; //type: uint64
ydk::YLeaf out_bytes; //type: uint64
}; // PppData::Pppoe::PppoeSessionList::Session
class PppData::Pppoe::PppoeStatistics : public ydk::Entity
{
public:
PppoeStatistics();
~PppoeStatistics();
bool has_data() const override;
bool has_operation() const override;
std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override;
std::string get_segment_path() const override;
std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override;
void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override;
void set_filter(const std::string & value_path, ydk::YFilter yfliter) override;
std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override;
bool has_leaf_or_child_of_name(const std::string & name) const override;
std::string get_absolute_path() const override;
ydk::YLeaf pppoe_padi_pkts; //type: uint32
ydk::YLeaf pppoe_pado_pkts; //type: uint32
ydk::YLeaf pppoe_padr_pkts; //type: uint32
ydk::YLeaf pppoe_pads_pkts; //type: uint32
ydk::YLeaf pppoe_padt_pkts; //type: uint32
ydk::YLeaf invalid_discovery_pkts; //type: uint32
}; // PppData::Pppoe::PppoeStatistics
class PppIosAuthType : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf ppp_ios_auth_none;
static const ydk::Enum::YLeaf ppp_ios_auth_chap;
static const ydk::Enum::YLeaf ppp_ios_auth_pap;
static const ydk::Enum::YLeaf ppp_ios_auth_mschap;
static const ydk::Enum::YLeaf ppp_ios_auth_mschap_v2;
static const ydk::Enum::YLeaf ppp_ios_auth_eap;
static int get_enum_value(const std::string & name) {
if (name == "ppp-ios-auth-none") return 0;
if (name == "ppp-ios-auth-chap") return 1;
if (name == "ppp-ios-auth-pap") return 2;
if (name == "ppp-ios-auth-mschap") return 3;
if (name == "ppp-ios-auth-mschap-v2") return 4;
if (name == "ppp-ios-auth-eap") return 5;
return -1;
}
};
class PppoeOperationalRole : public ydk::Enum
{
public:
static const ydk::Enum::YLeaf pppoe_client;
static const ydk::Enum::YLeaf pppoe_server;
static int get_enum_value(const std::string & name) {
if (name == "pppoe-client") return 0;
if (name == "pppoe-server") return 1;
return -1;
}
};
}
}
#endif /* _CISCO_IOS_XE_PPP_OPER_ */
| 44.632353 | 162 | 0.675783 | [
"vector"
] |
09ce210e86c2b6f9ea4a75ec58f797395e1a51f2 | 1,967 | cpp | C++ | main.cpp | vicelikedust/Ingress_max_recharge_distance | d6bc6ea1ca7e914020b250ab7d923bcb1db47e68 | [
"MIT"
] | 1 | 2020-11-11T17:19:33.000Z | 2020-11-11T17:19:33.000Z | main.cpp | vicelikedust/Ingress_max_recharge_distance | d6bc6ea1ca7e914020b250ab7d923bcb1db47e68 | [
"MIT"
] | null | null | null | main.cpp | vicelikedust/Ingress_max_recharge_distance | d6bc6ea1ca7e914020b250ab7d923bcb1db47e68 | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
int leveldist[] = {0,250,500,750,1000,1250,1500,1750,2000,2250,2500,2750,3000,3250,3500,3750,4000};
int get_level(){
int level;
cout << "What is your player level? (1-16) ";
cin >> level;
while(level == 0 || level >= 17){
cout << "That is an invaild level \nLevel " << level << " doesn't exist" << endl;
cout << "What is your player level? ";
cin >> level;
if(isdigit(level) == false){
cout << endl << "Error: Input must be a number" << endl;
cin.clear();
cin.ignore(256,'\n');
cin >> level;
}
}
return level;
}
int get_distance(){
int distance;
char buffer[256];
cout << "What is the distance in km? ";
cin >> buffer;
if(isdigit(buffer[256]) == false){
distance = atoi(buffer);
}else{
distance = buffer[256];
}
return distance;
}
void calc(){
int efficiency;
int level = get_level();
int distance = get_distance();
if(distance > leveldist[level]){
cout << "Portal is too far \nThe max distance for level " << level << " is " << leveldist[level] << " km" << endl;
} else {
efficiency = 100 - (distance)/(5 * level);
cout << "Recharge Efficiency is " << efficiency << "%" << endl;
}
}
void Clear()
{
#if defined _WIN32
system("cls");
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
#elif defined (__APPLE__)
system("clear");
#endif
}
int main()
{
string ans = "yes";
while(ans == "yes" || ans == "y"){
calc();
cout << "Do you want to calculate another one? ";
cin >> ans;
transform(ans.begin(), ans.end(), ans.begin(), ::tolower);
Clear();
}
cout << endl << "Program closing...";
return 0;
}
| 24.5875 | 123 | 0.52364 | [
"transform"
] |
09d05951349ebf62c52329c77e1ba6d461f85722 | 18,141 | cc | C++ | ggadget/qt/qt_canvas.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | ggadget/qt/qt_canvas.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | ggadget/qt/qt_canvas.cc | suzhe/google-gadgets-for-linux | b58baabd8458c8515c9902b8176151a08d240983 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2008 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <cmath>
#include <vector>
#include <stack>
#include <algorithm>
#include <QtGui/QImage>
#include <QtGui/QPainter>
#include <QtGui/QTextDocument>
#include <QtGui/QAbstractTextDocumentLayout>
#include <ggadget/scoped_ptr.h>
#include <ggadget/signals.h>
#include <ggadget/slot.h>
#include <ggadget/clip_region.h>
#include <ggadget/math_utils.h>
#include "qt_graphics.h"
#include "qt_canvas.h"
#include "qt_font.h"
#if 1
#undef DLOG
#define DLOG true ? (void) 0 : LOG
#endif
namespace ggadget {
namespace qt {
const char *const kEllipsisText = "...";
static void MakeImageTransparent(QImage *img) {
QPainter p(img);
p.setCompositionMode(QPainter::CompositionMode_Source);
p.fillRect(img->rect(), Qt::transparent);
}
static void SetupPainter(QPainter *p) {
p->setCompositionMode(QPainter::CompositionMode_SourceOver);
p->setRenderHint(QPainter::SmoothPixmapTransform, true);
p->setRenderHint(QPainter::Antialiasing, false);
p->setBackground(Qt::transparent);
}
class QtCanvas::Impl {
public:
Impl(QtCanvas *owner, const QtGraphics *g,
double w, double h, bool create_painter)
: owner_(owner),
width_(w), height_(h), opacity_(1.), zoom_(1.),
on_zoom_connection_(NULL),
image_(NULL), painter_(NULL), region_(NULL) {
if (g){
zoom_ = g->GetZoom();
on_zoom_connection_ =
g->ConnectOnZoom(NewSlot(this, &Impl::OnZoom));
}
image_ = new QImage(D2I(w*zoom_), D2I(h*zoom_),
QImage::Format_ARGB32_Premultiplied);
if (image_ == NULL) return;
MakeImageTransparent(image_);
if (create_painter) {
painter_ = new QPainter(image_);
SetupPainter(painter_);
painter_->scale(zoom_, zoom_);
}
}
Impl(QtCanvas *owner, const std::string &data, bool create_painter)
: owner_(owner),
width_(0), height_(0),
opacity_(1.), zoom_(1.),
on_zoom_connection_(NULL),
image_(NULL), painter_(NULL), region_(NULL) {
image_ = new QImage();
if (!image_) return;
bool ret = image_->loadFromData(
reinterpret_cast<const uchar *>(data.c_str()),
static_cast<int>(data.length()));
if (ret) {
width_ = image_->width();
height_ = image_->height();
if (create_painter) {
painter_ = new QPainter(image_);
SetupPainter(painter_);
}
} else {
delete image_;
image_ = NULL;
}
}
Impl(QtCanvas *owner, double w, double h, QPainter *painter)
: owner_(owner),
width_(w), height_(h), opacity_(1.), zoom_(1.),
on_zoom_connection_(NULL), image_(NULL),
painter_(painter), region_(NULL) {
SetupPainter(painter_);
}
~Impl() {
if (painter_ && image_) delete painter_;
if (image_) delete image_;
if (on_zoom_connection_)
on_zoom_connection_->Disconnect();
}
bool DrawLine(double x0, double y0, double x1, double y1,
double width, const Color &c) {
QPainter *p = painter_;
QColor color(c.RedInt(), c.GreenInt(), c.BlueInt());
QPen pen(color);
pen.setWidthF(width);
p->setPen(pen);
p->drawLine(QPointF(x0, y0), QPointF(x1, y1));
return true;
}
bool DrawFilledRect(double x, double y, double w, double h, const Color &c) {
DLOG("DrawFilledRect:%p", owner_);
QPainter *p = painter_;
QColor color(c.RedInt(), c.GreenInt(), c.BlueInt());
p->fillRect(QRectF(x, y, w, h), color);
return true;
}
bool DrawCanvas(double x, double y, const CanvasInterface *img) {
DLOG("DrawCanvas:%p on %p", img, owner_);
QPainter *p = painter_;
const QtCanvas *canvas = reinterpret_cast<const QtCanvas*>(img);
Impl *impl = canvas->impl_;
double sx, sy;
if (impl->GetScale(&sx, &sy)) {
p->save();
p->scale(sx, sy);
p->drawImage(QPointF(x / sx, y / sy), *canvas->GetImage());
p->restore();
} else {
p->drawImage(QPointF(x, y), *canvas->GetImage());
}
return true;
}
bool DrawFilledRectWithCanvas(double x, double y, double w, double h,
const CanvasInterface *img) {
DLOG("DrawFilledRectWithCanvas: %p on %p", img, owner_);
QPainter *p = painter_;
const QtCanvas *canvas = reinterpret_cast<const QtCanvas*>(img);
p->fillRect(QRectF(x, y, w, h), *canvas->GetImage());
return true;
}
bool DrawCanvasWithMask(double x, double y,
const CanvasInterface *img,
double mx, double my,
const CanvasInterface *mask) {
GGL_UNUSED(mx);
GGL_UNUSED(my);
DLOG("DrawCanvasWithMask: (%p, %p) on %p", img, mask, owner_);
QPainter *p = painter_;
const QtCanvas *s = reinterpret_cast<const QtCanvas*>(img);
const QtCanvas *m = reinterpret_cast<const QtCanvas*>(mask);
QImage *simg = s->GetImage();
// FIXME: the content of img will be changed. but hopefully it's ok
// in current drawing model, where DrawCanvasWithMask() is only used in
// BasicElement's Draw() method and img is a temporary buffer.
QPainter *spainter = s->GetQPainter();
spainter->setCompositionMode(QPainter::CompositionMode_DestinationIn);
spainter->drawImage(0, 0, *m->GetImage());
spainter->setCompositionMode(QPainter::CompositionMode_SourceOver);
Impl *simpl = s->impl_;
double sx, sy;
if (simpl->GetScale(&sx, &sy) && image_) {
p->save();
p->scale(sx, sy);
p->drawImage(QPointF(x / sx, y / sy), *simg);
p->restore();
} else {
p->drawImage(QPointF(x, y), *simg);
}
return true;
}
static void SetupQTextDocument(QTextDocument *doc,
const FontInterface *f,
int text_flags,
Alignment align,
double in_width) {
// Setup font
const QtFont *qtfont = down_cast<const QtFont*>(f);
QFont font = *qtfont->GetQFont();
if (text_flags & TEXT_FLAGS_UNDERLINE)
font.setUnderline(true);
else
font.setUnderline(false);
if (text_flags & TEXT_FLAGS_STRIKEOUT)
font.setStrikeOut(true);
else
font.setStrikeOut(false);
doc->setDefaultFont(font);
// Setup align
Qt::Alignment a;
a = align == ALIGN_RIGHT ? Qt::AlignRight :
align == ALIGN_CENTER ? Qt::AlignHCenter :
align == ALIGN_JUSTIFY ? Qt::AlignJustify :
Qt::AlignLeft;
QTextOption option(a);
if (text_flags & TEXT_FLAGS_WORDWRAP) {
option.setWrapMode(QTextOption::WordWrap);
} else {
option.setWrapMode(QTextOption::NoWrap);
}
if (in_width > 0)
doc->setTextWidth(in_width);
doc->setDefaultTextOption(option);
}
QString ElidedText(const QString &str, const FontInterface *f,
double width, Trimming trimming) {
const QtFont *qtfont = down_cast<const QtFont*>(f);
QFont font = *qtfont->GetQFont();
QFontMetrics fm(font);
Qt::TextElideMode mode =
trimming == TRIMMING_PATH_ELLIPSIS ? Qt::ElideMiddle : Qt::ElideRight;
return fm.elidedText(str, mode, static_cast<int>(width));
}
bool DrawText(double x, double y, double width, double height,
const char *text, const FontInterface *f,
const Color &c, Alignment align, VAlignment valign,
Trimming trimming, int text_flags) {
DLOG("DrawText:%s, %f, %f, %f, %f", text, x, y, width, height);
QPainter *p = painter_;
QString qt_text = QString::fromUtf8(text);
QTextDocument doc(qt_text);
SetupQTextDocument(&doc, f, text_flags, align, width);
// taking care valign
double text_height = doc.documentLayout()->documentSize().height();
if (text_height < height) {
if (valign == VALIGN_MIDDLE) {
y += (height - text_height)/2;
height -= (height - text_height)/2;
} else if (valign == VALIGN_BOTTOM) {
y += (height - text_height);
height = text_height;
}
}
// Handle trimming
double text_width = doc.documentLayout()->documentSize().width();
if (trimming != TRIMMING_NONE) {
if (text_width > width && !(text_flags & TEXT_FLAGS_WORDWRAP)) {
doc.setPlainText(ElidedText(qt_text, f, width, trimming));
} else if (text_height > height && (text_flags & TEXT_FLAGS_WORDWRAP)) {
double ypos = height - 8;
if (ypos < 0) ypos = 0;
int pos = doc.documentLayout()->hitTest(
QPointF(width, ypos), Qt::FuzzyHit);
if (pos >= 4 && pos < qt_text.length()) {
qt_text.chop(qt_text.length() - pos + 3);
qt_text.append("...");
doc.setPlainText(qt_text);
} else if (pos < 4) {
doc.setPlainText("...");
}
}
}
QRectF rect(0, 0, width, height);
QAbstractTextDocumentLayout::PaintContext ctx;
p->save();
ctx.clip = rect;
p->translate(x, y);
QColor color(c.RedInt(), c.GreenInt(), c.BlueInt());
ctx.palette.setBrush(QPalette::Text, color);
doc.documentLayout()->draw(p, ctx);
p->restore();
return true;
}
bool DrawTextWithTexture(double x, double y, double width,
double height, const char *text,
const FontInterface *f,
const CanvasInterface *texture,
Alignment align, VAlignment valign,
Trimming trimming, int text_flags) {
GGL_UNUSED(x);
GGL_UNUSED(y);
GGL_UNUSED(width);
GGL_UNUSED(height);
GGL_UNUSED(f);
GGL_UNUSED(texture);
GGL_UNUSED(align);
GGL_UNUSED(valign);
GGL_UNUSED(trimming);
GGL_UNUSED(text_flags);
DLOG("DrawTextWithTexture: %s", text);
ASSERT(0);
return true;
}
bool IntersectRectClipRegion(double x, double y,
double w, double h) {
if (w <= 0.0 || h <= 0.0) return false;
painter_->setClipRect(QRectF(x, y, w, h), Qt::IntersectClip);
return true;
}
bool IntersectRectangle(double x, double y, double w, double h) {
QRect qrect(D2I(x), D2I(y), D2I(w), D2I(h));
*region_ = region_->united(QRegion(qrect));
return true;
}
bool IntersectGeneralClipRegion(const ClipRegion ®ion) {
QRegion qregion;
region_ = &qregion;
if (region.EnumerateRectangles(NewSlot(this, &Impl::IntersectRectangle))) {
painter_->setClipRegion(qregion, Qt::IntersectClip);
}
return true;
}
bool GetPointValue(double x, double y,
Color *color, double *opacity) const {
// Canvas without image_ doesn't support GetPointValue
if (!image_) return false;
if (x < 0 || x >= width_ || y < 0 || y >= height_) return false;
QColor qcolor = image_->pixel(D2I(x), D2I(y));
if (color) {
color->red = qcolor.redF();
color->green = qcolor.greenF();
color->blue = qcolor.blueF();
}
if (opacity) *opacity = qcolor.alphaF();
return true;
}
void OnZoom(double zoom) {
DLOG("zoom, width_, height_:%f, %f, %f", zoom, width_, height_);
if (zoom == zoom_) return;
ASSERT(image_); // Not support zoom for such canvas
QImage* new_image = new QImage(D2I(width_*zoom), D2I(height_*zoom),
QImage::Format_ARGB32_Premultiplied);
if (!new_image) return;
if (painter_) delete painter_;
delete image_;
image_ = new_image;
MakeImageTransparent(image_);
painter_ = new QPainter(image_);
SetupPainter(painter_);
painter_->scale(zoom, zoom);
zoom_ = zoom;
}
// Return false if no scale at all
bool GetScale(double *sx, double *sy) {
if (image_->height() == height_ && image_->width() == width_) {
if (sx) *sx = 1.0;
if (sy) *sy = 1.0;
return false;
}
if (sx) *sx = width_ / image_->width();
if (sy) *sy = height_ / image_->height();
return true;
}
QtCanvas *owner_;
double width_, height_;
double opacity_;
double zoom_;
Connection *on_zoom_connection_;
QImage *image_;
QPainter *painter_;
QRegion *region_;
};
QtCanvas::QtCanvas(const QtGraphics *g, double w, double h, bool create_painter)
: impl_(new Impl(this, g, w, h, create_painter)) {
}
QtCanvas::QtCanvas(double w, double h, QPainter *painter)
: impl_(new Impl(this, w, h, painter)) {
}
QtCanvas::QtCanvas(const std::string &data, bool create_painter)
: impl_(new Impl(this, data, create_painter)) {
}
QtCanvas::~QtCanvas() {
delete impl_;
impl_ = NULL;
}
void QtCanvas::Destroy() {
delete this;
}
bool QtCanvas::ClearCanvas() {
ClearRect(0, 0, impl_->width_, impl_->height_);
return true;
}
bool QtCanvas::ClearRect(double x, double y, double w, double h) {
QPainter *p = impl_->painter_;
p->save();
p->setCompositionMode(QPainter::CompositionMode_Source);
p->eraseRect(QRectF(x, y, w, h));
p->restore();
return true;
}
bool QtCanvas::PopState() {
impl_->painter_->restore();
return true;
}
bool QtCanvas::PushState() {
impl_->painter_->save();
return true;
}
bool QtCanvas::MultiplyOpacity(double opacity) {
if (opacity >= 0.0 && opacity <= 1.0) {
// TODO: setOpacity is not recommended to use for performance issue.
impl_->painter_->setOpacity(impl_->painter_->opacity()*opacity);
return true;
}
return false;
}
bool QtCanvas::DrawLine(double x0, double y0, double x1, double y1,
double width, const Color &c) {
return impl_->DrawLine(x0, y0, x1, y1, width, c);
}
void QtCanvas::RotateCoordinates(double radians) {
impl_->painter_->rotate(RadiansToDegrees(radians));
}
void QtCanvas::TranslateCoordinates(double dx, double dy) {
impl_->painter_->translate(dx, dy);
}
void QtCanvas::ScaleCoordinates(double cx, double cy) {
impl_->painter_->scale(cx, cy);
}
bool QtCanvas::DrawFilledRect(double x, double y,
double w, double h, const Color &c) {
return impl_->DrawFilledRect(x, y, w, h, c);
}
bool QtCanvas::IntersectRectClipRegion(double x, double y,
double w, double h) {
return impl_->IntersectRectClipRegion(x, y, w, h);
}
bool QtCanvas::IntersectGeneralClipRegion(const ClipRegion ®ion) {
return impl_->IntersectGeneralClipRegion(region);
}
bool QtCanvas::DrawCanvas(double x, double y, const CanvasInterface *img) {
return impl_->DrawCanvas(x, y, img);
}
bool QtCanvas::DrawRawImage(double x, double y,
const char *data, RawImageFormat format,
int width, int height, int stride) {
GGL_UNUSED(stride);
QImage::Format qt_format;
if (format == RAWIMAGE_FORMAT_RGB24)
qt_format = QImage::Format_RGB32;
else
qt_format = QImage::Format_ARGB32;
QImage img(reinterpret_cast<const uchar*>(data), width, height, qt_format);
impl_->painter_->drawImage(D2I(x), D2I(y), img);
return true;
}
bool QtCanvas::DrawFilledRectWithCanvas(double x, double y,
double w, double h,
const CanvasInterface *img) {
return impl_->DrawFilledRectWithCanvas(x, y, w, h, img);
}
bool QtCanvas::DrawCanvasWithMask(double x, double y,
const CanvasInterface *img,
double mx, double my,
const CanvasInterface *mask) {
return impl_->DrawCanvasWithMask(x, y, img, mx, my, mask);
}
bool QtCanvas::DrawText(double x, double y, double width, double height,
const char *text, const FontInterface *f,
const Color &c, Alignment align, VAlignment valign,
Trimming trimming, int text_flags) {
return impl_->DrawText(x, y, width, height, text, f,
c, align, valign, trimming, text_flags);
}
bool QtCanvas::DrawTextWithTexture(double x, double y, double w, double h,
const char *text,
const FontInterface *f,
const CanvasInterface *texture,
Alignment align, VAlignment valign,
Trimming trimming, int text_flags) {
return impl_->DrawTextWithTexture(x, y, w, h, text, f, texture,
align, valign, trimming, text_flags);
}
bool QtCanvas::GetTextExtents(const char *text, const FontInterface *f,
int text_flags, double in_width,
double *width, double *height) {
QTextDocument doc(QString::fromUtf8(text));
if (in_width <= 0) {
text_flags &= ~TEXT_FLAGS_WORDWRAP;
}
Impl::SetupQTextDocument(&doc, f, text_flags, ALIGN_LEFT, in_width);
if (width)
*width = doc.documentLayout()->documentSize().width();
if (height)
*height = doc.documentLayout()->documentSize().height();
return true;
}
bool QtCanvas::GetPointValue(double x, double y,
Color *color, double *opacity) const {
return impl_->GetPointValue(x, y, color, opacity);
}
double QtCanvas::GetWidth() const {
return impl_->width_;
}
double QtCanvas::GetHeight() const {
return impl_->height_;
}
bool QtCanvas::IsValid() const {
if (impl_->painter_ != NULL)
return true;
else
return false;
}
QImage* QtCanvas::GetImage() const {
return impl_->image_;
}
QPainter* QtCanvas::GetQPainter() const {
return impl_->painter_;
}
} // namespace qt
} // namespace ggadget
| 30.9046 | 80 | 0.614905 | [
"vector",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.